<commit_before>// Copyright Hugh Perkins 2016

// 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 "ClWriter.h"

#include "readIR.h"
#include "LocalValueInfo.h"
#include "mutations.h"
#include "EasyCL/util/easycl_stringhelper.h"
#include "InstructionDumper.h"
#include "ExpressionsHelper.h"

#include "llvm/IR/Instructions.h"
#include "llvm/IR/Constants.h"

#include <iostream>
using namespace std;
using namespace llvm;

namespace cocl {

std::string ClWriter::getExpr() {
    if(localValueInfo->toBeDeclared) {
        return localValueInfo->name;
    }
    if(!localValueInfo->expressionValid) {
        cout << "expression not yet assigned for " << localValueInfo->name << endl;
        throw std::runtime_error("expression not yet assigned, name " + localValueInfo->name);
    }
    // cout << "ClWriter::GetExpr expression = [" << localValueInfo->expression << "]" << endl;
    return localValueInfo->expression;
}

void ClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {  // if we set this as to be assigned, this will write something, otherwise it wont
    // cout << "base ClWriter::writeDelcaratoin" << endl;
    if(localValueInfo->_skip) {
        return;
    }
    for(auto it = localValueInfo->declarationCl.begin(); it != localValueInfo->declarationCl.end(); it++) {
        // cout << "in localvalueinfo->declarationCl:" << endl;
        // cout << indent << *it << ";" << endl;
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        // cout << "in localvalueinfo.toBeDeclared:" << endl;
        // cout << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";" << endl;
        os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";\n";
    }
    // if(localValueInfo->toBeDeclared) {
    //     os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name;\n";
    // }
    // cout << "ClWriter::writeDeclaration()" << endl;
}

void ClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    // cout << "ClWriter::writeDeclaration()" << endl;
    if(localValueInfo->_skip) {
        return;
    }
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        if(!localValueInfo->expressionValid) {
            localValueInfo->value->dump();
            cout << "expression for " << localValueInfo->name + " not defined" << endl;
            throw runtime_error("expression for " + localValueInfo->name + " not defined");
        }
        string expression = ExpressionsHelper::stripOuterParams(localValueInfo->expression);
        os << indent << localValueInfo->name << " = " << expression << ";\n";
    }
    // expression = name;
}

void AllocaClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {
    // cout << "AllocaClWriter::writeDelcaratoin" << endl;
    // cout << "ClWriter::writeDeclaration()" << endl;
    string gencode = "";
    LocalValueInfo *l = localValueInfo;
    AllocaInst *alloca = cast<AllocaInst>(l->value);
    // AllocaInfo allocaInfo;
    if(PointerType *allocatypeptr = dyn_cast<PointerType>(alloca->getType())) {
        Type *ptrElementType = allocatypeptr->getElementType();
        std::string typestring = typeDumper->dumpType(ptrElementType);
        int count = ReadIR::readInt32Constant(alloca->getOperand(0));
        // string name = localNames->getOrCreateName(alloca);
        string name = l->name;
        // cout << "alloca var name [" << name << "]" << endl;
        // localExpressionByValue->operator[](alloca) = name;
        localValueInfo->setExpression(name);
        if(count == 1) {
            if(ArrayType *arrayType = dyn_cast<ArrayType>(ptrElementType)) {
                // cout << "alloca, is arraytype" << endl;
                int innercount = arrayType->getNumElements();
                Type *elementType = arrayType->getElementType();
                string allocaDeclaration = typeDumper->dumpType(elementType) + " " +
                    localValueInfo->name + "[" + easycl::toString(innercount) + "]";
                // allocaInfo.alloca = alloca;
                // allocaInfo.refValue = alloca;
                // allocaInfo.definition = allocaDeclaration;
                // allocaDeclarations->push_back(allocaInfo);
                os << indent << allocaDeclaration << ";\n";
                return;
            } else {
                // cout << "alloca, non-arraytype" << endl;
                // Value *refInstruction = alloca;
                // if the elementType is a pointer, assume its global?
                if(isa<PointerType>(ptrElementType)) {
                    // cout << "alloca, pointertype" << endl;
                    // find the store
                    for(auto it=alloca->user_begin(); it != alloca->user_end(); it++) {
                        User *user = *it;
                        if(StoreInst *store = dyn_cast<StoreInst>(user)) {
                            int storeop0space = cast<PointerType>(store->getOperand(0)->getType())->getAddressSpace();
                            // refInstruction = store->getOperand(0);
                            if(storeop0space == 1) {
                                gencode += "global ";
                                updateAddressSpace(alloca, 1);
                            }
                            copyAddressSpace(user, alloca);
                            typestring = typeDumper->dumpType(ptrElementType);
                        }
                    }
                }
                string allocaDeclaration = gencode + typestring + " " + localValueInfo->name + "[1]";
                // find the store
                // for(auto it=alloca->user_begin(); it != alloca->user_end(); it++) {
                    // User *user = *it;
                    // if(StoreInst *store = dyn_cast<StoreInst>(user)) {
                        // cout << "found store:" << endl;
                        // store->dump();
                        // cout << endl;
                        // refInstruction = store->getOperand(0);
                    // }
                // }
                // allocaInfo.alloca = alloca;
                // allocaInfo.refValue = refInstruction;
                // allocaInfo.definition = allocaDeclaration;
                // allocaDeclarations->push_back(allocaInfo);
                os << indent << allocaDeclaration << ";\n";
                return;
            }
        } else {
            throw runtime_error("not implemented: alloca for count != 1");
        }
    } else {
        alloca->dump();
        throw runtime_error("dumpalloca not implemented for non pointer type");
    }
}

void AllocaClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    // for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
    //     os << indent << *it << ";\n";
    // }
    // if(localValueInfo->toBeDeclared) {
    //     os << indent << localValueInfo->name << " = " << localValueInfo->getExpr() << ";\n";
    // }
    // expression = name;
}

void StoreClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
}

std::string InsertValueClWriter::getExpr() {
    // if(localValueInfo->toBeDeclared) {
    //     return localValueInfo->name;
    // }
    // if(!localValueInfo->expressionValid) {
    //     cout << "expression not yet assigned for " << localValueInfo->name << endl;
    //     throw std::runtime_error("expression not yet assigned, name " + localValueInfo->name);
    // }
    return localValueInfo->expression;
}

void InsertValueClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
}

void InsertValueClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {  // if we set this as to be assigned, this will write something, otherwise it wont
    // cout << "ClWriter::writeDelcaratoin" << endl;
    for(auto it = localValueInfo->declarationCl.begin(); it != localValueInfo->declarationCl.end(); it++) {
        os << indent << *it << ";\n";
    }
    if(fromUndef) {
        os << indent << typeDumper->dumpType(localValueInfo->value->getType()) << " " << localValueInfo->name << ";\n";
    }
}

void SharedClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {
    // cout << "sharedclwriter::writedeclaration" << endl;
    Value *value = localValueInfo->value;
    // cout << "value:" << endl;
    // value->dump();
    // cout << endl;
    // Type *valueType = value->getType();
    // if(GlobalVariable *globalVariable = dyn_cast<GlobalVariable>(value)) {
    // cout << "value type:" << endl;
    // value->getType()->dump();
    if(PointerType *pointerType = dyn_cast<PointerType>(value->getType())) {
        // cout << "globalvariable" << endl;
        // globalVariable->dump();
        // cout << "globalvariable->getType()" << endl;
        // Type *type = globalVariable->getType();
        // type->dump();
        // int addressSpace = globalVariable->getAddressSpace();
        int addressSpace = pointerType->getAddressSpace();
        // cout << "addressSpace " << addressSpace << endl;
        if(addressSpace != 3) {
            throw runtime_error("shouldnt be here");
        }
        Type *elementType = pointerType->getElementType();
        // cout << "elementType:" << endl;
        // elementType->dump();
        // cout << endl;
        int numElements = 0;
        Type *primitiveType = 0;
        if(ArrayType *arrayType = dyn_cast<ArrayType>(elementType)) {
            // cout << "got array type" << endl;
            numElements = arrayType->getNumElements();
            primitiveType = arrayType->getElementType();
            // cout << "numElements " << numElements << endl;
            // primitiveType->dump();
        } else {
            cout << "sharedclwriter::writedlecaraiotn, not implemneted for:" << endl;
            value->dump();
            cout << endl;
            throw runtime_error("not handled/implemented");
        }
        // GlobalVariable *globalVariable = cast<GlobalVariable>(value);
        // int count = pointerType->getArrayNumElements();
        // cout << "num elements " << count << endl;
        os << indent << "local " << typeDumper->dumpType(primitiveType) << " " << localValueInfo->name << "[" << numElements << "];\n";
    } else {
        cout << "sharedclwriter writedeclaration not implmeneted for htis type:" << endl;
        value->dump();
        cout << endl;
        throw runtime_error("not implemented: sharedclwriter for this type");
    }
}

void NoExpressionClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    if(localValueInfo->_skip) {
        return;
    }
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
}

void CallClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {  // if we set this as to be assigned, this will write something, otherwise it wont
    // cout << "base ClWriter::writeDelcaratoin" << endl;
    if(localValueInfo->_skip) {
        return;
    }
    // if return type is void, we dont need a declaration
    if(localValueInfo->value->getType()->isVoidTy()) {
        return;
    }
    for(auto it = localValueInfo->declarationCl.begin(); it != localValueInfo->declarationCl.end(); it++) {
        // cout << "in localvalueinfo->declarationCl:" << endl;
        // cout << indent << *it << ";" << endl;
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        // cout << "in localvalueinfo.toBeDeclared:" << endl;
        // cout << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";" << endl;
        os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";\n";
    }
    // if(localValueInfo->toBeDeclared) {
    //     os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name;\n";
    // }
}

void CallClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    if(localValueInfo->_skip) {
        return;
    }
    if(localValueInfo->value->getType()->isVoidTy()) {
        // we still need to write out hte call...
        os << indent << localValueInfo->expression << ";\n";
        return;
    }
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        if(!localValueInfo->expressionValid) {
            localValueInfo->value->dump();
            cout << "expression for " << localValueInfo->name + " not defined" << endl;
            throw runtime_error("expression for " + localValueInfo->name + " not defined");
        }
        string expression = ExpressionsHelper::stripOuterParams(localValueInfo->expression);
        os << indent << localValueInfo->name << " = " << expression << ";\n";
    }
    // expression = name;
}

} // namespace cocl;
<commit_msg>dont throw exception for certain shared sturctures<commit_after>// Copyright Hugh Perkins 2016

// 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 "ClWriter.h"

#include "readIR.h"
#include "LocalValueInfo.h"
#include "mutations.h"
#include "EasyCL/util/easycl_stringhelper.h"
#include "InstructionDumper.h"
#include "ExpressionsHelper.h"

#include "llvm/IR/Instructions.h"
#include "llvm/IR/Constants.h"

#include <iostream>
using namespace std;
using namespace llvm;

namespace cocl {

std::string ClWriter::getExpr() {
    if(localValueInfo->toBeDeclared) {
        return localValueInfo->name;
    }
    if(!localValueInfo->expressionValid) {
        cout << "expression not yet assigned for " << localValueInfo->name << endl;
        throw std::runtime_error("expression not yet assigned, name " + localValueInfo->name);
    }
    // cout << "ClWriter::GetExpr expression = [" << localValueInfo->expression << "]" << endl;
    return localValueInfo->expression;
}

void ClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {  // if we set this as to be assigned, this will write something, otherwise it wont
    // cout << "base ClWriter::writeDelcaratoin" << endl;
    if(localValueInfo->_skip) {
        return;
    }
    for(auto it = localValueInfo->declarationCl.begin(); it != localValueInfo->declarationCl.end(); it++) {
        // cout << "in localvalueinfo->declarationCl:" << endl;
        // cout << indent << *it << ";" << endl;
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        // cout << "in localvalueinfo.toBeDeclared:" << endl;
        // cout << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";" << endl;
        os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";\n";
    }
    // if(localValueInfo->toBeDeclared) {
    //     os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name;\n";
    // }
    // cout << "ClWriter::writeDeclaration()" << endl;
}

void ClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    // cout << "ClWriter::writeDeclaration()" << endl;
    if(localValueInfo->_skip) {
        return;
    }
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        if(!localValueInfo->expressionValid) {
            localValueInfo->value->dump();
            cout << "expression for " << localValueInfo->name + " not defined" << endl;
            throw runtime_error("expression for " + localValueInfo->name + " not defined");
        }
        string expression = ExpressionsHelper::stripOuterParams(localValueInfo->expression);
        os << indent << localValueInfo->name << " = " << expression << ";\n";
    }
    // expression = name;
}

void AllocaClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {
    // cout << "AllocaClWriter::writeDelcaratoin" << endl;
    // cout << "ClWriter::writeDeclaration()" << endl;
    string gencode = "";
    LocalValueInfo *l = localValueInfo;
    AllocaInst *alloca = cast<AllocaInst>(l->value);
    // AllocaInfo allocaInfo;
    if(PointerType *allocatypeptr = dyn_cast<PointerType>(alloca->getType())) {
        Type *ptrElementType = allocatypeptr->getElementType();
        std::string typestring = typeDumper->dumpType(ptrElementType);
        int count = ReadIR::readInt32Constant(alloca->getOperand(0));
        // string name = localNames->getOrCreateName(alloca);
        string name = l->name;
        // cout << "alloca var name [" << name << "]" << endl;
        // localExpressionByValue->operator[](alloca) = name;
        localValueInfo->setExpression(name);
        if(count == 1) {
            if(ArrayType *arrayType = dyn_cast<ArrayType>(ptrElementType)) {
                // cout << "alloca, is arraytype" << endl;
                int innercount = arrayType->getNumElements();
                Type *elementType = arrayType->getElementType();
                string allocaDeclaration = typeDumper->dumpType(elementType) + " " +
                    localValueInfo->name + "[" + easycl::toString(innercount) + "]";
                // allocaInfo.alloca = alloca;
                // allocaInfo.refValue = alloca;
                // allocaInfo.definition = allocaDeclaration;
                // allocaDeclarations->push_back(allocaInfo);
                os << indent << allocaDeclaration << ";\n";
                return;
            } else {
                // cout << "alloca, non-arraytype" << endl;
                // Value *refInstruction = alloca;
                // if the elementType is a pointer, assume its global?
                if(isa<PointerType>(ptrElementType)) {
                    // cout << "alloca, pointertype" << endl;
                    // find the store
                    for(auto it=alloca->user_begin(); it != alloca->user_end(); it++) {
                        User *user = *it;
                        if(StoreInst *store = dyn_cast<StoreInst>(user)) {
                            int storeop0space = cast<PointerType>(store->getOperand(0)->getType())->getAddressSpace();
                            // refInstruction = store->getOperand(0);
                            if(storeop0space == 1) {
                                gencode += "global ";
                                updateAddressSpace(alloca, 1);
                            }
                            copyAddressSpace(user, alloca);
                            typestring = typeDumper->dumpType(ptrElementType);
                        }
                    }
                }
                string allocaDeclaration = gencode + typestring + " " + localValueInfo->name + "[1]";
                // find the store
                // for(auto it=alloca->user_begin(); it != alloca->user_end(); it++) {
                    // User *user = *it;
                    // if(StoreInst *store = dyn_cast<StoreInst>(user)) {
                        // cout << "found store:" << endl;
                        // store->dump();
                        // cout << endl;
                        // refInstruction = store->getOperand(0);
                    // }
                // }
                // allocaInfo.alloca = alloca;
                // allocaInfo.refValue = refInstruction;
                // allocaInfo.definition = allocaDeclaration;
                // allocaDeclarations->push_back(allocaInfo);
                os << indent << allocaDeclaration << ";\n";
                return;
            }
        } else {
            throw runtime_error("not implemented: alloca for count != 1");
        }
    } else {
        alloca->dump();
        throw runtime_error("dumpalloca not implemented for non pointer type");
    }
}

void AllocaClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    // for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
    //     os << indent << *it << ";\n";
    // }
    // if(localValueInfo->toBeDeclared) {
    //     os << indent << localValueInfo->name << " = " << localValueInfo->getExpr() << ";\n";
    // }
    // expression = name;
}

void StoreClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
}

std::string InsertValueClWriter::getExpr() {
    // if(localValueInfo->toBeDeclared) {
    //     return localValueInfo->name;
    // }
    // if(!localValueInfo->expressionValid) {
    //     cout << "expression not yet assigned for " << localValueInfo->name << endl;
    //     throw std::runtime_error("expression not yet assigned, name " + localValueInfo->name);
    // }
    return localValueInfo->expression;
}

void InsertValueClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
}

void InsertValueClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {  // if we set this as to be assigned, this will write something, otherwise it wont
    // cout << "ClWriter::writeDelcaratoin" << endl;
    for(auto it = localValueInfo->declarationCl.begin(); it != localValueInfo->declarationCl.end(); it++) {
        os << indent << *it << ";\n";
    }
    if(fromUndef) {
        os << indent << typeDumper->dumpType(localValueInfo->value->getType()) << " " << localValueInfo->name << ";\n";
    }
}

void SharedClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {
    // cout << "sharedclwriter::writedeclaration" << endl;
    Value *value = localValueInfo->value;
    // cout << "value:" << endl;
    // value->dump();
    // cout << endl;
    // Type *valueType = value->getType();
    // if(GlobalVariable *globalVariable = dyn_cast<GlobalVariable>(value)) {
    // cout << "value type:" << endl;
    // value->getType()->dump();
    if(PointerType *pointerType = dyn_cast<PointerType>(value->getType())) {
        // cout << "globalvariable" << endl;
        // globalVariable->dump();
        // cout << "globalvariable->getType()" << endl;
        // Type *type = globalVariable->getType();
        // type->dump();
        // int addressSpace = globalVariable->getAddressSpace();
        int addressSpace = pointerType->getAddressSpace();
        // cout << "addressSpace " << addressSpace << endl;
        if(addressSpace != 3) {
            std::cout << "SharedClWriter::writeDeclaration, addressSpace=" << addressSpace << ".  This codepath not handled" << std::endl;
            throw runtime_error("shouldnt be here");
        }
        Type *elementType = pointerType->getElementType();
        // cout << "elementType:" << endl;
        // elementType->dump();
        // cout << endl;
        int numElements = 0;
        Type *primitiveType = 0;
        if(ArrayType *arrayType = dyn_cast<ArrayType>(elementType)) {
            // cout << "got array type" << endl;
            numElements = arrayType->getNumElements();
            primitiveType = arrayType->getElementType();
            // cout << "numElements " << numElements << endl;
            // primitiveType->dump();
        } else {
            cout << "ERROR: sharedclwriter::writedlecaraiotn, not implemneted for:" << endl;
            value->dump();
            cout << endl;
            // TODO: uncomment this line FIXME
            return;
            // throw runtime_error("not handled/implemented");
        }
        // GlobalVariable *globalVariable = cast<GlobalVariable>(value);
        // int count = pointerType->getArrayNumElements();
        // cout << "num elements " << count << endl;
        os << indent << "local " << typeDumper->dumpType(primitiveType) << " " << localValueInfo->name << "[" << numElements << "];\n";
    } else {
        cout << "sharedclwriter writedeclaration not implmeneted for htis type:" << endl;
        value->dump();
        cout << endl;
        throw runtime_error("not implemented: sharedclwriter for this type");
    }
}

void NoExpressionClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    if(localValueInfo->_skip) {
        return;
    }
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
}

void CallClWriter::writeDeclaration(std::string indent, TypeDumper *typeDumper, std::ostream &os) {  // if we set this as to be assigned, this will write something, otherwise it wont
    // cout << "base ClWriter::writeDelcaratoin" << endl;
    if(localValueInfo->_skip) {
        return;
    }
    // if return type is void, we dont need a declaration
    if(localValueInfo->value->getType()->isVoidTy()) {
        return;
    }
    for(auto it = localValueInfo->declarationCl.begin(); it != localValueInfo->declarationCl.end(); it++) {
        // cout << "in localvalueinfo->declarationCl:" << endl;
        // cout << indent << *it << ";" << endl;
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        // cout << "in localvalueinfo.toBeDeclared:" << endl;
        // cout << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";" << endl;
        os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name << ";\n";
    }
    // if(localValueInfo->toBeDeclared) {
    //     os << indent << typeDumper->dumpType(localValueInfo->value->getType(), true) << " " << localValueInfo->name;\n";
    // }
}

void CallClWriter::writeInlineCl(std::string indent, std::ostream &os) { // writes any cl required, eg if we toggled setAsAssigned, we need to do the assignment
                                          // some instructoins will *always* write something, eg stores
    if(localValueInfo->_skip) {
        return;
    }
    if(localValueInfo->value->getType()->isVoidTy()) {
        // we still need to write out hte call...
        os << indent << localValueInfo->expression << ";\n";
        return;
    }
    for(auto it = localValueInfo->inlineCl.begin(); it != localValueInfo->inlineCl.end(); it++) {
        os << indent << *it << ";\n";
    }
    if(localValueInfo->toBeDeclared) {
        if(!localValueInfo->expressionValid) {
            localValueInfo->value->dump();
            cout << "expression for " << localValueInfo->name + " not defined" << endl;
            throw runtime_error("expression for " + localValueInfo->name + " not defined");
        }
        string expression = ExpressionsHelper::stripOuterParams(localValueInfo->expression);
        os << indent << localValueInfo->name << " = " << expression << ";\n";
    }
    // expression = name;
}

} // namespace cocl;
<|endoftext|>


<commit_before>#include "Smartcar.h"

ESCMotor::ESCMotor(unsigned short pin) {
	_pin = pin;
	setFreqsAndSpeeds();
	setAllowedSpeedLimits();
}

void ESCMotor::setFreqsAndSpeeds(){
	FULL_FORWARD = 100;
        FULL_BACKWARD = 100;
	IDLE_RAW_SPEED = 1500;
	MAX_FRONT_RAW_SPEED = 1800;
	MAX_BACK_RAW_SPEED = 1200;
	_speed = IDLE_RAW_SPEED;
}

void ESCMotor::init(){
	attach(_pin); //attach the servo to its pin
}

void ESCMotor::setSpeed(int speed){ //receives a speed in the scale of -100 to 100
	_speed = filterSpeed(speed); //_speed now holds a value between MAX_BACK_ALLOWED_SPEED and MAX_FRONT_ALLOWED_SPEED
	writeMicroseconds(_speed); //write the appropriate pwm signal to the servo
}
<commit_msg>using the full range of allowed ESC values<commit_after>#include "Smartcar.h"

