<commit_before>#ifndef Matrix_hpp
#define Matrix_hpp
//https://msdn.microsoft.com/ru-ru/library/f1b2td24.aspx
#include <iostream>
#include <fstream>
#include "MatrixException.hpp"

template <class MatrixT> class Matrix;
template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException);
template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix);

template <class MatrixT = int>
class Matrix {
public:
	Matrix() : lines(0), columns(0), elements(nullptr) {}
	Matrix(unsigned int _lines, unsigned int _columns);
	Matrix(const Matrix<MatrixT>& source_matrix);
	Matrix& operator= (const Matrix& source_matrix);
	void InitFromRandom();
	void InitFromFile(const char *filename) throw (FileException);
	MatrixT* operator[](unsigned int index) const throw (IndexException);
	Matrix<MatrixT> operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException);
	Matrix<MatrixT> operator*(const Matrix<MatrixT>& right_matrix) const throw (MultiplyException);
	bool operator==(const Matrix<MatrixT>& right_matrix) const;
	bool operator!=(const Matrix<MatrixT>& right_matrix) const;
	unsigned int GetNumberOfLines() const;
	unsigned int GetNumberOfColumns() const;
	~Matrix();
	//template <class MatrixT>
	friend std::istream& operator>> <>(std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException);
	//template <class MatrixT>
	friend std::ostream& operator<< <>(std::ostream& stream, const Matrix<MatrixT>& matrix);
private:
	MatrixT **elements;
	unsigned int lines, columns;
};

template <class MatrixT>
std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException){
	for (unsigned int i = 0; i < matrix.lines; i++) {
		for (unsigned int j = 0; j < matrix.columns; j++) {
			if (!(stream >> matrix[i][j])) {
				throw StreamException();
			}
		}
	}
	return stream;
}
template <class MatrixT>
std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix) {
	for (unsigned int i = 0; i < matrix.lines; i++) {
		for (unsigned int j = 0; j < matrix.columns; j++) {
			stream << matrix[i][j] << " ";
		}
		stream << '\n';
	}
	return stream;
}
template <typename MatrixT>
Matrix<MatrixT>::Matrix(unsigned int _lines, unsigned int _columns) :
	lines(_lines), columns(_columns), elements(new MatrixT*[_lines]) {
	for (unsigned int i = 0; i < lines; i++) {
		elements[i] = new MatrixT[columns];
		for (unsigned int j = 0; j < columns; j++) {
			elements[i][j] = 0;
		}
	}
}

template <typename MatrixT>
Matrix<MatrixT>::Matrix(const Matrix<MatrixT>& source_matrix)
	: lines(source_matrix.lines), columns(source_matrix.columns) {
	elements = new MatrixT*[lines];
	for (unsigned int i = 0; i < lines; i++) {
		elements[i] = new MatrixT[columns];
		for (unsigned int j = 0; j < columns; j++) {
			elements[i][j] = source_matrix[i][j];
		}
	}
}

template <typename MatrixT>
Matrix<MatrixT>& Matrix<MatrixT>::operator= (const Matrix<MatrixT>& source_matrix) {
	if (lines != source_matrix.lines || columns != source_matrix.columns) {
		this -> ~Matrix();
		lines = source_matrix.lines;
		columns = source_matrix.columns;
		elements = new int*[lines];
		for (int i = 0; i < lines; i++) {
			elements[i] = new int[columns];
			for (int j = 0; j < columns; j++) {
				elements[i][j] = source_matrix[i][j];
			}
		}
	}
	else {
		for (int i = 0; i < lines; i++) {
			for (int j = 0; j < columns; j++) {
				elements[i][j] = source_matrix[i][j];
			}
		}
	}
	return *this;
}

template <typename MatrixT>
void Matrix<MatrixT>::InitFromRandom() {
	for (int i = 0; i < lines; i++) {
		for (int j = 0; j < columns; j++) {
			elements[i][j] = rand() % 90 + 10;
		}
	}
}

template <typename MatrixT>
void Matrix<MatrixT>::InitFromFile(const char *filename) throw (FileException){
	std::fstream file(filename);
	if (!file) throw FileException();
	file >> *this;
}

template <typename MatrixT>
MatrixT* Matrix<MatrixT>::operator[](unsigned int index) const throw (IndexException){
	if (index >= lines) throw IndexException();
	return elements[index];
}

template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException){
	if (columns != right_matrix.GetNumberOfColumns()
		|| lines != right_matrix.GetNumberOfLines())
		throw AddException();
	Matrix<MatrixT> result(lines, columns);
	for (int i = 0; i < lines; i++) {
		for (int j = 0; j < columns; j++) {
			result[i][j] = elements[i][j] + right_matrix[i][j];
		}
	}
	return result;
}

template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator*(const Matrix& right_matrix) const throw (MultiplyException) {
	if (columns != right_matrix.lines) throw MultiplyException();
	Matrix<MatrixT> result(lines, right_matrix.columns);
	for (int i = 0; i < lines; i++) {
		for (int j = 0; j < right_matrix.columns; j++) {
			result[i][j] = 0;
			for (int k = 0; k < right_matrix.lines; k++)
				result[i][j] += elements[i][k] * right_matrix[k][j];
		}
	}
	return result;
}

template<typename MatrixT>
bool Matrix<MatrixT>::operator==(const Matrix<MatrixT>& right_matrix) const
{
	if (lines != right_matrix.lines || columns != right_matrix.columns) {
		return false;
	}
	else {
		for (unsigned i = 0; i < lines; i++) {
			for (unsigned j = 0; j < columns; j++) {
				if (operator[](i)[j] != right_matrix[i][j]) {
					return false;
				}
			}
		}
		return true;
	}
}

template<typename MatrixT>
bool Matrix<MatrixT>::operator!=(const Matrix<MatrixT>& right_matrix) const
{
	return !(operator==(right_matrix));
}

template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfLines() const {
	return lines;
}

template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfColumns() const {
	return columns;
}

template <typename MatrixT>
Matrix<MatrixT>::~Matrix() {
	for (unsigned int i = 0; i < lines; i++)
		delete[] elements[i];
	delete[] elements;
}

#endif

<commit_msg>Update Matrix.hpp<commit_after>#ifndef Matrix_hpp
#define Matrix_hpp
//https://msdn.microsoft.com/ru-ru/library/f1b2td24.aspx
#include <iostream>
#include <fstream>
#include "MatrixException.hpp"

template <class MatrixT> class Matrix;
template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException);
template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix);

template <class MatrixT = int>
class Matrix {
public:
	Matrix() : lines(0), columns(0), elements(nullptr) {}
	Matrix(size_t _lines, unsigned int _columns);
	Matrix(const Matrix<MatrixT>& source_matrix);
	Matrix& operator= (const Matrix& source_matrix);
	void InitFromRandom();
	void InitFromFile(const char *filename) throw (FileException);
	MatrixT* operator[](unsigned int index) const throw (IndexException);
	Matrix<MatrixT> operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException);
	Matrix<MatrixT> operator*(const Matrix<MatrixT>& right_matrix) const throw (MultiplyException);
	bool operator==(const Matrix<MatrixT>& right_matrix) const;
	bool operator!=(const Matrix<MatrixT>& right_matrix) const;
	unsigned int GetNumberOfLines() const;
	unsigned int GetNumberOfColumns() const;
	~Matrix();
	//template <class MatrixT>
	friend std::istream& operator>> <>(std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException);
	//template <class MatrixT>
	friend std::ostream& operator<< <>(std::ostream& stream, const Matrix<MatrixT>& matrix);
private:
	MatrixT **elements;
	unsigned int lines, columns;
};

template <class MatrixT>
std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException){
	for (unsigned int i = 0; i < matrix.lines; i++) {
		for (unsigned int j = 0; j < matrix.columns; j++) {
			if (!(stream >> matrix[i][j])) {
				throw StreamException();
			}
		}
	}
	return stream;
}
template <class MatrixT>
std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix) {
	for (unsigned int i = 0; i < matrix.lines; i++) {
		for (unsigned int j = 0; j < matrix.columns; j++) {
			stream << matrix[i][j] << " ";
		}
		stream << '\n';
	}
	return stream;
}
template <typename MatrixT>
Matrix<MatrixT>::Matrix(unsigned int _lines, unsigned int _columns) :
	lines(_lines), columns(_columns), elements(new MatrixT*[_lines]) {
	for (unsigned int i = 0; i < lines; i++) {
		elements[i] = new MatrixT[columns];
		for (unsigned int j = 0; j < columns; j++) {
			elements[i][j] = 0;
		}
	}
}

template <typename MatrixT>
Matrix<MatrixT>::Matrix(const Matrix<MatrixT>& source_matrix)
	: lines(source_matrix.lines), columns(source_matrix.columns) {
	elements = new MatrixT*[lines];
	for (unsigned int i = 0; i < lines; i++) {
		elements[i] = new MatrixT[columns];
		for (unsigned int j = 0; j < columns; j++) {
			elements[i][j] = source_matrix[i][j];
		}
	}
}

template <typename MatrixT>
Matrix<MatrixT>& Matrix<MatrixT>::operator= (const Matrix<MatrixT>& source_matrix) {
	if (lines != source_matrix.lines || columns != source_matrix.columns) {
		this -> ~Matrix();
		lines = source_matrix.lines;
		columns = source_matrix.columns;
		elements = new int*[lines];
		for (int i = 0; i < lines; i++) {
			elements[i] = new int[columns];
			for (int j = 0; j < columns; j++) {
				elements[i][j] = source_matrix[i][j];
			}
		}
	}
	else {
		for (int i = 0; i < lines; i++) {
			for (int j = 0; j < columns; j++) {
				elements[i][j] = source_matrix[i][j];
			}
		}
	}
	return *this;
}

template <typename MatrixT>
void Matrix<MatrixT>::InitFromRandom() {
	for (int i = 0; i < lines; i++) {
		for (int j = 0; j < columns; j++) {
			elements[i][j] = rand() % 90 + 10;
		}
	}
}

template <typename MatrixT>
void Matrix<MatrixT>::InitFromFile(const char *filename) throw (FileException){
	std::fstream file(filename);
	if (!file) throw FileException();
	file >> *this;
}

template <typename MatrixT>
MatrixT* Matrix<MatrixT>::operator[](unsigned int index) const throw (IndexException){
	if (index >= lines) throw IndexException();
	return elements[index];
}

template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException){
	if (columns != right_matrix.GetNumberOfColumns()
		|| lines != right_matrix.GetNumberOfLines())
		throw AddException();
	Matrix<MatrixT> result(lines, columns);
	for (int i = 0; i < lines; i++) {
		for (int j = 0; j < columns; j++) {
			result[i][j] = elements[i][j] + right_matrix[i][j];
		}
	}
	return result;
}

template <typename MatrixT>
Matrix<MatrixT> Matrix<MatrixT>::operator*(const Matrix& right_matrix) const throw (MultiplyException) {
	if (columns != right_matrix.lines) throw MultiplyException();
	Matrix<MatrixT> result(lines, right_matrix.columns);
	for (int i = 0; i < lines; i++) {
		for (int j = 0; j < right_matrix.columns; j++) {
			result[i][j] = 0;
			for (int k = 0; k < right_matrix.lines; k++)
				result[i][j] += elements[i][k] * right_matrix[k][j];
		}
	}
	return result;
}

template<typename MatrixT>
bool Matrix<MatrixT>::operator==(const Matrix<MatrixT>& right_matrix) const
{
	if (lines != right_matrix.lines || columns != right_matrix.columns) {
		return false;
	}
	else {
		for (unsigned i = 0; i < lines; i++) {
			for (unsigned j = 0; j < columns; j++) {
				if (operator[](i)[j] != right_matrix[i][j]) {
					return false;
				}
			}
		}
		return true;
	}
}

template<typename MatrixT>
bool Matrix<MatrixT>::operator!=(const Matrix<MatrixT>& right_matrix) const
{
	return !(operator==(right_matrix));
}

template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfLines() const {
	return lines;
}

template <typename MatrixT>
unsigned int Matrix<MatrixT>::GetNumberOfColumns() const {
	return columns;
}

template <typename MatrixT>
Matrix<MatrixT>::~Matrix() {
	for (unsigned int i = 0; i < lines; i++)
		delete[] elements[i];
	delete[] elements;
}