ESCMotor::ESCMotor(unsigned short pin) {
	_pin = pin;
	setFreqsAndSpeeds();
	setAllowedSpeedLimits();
}

void ESCMotor::setFreqsAndSpeeds(){
	FULL_FORWARD = 100;
        FULL_BACKWARD = 100;
	IDLE_RAW_SPEED = 1500;
	MAX_FRONT_RAW_SPEED = 2000;
	MAX_BACK_RAW_SPEED = 1000;
	_speed = IDLE_RAW_SPEED;
}

void ESCMotor::init(){
	attach(_pin); //attach the servo to its pin
}

void ESCMotor::setSpeed(int speed){ //receives a speed in the scale of -100 to 100
	_speed = filterSpeed(speed); //_speed now holds a value between MAX_BACK_ALLOWED_SPEED and MAX_FRONT_ALLOWED_SPEED
	writeMicroseconds(_speed); //write the appropriate pwm signal to the servo
}
<|endoftext|>


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

#include "Exporter.h"
#include "Launcher.h"
#include <QCoreApplication>
#include <QtSql>
#include <QFile>
#include <QLocale>

const QString Exporter::DB_NAME = "";

Exporter::Exporter(QObject *parent) :
    QObject(parent)
{
    /* Open the SQLite database */
    QDir dbdir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));

    if (!dbdir.exists())
    {
        dbdir.mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    }
    qDebug() << QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE"));

    db->setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/harbour-workinghourstracker/harbour-workinghourstracker/QML/OfflineStorage/Databases/e1e57aa3b56d20de7b090320d566397e.sqlite");

    if (db->open())
    {
        qDebug() << "Open Success";
    }
    else
    {
        qDebug() << "Open error";
        qDebug() << " " << db->lastError().text();
    }
}

QVariantList Exporter::readHours()
{
    QSqlQuery query = QSqlQuery("SELECT * FROM hours;", *db);
    QVariantList tmp;
    QVariantMap map;

    if (query.exec())
    {
        map.clear();
        while (query.next())
        {
            //uid|date|startTime|endTime|duration|project|description|breakDuration

            map.insert("uid", query.record().value("uid").toString());
            map.insert("date", query.record().value("date").toString());
            map.insert("startTime", query.record().value("startTime").toString());
            map.insert("endTime", query.record().value("endTime").toString());
            map.insert("duration", query.record().value("duration").toString());
            map.insert("project", query.record().value("project").toString());
            map.insert("description", query.record().value("description").toString());
            map.insert("breakDuration", query.record().value("breakDuration").toString());
            tmp.append(map);

        }
    }
    else
    {
        qDebug() << "readHours failed " << query.lastError();
    }

    return tmp;
}

QVariantList Exporter::readProjects()
{
    QSqlQuery query = QSqlQuery("SELECT * FROM projects;", *db);
    QVariantList tmp;
    QVariantMap map;

    if (query.exec())
    {
        map.clear();
        while (query.next())
        {
            //id|name|hourlyRate|contractRate|budget|hourBudget|labelColor

            map.insert("id", query.record().value("id").toString());
            map.insert("name", query.record().value("name").toString());
            map.insert("hourlyRate", query.record().value("hourlyRate").toString());
            map.insert("contractRate", query.record().value("contractRate").toString());
            map.insert("budget", query.record().value("budget").toString());
            map.insert("hourBudget", query.record().value("hourBudget").toString());
            map.insert("labelColor", query.record().value("labelColor").toString());
            tmp.append(map);
        }
    }
    else
    {
        qDebug() << "readHours failed " << query.lastError();
    }

    return tmp;
}

/*
 * Export Hours to CSV file
 */
QString Exporter::exportHoursToCSV()
{
    qDebug() << "Exporting hours";

    //QLocale loc = QLocale::system(); /* Should return current locale */
    //QChar separator = (loc.decimalPoint() == '.') ? ',' : ';';
    //qDebug() << "Using" << separator << "as separator";

    QString filename = QString("%1/workinghours.csv").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");

    QVariantList hours = readHours();
    QListIterator<QVariant> i(hours);

    while (i.hasNext())
    {
        QVariantMap data = i.next().value<QVariantMap>();
        //uid|date|startTime|endTime|duration|project|description|breakDuration
        out << "'" << data["uid"].toString() << "'" << ',' << "'" << data["date"].toString() << "'" << ',' << "'" << data["startTime"].toString() << "'" << ',' << "'" << data["endTime"].toString() << "'" << ',' << data["duration"].toString().replace(',', '.') << ',' << "'" << data["project"].toString() << "'" << ',' << "'" << data["description"].toString().replace(',', ' ') << "'" << ','  << data["breakDuration"].toString().replace(',', '.') << "\n";
    }

    out.flush();
    file.close();

    return filename;
}

/*
 * Export Projects to CSV file
 */
QString Exporter::exportProjectsToCSV()
{
    qDebug() << "Exporting projects";

    //QLocale loc = QLocale::system(); /* Should return current locale */
    //QChar separator = (loc.decimalPoint() == '.') ? ',' : ';';
    //qDebug() << "Using" << separator << "as separator";

    QString filename = QString("%1/whtProjects.csv").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");

    QVariantList projects = readProjects();
    QListIterator<QVariant> n(projects);

    while (n.hasNext())
    {
        QVariantMap data = n.next().value<QVariantMap>();
        //id|name|hourlyRate|contractRate|budget|hourBudget|labelColor
        out << "'" << data["id"].toString() << "'" << ',' << "'" << data["name"].toString().replace(',', ' ') << "'" << ',' << data["hourlyRate"].toString().replace(',', '.') << ',' << data["contractRate"].toString().replace(',',',') << ',' << data["budget"].toString().replace(',', '.') << ',' << data["hourBudget"].toString().replace(',','.') << ',' << "'" << data["labelColor"].toString() << "'" << "\n";
    }

    out.flush();
    file.close();

    return filename;
}

QString Exporter::exportCategoryToCSV(QString section, QVariantList allHours) {
    qDebug() << "Exporting hours for " << section;

    //QLocale loc = QLocale::system(); /* Should return current locale */
    //QChar separator = (loc.decimalPoint() == '.') ? ',' : ';';
    //qDebug() << "Using" << separator << "as separator";

    QString filename = QString("%1/%2.csv").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).arg(section);
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");

    QListIterator<QVariant> n(allHours);

    while (n.hasNext())
    {
        QVariantMap data = n.next().value<QVariantMap>();
        //uid|date|startTime|endTime|duration|project|description|breakDuration
        out << "'" << data["uid"].toString() << "'" << ',' << "'" << data["date"].toString() << "'" << ',' << "'" << data["startTime"].toString() << "'" << ',' << "'" << data["endTime"].toString() << "'" << ',' << data["duration"].toString().replace(',','.') << ',' << "'" << data["project"].toString() << "'" << ',' << "'" << data["description"].toString().replace(',', ' ') << "'" << ',' << "'" << data["breakDuration"].toString() << "\n";
    }

    out.flush();
    file.close();

    return filename;
}

QString Exporter::dump() {
    qDebug() << "Dumping the database";

    QString filename = QString("%1/wht.sql").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");
    Launcher l;
    QString retval = l.launch("sqlite3 /home/nemo/.local/share/harbour-workinghourstracker/harbour-workinghourstracker/QML/OfflineStorage/Databases/e1e57aa3b56d20de7b090320d566397e.sqlite .dump");
    out << retval;
    file.close();

    if (retval.length() < 1)
        return "Error";
    return filename;
}