#endif

<|endoftext|>


<commit_before>#include "serialise.hh"
#include "util.hh"
#include "remote-store.hh"
#include "worker-protocol.hh"
#include "archive.hh"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <iostream>
#include <unistd.h>

namespace nix {

RemoteStore::RemoteStore()
{
    toChild.create();
    fromChild.create();

    /* Start the worker. */
    string worker = "nix-worker";

    child = fork();

    switch (child) {

    case -1:
        throw SysError("unable to fork");

    case 0:
        try { /* child */

            fromChild.readSide.close();
            if (dup2(fromChild.writeSide, STDOUT_FILENO) == -1)
                throw SysError("dupping write side");

            toChild.writeSide.close();
            if (dup2(toChild.readSide, STDIN_FILENO) == -1)
                throw SysError("dupping read side");

            int fdDebug = open("/tmp/worker-log", O_WRONLY | O_CREAT | O_TRUNC, 0644);
            assert(fdDebug != -1);
            if (dup2(fdDebug, STDERR_FILENO) == -1)
                throw SysError("dupping stderr");
            close(fdDebug);

            execlp(worker.c_str(), worker.c_str(),
                "-vvv", "--slave", NULL);

            throw SysError(format("executing `%1%'") % worker);

        } catch (std::exception & e) {
            std::cerr << format("child error: %1%\n") % e.what();
        }
        quickExit(1);
    }

    fromChild.writeSide.close();
    toChild.readSide.close();

    from.fd = fromChild.readSide;
    to.fd = toChild.writeSide;

    /* Send the magic greeting, check for the reply. */
    writeInt(WORKER_MAGIC_1, to);

    unsigned int magic = readInt(from);
    if (magic != WORKER_MAGIC_2) throw Error("protocol mismatch");
}

RemoteStore::~RemoteStore()
{
    try {
        fromChild.readSide.close();
        toChild.writeSide.close();
        child.wait(true);
    } catch (Error & e) {
        printMsg(lvlError, format("error (ignored): %1%") % e.msg());
    }
}

bool RemoteStore::isValidPath(const Path & path)
{
    writeInt(wopIsValidPath, to);
    writeString(path, to);
    unsigned int reply = readInt(from);
    return reply != 0;
}

Substitutes RemoteStore::querySubstitutes(const Path & path)
{
    throw Error("not implemented 2");
}

bool RemoteStore::hasSubstitutes(const Path & path)
{
    writeInt(wopHasSubstitutes, to);
    writeString(path, to);
    unsigned int reply = readInt(from);
    return reply != 0;
}

Hash RemoteStore::queryPathHash(const Path & path)
{
    writeInt(wopQueryPathHash, to);
    writeString(path, to);
    string hash = readString(from);
    return parseHash(htSHA256, hash);
}

void RemoteStore::queryReferences(const Path & path,
    PathSet & references)
{
    writeInt(wopQueryReferences, to);
    writeString(path, to);
    PathSet references2 = readStringSet(from);
    references.insert(references2.begin(), references2.end());
}

void RemoteStore::queryReferrers(const Path & path,
    PathSet & referrers)
{
    writeInt(wopQueryReferrers, to);
    writeString(path, to);
    PathSet referrers2 = readStringSet(from);
    referrers.insert(referrers2.begin(), referrers2.end());
}

Path RemoteStore::addToStore(const Path & _srcPath, bool fixed,
    bool recursive, string hashAlgo)
{
    Path srcPath(absPath(_srcPath));

    writeInt(wopAddToStore, to);
    writeString(baseNameOf(srcPath), to);
    writeInt(fixed ? 1 : 0, to);
    writeInt(recursive ? 1 : 0, to);
    writeString(hashAlgo, to);
    dumpPath(srcPath, to);
    Path path = readString(from);
    return path;
}

Path RemoteStore::addTextToStore(const string & suffix, const string & s,
    const PathSet & references)
{
    writeInt(wopAddTextToStore, to);
    writeString(suffix, to);
    writeString(s, to);
    writeStringSet(references, to);

    Path path = readString(from);
    return path;
}

void RemoteStore::buildDerivations(const PathSet & drvPaths)
{
    writeInt(wopBuildDerivations, to);
    writeStringSet(drvPaths, to);
    processStderr();
    readInt(from);
}

void RemoteStore::ensurePath(const Path & path)
{
    writeInt(wopEnsurePath, to);
    writeString(path, to);
    readInt(from);
}

void RemoteStore::addTempRoot(const Path & path)
{
    writeInt(wopAddTempRoot, to);
    writeString(path, to);
    readInt(from);
}

void RemoteStore::syncWithGC()
{
    writeInt(wopSyncWithGC, to);
    readInt(from);
}

void RemoteStore::processStderr()
{
    unsigned int msg;
    while ((msg = readInt(from)) == STDERR_NEXT) {
        string s = readString(from);
        writeToStderr((unsigned char *) s.c_str(), s.size());
    }
    if (msg == STDERR_ERROR)
        throw Error(readString(from));
    else if (msg != STDERR_LAST)
        throw Error("protocol error processing standard error");
}

}
<commit_msg>* Better error message if the worker doesn't start.<commit_after>#include "serialise.hh"
#include "util.hh"
#include "remote-store.hh"
#include "worker-protocol.hh"
#include "archive.hh"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <iostream>
#include <unistd.h>

namespace nix {

RemoteStore::RemoteStore()
{
    toChild.create();
    fromChild.create();

    /* Start the worker. */
    string worker = "nix-worker";

    child = fork();

    switch (child) {

    case -1:
        throw SysError("unable to fork");

    case 0:
        try { /* child */

            fromChild.readSide.close();
            if (dup2(fromChild.writeSide, STDOUT_FILENO) == -1)
                throw SysError("dupping write side");

            toChild.writeSide.close();
            if (dup2(toChild.readSide, STDIN_FILENO) == -1)
                throw SysError("dupping read side");

            int fdDebug = open("/tmp/worker-log", O_WRONLY | O_CREAT | O_TRUNC, 0644);
            assert(fdDebug != -1);
            if (dup2(fdDebug, STDERR_FILENO) == -1)
                throw SysError("dupping stderr");
            close(fdDebug);

            execlp(worker.c_str(), worker.c_str(),
                "-vvv", "--slave", NULL);

            throw SysError(format("executing `%1%'") % worker);

        } catch (std::exception & e) {
            std::cerr << format("child error: %1%\n") % e.what();
        }
        quickExit(1);
    }

    fromChild.writeSide.close();
    toChild.readSide.close();

    from.fd = fromChild.readSide;
    to.fd = toChild.writeSide;

    /* Send the magic greeting, check for the reply. */
    try {
        writeInt(WORKER_MAGIC_1, to);
        unsigned int magic = readInt(from);
        if (magic != WORKER_MAGIC_2) throw Error("protocol mismatch");
    } catch (Error & e) {
        throw Error(format("cannot start worker process `%1%' (%2%)")
            % worker % e.msg());
    }
}

RemoteStore::~RemoteStore()
{
    try {
        fromChild.readSide.close();
        toChild.writeSide.close();
        child.wait(true);
    } catch (Error & e) {
        printMsg(lvlError, format("error (ignored): %1%") % e.msg());
    }
}

bool RemoteStore::isValidPath(const Path & path)
{
    writeInt(wopIsValidPath, to);
    writeString(path, to);
    unsigned int reply = readInt(from);
    return reply != 0;
}

Substitutes RemoteStore::querySubstitutes(const Path & path)
{
    throw Error("not implemented 2");
}

bool RemoteStore::hasSubstitutes(const Path & path)
{
    writeInt(wopHasSubstitutes, to);
    writeString(path, to);
    unsigned int reply = readInt(from);
    return reply != 0;
}

Hash RemoteStore::queryPathHash(const Path & path)
{
    writeInt(wopQueryPathHash, to);
    writeString(path, to);
    string hash = readString(from);
    return parseHash(htSHA256, hash);
}

void RemoteStore::queryReferences(const Path & path,
    PathSet & references)
{
    writeInt(wopQueryReferences, to);
    writeString(path, to);
    PathSet references2 = readStringSet(from);
    references.insert(references2.begin(), references2.end());
}

void RemoteStore::queryReferrers(const Path & path,
    PathSet & referrers)
{
    writeInt(wopQueryReferrers, to);
    writeString(path, to);
    PathSet referrers2 = readStringSet(from);
    referrers.insert(referrers2.begin(), referrers2.end());
}

Path RemoteStore::addToStore(const Path & _srcPath, bool fixed,
    bool recursive, string hashAlgo)
{
    Path srcPath(absPath(_srcPath));

    writeInt(wopAddToStore, to);
    writeString(baseNameOf(srcPath), to);
    writeInt(fixed ? 1 : 0, to);
    writeInt(recursive ? 1 : 0, to);
    writeString(hashAlgo, to);
    dumpPath(srcPath, to);
    Path path = readString(from);
    return path;
}

Path RemoteStore::addTextToStore(const string & suffix, const string & s,
    const PathSet & references)
{
    writeInt(wopAddTextToStore, to);
    writeString(suffix, to);
    writeString(s, to);
    writeStringSet(references, to);

    Path path = readString(from);
    return path;
}

void RemoteStore::buildDerivations(const PathSet & drvPaths)
{
    writeInt(wopBuildDerivations, to);
    writeStringSet(drvPaths, to);
    processStderr();
    readInt(from);
}

void RemoteStore::ensurePath(const Path & path)
{
    writeInt(wopEnsurePath, to);
    writeString(path, to);
    readInt(from);
}

void RemoteStore::addTempRoot(const Path & path)
{
    writeInt(wopAddTempRoot, to);
    writeString(path, to);
    readInt(from);
}

void RemoteStore::syncWithGC()
{
    writeInt(wopSyncWithGC, to);
    readInt(from);
}

void RemoteStore::processStderr()
{
    unsigned int msg;
    while ((msg = readInt(from)) == STDERR_NEXT) {
        string s = readString(from);
        writeToStderr((unsigned char *) s.c_str(), s.size());
    }
    if (msg == STDERR_ERROR)
        throw Error(readString(from));
    else if (msg != STDERR_LAST)
        throw Error("protocol error processing standard error");
}

}
<|endoftext|>


<commit_before>#pragma once
#include "stdafx.h"

static std::map<std::string,void*> s_InitializationMap;		//ʼֵ

inline void InitInitializationMap()			//ʼʼֵ
{
	s_InitializationMap[typeid(int).name()] = new int(0);
	s_InitializationMap[typeid(float).name()] = new float(0.00f);
	s_InitializationMap[typeid(double).name()] = new double(0.00f);
	s_InitializationMap[typeid(char).name()] = new char(char(0));
	s_InitializationMap[typeid(bool).name()] = new bool(false);
}

inline void ReleaseInitializationMap()		//ͷųʼֵ
{
	for (auto i : s_InitializationMap)
	{
		delete i.second;
	}
}
template <typename T>
inline void GetInitialization(T** c)		//ȡ͵ĳʼֵ
{
	auto i = find(s_InitializationMap.begin(), s_InitializationMap.end(), typeid(*(*c)).name());
	if (i != s_InitializationMap.end())
	{
		memcpy(*c, (*i).second, sizeof(T));
	}
	else
	{
		s_InitializationMap.insert(make_pair(typeid(T).name(), new T()));
		memcpy(*c, s_InitializationMap[typeid(T).name()], sizeof(T));
	}
}

struct MemoryBlock	//ڴϢ
{
	void* m_Address;
	size_t m_Size;
	MemoryBlock()
	{
		m_Address = NULL;
		m_Size = 0;
	}
	MemoryBlock(void* address, size_t size)
	{
		m_Address = address;
		m_Size = size;
	}
};

void CleanMemoryBlock(const MemoryBlock& mb)
{
	memset(mb.m_Address, NULL, mb.m_Size);
}

class MemoryManager		//ڴջΨһģ
{
protected:
	size_t m_Top;
	void* m_Memory;
	std::vector<MemoryBlock> m_MemoryBlocks;
	std::vector<MemoryBlock> m_FreeMemoryBlocks;
public:
	static const size_t m_MemorySize = 0xffff;
	MemoryManager()
	{
		m_Memory = malloc(m_MemorySize);
		m_Top = 0;
		InitInitializationMap();
	}

	~MemoryManager()
	{
		free(m_Memory);
		m_Memory = NULL;
		ReleaseInitializationMap();
	}

	template<typename T>
	bool ReuseMemory(T** dest)
	{
		if (m_FreeMemoryBlocks.size() == 0)
			return false;
		else
		{
			for (vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1)
			{
				if ((*i).m_Size >= sizeof(T))
				{
					m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, sizeof(T)));
					*dest = (T*)((*i).m_Address);
					CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
					GetInitialization(dest);
					if ((*i).m_Size == sizeof(T))
					{
						m_FreeMemoryBlocks.erase(i);
					}
					else
					{
						(*i).m_Address = *dest + sizeof(T);
						(*i).m_Size -= sizeof(T);
					}
					return true;
				}
			}
		}
		return false;
	}

	template<typename T>
	bool ReuseMemory(std::pair<T**, size_t> c)
	{
		if (m_FreeMemoryBlocks.size() == 0)
			return false;
		else
		{
			for (vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1)
			{
				if ((*i).m_Size >= c.second * sizeof(T))
				{
					m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, c.second * sizeof(T)));
					*c.first = (T*)((*i).m_Address);
					CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
					GetInitialization(dest);
					if ((*i).m_Size == c.second * sizeof(T))
					{
						m_FreeMemoryBlocks.erase(i);
					}
					else
					{
						(*i).m_Address = *c.first + c.second * sizeof(T);
						(*i).m_Size -= c.second * sizeof(T);
					}
					return true;
				}
			}
		}
		return false;
	}

	template<typename T>
	void NewObject(T** dest)
	{
		if (!ReuseMemory(dest))
		{
			m_MemoryBlocks.push_back(MemoryBlock(m_Memory + m_Top, sizeof(T)));
			*dest = (T*)(m_Memory + m_Top);
			CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
			GetInitialization(dest);
			m_Top += sizeof(T);
		}
	}

	template<typename T, typename... TS>
	void NewObject(T** dest, TS**... ts)
	{
		NewObject(dest);
		NewObject(ts...);
	}

	template<typename T>
	void NewObject(std::pair<T**, size_t> c)
	{
		if (!ReuseMemory(c))
		{
			m_MemoryBlocks.push_back(MemoryBlock(m_Memory + m_Top, c.second * sizeof(T)));
			*c.first = (T*)(m_Memory + m_Top);
			CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
			GetInitialization(dest);
			m_Top += c.second * sizeof(T);
		}
	}

	template<typename T>
	bool ReleaseObject(T** dest)
	{
		for (vector<MemoryBlock>::iterator i = m_MemoryBlocks.begin(); i != m_MemoryBlocks.end(); i += 1)
		{
			if ((*i).m_Address == *dest)
			{
				m_FreeMemoryBlocks.push_back(*i);
				m_MemoryBlocks.erase(i);
				*dest = NULL;
				return true;
			}
		}
		return false;
	}

	template<typename T, typename... TS>
	bool ReleaseObject(T** dest, TS**... ts)
	{
		return (Release(dest)&Release(ts...));
	}
};

template<typename T>
class Pointer			//ʹڴָ
{
protected:
	MemoryManager& m_MemoryManager;
	T* m_pContent;
public:
	Pointer(MemoryManager& m) :m_MemoryManager(m),m_pContent(NULL){}
	~Pointer()
	{
		if (m_pContent)
			m_MemoryManager.ReleaseObject(&m_pContent);
	}
	void InitUnit()
	{
		m_MemoryManager.NewObject(&m_pContent);
	}
	void InitArray(size_t size)
	{
		m_MemoryManager.NewObject(make_pair(&m_pContent, size));
	}
	bool operator = (const Pointer&) = delete;
	T& operator * ()
	{
		return *m_pContent;
	}
};

template<typename T>
class UnitPointer :public Pointer<T>	//ָ򵥸ָ
{
	UnitPointer(MemoryManager& m) :Pointer(m)
	{
		InitUnit();
	}
	~UnitPointer()
	{
		~Pointer();
	}
};

template<typename T>
class ArrayPointer :public Pointer<T>	//ָγɵָ
{
	ArrayPointer(MemoryManager& m,size_t size) :Pointer(m)
	{
		InitArray(size);
	}
	~ArrayPointer()
	{
		~Pointer();
	}
};<commit_msg>the MemorytInitialization can't use<commit_after>#pragma once
#include "stdafx.h"

/*
static std::map<std::string,void*> s_InitializationMap;		//ʼֵ

inline void InitInitializationMap()			//ʼʼֵ
{
	s_InitializationMap[typeid(int).name()] = new int(0);
	s_InitializationMap[typeid(float).name()] = new float(0.00f);
	s_InitializationMap[typeid(double).name()] = new double(0.00f);
	s_InitializationMap[typeid(char).name()] = new char(char(0));
	s_InitializationMap[typeid(bool).name()] = new bool(false);
}

inline void ReleaseInitializationMap()		//ͷųʼֵ
{
	for (auto i : s_InitializationMap)
	{
		delete i.second;
	}
}
template <typename T>
inline void GetInitialization(T** c)		//ȡ͵ĳʼֵ
{
	auto i = find(s_InitializationMap.begin(), s_InitializationMap.end(), typeid(*(*c)).name());
	if (i != s_InitializationMap.end())
	{
		memcpy(*c, (*i).second, sizeof(T));
	}
	else
	{
		s_InitializationMap.insert(std::make_pair(typeid(T).name(), new T()));
		memcpy(*c, s_InitializationMap[typeid(T).name()], sizeof(T));
	}
}
*/

struct MemoryBlock	//ڴϢ
{
	void* m_Address;
	size_t m_Size;
	MemoryBlock()
	{
		m_Address = NULL;
		m_Size = 0;
	}
	MemoryBlock(void* address, size_t size)
	{
		m_Address = address;
		m_Size = size;
	}
};

void CleanMemoryBlock(const MemoryBlock& mb)
{
	memset(mb.m_Address, NULL, mb.m_Size);
}

class MemoryManager		//ڴջΨһģ
{
protected:
	size_t m_Top;
	void* m_Memory;
	std::vector<MemoryBlock> m_MemoryBlocks;
	std::vector<MemoryBlock> m_FreeMemoryBlocks;
public:
	static const size_t m_MemorySize = 0xffff;
	MemoryManager()
	{
		m_Memory = malloc(m_MemorySize);
		m_Top = 0;
//		InitInitializationMap();
	}

	~MemoryManager()
	{
		free(m_Memory);
		m_Memory = NULL;
//		ReleaseInitializationMap();
	}

	template<typename T>
	bool ReuseMemory(T** dest)
	{
		if (m_FreeMemoryBlocks.size() == 0)
			return false;
		else
		{
			for (std::vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1)
			{
				if ((*i).m_Size >= sizeof(T))
				{
					m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, sizeof(T)));
					*dest = (T*)((*i).m_Address);
					CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
//					GetInitialization(dest);
					if ((*i).m_Size == sizeof(T))
					{
						m_FreeMemoryBlocks.erase(i);
					}
					else
					{
						(*i).m_Address = *dest + sizeof(T);
						(*i).m_Size -= sizeof(T);
					}
					return true;
				}
			}
		}
		return false;
	}

	template<typename T>
	bool ReuseMemory(std::pair<T**, size_t> c)
	{
		if (m_FreeMemoryBlocks.size() == 0)
			return false;
		else
		{
			for (vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1)
			{
				if ((*i).m_Size >= c.second * sizeof(T))
				{
					m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, c.second * sizeof(T)));
					*c.first = (T*)((*i).m_Address);
					CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
//					GetInitialization(dest);
					if ((*i).m_Size == c.second * sizeof(T))
					{
						m_FreeMemoryBlocks.erase(i);
					}
					else
					{
						(*i).m_Address = *c.first + c.second * sizeof(T);
						(*i).m_Size -= c.second * sizeof(T);
					}
					return true;
				}
			}
		}
		return false;
	}

	template<typename T>
	void NewObject(T** dest)
	{
		if (!ReuseMemory(dest))
		{
			m_MemoryBlocks.push_back(MemoryBlock((void*)((char*)m_Memory + m_Top), sizeof(T)));
			*dest = (T*)((char*)m_Memory + m_Top);
			CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
//			GetInitialization(dest);
			m_Top += sizeof(T);
		}
	}

	template<typename T, typename... TS>
	void NewObject(T** dest, TS**... ts)
	{
		NewObject(dest);
		NewObject(ts...);
	}

	template<typename T>
	void NewObject(std::pair<T**, size_t> c)
	{
		if (!ReuseMemory(c))
		{
			m_MemoryBlocks.push_back(MemoryBlock(m_Memory + m_Top, c.second * sizeof(T)));
			*c.first = (T*)(m_Memory + m_Top);
			CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]);
//			GetInitialization(dest);
			m_Top += c.second * sizeof(T);
		}
	}

	template<typename T>
	bool ReleaseObject(T** dest)
	{
		for (std::vector<MemoryBlock>::iterator i = m_MemoryBlocks.begin(); i != m_MemoryBlocks.end(); i += 1)
		{
			if ((*i).m_Address == *dest)
			{
				m_FreeMemoryBlocks.push_back(*i);
				m_MemoryBlocks.erase(i);
				*dest = NULL;
				return true;
			}
		}
		return false;
	}

	template<typename T, typename... TS>
	bool ReleaseObject(T** dest, TS**... ts)
	{
		return (Release(dest)&Release(ts...));
	}
};

template<typename T>
class Pointer			//ʹڴָ
{
protected:
	MemoryManager& m_MemoryManager;
	T* m_pContent;
public:
	Pointer(MemoryManager& m) :m_MemoryManager(m),m_pContent(NULL){}
	~Pointer()
	{
		if (m_pContent)
			m_MemoryManager.ReleaseObject(&m_pContent);
	}
	void InitUnit()
	{
		m_MemoryManager.NewObject(&m_pContent);
	}
	void InitArray(size_t size)
	{
		m_MemoryManager.NewObject(make_pair(&m_pContent, size));
	}
	bool operator = (const Pointer&) = delete;
	T& operator * ()
	{
		return *m_pContent;
	}
};

template<typename T>
class UnitPointer :public Pointer<T>	//ָ򵥸ָ
{
public:
	UnitPointer(MemoryManager& m) :Pointer(m)
	{
		Pointer<T>::InitUnit();
	}
};

template<typename T>
class ArrayPointer :public Pointer<T>	//ָγɵָ
{
public:
	ArrayPointer(MemoryManager& m,size_t size) :Pointer(m)
	{
		Pointer<T>::InitArray(size);
	}
};<|endoftext|>


<commit_before>/**
 * @file       paramgen.cpp
 *
 * @brief      Parameter generation utility for Zerocoin.
 *
 * @author     Ian Miers, Christina Garman and Matthew Green
 * @date       June 2013
 *
 * @copyright  Copyright 2013 Ian Miers, Christina Garman and Matthew Green
 * @license    This project is released under the MIT license.
 **/
// Copyright (c) 2017-2019 The PIVX developers

#include <string>
#include <iostream>
#include <fstream>
//#include <curses.h>
#include <exception>
#include "Zerocoin.h"

#define DEFAULT_MODULUS_SIZE    3072
#define MIN_MODULUS_SIZE        1026

void
PrintWarning()
{
    cout << "Zerocoin parameter generation utility" << endl;
    cout << "-------------------------------------" << endl << endl;
    cout << "This utility generates an l-bit modulus N as the product of" << endl;
    cout << "two safe primes p, q. The values p and q are not stored." << endl;
    cout << "Call this program with no arguments to see usage options." << endl;
    cout << endl;
    cout << "SECURITY WARNING: ZEROCOIN PARAMETERS MUST BE GENERATED BY" << endl;
    cout << "A TRUSTED PARTY WHO DOES NOT STORE THE FACTORS. WHILE WE MAKE" << endl;
    cout << "A BEST EFFORT TO DESTROY THIS INFORMATION WE DO NOT TAKE" << endl;
    cout << "SPECIAL PRECAUTIONS TO ENSURE THAT THEY ARE DESTROYED." << endl;
    cout << endl;
    cout << "USE THIS UTILITY AT YOUR OWN RISK" << endl << endl;
}