QString Exporter::importHoursFromCSV(QString filename) {
    return "Not implemented";
}

QString Exporter::importProjectsFromCSV(QString filename) {
    return "Not implemented";
}

QString Exporter::importDump(QString filename){
    qDebug() << "Trying to import from a dump file";
    qDebug() << "Input filename is" << filename;

    /**
    * @brief executeQueriesFromFile Read each line from a .sql QFile
    * (assumed to not have been opened before this function), and when ; is reached, execute
    * the SQL gathered until then on the query object. Then do this until a COMMIT SQL
    * statement is found. In other words, this function assumes each file is a single
    * SQL transaction, ending with a COMMIT line.
    */

    QFile file(filename);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QSqlQuery query;
        int counter = 0;
        int errors = 0;
        while (!file.atEnd()){
            QByteArray readLine="";
            QString cleanedLine;
            QString line="";
            bool finished=false;
            while(!finished){
                readLine = file.readLine();
                cleanedLine=readLine.trimmed();
                // remove comments at end of line
                //QStringList strings=cleanedLine.split("--");
                //cleanedLine=strings.at(0);

                // remove lines with only comment, and DROP lines
                if(!cleanedLine.startsWith("--") && !cleanedLine.startsWith("DROP")&& !cleanedLine.isEmpty()){
                    line+=cleanedLine;
                }
                if(cleanedLine.endsWith(";")){
                    break;
                }
                if(cleanedLine.startsWith("COMMIT")){
                    finished=true;
                }
            }
            if(!line.isEmpty()){
                // Change to INSERT OR REPLACE
                if(line.startsWith("INSERT")) {
                    line.replace(QString("INSERT"), QString("INSERT OR REPLACE"));
                }

                // Change to CREATE TABLE IF NOT EXISTS
                if(line.startsWith("CREATE TABLE")) {
                    line.replace(QString("CREATE TABLE"), QString("CREATE TABLE IF NOT EXISTS"));
                }

                if(query.exec(line)) {
                    qDebug() << "Succesful line: "<< line;
                    if(!line.startsWith("COMMIT") && !line.startsWith("PRAGMA") && !line.startsWith("BEGIN") && !line.startsWith("CREATE TABLE"))
                        counter++;
                }
                else {
                    if(!line.startsWith("COMMIT") && !line.startsWith("PRAGMA") && !line.startsWith("BEGIN") && !line.startsWith("CREATE TABLE"))
                        errors++;
                    qDebug() <<  query.lastError();
                    qDebug() << "Error in query: "<< query.lastQuery();
                }
            }
        }
        int inserted = counter - errors;
        QString ret = QString("Done: %1 rows inserted or updated \n%2 errors occured.").arg(inserted).arg(errors);
        return ret;
    }
    return "Error opening the file!";
}

Exporter::~Exporter(){}
<commit_msg>check if no errors<commit_after>/*
Copyright (C) 2015 Olavi Haapala ojhaapala@gmail.com  Twitter: @olpetik
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "Exporter.h"
#include "Launcher.h"
#include <QCoreApplication>
#include <QtSql>
#include <QFile>
#include <QLocale>

const QString Exporter::DB_NAME = "";

Exporter::Exporter(QObject *parent) :
    QObject(parent)
{
    /* Open the SQLite database */
    QDir dbdir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));

    if (!dbdir.exists())
    {
        dbdir.mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
    }
    qDebug() << QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    db = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE"));

    db->setDatabaseName(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/harbour-workinghourstracker/harbour-workinghourstracker/QML/OfflineStorage/Databases/e1e57aa3b56d20de7b090320d566397e.sqlite");

    if (db->open())
    {
        qDebug() << "Open Success";
    }
    else
    {
        qDebug() << "Open error";
        qDebug() << " " << db->lastError().text();
    }
}

QVariantList Exporter::readHours()
{
    QSqlQuery query = QSqlQuery("SELECT * FROM hours;", *db);
    QVariantList tmp;
    QVariantMap map;

    if (query.exec())
    {
        map.clear();
        while (query.next())
        {
            //uid|date|startTime|endTime|duration|project|description|breakDuration

            map.insert("uid", query.record().value("uid").toString());
            map.insert("date", query.record().value("date").toString());
            map.insert("startTime", query.record().value("startTime").toString());
            map.insert("endTime", query.record().value("endTime").toString());
            map.insert("duration", query.record().value("duration").toString());
            map.insert("project", query.record().value("project").toString());
            map.insert("description", query.record().value("description").toString());
            map.insert("breakDuration", query.record().value("breakDuration").toString());
            tmp.append(map);

        }
    }
    else
    {
        qDebug() << "readHours failed " << query.lastError();
    }

    return tmp;
}

QVariantList Exporter::readProjects()
{
    QSqlQuery query = QSqlQuery("SELECT * FROM projects;", *db);
    QVariantList tmp;
    QVariantMap map;

    if (query.exec())
    {
        map.clear();
        while (query.next())
        {
            //id|name|hourlyRate|contractRate|budget|hourBudget|labelColor

            map.insert("id", query.record().value("id").toString());
            map.insert("name", query.record().value("name").toString());
            map.insert("hourlyRate", query.record().value("hourlyRate").toString());
            map.insert("contractRate", query.record().value("contractRate").toString());
            map.insert("budget", query.record().value("budget").toString());
            map.insert("hourBudget", query.record().value("hourBudget").toString());
            map.insert("labelColor", query.record().value("labelColor").toString());
            tmp.append(map);
        }
    }
    else
    {
        qDebug() << "readHours failed " << query.lastError();
    }

    return tmp;
}

/*
 * Export Hours to CSV file
 */
QString Exporter::exportHoursToCSV()
{
    qDebug() << "Exporting hours";

    //QLocale loc = QLocale::system(); /* Should return current locale */
    //QChar separator = (loc.decimalPoint() == '.') ? ',' : ';';
    //qDebug() << "Using" << separator << "as separator";

    QString filename = QString("%1/workinghours.csv").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");

    QVariantList hours = readHours();
    QListIterator<QVariant> i(hours);

    while (i.hasNext())
    {
        QVariantMap data = i.next().value<QVariantMap>();
        //uid|date|startTime|endTime|duration|project|description|breakDuration
        out << "'" << data["uid"].toString() << "'" << ',' << "'" << data["date"].toString() << "'" << ',' << "'" << data["startTime"].toString() << "'" << ',' << "'" << data["endTime"].toString() << "'" << ',' << data["duration"].toString().replace(',', '.') << ',' << "'" << data["project"].toString() << "'" << ',' << "'" << data["description"].toString().replace(',', ' ') << "'" << ','  << data["breakDuration"].toString().replace(',', '.') << "\n";
    }

    out.flush();
    file.close();

    return filename;
}

/*
 * Export Projects to CSV file
 */
QString Exporter::exportProjectsToCSV()
{
    qDebug() << "Exporting projects";

    //QLocale loc = QLocale::system(); /* Should return current locale */
    //QChar separator = (loc.decimalPoint() == '.') ? ',' : ';';
    //qDebug() << "Using" << separator << "as separator";

    QString filename = QString("%1/whtProjects.csv").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");

    QVariantList projects = readProjects();
    QListIterator<QVariant> n(projects);

    while (n.hasNext())
    {
        QVariantMap data = n.next().value<QVariantMap>();
        //id|name|hourlyRate|contractRate|budget|hourBudget|labelColor
        out << "'" << data["id"].toString() << "'" << ',' << "'" << data["name"].toString().replace(',', ' ') << "'" << ',' << data["hourlyRate"].toString().replace(',', '.') << ',' << data["contractRate"].toString().replace(',',',') << ',' << data["budget"].toString().replace(',', '.') << ',' << data["hourBudget"].toString().replace(',','.') << ',' << "'" << data["labelColor"].toString() << "'" << "\n";
    }

    out.flush();
    file.close();

    return filename;
}