void usage()
{
    printf("Usage:\n");
    printf(" -b <numbits>\n");
    printf(" -o <output file>\n");

    exit (8);
}

int main(int argc, char **argv)
{
    static CBigNum resultModulus(0);
    uint32_t numBits = DEFAULT_MODULUS_SIZE;
    ofstream outfile;
    char* outfileName;
    bool writeToFile = false;

    while ((argc > 1) && (argv[1][0] == '-'))
    {
        switch (argv[1][1])
        {
        case 'b':
            numBits = atoi(argv[2]);
            ++argv;
            --argc;
            break;

        case 'o':
            outfileName = argv[2];
            writeToFile = true;
            break;

        case 'h':
            usage();
            break;

        default:
            printf("Wrong Argument: %s\n", argv[1]);
            usage();
            break;
        }

        ++argv;
        --argc;
    }

    if (numBits < MIN_MODULUS_SIZE) {
        cout << "Modulus is below minimum length (" << MIN_MODULUS_SIZE << ") bits" << endl;
        return(0);
    }

    PrintWarning();

    cout << "Modulus size set to " << numBits << " bits." << endl;
    cout << "Generating parameters. This may take a few minutes..." << endl;

    // Generate two safe primes "p" and "q"
    CBigNum *p, *q;
    p = new CBigNum(0);
    q = new CBigNum(0);
    *p = CBigNum::generatePrime(numBits / 2, true);
    *q = CBigNum::generatePrime(numBits / 2, true);

    // Multiply to compute N
    resultModulus = (*p) * (*q);

    // Wipe out the factors
    delete p;
    delete q;

    // Convert to a hexidecimal string
    std::string resultHex = resultModulus.ToString(16);

    cout << endl << "N = " << endl << resultHex << endl;

    if (writeToFile) {
        try {
            outfile.open (outfileName);
            outfile << resultHex;
            outfile.close();
            cout << endl << "Result has been written to file '" << outfileName << "'." << endl;
        } catch (const std::runtime_error& e) {
            cout << "Unable to write to file:" << e.what() << endl;
        }
    }
}
<commit_msg>[Cleanup] Remove unused Parameter generation utility for zerocoin<commit_after><|endoftext|>


<commit_before>#include "lxqtfiledialoghelper.h"

#include <libfm-qt/libfmqt.h>
#include <libfm-qt/filedialog.h>

#include <QWindow>
#include <QMimeDatabase>
#include <QDebug>
#include <QTimer>

#include <memory>

static std::unique_ptr<Fm::LibFmQt> libfmQtContext_;

LXQtFileDialogHelper::LXQtFileDialogHelper() {
    if(!libfmQtContext_) {
        // initialize libfm-qt only once
        libfmQtContext_ = std::unique_ptr<Fm::LibFmQt>{new Fm::LibFmQt()};
    }

    // can only be used after libfm-qt initialization
    dlg_ = std::unique_ptr<Fm::FileDialog>(new Fm::FileDialog());
    connect(dlg_.get(), &Fm::FileDialog::accepted, this, &LXQtFileDialogHelper::accept);
    connect(dlg_.get(), &Fm::FileDialog::rejected, this, &LXQtFileDialogHelper::reject);

    connect(dlg_.get(), &Fm::FileDialog::fileSelected, this, &LXQtFileDialogHelper::fileSelected);
    connect(dlg_.get(), &Fm::FileDialog::filesSelected, this, &LXQtFileDialogHelper::filesSelected);
    connect(dlg_.get(), &Fm::FileDialog::currentChanged, this, &LXQtFileDialogHelper::currentChanged);
    connect(dlg_.get(), &Fm::FileDialog::directoryEntered, this, &LXQtFileDialogHelper::directoryEntered);
    connect(dlg_.get(), &Fm::FileDialog::filterSelected, this, &LXQtFileDialogHelper::filterSelected);
}

LXQtFileDialogHelper::~LXQtFileDialogHelper() {
}

void LXQtFileDialogHelper::exec() {
    dlg_->exec();
}

bool LXQtFileDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow* parent) {
    dlg_->setAttribute(Qt::WA_NativeWindow, true); // without this, sometimes windowHandle() will return nullptr

    dlg_->setWindowFlags(windowFlags);
    dlg_->setWindowModality(windowModality);

    // Reference: KDE implementation
    // https://github.com/KDE/plasma-integration/blob/master/src/platformtheme/kdeplatformfiledialoghelper.cpp
    dlg_->windowHandle()->setTransientParent(parent);

    applyOptions();

    // NOTE: the timer here is required as a workaround borrowed from KDE. Without this, the dialog UI will be blocked.
    // QFileDialog calls our platform plugin to show our own native file dialog instead of showing its widget.
    // However, it still creates a hidden dialog internally, and then make it modal.
    // So user input from all other windows that are not the children of the QFileDialog widget will be blocked.
    // This includes our own dialog. After the return of this show() method, QFileDialog creates its own window and
    // then make it modal, which blocks our UI. The timer schedule a delayed popup of our file dialog, so we can
    // show again after QFileDialog and override the modal state. Then our UI can be unblocked.
    QTimer::singleShot(0, dlg_.get(), &QDialog::show);
    dlg_->setFocus();
    return true;
}

void LXQtFileDialogHelper::hide() {
    dlg_->hide();
}

bool LXQtFileDialogHelper::defaultNameFilterDisables() const {
    return false;
}

void LXQtFileDialogHelper::setDirectory(const QUrl& directory) {
    dlg_->setDirectory(directory);
}

QUrl LXQtFileDialogHelper::directory() const {
    return dlg_->directory();
}

void LXQtFileDialogHelper::selectFile(const QUrl& filename) {
    dlg_->selectFile(filename);
}

QList<QUrl> LXQtFileDialogHelper::selectedFiles() const {
    return dlg_->selectedFiles();
}

void LXQtFileDialogHelper::setFilter() {
    // FIXME: what's this?
    // The gtk+ 3 file dialog helper in Qt5 update options in this method.
    applyOptions();
}

void LXQtFileDialogHelper::selectNameFilter(const QString& filter) {
    dlg_->selectNameFilter(filter);
}

#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
QString LXQtFileDialogHelper::selectedMimeTypeFilter() const {
    const auto mimeTypeFromFilter = QMimeDatabase().mimeTypeForName(dlg_->selectedNameFilter());
    if(mimeTypeFromFilter.isValid()) {
        return mimeTypeFromFilter.name();
    }
    QList<QUrl> sel = dlg_->selectedFiles();
    if(sel.isEmpty()) {
        return QString();
    }
    return QMimeDatabase().mimeTypeForUrl(sel.at(0)).name();
}

void LXQtFileDialogHelper::selectMimeTypeFilter(const QString& filter) {
    dlg_->selectNameFilter(filter);
}
#endif

QString LXQtFileDialogHelper::selectedNameFilter() const {
    return dlg_->selectedNameFilter();
}

bool LXQtFileDialogHelper::isSupportedUrl(const QUrl& url) const {
    return dlg_->isSupportedUrl(url);
}

void LXQtFileDialogHelper::applyOptions() {
    auto& opt = options();
    if(options()->testOption(QFileDialogOptions::ShowDirsOnly)) {
        if(!options()->windowTitle().isEmpty()) {
            dlg_->setWindowTitle(options()->windowTitle());
        }
    }
    else {
        if(options()->windowTitle().isEmpty()) {
            dlg_->setWindowTitle(options()->acceptMode() == QFileDialogOptions::AcceptOpen ? tr("Open File")
                                                                                : tr("Save File"));
        }
        else {
            dlg_->setWindowTitle(options()->windowTitle());
        }
    }
    dlg_->setFilter(opt->filter());
    dlg_->setViewMode(opt->viewMode() == QFileDialogOptions::Detail ? Fm::FolderView::DetailedListMode : Fm::FolderView::CompactMode);
    dlg_->setFileMode(QFileDialog::FileMode(opt->fileMode()));
    dlg_->setAcceptMode(QFileDialog::AcceptMode(opt->acceptMode()));
    // bool useDefaultNameFilters() const;
    dlg_->setNameFilters(opt->nameFilters());
    if(!opt->mimeTypeFilters().empty()) {
        dlg_->setMimeTypeFilters(opt->mimeTypeFilters());
    }

    dlg_->setDefaultSuffix(opt->defaultSuffix());
    // QStringList history() const;

    for(int i = 0; i < QFileDialogOptions::DialogLabelCount; ++i) {
        auto label = static_cast<QFileDialogOptions::DialogLabel>(i);
        if(opt->isLabelExplicitlySet(label)) {
            dlg_->setLabelText(static_cast<QFileDialog::DialogLabel>(label), opt->labelText(label));
        }
    }

    auto url = opt->initialDirectory();
    if(url.isValid()) {
        dlg_->setDirectory(url);
    }

#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
    auto filter = opt->initiallySelectedMimeTypeFilter();
    if(!filter.isEmpty()) {
        selectMimeTypeFilter(filter);
    }
    else {
        filter = opt->initiallySelectedNameFilter();
        if(!filter.isEmpty()) {
            selectNameFilter(options()->initiallySelectedNameFilter());
        }
    }
#else
    filter = opt->initiallySelectedNameFilter();
    if(!filter.isEmpty()) {
        selectNameFilter(filter);
    }
#endif

    auto selectedFiles = opt->initiallySelectedFiles();
    for(const auto& selectedFile: selectedFiles) {
        selectFile(selectedFile);
    }
    // QStringList supportedSchemes() const;
}

/*
FileDialogPlugin::FileDialogPlugin() {

}

QPlatformFileDialogHelper *FileDialogPlugin::createHelper() {
    return new LXQtFileDialogHelper();
}
*/
<commit_msg>Central positioning with respect to parent<commit_after>#include "lxqtfiledialoghelper.h"

#include <libfm-qt/libfmqt.h>
#include <libfm-qt/filedialog.h>

#include <QWindow>
#include <QMimeDatabase>
#include <QDebug>
#include <QTimer>

#include <memory>

static std::unique_ptr<Fm::LibFmQt> libfmQtContext_;

LXQtFileDialogHelper::LXQtFileDialogHelper() {
    if(!libfmQtContext_) {
        // initialize libfm-qt only once
        libfmQtContext_ = std::unique_ptr<Fm::LibFmQt>{new Fm::LibFmQt()};
    }

    // can only be used after libfm-qt initialization
    dlg_ = std::unique_ptr<Fm::FileDialog>(new Fm::FileDialog());
    connect(dlg_.get(), &Fm::FileDialog::accepted, this, &LXQtFileDialogHelper::accept);
    connect(dlg_.get(), &Fm::FileDialog::rejected, this, &LXQtFileDialogHelper::reject);

    connect(dlg_.get(), &Fm::FileDialog::fileSelected, this, &LXQtFileDialogHelper::fileSelected);
    connect(dlg_.get(), &Fm::FileDialog::filesSelected, this, &LXQtFileDialogHelper::filesSelected);
    connect(dlg_.get(), &Fm::FileDialog::currentChanged, this, &LXQtFileDialogHelper::currentChanged);
    connect(dlg_.get(), &Fm::FileDialog::directoryEntered, this, &LXQtFileDialogHelper::directoryEntered);
    connect(dlg_.get(), &Fm::FileDialog::filterSelected, this, &LXQtFileDialogHelper::filterSelected);
}

LXQtFileDialogHelper::~LXQtFileDialogHelper() {
}

void LXQtFileDialogHelper::exec() {
    dlg_->exec();
}

bool LXQtFileDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow* parent) {
    dlg_->setAttribute(Qt::WA_NativeWindow, true); // without this, sometimes windowHandle() will return nullptr

    dlg_->setWindowFlags(windowFlags);
    dlg_->setWindowModality(windowModality);

    // Reference: KDE implementation
    // https://github.com/KDE/plasma-integration/blob/master/src/platformtheme/kdeplatformfiledialoghelper.cpp
    dlg_->windowHandle()->setTransientParent(parent);

    // central positioning with respect to the parent window
    if(parent && parent->isVisible()) {
        dlg_->move(parent->x() + parent->width()/2 - dlg_->width()/2,
                   parent->y() + parent->height()/2 - dlg_->height()/ 2);
    }

    applyOptions();

    // NOTE: the timer here is required as a workaround borrowed from KDE. Without this, the dialog UI will be blocked.
    // QFileDialog calls our platform plugin to show our own native file dialog instead of showing its widget.
    // However, it still creates a hidden dialog internally, and then make it modal.
    // So user input from all other windows that are not the children of the QFileDialog widget will be blocked.
    // This includes our own dialog. After the return of this show() method, QFileDialog creates its own window and
    // then make it modal, which blocks our UI. The timer schedule a delayed popup of our file dialog, so we can
    // show again after QFileDialog and override the modal state. Then our UI can be unblocked.
    QTimer::singleShot(0, dlg_.get(), &QDialog::show);
    dlg_->setFocus();
    return true;
}

void LXQtFileDialogHelper::hide() {
    dlg_->hide();
}

bool LXQtFileDialogHelper::defaultNameFilterDisables() const {
    return false;
}

void LXQtFileDialogHelper::setDirectory(const QUrl& directory) {
    dlg_->setDirectory(directory);
}

QUrl LXQtFileDialogHelper::directory() const {
    return dlg_->directory();
}

void LXQtFileDialogHelper::selectFile(const QUrl& filename) {
    dlg_->selectFile(filename);
}

QList<QUrl> LXQtFileDialogHelper::selectedFiles() const {
    return dlg_->selectedFiles();
}

void LXQtFileDialogHelper::setFilter() {
    // FIXME: what's this?
    // The gtk+ 3 file dialog helper in Qt5 update options in this method.
    applyOptions();
}

void LXQtFileDialogHelper::selectNameFilter(const QString& filter) {
    dlg_->selectNameFilter(filter);
}

#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
QString LXQtFileDialogHelper::selectedMimeTypeFilter() const {
    const auto mimeTypeFromFilter = QMimeDatabase().mimeTypeForName(dlg_->selectedNameFilter());
    if(mimeTypeFromFilter.isValid()) {
        return mimeTypeFromFilter.name();
    }
    QList<QUrl> sel = dlg_->selectedFiles();
    if(sel.isEmpty()) {
        return QString();
    }
    return QMimeDatabase().mimeTypeForUrl(sel.at(0)).name();
}

void LXQtFileDialogHelper::selectMimeTypeFilter(const QString& filter) {
    dlg_->selectNameFilter(filter);
}
#endif

QString LXQtFileDialogHelper::selectedNameFilter() const {
    return dlg_->selectedNameFilter();
}

bool LXQtFileDialogHelper::isSupportedUrl(const QUrl& url) const {
    return dlg_->isSupportedUrl(url);
}

void LXQtFileDialogHelper::applyOptions() {
    auto& opt = options();

    // set title
    if(opt->windowTitle().isEmpty()) {
        dlg_->setWindowTitle(opt->acceptMode() == QFileDialogOptions::AcceptOpen ? tr("Open File")
                                                                                : tr("Save File"));
    }
    else {
        dlg_->setWindowTitle(opt->windowTitle());
    }

    dlg_->setFilter(opt->filter());
    dlg_->setViewMode(opt->viewMode() == QFileDialogOptions::Detail ? Fm::FolderView::DetailedListMode
                                                                    : Fm::FolderView::CompactMode);
    dlg_->setFileMode(QFileDialog::FileMode(opt->fileMode()));
    dlg_->setAcceptMode(QFileDialog::AcceptMode(opt->acceptMode())); // also sets a default label for accept button
    // bool useDefaultNameFilters() const;
    dlg_->setNameFilters(opt->nameFilters());
    if(!opt->mimeTypeFilters().empty()) {
        dlg_->setMimeTypeFilters(opt->mimeTypeFilters());
    }

    dlg_->setDefaultSuffix(opt->defaultSuffix());
    // QStringList history() const;

    // explicitly set labels
    for(int i = 0; i < QFileDialogOptions::DialogLabelCount; ++i) {
        auto label = static_cast<QFileDialogOptions::DialogLabel>(i);
        if(opt->isLabelExplicitlySet(label)) {
            dlg_->setLabelText(static_cast<QFileDialog::DialogLabel>(label), opt->labelText(label));
        }
    }

    auto url = opt->initialDirectory();
    if(url.isValid()) {
        dlg_->setDirectory(url);
    }

#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
    auto filter = opt->initiallySelectedMimeTypeFilter();
    if(!filter.isEmpty()) {
        selectMimeTypeFilter(filter);
    }
    else {
        filter = opt->initiallySelectedNameFilter();
        if(!filter.isEmpty()) {
            selectNameFilter(opt->initiallySelectedNameFilter());
        }
    }
#else
    filter = opt->initiallySelectedNameFilter();
    if(!filter.isEmpty()) {
        selectNameFilter(filter);
    }
#endif

    auto selectedFiles = opt->initiallySelectedFiles();
    for(const auto& selectedFile: selectedFiles) {
        selectFile(selectedFile);
    }
    // QStringList supportedSchemes() const;
}

/*
FileDialogPlugin::FileDialogPlugin() {

}

QPlatformFileDialogHelper *FileDialogPlugin::createHelper() {
    return new LXQtFileDialogHelper();
}
*/
<|endoftext|>


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

#include "gtest/gtest.h"

#include <DGLCommon/gl-types.h>
#include <DGLCommon/gl-formats.h>
#include <DGLCommon/os.h>

#include <DGLWrapper/api-loader.h>

namespace {

    // The fixture for testing class Foo.
    class DGLCommonUT : public ::testing::Test {
    protected:
        // You can remove any or all of the following functions if its body
        // is empty.

        DGLCommonUT() {
            // You can do set-up work for each test here.
        }

        virtual ~DGLCommonUT() {
            // You can do clean-up work that doesn't throw exceptions here.
        }

        // If the constructor and destructor are not enough for setting up
        // and cleaning up each test, you can define the following methods:

        virtual void SetUp() {
            // Code here will be called immediately after the constructor (right
            // before each test).
        }

        virtual void TearDown() {
            // Code here will be called immediately after each test (right
            // before the destructor).
        }

        // Objects declared here can be used by all tests in the test case for Foo.
    };

    // Smoke test all inputs of codegen has been parsed to functionList
    TEST_F(DGLCommonUT, codegen_entryps) {
        //gl.h + gl2.h
        ASSERT_STREQ(GetEntryPointName(glEnable_Call), "glEnable");

        //glext.h
        ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedBaseInstance_Call), "glDrawArraysInstancedBaseInstance");
        ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedARB_Call), "glDrawArraysInstancedARB");

        //wgl
        ASSERT_STREQ(GetEntryPointName(wglCreateContext_Call), "wglCreateContext");

        //wgl-notrace
        ASSERT_STREQ(GetEntryPointName(wglSetPixelFormat_Call), "wglSetPixelFormat");

        //wglext.h
        ASSERT_STREQ(GetEntryPointName(wglCreateContextAttribsARB_Call), "wglCreateContextAttribsARB");

        //egl.h
        ASSERT_STREQ(GetEntryPointName(eglBindAPI_Call), "eglBindAPI");

        ASSERT_STREQ(GetEntryPointName(eglCreateContext_Call), "eglCreateContext");
        ASSERT_STREQ(GetEntryPointName(eglMakeCurrent_Call), "eglMakeCurrent");
        ASSERT_STREQ(GetEntryPointName(eglGetProcAddress_Call), "eglGetProcAddress");

        //eglext.h
        ASSERT_STREQ(GetEntryPointName(eglCreateImageKHR_Call), "eglCreateImageKHR");
        ASSERT_STREQ(GetEntryPointName(eglQuerySurfacePointerANGLE_Call), "eglQuerySurfacePointerANGLE");

        //glx.h
        ASSERT_STREQ(GetEntryPointName(glXChooseFBConfig_Call), "glXChooseFBConfig");

        const char* null = NULL;
        //null
        ASSERT_STREQ(GetEntryPointName(NO_ENTRYPOINT), "<unknown>");
    }

    //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation
    //use DIRECT_CALL(name) to call one of these pointers
    int ut_PointerLibraries[Entrypoints_NUM] = {
#define FUNC_LIST_ELEM_SUPPORTED(name, type, library)  library,
#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)
#include "codegen/functionList.inl"
#undef FUNC_LIST_ELEM_SUPPORTED
#undef FUNC_LIST_ELEM_NOT_SUPPORTED
    };

    TEST_F(DGLCommonUT, codegen_libraries) {
        //gl.h + gl2.h
        EXPECT_EQ(LIBRARY_GL | LIBRARY_ES2, ut_PointerLibraries[glEnable_Call]);

        //all ES2 entryps are should be shared with GL or GL_EXT
        for (int i = 0; i < NUM_ENTRYPOINTS; i++) {
            if (ut_PointerLibraries[i] & LIBRARY_ES2) {
                EXPECT_GT(ut_PointerLibraries[i] & (LIBRARY_GL | LIBRARY_GL_EXT), 0);
            }
        }

        //glext.h
        EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedBaseInstance_Call]);
        EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedARB_Call]);

        //wgl
        EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglCreateContext_Call]);

        //wgl-notrace
        EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglSetPixelFormat_Call]);

        //wglext.h
        EXPECT_EQ(LIBRARY_WGL_EXT, ut_PointerLibraries[wglCreateContextAttribsARB_Call]);

        //egl.h
        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglBindAPI_Call]);

        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglCreateContext_Call]);
        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglMakeCurrent_Call]);
        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglGetProcAddress_Call]);

        //eglext.h
        EXPECT_EQ(LIBRARY_EGL_EXT, ut_PointerLibraries[eglCreateImageKHR_Call]);

        //glx.h
        EXPECT_EQ(LIBRARY_GLX, ut_PointerLibraries[glXChooseFBConfig_Call]);

    }

    TEST_F(DGLCommonUT, codegen_entryp_names) {
        EXPECT_EQ(GetEntryPointEnum("bad"), NO_ENTRYPOINT);
        EXPECT_EQ(GetEntryPointEnum("glDrawArrays"), glDrawArrays_Call);
        EXPECT_EQ(GetEntryPointName(GetEntryPointEnum("glDrawArrays")), "glDrawArrays");
        EXPECT_EQ(GetEntryPointEnum(GetEntryPointName(glDrawArrays_Call)), glDrawArrays_Call);
    }

    TEST_F(DGLCommonUT, formats_iformat) {
       DGLPixelTransfer rgba8(std::vector<GLint>(), std::vector<GLint>(), GL_RGBA8);
       EXPECT_EQ(rgba8.getFormat(), GL_RGBA);
       EXPECT_EQ(rgba8.getType(), GL_UNSIGNED_BYTE);

    }

    TEST_F(DGLCommonUT, formats_noiformat) {

        std::vector<GLint>rgbaSizes(4, 0);
        rgbaSizes[0] = rgbaSizes[1] = rgbaSizes[2] = 8;
        std::vector<GLint>dsSizes(2, 0);

        DGLPixelTransfer rgba8(rgbaSizes, dsSizes, 0);
        EXPECT_EQ(rgba8.getFormat(), GL_RGB);
        EXPECT_EQ(rgba8.getType(), GL_FLOAT);
    }

    TEST_F(DGLCommonUT, os_env) {
        EXPECT_EQ("", Os::getEnv("test_name"));
        Os::setEnv("test_name", "test_value");
        EXPECT_EQ("test_value", Os::getEnv("test_name"));
    }

}  // namespace

<commit_msg>Actualize UT tests (glEnable is also in ES3, default read type is UBYTE).<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "gtest/gtest.h"

#include <DGLCommon/gl-types.h>
#include <DGLCommon/gl-formats.h>
#include <DGLCommon/os.h>

#include <DGLWrapper/api-loader.h>

namespace {

    // The fixture for testing class Foo.
    class DGLCommonUT : public ::testing::Test {
    protected:
        // You can remove any or all of the following functions if its body
        // is empty.

        DGLCommonUT() {
            // You can do set-up work for each test here.
        }

        virtual ~DGLCommonUT() {
            // You can do clean-up work that doesn't throw exceptions here.
        }

        // If the constructor and destructor are not enough for setting up
        // and cleaning up each test, you can define the following methods:

        virtual void SetUp() {
            // Code here will be called immediately after the constructor (right
            // before each test).
        }

        virtual void TearDown() {
            // Code here will be called immediately after each test (right
            // before the destructor).
        }

        // Objects declared here can be used by all tests in the test case for Foo.
    };