QString Exporter::exportCategoryToCSV(QString section, QVariantList allHours) {
    qDebug() << "Exporting hours for " << section;

    //QLocale loc = QLocale::system(); /* Should return current locale */
    //QChar separator = (loc.decimalPoint() == '.') ? ',' : ';';
    //qDebug() << "Using" << separator << "as separator";

    QString filename = QString("%1/%2.csv").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).arg(section);
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");

    QListIterator<QVariant> n(allHours);

    while (n.hasNext())
    {
        QVariantMap data = n.next().value<QVariantMap>();
        //uid|date|startTime|endTime|duration|project|description|breakDuration
        out << "'" << data["uid"].toString() << "'" << ',' << "'" << data["date"].toString() << "'" << ',' << "'" << data["startTime"].toString() << "'" << ',' << "'" << data["endTime"].toString() << "'" << ',' << data["duration"].toString().replace(',','.') << ',' << "'" << data["project"].toString() << "'" << ',' << "'" << data["description"].toString().replace(',', ' ') << "'" << ',' << "'" << data["breakDuration"].toString() << "\n";
    }

    out.flush();
    file.close();

    return filename;
}

QString Exporter::dump() {
    qDebug() << "Dumping the database";

    QString filename = QString("%1/wht.sql").arg(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    qDebug() << "Output filename is" << filename;

    QFile file(filename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out.setCodec("ISO-8859-1");
    Launcher l;
    QString retval = l.launch("sqlite3 /home/nemo/.local/share/harbour-workinghourstracker/harbour-workinghourstracker/QML/OfflineStorage/Databases/e1e57aa3b56d20de7b090320d566397e.sqlite .dump");
    out << retval;
    file.close();

    if (retval.length() < 1)
        return "Error";
    return filename;
}

QString Exporter::importHoursFromCSV(QString filename) {
    return "Not implemented";
}

QString Exporter::importProjectsFromCSV(QString filename) {
    return "Not implemented";
}

QString Exporter::importDump(QString filename){
    qDebug() << "Trying to import from a dump file";
    qDebug() << "Input filename is" << filename;

    /**
    * Read each line from a .sql QFile and when ; is reached, execute
    * the SQL gathered until then on the query object. Then do this until a COMMIT SQL
    * statement is found. In other words, this function assumes each file is a single
    * SQL transaction, ending with a COMMIT line.
    */

    QFile file(filename);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QSqlQuery query;
        int counter = 0;
        int errors = 0;
        while (!file.atEnd()){
            QByteArray readLine="";
            QString cleanedLine;
            QString line="";
            bool finished=false;
            while(!finished){
                readLine = file.readLine();
                cleanedLine=readLine.trimmed();
                // remove comments at end of line
                //QStringList strings=cleanedLine.split("--");
                //cleanedLine=strings.at(0);

                // remove lines with only comment, and DROP lines
                if(!cleanedLine.startsWith("--") && !cleanedLine.startsWith("DROP")&& !cleanedLine.isEmpty()){
                    line+=cleanedLine;
                }
                if(cleanedLine.endsWith(";")){
                    break;
                }
                if(cleanedLine.startsWith("COMMIT")){
                    finished=true;
                }
            }
            if(!line.isEmpty()){
                if(!line.startsWith("COMMIT") && !line.startsWith("PRAGMA") && !line.startsWith("BEGIN") && !line.startsWith("CREATE TABLE"))
                    counter++;
                // Change to INSERT OR REPLACE
                if(line.startsWith("INSERT")) {
                    line.replace(QString("INSERT"), QString("INSERT OR REPLACE"));
                }

                // Change to CREATE TABLE IF NOT EXISTS
                if(line.startsWith("CREATE TABLE")) {
                    line.replace(QString("CREATE TABLE"), QString("CREATE TABLE IF NOT EXISTS"));
                }

                if(query.exec(line)) {
                    qDebug() << "Succesful line: "<< line;
                }
                else {
                    if(!line.startsWith("COMMIT") && !line.startsWith("PRAGMA") && !line.startsWith("BEGIN") && !line.startsWith("CREATE TABLE"))
                        errors++;
                    qDebug() <<  query.lastError();
                    qDebug() << "Error in query: "<< query.lastQuery();
                }
            }
        }
        if (errors) {
            int inserted = counter - errors;
            return QString("Done: %1 rows inserted or updated \n%2 errors occured.").arg(inserted).arg(errors);
        }
        else
            return QString("Done: %1 rows inserted or updated").arg(inserted);

    }
    return "Error opening the file!";
}

Exporter::~Exporter(){}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

const int length = sizeof(int) * 8;

void binaryNumber(int number, bool binaryArray[])
{
	for (int i = 0; i < length; i++)
	{
		if (number & 1)
		{
			binaryArray[i] = 1;
		}

		number = number >> 1;
	}
}

void binarySum(bool binaryNumber1[], bool binaryNumber2[], bool binSum[])
{
	int sum = 0;
	bool remainder = 0;
	for (int i = 0; i < length; i++)
	{
		sum = binaryNumber1[i] + binaryNumber2[i] + remainder;
		if (sum == 0)
		{
			remainder = 0;
		}
		if (sum == 1)
		{
			binSum[i] = 1;
			remainder = 0;
		}
		if (sum == 2)
		{
			remainder = 1;
		}
		if (sum == 3)
		{
			binSum[i] = 1;
			remainder = 1;
		}
	}
}

int decimalPositiveSum(bool binSum[])
{
	int decimalSum = 0;
	int power = 1;

	for (int i = 0; i < length - 1; i++)
	{
		if (binSum[i])
		{
			decimalSum = decimalSum + power;
		}
		power = power * 2;
	}

	return decimalSum;
}

int decimalSum(bool binSum[])
{
	int decimalSum = 0;

	if (!binSum[length - 1])
	{
		decimalSum = decimalPositiveSum(binSum);
	}
	else
	{
		for (int i = 0; i < length; i++)
		{
			binSum[i] = !binSum[i];
		}

		bool exit = false;
		int i = 0;

		while(!exit)
		{
			if (!binSum[i])
			{
				binSum[i] = 1;
				exit = true;
			}
			else
			{
				binSum[i] = 0;
				++i;
			}
		}

		decimalSum = - decimalPositiveSum(binSum);
	}

	return decimalSum;
}

void coutArray(bool array[])
{
	for (int i = 0; i < length; i++)
	{
		cout << array[length - 1 - i];
	}
	cout << endl;
}

bool test1()
{
	int num1 = 5;
	int num2 = 9;

	bool binNum1[length] = {};
	bool binNum2[length] = {};

	binaryNumber(num1, binNum1);
	binaryNumber(num2, binNum2);

	bool binSum[length] = {};

	binarySum(binNum1, binNum2, binSum);

	return (decimalSum(binSum) == 14);
}

bool test2()
{
	int num1 = -3;
	int num2 = 8;

	bool binNum1[length] = {};
	bool binNum2[length] = {};

	binaryNumber(num1, binNum1);
	binaryNumber(num2, binNum2);

	bool binSum[length] = {};

	binarySum(binNum1, binNum2, binSum);

	return (decimalSum(binSum) == 5);
}

bool test3()
{
	int num1 = -7;
	int num2 = -2;

	bool binNum1[length] = {};
	bool binNum2[length] = {};

	binaryNumber(num1, binNum1);
	binaryNumber(num2, binNum2);

	bool binSum[length] = {};

	binarySum(binNum1, binNum2, binSum);

	return (decimalSum(binSum) == -9);
}

bool tests()
{
	return (test1() && test2() && test3());
}

int main()
{
	setlocale (LC_ALL, "Russian");

	if (!tests())
	{
		cout << "";
		return 0;
	}

	cout << "  : ";
	int a = 0;
	int b = 0;
	cin >> a;
	cin >> b;

	bool binaryA[length] = {};
	bool binaryB[length] = {};

	binaryNumber(a, binaryA);
	binaryNumber(b, binaryB);

	cout << "   " << a << ": ";
	coutArray(binaryA);

	cout << "   " << b << ": ";
	coutArray(binaryB);

	bool binSum[length] = {};

	binarySum(binaryA, binaryB, binSum);

	cout << "    : ";
	coutArray(binSum);

	cout << "    : " << decimalSum(binSum) << endl;

	return 0;
}<commit_msg>combined functions for positive and negative sum into one<commit_after>#include <iostream>

using namespace std;

const int length = sizeof(int) * 8;

void binaryNumber(int number, bool binaryArray[])
{
	for (int i = 0; i < length; i++)
	{
		if (number & 1)
		{
			binaryArray[i] = true;
		}

		number = number >> 1;
	}
}

void binarySum(bool binaryNumber1[], bool binaryNumber2[], bool binSum[])
{
	int sum = 0;
	bool remainder = false;
	for (int i = 0; i < length; i++)
	{
		sum = binaryNumber1[i] + binaryNumber2[i] + remainder;
		if (sum == 0)
		{
			remainder = false;
		}
		if (sum == 1)
		{
			binSum[i] = true;
			remainder = false;
		}
		if (sum == 2)
		{
			remainder = true;
		}
		if (sum == 3)
		{
			binSum[i] = true;
			remainder = true;
		}
	}
}

int decimalSum(bool binSum[])
{
	int decimalSum = 0;
	int power = 1;

	for (int i = 0; i < length; i++)
	{
		if (binSum[i])
		{
			decimalSum = decimalSum + power;
		}
		power = power * 2;
	}

	return decimalSum;
}

void coutArray(bool array[])
{
	for (int i = 0; i < length; i++)
	{
		cout << array[length - 1 - i];
	}
	cout << endl;
}

bool test1()
{
	int num1 = 5;
	int num2 = 9;

	bool binNum1[length] = {};
	bool binNum2[length] = {};

	binaryNumber(num1, binNum1);
	binaryNumber(num2, binNum2);

	bool binSum[length] = {};

	binarySum(binNum1, binNum2, binSum);

	return (decimalSum(binSum) == 14);
}

bool test2()
{
	int num1 = -3;
	int num2 = 8;

	bool binNum1[length] = {};
	bool binNum2[length] = {};

	binaryNumber(num1, binNum1);
	binaryNumber(num2, binNum2);

	bool binSum[length] = {};

	binarySum(binNum1, binNum2, binSum);

	return (decimalSum(binSum) == 5);
}

bool test3()
{
	int num1 = -7;
	int num2 = -2;

	bool binNum1[length] = {};
	bool binNum2[length] = {};

	binaryNumber(num1, binNum1);
	binaryNumber(num2, binNum2);

	bool binSum[length] = {};

	binarySum(binNum1, binNum2, binSum);

	return (decimalSum(binSum) == -9);
}

bool tests()
{
	return (test1() && test2() && test3());
}

int main()
{
	setlocale (LC_ALL, "Russian");

	if (!tests())
	{
		cout << "";
		return 0;
	}

	cout << "  : ";
	int a = 0;
	int b = 0;
	cin >> a;
	cin >> b;

	bool binaryA[length] = {};
	bool binaryB[length] = {};

	binaryNumber(a, binaryA);
	binaryNumber(b, binaryB);

	cout << "   " << a << ": ";
	coutArray(binaryA);

	cout << "   " << b << ": ";
	coutArray(binaryB);

	bool binSum[length] = {};

	binarySum(binaryA, binaryB, binSum);

	cout << "    : ";
	coutArray(binSum);

	cout << "    : " << decimalSum(binSum) << endl;

	return 0;
}<|endoftext|>


<commit_before>#include <iostream>
//#include <conio.h>
#include <vector>

#include "../include/Common.h"
#include "../include/Gambling.h"
#include "../include/Player.h"

using namespace std;
using namespace Common;

// Contains the functions needed to simulate a gamble for items.

void Gambling::Gamble(Player *_Player) {
    // A gambling arena, in which the die you roll must be equal or higher than requirement
    // Uses the Player object passed in to give won items to player.
    /// Maybe check Coins? If too low then can't gamble.
    // Generates random values for the local variables declared in the class.
    GenerateValues();
    // check if the player has enough money to play
    if (_Player->GetCoins() < CoinsDeduction) {
        // the player does not have enough money
        cout << "You need at least " << CoinsDeduction << " coins to gamble." << endl;
        Sleep(SLEEP_MS);
        return;
    }
    // Player's die. Equal to a random number between 1 and 9.
    int Die=ReturnShakenDie();
    // Initialized to analyze user input.
    int choice = 0;
    // Loops until player chooses to reveal die.
    while (choice!=1) {
        /// Since the ClearScreen() method is in class Game, system("CLS") is used instead.
        /// Must fix.
        ClearScreen();
        // Prints required die number to win gamble.
        /// Currently says 'REQUIREMENT: 9 and over' when DieRequirement==9, when dies cannot go over 9.
        cout << endl << "REQUIREMENT: " << DieRequirement << " and over" << endl;
        // Prints the amount of items received if gamble is won.
        cout << "PRIZE: [" << ItemNumber << "] ";
        // Prints the item name according to the char Item.
        switch(Item) {
        case 0:
            cout << "arrows" << endl;
            break;
        case 1:
            cout << "bombs" << endl;
            break;
        case 2:
            cout << "potions" << endl;
            break;
        case 3:
            cout << "whetstones" << endl;
            break;
        default:
            // No default, since ReturnItem(), which GenerateValue() calls, already has one.
            // Technically impossible for char Item to be other than b, p, w, a.
            break;
        }
        // Prints Coins deduction if you lose the gamble.
        cout << "PENALTY: [" << CoinsDeduction << "] coins" << endl << endl;
        cout << "1) Reveal Die" << endl;
        cout << "2) Shake Die" << endl;
        cout << "3) Pass" << endl << "\n";
        choice = input();
        switch (choice) {
        case 1:
            // Only breaks because the loop stops since choice==1.
            break;
        case 2:
            cout << "You shake the die." << endl;
            Sleep(SLEEP_MS);
            // Generates another random number for the die, simulating the real life die shake.
            Die=ReturnShakenDie();
            break;
        case 3:
            // Returns to Intermission().
            return;
        default:
            break;
        }
    }
    // Prints what you rolled.
    cout << "You rolled a " << Die << "." << endl;
    Sleep(SLEEP_MS);
    // Evaluates whether or not you won the bet.
    if (Die>=DieRequirement)
        // Passes in Player object to give player the items won.
    {
        WinGamble(_Player);
    } else
        // Passes in Player object to deduct experience from the player for losing the gamble.
    {
        LoseGamble(_Player);
    }
}

void Gambling::GenerateValues() {
    // Generates values for the variables used in the gamble.
    // Generates a number between 1 and 9, the number that  the player's die must be equal to or greater than.
    DieRequirement = Common::RandomInt(1, 9);
    // The amount of items won if the player win the gamble.
    ItemNumber = Common::RandomInt(1, 4);
    // The amount of experience lost if the player loses the gamble.
    CoinsDeduction=100;
    // Initializes Item equal to a random char to indicate the item won.
    Item=ReturnItem();
}

int Gambling::ReturnShakenDie() {
    // Returns a random integer between 1 and 9.
    return Common::RandomInt(1, 9);
}

char Gambling::ReturnItem() {
    // Generates a random char with a random integer selector, indicating the item won in the gamble.
    int selector=Common::RandomInt(0, 3);
    switch(selector) {
    case 0:
        // Arrows are the item.
        return 0;
    case 1:
        // Bombs are the item.
        return 1;
    case 2:
        // Potions are the item.
        return 2;
    case 3:
        // Whetstones are the item.
        return 3;
    default:
        // By default, arrows are the item if the random integer does not equal any of the above cases.
        return 0;
    }
}

void Gambling::WinGamble(Player *_Player) {
    // Executes the events when the gamble is won.
    // Uses the Player object to give player items won.
    cout << "You win the bet!" << endl;
    vector<int> drops;
    for (int i = 0; i < NUM_ITEMS; i++) {
        drops.push_back((Item == i) ? ItemNumber : 0);
    }
    // Evaluates local class variable Item to see what item was won.
    // ItemNumber is passed in to AddToInventory() to provide the number of items won.
    // The place of ItemNumber in the arguments is to specify which item was won.
    // More clarification and information in the _Player->AddToInventory(int, int, int ,int) function.
    _Player->AddToInventory(drops);
    // Used to pause the console to let the player see what they won.
    /// Must use something more efficient.
    system("PAUSE");
}

void Gambling::LoseGamble(Player *_Player) {
    // Executes the events when gamble is lost.
    // Uses the Player object passed in to deduct experience.
    cout << "You lost the bet! You lose " << CoinsDeduction << " coins!" << endl;
    // Deducts the player's experience.
    _Player->LoseCoins(CoinsDeduction);
    system("PAUSE");
}
<commit_msg>In reference to issue #129<commit_after>#include <iostream>
//#include <conio.h>
#include <vector>

#include "../include/Common.h"
#include "../include/Gambling.h"
#include "../include/Player.h"

using namespace std;
using namespace Common;

// Contains the functions needed to simulate a gamble for items.

void Gambling::Gamble(Player *_Player) {
    // A gambling arena, in which the die you roll must be equal or higher than requirement
    // Uses the Player object passed in to give won items to player.
    /// Maybe check Coins? If too low then can't gamble.
    // Generates random values for the local variables declared in the class.
    GenerateValues();
    // check if the player has enough money to play
    if (_Player->GetCoins() < CoinsDeduction) {
        // the player does not have enough money
        cout << "You need at least " << CoinsDeduction << " coins to gamble." << endl;
        Sleep(SLEEP_MS);
        return;
    }
    // Player's die. Equal to a random number between 1 and 9.
    int Die=ReturnShakenDie();
    // Initialized to analyze user input.
    int choice = 0;
    // Loops until player chooses to reveal die.
    while (choice!=1) {
        /// Since the ClearScreen() method is in class Game, system("CLS") is used instead.
        /// Must fix.
        ClearScreen();
        // Prints required die number to win gamble.
        /// Currently says 'REQUIREMENT: 9 and over' when DieRequirement==9, when dies cannot go over 9.
        cout << endl << "REQUIREMENT: " << DieRequirement << " and over" << endl;
        // Prints the amount of items received if gamble is won.
        cout << "PRIZE: [" << ItemNumber << "] ";
        // Prints the item name according to the char Item.
        switch(Item) {
        case 0:
            cout << "arrows" << endl;
            break;
        case 1:
            cout << "bombs" << endl;
            break;
        case 2:
            cout << "potions" << endl;
            break;
        case 3:
            cout << "whetstones" << endl;
            break;
        default:
            // No default, since ReturnItem(), which GenerateValue() calls, already has one.
            // Technically impossible for char Item to be other than b, p, w, a.
            break;
        }
        // Prints Coins deduction if you lose the gamble.
        cout << "PENALTY: [" << CoinsDeduction << "] coins" << endl << endl;
        cout << "1) Reveal Die" << endl;
        cout << "2) Shake Die" << endl;
        cout << "0) Pass" << endl << "\n";
        choice = input();
        switch (choice) {
        case 1:
            // Only breaks because the loop stops since choice==1.
            break;
        case 2:
            cout << "You shake the die." << endl;
            Sleep(SLEEP_MS);
            // Generates another random number for the die, simulating the real life die shake.
            Die=ReturnShakenDie();
            break;
        case 0:
            // Returns to Intermission().
            return;
        default:
            break;
        }
    }
    // Prints what you rolled.
    cout << "You rolled a " << Die << "." << endl;
    Sleep(SLEEP_MS);
    // Evaluates whether or not you won the bet.
    if (Die>=DieRequirement)
        // Passes in Player object to give player the items won.
    {
        WinGamble(_Player);
    } else
        // Passes in Player object to deduct experience from the player for losing the gamble.
    {
        LoseGamble(_Player);
    }
}

void Gambling::GenerateValues() {
    // Generates values for the variables used in the gamble.
    // Generates a number between 1 and 9, the number that  the player's die must be equal to or greater than.
    DieRequirement = Common::RandomInt(1, 9);
    // The amount of items won if the player win the gamble.
    ItemNumber = Common::RandomInt(1, 4);
    // The amount of experience lost if the player loses the gamble.
    CoinsDeduction=100;
    // Initializes Item equal to a random char to indicate the item won.
    Item=ReturnItem();
}

int Gambling::ReturnShakenDie() {
    // Returns a random integer between 1 and 9.
    return Common::RandomInt(1, 9);
}

char Gambling::ReturnItem() {
    // Generates a random char with a random integer selector, indicating the item won in the gamble.
    int selector=Common::RandomInt(0, 3);
    switch(selector) {
    case 0:
        // Arrows are the item.
        return 0;
    case 1:
        // Bombs are the item.
        return 1;
    case 2:
        // Potions are the item.
        return 2;
    case 3:
        // Whetstones are the item.
        return 3;
    default:
        // By default, arrows are the item if the random integer does not equal any of the above cases.
        return 0;
    }
}

void Gambling::WinGamble(Player *_Player) {
    // Executes the events when the gamble is won.
    // Uses the Player object to give player items won.
    cout << "You win the bet!" << endl;
    vector<int> drops;
    for (int i = 0; i < NUM_ITEMS; i++) {
        drops.push_back((Item == i) ? ItemNumber : 0);
    }
    // Evaluates local class variable Item to see what item was won.
    // ItemNumber is passed in to AddToInventory() to provide the number of items won.
    // The place of ItemNumber in the arguments is to specify which item was won.
    // More clarification and information in the _Player->AddToInventory(int, int, int ,int) function.
    _Player->AddToInventory(drops);
    // Used to pause the console to let the player see what they won.
    /// Must use something more efficient.
    system("PAUSE");
}

void Gambling::LoseGamble(Player *_Player) {
    // Executes the events when gamble is lost.
    // Uses the Player object passed in to deduct experience.
    cout << "You lost the bet! You lose " << CoinsDeduction << " coins!" << endl;
    // Deducts the player's experience.
    _Player->LoseCoins(CoinsDeduction);
    system("PAUSE");
}
<|endoftext|>


<commit_before><commit_msg>reset remote ids on inter-resource moves<commit_after><|endoftext|>