    // Smoke test all inputs of codegen has been parsed to functionList
    TEST_F(DGLCommonUT, codegen_entryps) {
        //gl.h + gl2.h
        ASSERT_STREQ(GetEntryPointName(glEnable_Call), "glEnable");

        //glext.h
        ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedBaseInstance_Call), "glDrawArraysInstancedBaseInstance");
        ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedARB_Call), "glDrawArraysInstancedARB");

        //wgl
        ASSERT_STREQ(GetEntryPointName(wglCreateContext_Call), "wglCreateContext");

        //wgl-notrace
        ASSERT_STREQ(GetEntryPointName(wglSetPixelFormat_Call), "wglSetPixelFormat");

        //wglext.h
        ASSERT_STREQ(GetEntryPointName(wglCreateContextAttribsARB_Call), "wglCreateContextAttribsARB");

        //egl.h
        ASSERT_STREQ(GetEntryPointName(eglBindAPI_Call), "eglBindAPI");

        ASSERT_STREQ(GetEntryPointName(eglCreateContext_Call), "eglCreateContext");
        ASSERT_STREQ(GetEntryPointName(eglMakeCurrent_Call), "eglMakeCurrent");
        ASSERT_STREQ(GetEntryPointName(eglGetProcAddress_Call), "eglGetProcAddress");

        //eglext.h
        ASSERT_STREQ(GetEntryPointName(eglCreateImageKHR_Call), "eglCreateImageKHR");
        ASSERT_STREQ(GetEntryPointName(eglQuerySurfacePointerANGLE_Call), "eglQuerySurfacePointerANGLE");

        //glx.h
        ASSERT_STREQ(GetEntryPointName(glXChooseFBConfig_Call), "glXChooseFBConfig");

        const char* null = NULL;
        //null
        ASSERT_STREQ(GetEntryPointName(NO_ENTRYPOINT), "<unknown>");
    }

    //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation
    //use DIRECT_CALL(name) to call one of these pointers
    int ut_PointerLibraries[Entrypoints_NUM] = {
#define FUNC_LIST_ELEM_SUPPORTED(name, type, library)  library,
#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)
#include "codegen/functionList.inl"
#undef FUNC_LIST_ELEM_SUPPORTED
#undef FUNC_LIST_ELEM_NOT_SUPPORTED
    };

    TEST_F(DGLCommonUT, codegen_libraries) {
        //gl.h + gl2.h
        EXPECT_EQ(LIBRARY_GL | LIBRARY_ES2 | LIBRARY_ES3, ut_PointerLibraries[glEnable_Call]);

        //all ES2 entryps are should be shared with GL or GL_EXT
        for (int i = 0; i < NUM_ENTRYPOINTS; i++) {
            if (ut_PointerLibraries[i] & LIBRARY_ES2) {
                EXPECT_GT(ut_PointerLibraries[i] & (LIBRARY_GL | LIBRARY_GL_EXT), 0);
            }
        }

        //glext.h
        EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedBaseInstance_Call]);
        EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedARB_Call]);

        //wgl
        EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglCreateContext_Call]);

        //wgl-notrace
        EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglSetPixelFormat_Call]);

        //wglext.h
        EXPECT_EQ(LIBRARY_WGL_EXT, ut_PointerLibraries[wglCreateContextAttribsARB_Call]);

        //egl.h
        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglBindAPI_Call]);

        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglCreateContext_Call]);
        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglMakeCurrent_Call]);
        EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglGetProcAddress_Call]);

        //eglext.h
        EXPECT_EQ(LIBRARY_EGL_EXT, ut_PointerLibraries[eglCreateImageKHR_Call]);

        //glx.h
        EXPECT_EQ(LIBRARY_GLX, ut_PointerLibraries[glXChooseFBConfig_Call]);

    }

    TEST_F(DGLCommonUT, codegen_entryp_names) {
        EXPECT_EQ(GetEntryPointEnum("bad"), NO_ENTRYPOINT);
        EXPECT_EQ(GetEntryPointEnum("glDrawArrays"), glDrawArrays_Call);
        EXPECT_EQ(GetEntryPointName(GetEntryPointEnum("glDrawArrays")), "glDrawArrays");
        EXPECT_EQ(GetEntryPointEnum(GetEntryPointName(glDrawArrays_Call)), glDrawArrays_Call);
    }

    TEST_F(DGLCommonUT, formats_iformat) {
       DGLPixelTransfer rgba8(std::vector<GLint>(), std::vector<GLint>(), GL_RGBA8);
       EXPECT_EQ(rgba8.getFormat(), GL_RGBA);
       EXPECT_EQ(rgba8.getType(), GL_UNSIGNED_BYTE);

    }

    TEST_F(DGLCommonUT, formats_noiformat) {

        std::vector<GLint>rgbaSizes(4, 0);
        rgbaSizes[0] = rgbaSizes[1] = rgbaSizes[2] = 8;
        std::vector<GLint>dsSizes(2, 0);

        DGLPixelTransfer rgba8(rgbaSizes, dsSizes, 0);
        EXPECT_EQ(rgba8.getFormat(), GL_RGB);
        EXPECT_EQ(rgba8.getType(), GL_UNSIGNED_BYTE);
    }

    TEST_F(DGLCommonUT, os_env) {
        EXPECT_EQ("", Os::getEnv("test_name"));
        Os::setEnv("test_name", "test_value");
        EXPECT_EQ("test_value", Os::getEnv("test_name"));
    }

}  // namespace

<|endoftext|>


<commit_before>#include "catch.hpp"
#include "graph/expression_graph.h"
#include "graph/expression_operators.h"

using namespace marian;

TEST_CASE("Expression graph supports basic math operations", "[operator]") {

  auto floatApprox = [](float x, float y) -> bool { return x == Approx(y); };

  auto graph = New<ExpressionGraph>();
  graph->setDevice(0);
  graph->reserveWorkspaceMB(16);

  std::vector<float> vA({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
  std::vector<float> vB({1, 2, 3, 4, 5, 6});
  std::vector<float> values;

  SECTION("dot product") {
    graph->clear();
    values.clear();
    std::vector<float> vC({22, 28, 49, 64, 76, 100, 103, 136});

    auto A = graph->param("A", {4, 3}, keywords::init = inits::from_vector(vA));
    auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB));
    auto C = dot(A, B);
    graph->forward();

    CHECK(C->shape() == Shape({4, 2}));
    C->val()->get(values);
    CHECK(values == vC);
  }

  SECTION("scalar multiplication") {
    graph->clear();
    values.clear();
    std::vector<float> vB2({2, 4, 6, 8, 10, 12});

    auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB));
    auto B2 = B * 2.0f;
    graph->forward();

    CHECK(B2->shape() == Shape({3, 2}));
    B2->val()->get(values);
    CHECK(values == vB2);
  }

  SECTION("softmax") {
    graph->clear();
    values.clear();
    std::vector<float> in({-.2, -.3, 4.5, 5.2, -10, 101.45, -100.05, 1.05e-5});

    std::vector<float> smOut({ 0.52498f, 0.47502f, 0.33181f, 0.66819f,
                               0.0f, 1.0f, 0.0f, 1.0f });

    std::vector<float> lsmOut({ -0.6444f, -0.7444f, -1.10319f, -0.40319f,
                                -111.45f, 0.0f, -100.05001f, 0.0f });

    auto input = graph->constant({2, 2, 2}, keywords::init = inits::from_vector(in));

    auto sm  = softmax(input);
    auto lsm = logsoftmax(input);

    graph->forward();

    CHECK(sm->shape() == Shape({2, 2, 2}));
    CHECK(lsm->shape() == Shape({2, 2, 2}));

    sm->val()->get(values);

    CHECK( std::equal(values.begin(), values.end(),
                        smOut.begin(), floatApprox) );

    lsm->val()->get(values);

    CHECK( std::equal(values.begin(), values.end(),
                        lsmOut.begin(), floatApprox) );
  }

  SECTION("elementwise binary operators with broadcasting") {
    graph->clear();
    values.clear();

    std::vector<float> vA({1, -2, 3, -4});
    std::vector<float> vB({0.5, 1.5});

    std::vector<float> vAdd({1.5, -0.5, 3.5, -2.5});
    std::vector<float> vMinus({-0.5, 3.5, -2.5, 5.5});
    std::vector<float> vMult({0.5, -3.0, 1.5, -6.0});
    std::vector<float> vDiv({2.0f, -1.33333f, 6.0f, -2.66667f});

    auto a = graph->constant({2, 2, 1}, keywords::init = inits::from_vector(vA));
    auto b = graph->constant({1, 2, 1}, keywords::init = inits::from_vector(vB));

    auto add = a + b;
    auto minus = b - a;
    auto mult = a * b;
    auto div = a / b;

    graph->forward();

    CHECK(add->shape() == Shape({2, 2, 1}));
    CHECK(minus->shape() == Shape({2, 2, 1}));
    CHECK(mult->shape() == Shape({2, 2, 1}));
    CHECK(div->shape() == Shape({2, 2, 1}));

    add->val()->get(values);
    CHECK( values == vAdd );

    minus->val()->get(values);
    CHECK( values == vMinus );

    mult->val()->get(values);
    CHECK( values == vMult );

    div->val()->get(values);
    CHECK( std::equal(values.begin(), values.end(),
                      vDiv.begin(), floatApprox) );
  }
}
<commit_msg>tests for reshape and transpose<commit_after>#include "catch.hpp"
#include "graph/expression_graph.h"
#include "graph/expression_operators.h"

using namespace marian;

TEST_CASE("Expression graph supports basic math operations", "[operator]") {

  auto floatApprox = [](float x, float y) -> bool { return x == Approx(y); };

  auto graph = New<ExpressionGraph>();
  graph->setDevice(0);
  graph->reserveWorkspaceMB(16);

  std::vector<float> vA({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
  std::vector<float> vB({1, 2, 3, 4, 5, 6});
  std::vector<float> values;

  SECTION("dot product") {
    graph->clear();
    values.clear();
    std::vector<float> vC({22, 28, 49, 64, 76, 100, 103, 136});

    auto A = graph->param("A", {2, 3, 2}, keywords::init = inits::from_vector(vA));
    auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB));
    auto C = dot(A, B);
    graph->forward();

    CHECK(C->shape() == Shape({2, 2, 2}));
    C->val()->get(values);
    CHECK(values == vC);
  }

  SECTION("scalar multiplication") {
    graph->clear();
    values.clear();
    std::vector<float> vB2({2, 4, 6, 8, 10, 12});

    auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB));
    auto B2 = B * 2.0f;
    graph->forward();

    CHECK(B2->shape() == Shape({3, 2}));
    B2->val()->get(values);
    CHECK(values == vB2);
  }

  SECTION("softmax and logsoftmax") {
    graph->clear();
    values.clear();
    std::vector<float> in({-.2, -.3, 4.5, 5.2, -10, 101.45, -100.05, 1.05e-5});

    std::vector<float> smOut({ 0.52498f, 0.47502f, 0.33181f, 0.66819f,
                               0.0f, 1.0f, 0.0f, 1.0f });

    std::vector<float> lsmOut({ -0.6444f, -0.7444f, -1.10319f, -0.40319f,
                                -111.45f, 0.0f, -100.05001f, 0.0f });

    auto input = graph->constant({2, 2, 2}, keywords::init = inits::from_vector(in));

    auto sm  = softmax(input);
    auto lsm = logsoftmax(input);

    graph->forward();

    CHECK(sm->shape() == Shape({2, 2, 2}));
    CHECK(lsm->shape() == Shape({2, 2, 2}));

    sm->val()->get(values);

    CHECK( std::equal(values.begin(), values.end(),
                        smOut.begin(), floatApprox) );

    lsm->val()->get(values);

    CHECK( std::equal(values.begin(), values.end(),
                        lsmOut.begin(), floatApprox) );
  }

  SECTION("elementwise binary operators with broadcasting") {
    graph->clear();
    values.clear();

    std::vector<float> vA({1, -2, 3, -4});
    std::vector<float> vB({0.5, 1.5});

    std::vector<float> vAdd({1.5, -0.5, 3.5, -2.5});
    std::vector<float> vMinus({-0.5, 3.5, -2.5, 5.5});
    std::vector<float> vMult({0.5, -3.0, 1.5, -6.0});
    std::vector<float> vDiv({2.0f, -1.33333f, 6.0f, -2.66667f});

    auto a = graph->constant({2, 2, 1}, keywords::init = inits::from_vector(vA));
    auto b = graph->constant({1, 2, 1}, keywords::init = inits::from_vector(vB));

    auto add = a + b;
    auto minus = b - a;
    auto mult = a * b;
    auto div = a / b;

    graph->forward();

    CHECK(add->shape() == Shape({2, 2, 1}));
    CHECK(minus->shape() == Shape({2, 2, 1}));
    CHECK(mult->shape() == Shape({2, 2, 1}));
    CHECK(div->shape() == Shape({2, 2, 1}));

    add->val()->get(values);
    CHECK( values == vAdd );

    minus->val()->get(values);
    CHECK( values == vMinus );

    mult->val()->get(values);
    CHECK( values == vMult );

    div->val()->get(values);
    CHECK( std::equal(values.begin(), values.end(),
                      vDiv.begin(), floatApprox) );
  }

  SECTION("transposing and reshaping") {
    graph->clear();
    values.clear();

    std::vector<float> vA({1, 2, 3, 4, 5, 6, 7, 8});

    std::vector<float> vT1({1, 5, 2, 6, 3, 7, 4, 8});
    std::vector<float> vT3({1, 2, 5, 6, 3, 4, 7, 8});
    std::vector<float> vT4({1, 5, 3, 7, 2, 6, 4, 8});
    std::vector<float> vT5({1, 3, 2, 4, 5, 7, 6, 8});

    auto a = graph->constant({2, 4}, keywords::init = inits::from_vector(vA));

    auto t1 = transpose(a);
    auto t2 = transpose(t1);
    auto t3 = transpose(reshape(t1, {2, 2, 2}));
    auto t4 = transpose(reshape(a, {2, 2, 1, 2}), {2, 3, 0, 1});
    auto t5 = transpose(reshape(a, {2, 2, 1, 2}), {1, 2, 3, 0});

    graph->forward();

    CHECK(t1->shape() == Shape({4, 2}));
    CHECK(t2->shape() == Shape({2, 4}));
    CHECK(t3->shape() == Shape({2, 2, 2}));
    CHECK(t4->shape() == Shape({1, 2, 2, 2}));
    CHECK(t5->shape() == Shape({2, 1, 2, 2}));

    t1->val()->get(values);
    CHECK( values == vT1 );

    t2->val()->get(values);
    CHECK( values == vA );

    t3->val()->get(values);
    CHECK( values == vT3 );

    t4->val()->get(values);
    CHECK( values == vT4 );

    t5->val()->get(values);
    CHECK( values == vT5 );
  }
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCWorldNet_ClientModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCWorldNet_ClientModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFCWorldToMasterModule.h"
#include "NFWorldNet_ClientPlugin.h"
#include "NFComm/NFCore/NFCDataList.h"
#include "NFComm/NFMessageDefine/NFMsgPreGame.pb.h"

bool NFCWorldToMasterModule::Init()
{

    return true;
}

bool NFCWorldToMasterModule::Shut()
{
	return true;
}

bool NFCWorldToMasterModule::AfterInit()
{
	m_pWorldLogicModule = pPluginManager->FindModule<NFIWorldLogicModule>("NFCWorldLogicModule");
	m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule");
	m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule");
	m_pLogModule = pPluginManager->FindModule<NFILogModule>("NFCLogModule");
	m_pWorldNet_ServerModule = pPluginManager->FindModule<NFIWorldNet_ServerModule>("NFCWorldNet_ServerModule");

	assert(NULL != m_pWorldLogicModule);
	assert(NULL != m_pLogicClassModule);
    assert(NULL != m_pElementInfoModule);
	assert(NULL != m_pLogModule);
	assert(NULL != m_pWorldNet_ServerModule);

	NFIClusterClientModule::Bind(this, &NFCWorldToMasterModule::OnReciveMSPack, &NFCWorldToMasterModule::OnSocketMSEvent);

	NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server");
	if (xLogicClass.get())
	{
		NFList<std::string>& xNameList = xLogicClass->GetConfigNameList();
		std::string strConfigName;
		for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName))
		{
			const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type");
            const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID");
			if (nServerType == NF_SERVER_TYPES::NF_ST_MASTER)
			{
				const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port");
				const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline");
				const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount");
				const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name");
				const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP");

				ConnectData xServerData;

				xServerData.nGameID = nServerID;
				xServerData.eServerType = (NF_SERVER_TYPES)nServerType;
				xServerData.strIP = strIP;
				xServerData.nPort = nPort;
				xServerData.strName = strName;

				NFIClusterClientModule::AddServer(xServerData);
			}
		}
	}

	return true;
}

bool NFCWorldToMasterModule::Execute()
{
	return NFIClusterClientModule::Execute();
}

void NFCWorldToMasterModule::Register(NFINet* pNet)
{
	NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server");
	if (xLogicClass.get())
	{
		NFList<std::string>& xNameList = xLogicClass->GetConfigNameList();
		std::string strConfigName;
		for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName))
		{
			const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type");
            const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID");
			if (nServerType == NF_SERVER_TYPES::NF_ST_WORLD && pPluginManager->AppID() == nServerID)
			{
				const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port");
				const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline");
				const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount");
				const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name");
				const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP");

				NFMsg::ServerInfoReportList xMsg;
				NFMsg::ServerInfoReport* pData = xMsg.add_server_list();

				pData->set_server_id(nServerID);
				pData->set_server_name(strName);
				pData->set_server_cur_count(0);
				pData->set_server_ip(strIP);
				pData->set_server_port(nPort);
				pData->set_server_max_online(nMaxConnect);
				pData->set_server_state(NFMsg::EST_NARMAL);
				pData->set_server_type(nServerType);

				NF_SHARE_PTR<ConnectData> pServerData = GetServerNetInfo(pNet);
				if (pServerData)
				{
					int nTargetID = pServerData->nGameID;
					SendToServerByPB(nTargetID, NFMsg::EGameMsgID::EGMI_MTL_WORLD_REGISTERED, xMsg);

					m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, pData->server_id()), pData->server_name(), "Register");
				}
			}
		}
	}
}

void NFCWorldToMasterModule::RefreshWorldInfo()
{

}

int NFCWorldToMasterModule::OnSelectServerProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
	NFGUID nPlayerID;
	NFMsg::ReqConnectWorld xMsg;
	if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
	{
		return 0;
	}

	NF_SHARE_PTR<ServerData> xServerData = m_pWorldNet_ServerModule->GetSuitProxyForEnter();
	if (xServerData)
	{
		NFMsg::AckConnectWorldResult xData;

		xData.set_world_id(xMsg.world_id());
		xData.mutable_sender()->CopyFrom(xMsg.sender());
		xData.set_login_id(xMsg.login_id());
		xData.set_account(xMsg.account());

		xData.set_world_ip(xServerData->pData->server_ip());
		xData.set_world_port(xServerData->pData->server_port());
		xData.set_world_key(xMsg.account());

		m_pWorldNet_ServerModule->SendMsgPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xData, xServerData->nFD);

		SendSuitByPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xMsg);
	}

	return 0;
}

int NFCWorldToMasterModule::OnKickClientProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
	NFGUID nPlayerID;
	NFMsg::ReqKickFromWorld xMsg;
	if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
	{
		return 0;
	}

    //T,
//     NFCDataList var;
//     var << xMsg.world_id() << xMsg.account();
//     m_pEventProcessModule->DoEvent(NFGUID(), NFED_ON_KICK_FROM_SERVER, var);
    return 0;
}

void NFCWorldToMasterModule::OnReciveMSPack(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
	switch (nMsgID)
	{
	case NFMsg::EGameMsgID::EGMI_REQ_CONNECT_WORLD:
		OnSelectServerProcess(nSockIndex, nMsgID, msg, nLen);
		break;

	case NFMsg::EGameMsgID::EGMI_REQ_KICK_CLIENT_INWORLD:
		OnKickClientProcess(nSockIndex, nMsgID, msg, nLen);
		break;

	default:
		printf("NFNet || ǷϢ:unMsgID=%d\n", nMsgID);
		break;
	}
}

void NFCWorldToMasterModule::OnSocketMSEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet )
{
    if (eEvent & NF_NET_EVENT_EOF)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_EOF", "Connection closed", __FUNCTION__, __LINE__);
    }
    else if (eEvent & NF_NET_EVENT_ERROR)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_ERROR", "Got an error on the connection", __FUNCTION__, __LINE__);
    }
    else if (eEvent & NF_NET_EVENT_TIMEOUT)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_TIMEOUT", "read timeout", __FUNCTION__, __LINE__);
    }
    else  if (eEvent == NF_NET_EVENT_CONNECTED)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__);
        Register(pNet);
    }
}

void NFCWorldToMasterModule::OnClientDisconnect( const int nAddress )
{

}

void NFCWorldToMasterModule::OnClientConnected( const int nAddress )
{

}

bool NFCWorldToMasterModule::BeforeShut()
{
    return true;
}

void NFCWorldToMasterModule::LogServerInfo( const std::string& strServerInfo )
{
	m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), strServerInfo, "");
}
<commit_msg>fixed write error<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCWorldNet_ClientModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCWorldNet_ClientModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFCWorldToMasterModule.h"
#include "NFWorldNet_ClientPlugin.h"
#include "NFComm/NFCore/NFCDataList.h"
#include "NFComm/NFMessageDefine/NFMsgPreGame.pb.h"

bool NFCWorldToMasterModule::Init()
{

    return true;
}

bool NFCWorldToMasterModule::Shut()
{
	return true;
}

bool NFCWorldToMasterModule::AfterInit()
{
	m_pWorldLogicModule = pPluginManager->FindModule<NFIWorldLogicModule>("NFCWorldLogicModule");
	m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule");
	m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule");
	m_pLogModule = pPluginManager->FindModule<NFILogModule>("NFCLogModule");
	m_pWorldNet_ServerModule = pPluginManager->FindModule<NFIWorldNet_ServerModule>("NFCWorldNet_ServerModule");

	assert(NULL != m_pWorldLogicModule);
	assert(NULL != m_pLogicClassModule);
    assert(NULL != m_pElementInfoModule);
	assert(NULL != m_pLogModule);
	assert(NULL != m_pWorldNet_ServerModule);

	NFIClusterClientModule::Bind(this, &NFCWorldToMasterModule::OnReciveMSPack, &NFCWorldToMasterModule::OnSocketMSEvent);

	NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server");
	if (xLogicClass.get())
	{
		NFList<std::string>& xNameList = xLogicClass->GetConfigNameList();
		std::string strConfigName;
		for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName))
		{
			const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type");
            const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID");
			if (nServerType == NF_SERVER_TYPES::NF_ST_MASTER)
			{
				const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port");
				const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline");
				const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount");
				const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name");
				const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP");

				ConnectData xServerData;

				xServerData.nGameID = nServerID;
				xServerData.eServerType = (NF_SERVER_TYPES)nServerType;
				xServerData.strIP = strIP;
				xServerData.nPort = nPort;
				xServerData.strName = strName;

				NFIClusterClientModule::AddServer(xServerData);
			}
		}
	}

	return true;
}

bool NFCWorldToMasterModule::Execute()
{
	return NFIClusterClientModule::Execute();
}

void NFCWorldToMasterModule::Register(NFINet* pNet)
{
	NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server");
	if (xLogicClass.get())
	{
		NFList<std::string>& xNameList = xLogicClass->GetConfigNameList();
		std::string strConfigName;
		for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName))
		{
			const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type");
            const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID");
			if (nServerType == NF_SERVER_TYPES::NF_ST_WORLD && pPluginManager->AppID() == nServerID)
			{
				const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port");
				const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline");
				const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount");
				const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name");
				const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP");

				NFMsg::ServerInfoReportList xMsg;
				NFMsg::ServerInfoReport* pData = xMsg.add_server_list();

				pData->set_server_id(nServerID);
				pData->set_server_name(strName);
				pData->set_server_cur_count(0);
				pData->set_server_ip(strIP);
				pData->set_server_port(nPort);
				pData->set_server_max_online(nMaxConnect);
				pData->set_server_state(NFMsg::EST_NARMAL);
				pData->set_server_type(nServerType);

				NF_SHARE_PTR<ConnectData> pServerData = GetServerNetInfo(pNet);
				if (pServerData)
				{
					int nTargetID = pServerData->nGameID;
					SendToServerByPB(nTargetID, NFMsg::EGameMsgID::EGMI_MTL_WORLD_REGISTERED, xMsg);

					m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, pData->server_id()), pData->server_name(), "Register");
				}
			}
		}
	}
}

void NFCWorldToMasterModule::RefreshWorldInfo()
{

}

int NFCWorldToMasterModule::OnSelectServerProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
	NFGUID nPlayerID;
	NFMsg::ReqConnectWorld xMsg;
	if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
	{
		return 0;
	}

	NF_SHARE_PTR<ServerData> xServerData = m_pWorldNet_ServerModule->GetSuitProxyForEnter();
	if (xServerData)
	{
		NFMsg::AckConnectWorldResult xData;

		xData.set_world_id(xMsg.world_id());
		xData.mutable_sender()->CopyFrom(xMsg.sender());
		xData.set_login_id(xMsg.login_id());
		xData.set_account(xMsg.account());

		xData.set_world_ip(xServerData->pData->server_ip());
		xData.set_world_port(xServerData->pData->server_port());
		xData.set_world_key(xMsg.account());

		m_pWorldNet_ServerModule->SendMsgPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xData, xServerData->nFD);

		SendSuitByPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xData);
	}

	return 0;
}

int NFCWorldToMasterModule::OnKickClientProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
	NFGUID nPlayerID;
	NFMsg::ReqKickFromWorld xMsg;
	if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
	{
		return 0;
	}

    //T,
//     NFCDataList var;
//     var << xMsg.world_id() << xMsg.account();
//     m_pEventProcessModule->DoEvent(NFGUID(), NFED_ON_KICK_FROM_SERVER, var);
    return 0;
}

void NFCWorldToMasterModule::OnReciveMSPack(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
	switch (nMsgID)
	{
	case NFMsg::EGameMsgID::EGMI_REQ_CONNECT_WORLD:
		OnSelectServerProcess(nSockIndex, nMsgID, msg, nLen);
		break;

	case NFMsg::EGameMsgID::EGMI_REQ_KICK_CLIENT_INWORLD:
		OnKickClientProcess(nSockIndex, nMsgID, msg, nLen);
		break;

	default:
		printf("NFNet || ǷϢ:unMsgID=%d\n", nMsgID);
		break;
	}
}

void NFCWorldToMasterModule::OnSocketMSEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet )
{
    if (eEvent & NF_NET_EVENT_EOF)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_EOF", "Connection closed", __FUNCTION__, __LINE__);
    }
    else if (eEvent & NF_NET_EVENT_ERROR)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_ERROR", "Got an error on the connection", __FUNCTION__, __LINE__);
    }
    else if (eEvent & NF_NET_EVENT_TIMEOUT)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_TIMEOUT", "read timeout", __FUNCTION__, __LINE__);
    }
    else  if (eEvent == NF_NET_EVENT_CONNECTED)
    {
        m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__);
        Register(pNet);
    }
}

void NFCWorldToMasterModule::OnClientDisconnect( const int nAddress )
{

}

void NFCWorldToMasterModule::OnClientConnected( const int nAddress )
{

}

bool NFCWorldToMasterModule::BeforeShut()
{
    return true;
}

void NFCWorldToMasterModule::LogServerInfo( const std::string& strServerInfo )
{
	m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), strServerInfo, "");
}
<|endoftext|>


<commit_before>#include "muteexecutor.h"
#include <QDebug>
#include <alsa/asoundlib.h>

MuteExecutor::MuteExecutor()
{
}

void MuteExecutor::execute(const QJsonObject &jobj)
{
    qDebug()<<"Mute execute";
    long min, max;
    snd_mixer_t *handle;
    snd_mixer_selem_id_t *sid;
    const char *card = "default";
    const char *selem_name = "Master";

    snd_mixer_open(&handle, 0);
    snd_mixer_attach(handle, card);
    snd_mixer_selem_register(handle, NULL, NULL);
    snd_mixer_load(handle);

    snd_mixer_selem_id_alloca(&sid);
    snd_mixer_selem_id_set_index(sid, 0);
    snd_mixer_selem_id_set_name(sid, selem_name);
    snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);

    if (snd_mixer_selem_has_playback_switch(elem)) {
        snd_mixer_selem_set_playback_switch_all(elem, 0);
    }

    snd_mixer_close(handle);
}
<commit_msg>mute behaves like mute/unmute<commit_after>#include "muteexecutor.h"
#include <QDebug>
#include <alsa/asoundlib.h>

MuteExecutor::MuteExecutor()
{
}

void MuteExecutor::execute(const QJsonObject &jobj)
{
    qDebug()<<"Mute execute";
    long min, max, volume, cur_vol;
    snd_mixer_t *handle;
    snd_mixer_selem_id_t *sid;
    const char *card = "default";
    const char *selem_name = "Master";

    snd_mixer_open(&handle, 0);
    snd_mixer_attach(handle, card);
    snd_mixer_selem_register(handle, NULL, NULL);
    snd_mixer_load(handle);

    snd_mixer_selem_id_alloca(&sid);
    snd_mixer_selem_id_set_index(sid, 0);
    snd_mixer_selem_id_set_name(sid, selem_name);
    snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);

    snd_mixer_selem_get_playback_volume(elem, snd_mixer_selem_channel_id_t(0), &cur_vol);

    snd_mixer_selem_get_playback_volume_range(elem, &min, &max);

    volume = (cur_vol > 0) ? 0 : 0.8*max;
    int err = snd_mixer_selem_set_playback_volume_all(elem, volume);

    qDebug()<<volume<<min<<max<<cur_vol<<err;

    snd_mixer_close(handle);
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * lxqt-connman-applet - a gui frontend for connman
 *
 * Copyright: 2014-2015 Christian Surlykke
 *
 * This program or 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "iconfinder.h"
#include "connectionstate.h"
#include <XdgIcon>

class IconNameFinder
{
public:
    virtual QString wirelessConnectedIconName(int strength) = 0;
    virtual QString bluetoothConnectedIconName(int strength) { return wirelessConnectedIconName(strength); }
    virtual QString ethernetConnectedIconName() = 0;
    virtual QString notConnectedIconName() = 0;
};

class IconNameFinderForOxygen : public IconNameFinder
{

public:
    virtual QString wirelessConnectedIconName(int strength)
    {
        if (strength < 13)      return "network-wireless-connected-00";
        else if (strength < 28) return "network-wireless-connected-25";
        else if (strength < 63) return "network-wireless-connected-50";
        else if (strength < 88) return "network-wireless-connected-75";
        else                    return "network-wireless-connected-100";
    }

    virtual QString ethernetConnectedIconName() { return "network-connnect";}
    virtual QString notConnectedIconName() { return "network-disconnect"; }

};

class IconNameFinderForGnome : public IconNameFinder
{
public:
    virtual QString wirelessConnectedIconName(int strength)
    {
        if (strength < 13)      return "network-wireless-signal-none";
        else if (strength < 28) return "network-wireless-signal-weak";
        else if (strength < 63) return "network-wireless-signal-ok";
        else if (strength < 88) return "network-wireless-signal-good";
        else                    return "network-wireless-signal-excellent";

    }

    virtual QString ethernetConnectedIconName() { return "network-wired"; }
    virtual QString notConnectedIconName() { return "network-offline"; }

};

IconFinder* IconFinder::instance()
{
    static IconFinder *_instance = new IconFinder();
    return _instance;
}

QIcon& IconFinder::icon()
{
    qDebug() << "icon(), themename:" << QIcon::themeName();
    qDebug() << "xdgIcon.themeName:" << XdgIcon::themeName();
    qDebug() << "iconTheme:" <<
    IconNameFinder *iconNameFinder;
    if (QIcon::themeName() == "Oxygen")
    {
        qDebug() << "Oxygen";
        iconNameFinder = new IconNameFinderForOxygen();
    }
    else
    {
        qDebug() << "Gnome";
        iconNameFinder = new IconNameFinderForGnome();
    }

    QString iconName;

    ConnectionState *connectionState = ConnectionState::instance();

    if (connectionState->connectedWireless())
    {
        iconName = iconNameFinder->wirelessConnectedIconName(connectionState->connectedWireless()->signalStrength());
    }
    else if (connectionState->connectedBluetooth())
    {
        iconName = iconNameFinder->bluetoothConnectedIconName(connectionState->connectedBluetooth()->signalStrength());
    }
    else if (connectionState->connectedEthernet())
    {
        iconName = iconNameFinder->ethernetConnectedIconName();
    }
    else
    {
        iconName = iconNameFinder->notConnectedIconName();
    }

    qDebug() << "IconFinder found: "  << iconName;
    qDebug() << QIcon::hasThemeIcon(iconName);

    mIcon = QIcon::fromTheme(iconName);

    return mIcon;
}

IconFinder::IconFinder()
{
}

<commit_msg>Fix spelling error in iconfinder.cpp<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * lxqt-connman-applet - a gui frontend for connman
 *
 * Copyright: 2014-2015 Christian Surlykke
 *
 * This program or 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "iconfinder.h"
#include "connectionstate.h"
#include <XdgIcon>

class IconNameFinder
{
public:
    virtual QString wirelessConnectedIconName(int strength) = 0;
    virtual QString bluetoothConnectedIconName(int strength) { return wirelessConnectedIconName(strength); }
    virtual QString ethernetConnectedIconName() = 0;
    virtual QString notConnectedIconName() = 0;
};

class IconNameFinderForOxygen : public IconNameFinder
{

public:
    virtual QString wirelessConnectedIconName(int strength)
    {
        if (strength < 13)      return "network-wireless-connected-00";
        else if (strength < 28) return "network-wireless-connected-25";
        else if (strength < 63) return "network-wireless-connected-50";
        else if (strength < 88) return "network-wireless-connected-75";
        else                    return "network-wireless-connected-100";
    }

    virtual QString ethernetConnectedIconName() { return "network-connect";}
    virtual QString notConnectedIconName() { return "network-disconnect"; }

};

class IconNameFinderForGnome : public IconNameFinder
{
public:
    virtual QString wirelessConnectedIconName(int strength)
    {
        if (strength < 13)      return "network-wireless-signal-none";
        else if (strength < 28) return "network-wireless-signal-weak";
        else if (strength < 63) return "network-wireless-signal-ok";
        else if (strength < 88) return "network-wireless-signal-good";
        else                    return "network-wireless-signal-excellent";

    }

    virtual QString ethernetConnectedIconName() { return "network-wired"; }
    virtual QString notConnectedIconName() { return "network-offline"; }

};

IconFinder* IconFinder::instance()
{
    static IconFinder *_instance = new IconFinder();
    return _instance;
}

QIcon& IconFinder::icon()
{
    qDebug() << "icon(), themename:" << QIcon::themeName();
    qDebug() << "xdgIcon.themeName:" << XdgIcon::themeName();
    qDebug() << "iconTheme:" <<
    IconNameFinder *iconNameFinder;
    if (QIcon::themeName() == "Oxygen")
    {
        qDebug() << "Oxygen";
        iconNameFinder = new IconNameFinderForOxygen();
    }
    else
    {
        qDebug() << "Gnome";
        iconNameFinder = new IconNameFinderForGnome();
    }

    QString iconName;

    ConnectionState *connectionState = ConnectionState::instance();

    if (connectionState->connectedWireless())
    {
        iconName = iconNameFinder->wirelessConnectedIconName(connectionState->connectedWireless()->signalStrength());
    }
    else if (connectionState->connectedBluetooth())
    {
        iconName = iconNameFinder->bluetoothConnectedIconName(connectionState->connectedBluetooth()->signalStrength());
    }
    else if (connectionState->connectedEthernet())
    {
        iconName = iconNameFinder->ethernetConnectedIconName();
    }
    else
    {
        iconName = iconNameFinder->notConnectedIconName();
    }

    qDebug() << "IconFinder found: "  << iconName;
    qDebug() << QIcon::hasThemeIcon(iconName);

    mIcon = QIcon::fromTheme(iconName);

    return mIcon;
}

IconFinder::IconFinder()
{
}

<|endoftext|>