dimanche 30 avril 2023

How to call the destructor for 2 objects that has each other as reference in different files?

I have 2 classes named student and course with constructors etc. in separate files as such :

//student.h
class course;
class student {
  public:
    ~Student();
  private:
    course *course_ref;
}

// student.cpp
student::~student() {delete [] course_ref ; course_ref = NULL;}

// course.h
class student;
class course {
  public:
    ~Course();
  private:
    student *student_ref;

//course.cpp
course::~course() { delete [] student_ref; student_ref = NULL;}


I guess it has to do with the undefined behavior and compiler needs to know the body of the class before destroying it but I couldn't find a way to do it. Classes have to be in different files, *.h and *.cpp, is there any way to do it?

I've tried putting course's destructor in student.cpp but then again it doesn't know the course fully yet so got an error.

How does asmjit get code relocation when use AsmParser(&a).parse

I use asmjit in my c++ code and defined a function like below:

    // parse asm_str to byte code, return the length of byte code
    int assemble(bool isx64, unsigned long long addr, const char* asm_str, char buffer[MAX_INSTRUCTION_LENGTH])
    {
        // for test, I modified param's value
        isx64 = true;
        addr = 0x6a9ec0;
        asm_str = "call 0x00007FFF1CF8CEE0";

        auto arch = isx64 ? Arch::kX64 : Arch::kX86;

        // Initialize Environment with the requested architecture.
        Environment environment;
        environment.setArch(arch);

        // Initialize CodeHolder.
        CodeHolder code;
        Error err = code.init(environment, addr);

        if (err) {
            dbg_print_err("code.init failed, reason:%s", DebugUtils::errorAsString(err));
            return 0;
        }
        x86::Assembler a(&code);
        err = AsmParser(&a).parse(asm_str, strlen(asm_str));

        if (err) {
            dbg_print_err("AsmParser(&a).parse failed, asm_str=\"%s\" addr=0x%llx reason:%s", asm_str, addr, DebugUtils::errorAsString(err));
            return 0;
        }
        else {
            CodeBuffer& buf = code.sectionById(0)->buffer();
            memcpy(buffer, buf.data(), buf.size());
            print_byte_hex(buffer, buf.size());
            return (int)buf.size();
        }
    }

When I run this funciton and got the result of buffer is 40 E8 00 00 00 00 and not find any error. Actually, I known about that this instruction could not compile to byte code in addr(0x6a9ec0). So, I want to know how to determine if such instructions are compiled successfully in the code.

How to determine if such instructions are compiled with errors in the byte code.

Why std::declval cannot be directly replaced by std::add_rvalue_reference

According to https://en.cppreference.com/w/cpp/utility/declval, the possible implementation of declval is following:

template<typename T>
constexpr bool always_false = false;
 
template<typename T>
typename std::add_rvalue_reference<T>::type declval() noexcept
{
    static_assert(always_false<T>, "declval not allowed in an evaluated context");
}

I am trying to replace the use case of std::declval<T>() with std::add_rvalue_reference<Test>::type but it doesn't compile. Why is that?

Following is my testing code snippet:

#include <iostream>
#include <type_traits>
#include <utility>

struct Test {
    int func() {
        return 1;
    }
};

template<typename T>
constexpr bool always_false = false;
 
template<typename T>
typename std::add_rvalue_reference<T>::type Decltype() noexcept
{
    static_assert(always_false<T>, "declval not allowed in an evaluated context");
}

int main() {
    if (std::is_same_v<decltype(std::add_rvalue_reference<Test>::type.func()),int>) {
        std::cout <<"same\n";
    } else {
        std::cout <<"different\n";
    }
}

samedi 29 avril 2023

Why do associative containers have an erase overload with non-const iterator argument?

C++11 changed std::vector::erase to take a const_iterator instead of an iterator. The same thing applies to std::deque and std::list, while std::forward_list came in C++11 with erase_after, which also takes a const_iterator.

In contrast, std::set::erase kept its iterator overload and C++11 simply added the const_iterator one. The same thing applies to all associative containers: std::map, std::multiset, and std::multimap all kept the pre-C++11 iterator overload while std::unordered_set, std::unordered_map, std::unordered_multiset, and std::unordered_multimap all were introduced with both iterator and const_iterator overloads.

In fact, for all four set classes, iterator and const_iterator may very well be the same type.

So why the discrepancy? In addition to the inconsistency with the non-associative containers, there is also an inconsistency with the range erase overloads, which were all changed with C++11 to take a pair of const_iterators instead of a pair of iterators. Since an iterator must be convertible to a const_iterator, there is no need to have all four possible combinations of parameters for the range erase. Similarly, there is no need to have "all two combinations" for the single-value erase, so why keep the iterator overload?

OpenGL application not drawing/rendering anything [closed]

This is a very broad question, and I try my best to avoid those, or at least narrow them down so it's easier to fix. However, this problem I cannot seem to solve.

Recently, I rewrote my entire basic rendering engine with more optimized and efficient code. I basically used the old code as a reference to write the new code. However, in my own idiocracy, I deleted the old source code thinking the new one would work straight off the bat. To my dismay, it did not.

The problem here is that OpenGL is simply not drawing anything. I can tell the model loads, but when I move the camera around, nothing...

This could be an infinite amount of problems, so I apologize in advance. I hope it's an easy fix.

Instead of linking the source code in this question, the code is open source: here

This is the latest version of the code. All that is needed to do is open the solution and build. Any help at all would be appreciated. Thank you.

Caching BFS traversal in an undirected and unweighted graph

I have an undirected and unweighted graph with about a million nodes - visualized in a matrix format.

Representation of a sample graph:

enter image description here

The red cells are blocked.

My problem is to find the shortest distance between any two cells. The source and destination cells will be given one by one, and I need to return the shortest paths for all given cell pairs.

I looked at the following:

  • the Floyd-warshall algorithm: but it takes too much memory.
  • Dijkstra's algorithm for all nodes, but it is too slow.
  • A* could work, but would still be slow - if the shortest path needs to be found for all pairs.

Is there any other approach for it?

Since it's just a uniform matrix, I would think that there might be some pattern I am unaware of.

Can a BFS traversal be cached somehow, so that a search can resume at an already visited node rather than starting from scratch again?

jeudi 27 avril 2023

how to use gdb debuger with input test file [duplicate]

I am trying to use the gdb debugger on a c++ program that takes a text file on standard input, but I'm unable to figure out how to make the debugger work with my input. I have included my input and executable below so if someone could just show me how to make that work with the debugger I would greatly appreciate it.

./bin/bstree_tester - < /home/mydrive/computing/Labs/LabA/inputExample/020.txt 

Why am I getting a Segmentation Fault in my program?

I was trying to do this program when I noticed in my points3D method that something was causing a Segmentation fault and I don't know what caused it. The goal of this program is to test out 4 different methods and try to get a certain answer. I thought I mostly did it right until I noticed my method ~point3D. Although I fixed this problem, I cant find any problem why this would happen.

//You only need iostream, no other header files are allowed
#include <iostream>
using namespace std;

//Code for part 1
class point2D {
    int x, y;
      char* label;
public:
    int getX(){
      return x;
    }
    int getY(){
      return y;
    }
   char* getLabel(){
      return label;
    }
    void setX(int a){
      x = a;
    }
    void setY(int b){
      y = b;
    }
    void setLabel(char* g){
      label = g;
    }
    virtual void show(){
      cout << "The point data is " << "(" << x << "," << y << "," << label << ")" << endl;
    }
    point2D(int x, int y, char * label){
      this->x = x;
      this->y = y;
      label = nullptr;
      setLabel(label);
    };
    ~point2D(){
      if(label != nullptr){
        delete[] label;
      }
    };

};

//Code for part 2
class point3D : public point2D {
protected:
  int z;
public:

  int getZ(){
    return z;
  }
  void setZ(int c){
    z = c;
  }
  void show(){
    cout << "(" << getX() << "," << getY() << "," << z << "," << getLabel() << ")\n";
  };
  point3D(int a, int b, int c, char * l) : point2D(a,b,l) {
      z = c;
  };
  ~point3D();
  
};
/*
//Code for Part 3
class node {
public:
  point3D* data;
  node* next;
  static int counter;
  void show(){
    if(data != nullptr){
      data->show();
    }
  }
  node(){
    data = nullptr;
    next = nullptr;
  }
  ~node(){
    if(data != nullptr){
      delete[] data;
    }
  }
};

//Code for Part 4
class linkedList {
    node* head;
public:
  bool empty() {
        return head == nullptr;
    }
    int size() {
        int c = 0;
        node* it = head;
        while (it != nullptr) {
            c++;
            it = it->next;
        }
        return c;
    }
    bool push(point3D* np) {
        node* nn = new node();
        nn->data = np;
        return push(nn);
    }
    bool push(node* nn) {
        nn->next = head;
        head = nn;
        return true;
    }
    bool append(point3D* np) {
        node* nn = new node();
        nn->data = np;
        return append(nn);
    }
    bool append(node* nn) {
        if (head != nullptr) {
            node* it = head;
            while (it->next != nullptr) {
                it = it->next;
            }
            it->next = nn;
        }
        else {
            head = nn;
        }
        return true;
    }
    void show() {
        node* it = head;
        while (it != nullptr) {
            it->show();
            it = it->next;
        }
    }
    linkedList() {
        head = nullptr;
    }
  ~linkedList(){
    node * it = head;
    node = nullptr;
    while(it != nullptr){
      
    }
  }
};

int node::counter = 0;
*/
int main() {
    int testMode;//Determines the test to be executed
    std::cin >> testMode;
    switch (testMode) {
    case 1:{
        //1) Test part 1
        point2D * p12D = new point2D(12, 24, (char*)"test 1");
        p12D->setX(25);
        p12D->setLabel((char*)"Landing Zone A");
        p12D->show();
        delete p12D;
        break;
    }
   case 2: {
        //2) Test part 2
        point3D* p13D = new point3D(12, 24, 36,(char*) "test 2");
        p13D->setY(50);
        p13D->setLabel((char*)"Landing Zone B");
        p13D->show();
        point2D* p22D = dynamic_cast<point2D*>(p13D);
        p22D->show();
        std::decay_t(&p13D);
        break;
    }
    /*
    case 3: {
        //3) Test part 3
        node* nn = new node();
        std::cout << node::counter << std::endl;
        delete nn;

        nn = new node();
        std::cout << node::counter << std::endl;
        point3D* p23D = new point3D(48,60,72,"Landing Zone C");
        nn->data = p23D;
        nn->show();
        
        delete nn;

        break;
    }
    case 4: {
        //4) Test part 4
        linkedList* myList = new linkedList();
        int i;
        for (i = 0; i < 3; i++) {
            node* nn = new node();
            point3D* p3D = new point3D(12*i, 24*i, 36*i, "Landing Zone ");
            myList->addNode(p3D);
        }
        myList->show();

        point3D* p3D = new point3D(12 * i, 24 * i, 36 * i, "Landing Zone ");
        myList->insertNode(p3D, 1);
        myList->show();
        delete myList;
        break;
    }
    */
    }
    return 0;
    
}

I have tried multiple things and got a error that was void operator delete(void*, std::size_t)’ called on unallocated object ‘p13D.

mardi 25 avril 2023

usleep() behaving in a weird way

I am working on one of my assignments and I have run into an issue.

I wrote my test cases, and I am pushing back the boolean values returned by the functions into a vector.

While trying to print the test results, I ran into an issue with usleep(). I am trying to print out std::cout << "\n\n*** RUNNING ALL TESTS ***"; first, and then pause for a second, and then print the results.

For some reason, my program pauses first, and then prints it all out at once. Is there something I have missed or overlooked?

I am using a makefile to compile all my code, and I made sure the path is correct (I am not working on the wrong file and compiling a completely different file).

p.s Is there a way I can make my runAllTests() look prettier?

A function that runs all tests:

std::vector<bool> ShelterBST::runAllTests(std::vector<bool> &testResults) {
  testResults.push_back(testSearch());
  testResults.push_back(testSearchB());
  testResults.push_back(testInsert()); 
  testResults.push_back(testFindParent());
  testResults.push_back(testFindPredecessor());
  testResults.push_back(testDeleteNode());
  testResults.push_back(testDestroyTree());
  testResults.push_back(testNumberOfChildren());
  testResults.push_back(testNumberOfNodes());
  testResults.push_back(testNumberOfInternalNodes());
  testResults.push_back(testHeight());
  testResults.push_back(testBalance()); 
  testResults.push_back(testNodesAtLevel()); 
  testResults.push_back(testInOrder());
  testResults.push_back(testPreOrder()); 
  testResults.push_back(testPostOrder());
  
  return testResults;
}

The part that includes my question:

void ShelterBST::test() {
  using std::vector;
  #define PASS true
  #define FAIL false
  std::string const TEST = "*** TEST ";
  std::string const PASSED = "  PASSED ***";
  std::string const FAILED = "  - FAILED ###";
  std::string const PASSED_2 = " PASSED ***";
  std::string const FAILED_2 = " - FAILED ###";
  long int const PAUSE = 1000000;

  vector<bool> testValues;
  std::cout << "\n\n*** RUNNING ALL TESTS ***";
  usleep(PAUSE);
  runAllTests(testValues);
  std::cout << std::endl << std::endl;
  for(auto i = 0; i < (int)testValues.size(); i++) {
    if(testValues[i] == PASS && i < 9) {
      std::cout << TEST << i+1 << PASSED << std::endl;

    } else if(testValues[i] == FAIL && i < 9) {
      std::cout << TEST << i+1 << FAILED << std::endl;

    } else if(testValues[i] == PASS && i > 9) {
      std::cout << TEST << i+1 << PASSED_2 << std::endl;

    } else if(testValues[i] == FAIL && i > 9) {
      std::cout << TEST << i+1 << FAILED_2 << std::endl;
    }
  }
}

makefile:

CC=g++
CFLAGS= -g -Wall -Werror -pedantic -std=c++11

SRCS=ShelterBST.cpp assignment3.cpp
OBJS=$(subst .cpp,.o,$(SRCS))

all: prog

prog: $(OBJS)
    $(CC) $(CFLAGS) $(OBJS) -o prog

%.o: %.cpp
    $(CC) $(CFLAGS) -c $< -o $@

clean:
    rm -f $(OBJS) prog

Value category of member enumerator

According to cppreference.com a.m is prvalue the member of object expression, where m is a member enumerator or a non-static member function[2];

Does it mean for object expression ie a.m where m is a member of a of enumeration type, the value category of expression itself would be prvalue?

As per my following testing, it does not seem to be the case. What did I miss?

enum class Color : char {
    Red = 'r'
};

struct Test {
    Color c;
};

void func(Color&&) {
    std::cout << "rvalue ref\n";
}

void func(Color&) {
    std::cout << "lvalue ref\n";
}

int main()
{
    Test t;
    func(t.c);
    return 0;
}

Output: lvalue ref

How can I access a C++ function if an inline namespace has the same function?

The following situation:

namespace abc{
    inline namespace x{
        int f() { return 5; }
    }

    inline namespace y{
        int f() { return 6; }
    }

    int f() { return 7; }

    void g(){
        x::f();   // okay
        y::f();   // okay

        f();      // error: ambiguous!
        abc::f(); // error: ambiguous!
    }
}

GCC and clang agree, here is the GCC error message:

<source>: In function 'void abc::g()':
<source>:16:10: error: call of overloaded 'f()' is ambiguous
   16 |         f();      // error: ambiguous!
      |         ~^~
<source>:10:9: note: candidate: 'int abc::f()'
   10 |     int f() { return 7; }
      |         ^
<source>:3:13: note: candidate: 'int abc::x::f()'
    3 |         int f() { return 5; }
      |             ^
<source>:7:13: note: candidate: 'int abc::y::f()'
    7 |         int f() { return 6; }
      |             ^
<source>:17:15: error: call of overloaded 'f()' is ambiguous
   17 |         abc::f(); // error: ambiguous!
      |         ~~~~~~^~
<source>:10:9: note: candidate: 'int abc::f()'
   10 |     int f() { return 7; }
      |         ^
<source>:7:13: note: candidate: 'int abc::y::f()'
    7 |         int f() { return 6; }
      |             ^
<source>:3:13: note: candidate: 'int abc::x::f()'
    3 |         int f() { return 5; }
      |             ^
Compiler returned: 1

I can explicitly specify the inline namespace to access the overload there, but what about the abc::f() version? I can't find a syntactical way to access it. Is there really no way to do this?

I know the question is not very relevant to practice. Nevertheless, I find it interesting.

How to build Google test in Visual Studio 2013?

I am trying to build Google test in VS 2013 Pro. Because it supports C++11, so I downloaded Google test version 1.12.0 in https://github.com/google/googletest/releases/tag/release-1.12.0.

After that I used CMake GUI to create .sln file and load into Visual Studio.

enter image description here

Then I tried to build the solution. But there were so many errors relating to gtest-port.h and gtest-internal.h.

enter image description here

I have googled but not much info about this. Could you help me to solve this? I am totally a newbie with Google test.

I am getting sigterm repeatedly [closed]

Here is the problem: https://www.spoj.com/problems/SUMFOUR/ Here is my code: https://pastebin.ubuntu.com/p/2xS3dFcttD/

I am getting sigterm here.Where is the problem

I was expecting this: 6 -45 22 42 -16 -41 -27 56 30 -36 53 -37 77 -36 30 -75 -46 26 -38 -10 62 -32 -54 -6 45 Output: 5

lundi 24 avril 2023

Directx9 does not work on Intel 12th generation built-in graphics

Directx9 does not work properly on current intel 12th generation mobile gpu.

The strange thing is that it worked fine in 32bit environment, but when I rebuild in 64bit, I can't CreateDevice directx9.

However, amd built-in graphics or previous generation intel gpu work properly.

The current development environment is c++11, windows sdk 2010.

I am using visual studio 2010.

I've seen news that intel doesn't support directx9 starting with 12th gen chips. It worked fine in a 32-bit environment, so I switched to 64-bit. Since then I can't use directx9 properly.

Is there something I'm missing?

dimanche 23 avril 2023

C# learning from intermediate to advanced topics

Hello Everyone i would like to mention i have been on and off as a game developer so for me i use both unity and unreal for the games i make My question over here how do i make my decisions while choosing the correct methodology This question is not for single scenario this is to choose the methodology without searching a youtube tutorial. Let's say i want to make a playercontrol i know we can use vector3 for transformation/positioning/moving the player and quaternion for the rotation and destroy.game object for killing an object and i know there are more concepts too integrate but what would be the best way to optimize the code or the language i use exactly to my need and give the player smoother experience

I have tried c# and c++ both while doing my practice but whenever i get an idea of certain mechanics i seriously type the issue in youtube which makes me blindly follow the method and if at all i stuck in something and i again go watch youtube videos which is actually making me dependent on something to avoid these issues can someone guide me how to learn c# or C++ and write the program according to my requirement without following any kind of resources if at all i need to follow ressources which is the best way to follow

Thank you in advance

c++ how to create 2d vector in heap?

I know I can create 2d vector in the stack for

 vector<vector<int>> dp(10,vector<int>(10,0));

But the question is, how do I create that in heap?

can I do something like?

vector<vector<int>> dp(10,vector<int>(10,0)) = new vector<vector<int>>(10,vector<int>(10,0));

samedi 22 avril 2023

How can I create a method with a variable number of arguments in a class with Q_OBJECT? [duplicate]

I'm trying to create an object that both has Qt events, AND has a function that can accept a variable number of arguments. This is a minimal example, although lacking in the events, but with the QObject stuff needed for the events. The problem is that it generates a link error. It's based on the first answer to this SO ?: [Variable number of arguments in C++?][1]

#include <iostream>
#include <string>
#include <initializer_list>
#include <qobject.h>
#include <qdebug.h>

class aClass : public QObject
{
    Q_OBJECT

public:
    template <typename T>
    void func(T t)
    {
        qDebug() << t;
    }

    template<typename T, typename... Args>
    void func(T t, Args... args) // recursive variadic function
    {
        qDebug() << t;

        func(args...) ;
    }
};

int main()
{
    QString str1( "Hello" );

    aClass a;
    a.func(1, 2.5, 'a', str1);
}

The errors I get are:

main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __cdecl aClass::metaObject(void)const " (?metaObject@aClass@@UEBAPEBUQMetaObject@@XZ)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void * __cdecl aClass::qt_metacast(char const *)" (?qt_metacast@aClass@@UEAAPEAXPEBD@Z)
main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual int __cdecl aClass::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@aClass@@UEAAHW4Call@QMetaObject@@HPEAPEAX@Z)

If I remove the QObject stuff, it works. If the functions are outside the class it works. Is there a way to have both in the same class? I want to have three arguments of predetermined types as the first arguments, not of the same types, and then from zero to any number of QString arguments after that. This is for a project in c++11, but a c++17 answer would be acceptable, too. [1]: https://stackoverflow.com/a/16338804/1378243

Function Template Overloading with Different Return Types

Following code snippets are from https://en.cppreference.com/w/cpp/language/function_template#Function_template_overloading.

How is it possible to overload functions/function templates with return type A<I+J> Vs A<I-J>?

Did the page really mean that overload #1 & overload #2 compose valid function overload set?

Or I misunderstood the meaning of the page?

template<int I, int J>
A<I+J> f(A<I>, A<J>); // overload #1
 
template<int K, int L>
A<K+L> f(A<K>, A<L>); // same as #1
 
template<int I, int J>
A<I-J> f(A<I>, A<J>); // overload #2

I have tried followings in godbolt.org which did not compile as expected with errors:

ASM generation compiler returned: 1
<source>: In function 'int main()':
<source>:48:24: error: call of overloaded 'func<1, 2>(A<1>, A<2>)' is ambiguous
   48 |     A<-1> a = func<1,2>(A<1>{}, A<2>{});
      |               ~~~~~~~~~^~~~~~~~~~~~~~~~
<source>:35:8: note: candidate: 'A<(I + J)> func(A<I>, A<J>) [with int I = 1; int J = 2]'
   35 | A<I+J> func(A<I>, A<J>) {
      |        ^~~~
<source>:41:8: note: candidate: 'A<(I - J)> func(A<I>, A<J>) [with int I = 1; int J = 2]'
   41 | A<I-J> func(A<I>, A<J>) {
      |        ^~~~
template <int>
struct A {
};

template <int I, int J>
A<I+J> func(A<I>, A<J>) {
    std::cout << "func1\n";
    return A<I+J>{};
}

template <int I, int J>
A<I-J> func(A<I>, A<J>) {
    std::cout << "func2\n";
    return A<I-J>{};
}

int main()
{
    A<-1> a = func<1,2>(A<1>{}, A<2>{});
    return 0;
}

Is there a better practice than defining this constexpr struct in a header file?

I'm trying to design a program to play musical notes

To test each note, I created a series of constexpr structs to contain the frequency and period of each note in a header file and call them in the source files I want to test them.

MusicNotes.hpp

typedef struct Note_t{
    float frequency_hz {};
    uint32_t period_us {};
} Note_t;

class MusicalNotes{
public:
    MusicalNotes() {};
    void playNote(Note_t musicNote, uint32_t duration_ms);

    static constexpr Note_t C0 { 16.35, 61162};
    static constexpr Note_t CSh0_Db0 { 17.32, 57736};
...
    static constexpr Note_t ASh8_Bb8 { 7458.62, 134};
    static constexpr Note_t B8 { 7902.13, 126};
};

In another source file, I'll call something like:

void sendNote(void) {
    musicalNotes.playNote(musicalNotes.E4, 500);

I wish to have a the ability to call these Notes from a number of source files and I never plan to change these values which is why I preferred constexpr. However, I know there are pitfalls to defining all of this in a header file such as unnecessary copies of notes in each source file. I have run into issues regarding modifying an expression's lvalue and requiring an in-class initializer (I assume the class definition) when attempting to forward declare my current method.

Is it better practice to have these structs instead not be constexpr at all, forward declare them, and then define them in my MusicalNotes constructor, or will the multiple copies of the struct not represent a big problem?

I have a problem while installing opencv in m1 Mac

I have a problem while installing opencv in m1 Mac:

Undefined symbol: cv::Mat::Mat(int, int, int)
Undefined symbol: cv::Mat::~Mat()
Undefined symbol: cv::imshow(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, cv::_InputArray const&)
Undefined symbol: cv::waitKey(int)

Linker command failed with exit code 1 (use -v to see invocation)

I get this error when I try to run normal code with opencv:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main(){
    cv::Mat imMat(400,400, CV_8UC3);

    for(int y = 0 ; y < imMat.rows; y++){
        for(int x = 0 ; x < imMat.cols; x++){
            cv::Vec3b &p = imMat.at<cv::Vec3b>( y, x);
            p[0] = x;
            p[1] = y;
            p[2] = (int)((x+y)/2);
        }
    }
    imshow("openCVTest",imMat);
    waitKey(0);
    return 0;
}

To install OpenCV in Xcode through Homebrew, I followed these steps:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew update
brew install opencv
pkg-config --modversion opencv4

And finally I added the installation in Header Search Paths (Xcode) with c++ Language Dialect C++-11.

Static typing concept in C++ [duplicate]

I am going through C++ primer (fifth edition). In that on page 46 'Key Concept: Static Typing' section it says and I quote

As we’ve seen, the type of an object constrains the operations that the object can perform. In C++, the compiler checks whether the operations we write are supported by the types we use. If we try to do things that the type does not support, the compiler generates an error message and does not produce an executable file.

Do the authors mean that static typing (done by type checking) checks whether a type actually supports an operation, for example, if we have have defined a type 'Calc' with an Add() method, does the compiler actually verifies that Add() is defined as part of static typing?

Or do they mean that if the user of the type is calling Multiply() but if the doesn't have that then compiler checks it as part of static typing?

Which of these two are they referring to in this context?

I googled 'static typing C++ primer' and stackoverflow results didn't seem to have any related questions on this.

jeudi 20 avril 2023

C++11 code for removing delay-queue elements in temporal order

I need to remove elements from a delay-queue in temporal order (where earlier elements have higher priority). I have a C++11 solution, but I'm wondering if there isn't a better one.

The relevant sections of code are these. (Please forgive or correct any typos.)

#include <chrono>
#include <condition_variable>
#include <mutex>
#include <queue>
...
using Clock = std::steady_clock;
using Value = ...; ///< The values stored in the delay-queue

std::mutex              mutex;
std::condition_variable cond;
struct Elt {
    Value             value;
    Clock::time_point time;
    Elt(const Value& value, const Clock::time_point& time)
        : value(value)
        , time(time)
    {}
    bool operator<(const Elt& rhs) {
        return time > rhs.time; // Later times have lower priority
    }
}
std::priority_queue<Elt> queue; ///< The delay-queue
...
    // On one thread
    Clock::duration delay = ...; ///< The delay before the value should be removed
    std::lock_guard guard{mutex};
    queue.emplace(value, Clock::now() + delay);
    cond.notify_one();
...
    // On another thread
    std::unique_lock lock{mutex};

    if (queue.empty())
        cond.wait(lock, [&]{return !queue.empty();});

    auto pred = [&]{return queue.top().time >= Clock::now();};
    cond.wait_until(lock, queue.top().time, pred);

    auto value = queue.top().value;
    queue.pop();
...

In particular, I wonder if two condition-variable calls are necessary to ensure correct behavior under all circumstances.

Is there a "better" way?

Understanding Async function in c++

I am relatively new to c++ programming. I am trying to understand the meaning of this header in std::async library

template< class Function, class... Args >
std::future<typename std::result_of<typename std::decay<Function>::type(
        typename std::decay<Args>::type...)>::type>
    async( Function&& f, Args&&... args );```



Can someone breakdown and explain the return types of this please? 

    `std::future<typename std::result_of<typename std::decay<Function>::type(
            typename std::decay<Args>::type...)>::type>`

    std::future<std::invoke_result_t<std::decay_t<Function>,
                                     std::decay_t<Args>...>>

    [[nodiscard]] std::future<std::invoke_result_t<std::decay_t<Function>,
                                                   std::decay_t<Args>...>>

Grpc channel state going to ready state from transient failure state when trying to connect server of invalid ip address after few minutes

I am running grpc 1.24 version. server is of invalid ip address. when client tries to connect server, grpc state going to connecting and then transient failure. this toggling is happening for few minutes. but after 8 or 9 minutes of observation, suddenly grpc status changes from transient failure to ready instead of connecting state. grpc status should never change to ready if server ip address is invaid. so anybody has fix for this ?

I checked in 1.46 grpc version. issue is not there but due some project concerns, I can't upgrade to 1.46 version. please help me with this.

grpc status changes from transient failure to ready instead of connecting state. this should never happen.

Can the "delete" keyword be used for virtual functions?

Consider the following scenario: Class A defines many virtual functions. Class B and class C inherit from class A, but I want some virtual functions in class A to be available only in class B and not in class C.

I wrote the following code to try it out:

class A
{
public:
    A() { }
    virtual void play() 
    {
        printf("A::play() \n");
    }
};

class B : public A
{
public:
    B() { }
    virtual void play() = delete;
private:

};

The error is as follows: error C2282: "B::play" cannot be overwritten "A::play"

mercredi 19 avril 2023

CMake failing to tell MSVC to use C++11?

I'm using CMake to generate the build system of a library of mine. I have some example programs, while I build with the language standard set to C++11:

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

Now, for a Windows build, I (or rather GitHub) is using MSVC 16 on Windows 10. For this program:

add_executable(bandwidthtest modified_cuda_samples/bandwidthtest/bandwidthtest.cpp)

I get this compilation command generated by CMake (I think it's CMake 3.26.3; lines broken for readability):

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\bin\HostX64\x64\CL.exe
/c /I"D:\a\cuda-api-wrappers\cuda-api-wrappers\src"
/I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\include" /nologo /W4 
/WX- /diagnostics:column /O2 /Ob2 /D _MBCS /D WIN32 /D _WINDOWS /D NDEBUG 
/D _CRT_SECURE_NO_DEPRECATE /D _CRT_SECURE_NO_WARNINGS 
/D _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING /D "CMAKE_INTDIR=\"Release\"" 
/Gm- /EHsc /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Zc:inline /Fo"bandwidthtest.dir\Release\\" /Fd"bandwidthtest.dir\Release\vc142.pdb" /external:W0 
/Gd /TP /errorReport:queue  
/external:I "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.7/include" /Zc:__cplusplus 
"D:\a\cuda-api-wrappers\cuda-api-wrappers\examples\modified_cuda_samples\bandwidthtest\bandwidthtest.cpp"

So, this doesn't have an /std option. It does have /Zc:__cplusplus, but I added that one myself (I think CMake should have added it as well, but that's a known open issue).

Why does CMake not add /std:c++11?

mardi 18 avril 2023

Bind boost::asio socket to new port

I haven’t yet successfully found a way to change the port of a boost asio udp socket at run time, after the initialization. Is this possible or would I have to close the socket and re-open with a completely new socket? Thanks in advance.

For some background, I initialized the socket using socket(io_service, udp::endpoint(udp::v4, port)) and then use an async_receive_from() function to receive the data.

no matching constructor for initialization of 'std::map

i am trying to initialize the following map in c++11

#include <map>
std::map<char, const char []> nomi = {
    { (char) 0, "Oggetto" },
    { (char) 1, "Entity" },
    { (char) 2, "Player" },
    { (char) 3, "Proiettile" },
    { (char) 4, "SaltoInAlto" },
    { (char) 5, "SuperVelocita" },
    { (char) 6, "Volo" },
    { (char) 7, "Pavimento" }
};

if i use previous versions i get different errors since i can't initialize this way a map... so i am using -std=c++11

Compilation error when forwarding functions with C++11: using variables from templates in lambda

This is the toy program that I try to compile:

#include <functional>

template<typename Func, typename... Args>
int do_something_1(int foo_1, Func&& func, Args&&... args, int foo_0 = 0) { 
    int var_1 = foo_0 + 2 * foo_1; 
    return std::forward<Func>(func)(var_1, std::forward<Args>(args)...);
};

template<typename Func, typename... Args>
int do_something_2(int foo_2, Func&& func, Args&&... args) { 
    int var_2 = 10 - foo_2; 
    return do_something_1(3, std::forward<Func>(func)(var_2, std::forward<Args>(args)...));
};


int main (void) {
    return do_something_2(1, [&](int var_1, int var_2) { return (var_1 * var_2); });
}

And this is the error that I get:

<source>: In instantiation of 'int do_something_2(int, Func&&, Args&& ...) [with Func = main()::<lambda(int, int)>; Args = {}]':
<source>:18:83:   required from here
<source>:13:54: error: no match for call to '(main()::<lambda(int, int)>) (int&)'
   13 |     return do_something_1(3, std::forward<Func>(func)(var_2, std::forward<Args>(args)...));
      |                              ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:18:30: note: candidate: 'main()::<lambda(int, int)>'
   18 |     return do_something_2(1, [](int var_1, int var_2) { return (var_1 * var_2); });
      |                              ^
<source>:18:30: note:   candidate expects 2 arguments, 1 provided

It is an extended version of another toy program that gave me some troubles: Why do I get "candidate expects 2 arguments, 1 provided" compilation error when forwarding functions with C++11?

I want to multiply var2 = 10 - 1 = 9 (line 11), var1 = 0 + 2 * 3 = 6 (line 5), result = 6 * 9 = 54 (line 17)

I don't know how to solve it neither where I can find examples/tutorials in the internet.

lundi 17 avril 2023

In C++, are using reference types for member fields considered proper usage? Particularly when memory is allocated and owned outside the class

When memory is allocated and owned outside a class, is it cool to use a reference member field to reference the memory rather than passing it through as a pointer?

I'm mostly looking for best practices and what is and isn't "proper" usage.

There can't be any smart pointers.

Something like:

struct Fizz
{
    std::vector<bool> m_results;
    bool m_finalResult;
};

class Bar
{
public:
    Bar(Fizz& _givenFizz)
        : m_heldFizz(_givenFizz)
    {
    }

    void StartRunningThingsAsync()
    {
        // Run calculations with m_heldFizz.m_results asyncronously and then
        //    return from the other thread using the signal
        {
            m_heldFizz.m_finalResult = m_heldFizz.m_results[0];
            emit SignalStuffIsDone();
        }
    }

Q_SIGNALS:
    void SignalStuffIsDone();

private:
    Fizz& m_heldFizz;
};

class Foo
{
public:
    void RunCalculations()
    {
        m_usedFizz = new Fizz();
        m_usedFizz->m_results = {true, false};

        m_usedBar = new Bar(*m_usedFizz);
        connect(m_usedBar, &Bar::SignalStuffIsDone, this, &Foo::OnSignalStuffIsDone);
        m_usedBar->StartRunningThingsAsync();
    }

public Q_SLOTS:
    void OnSignalStuffIsDone()
    {
        if ( m_usedFizz->m_finalResult )
        {
            // Do some stuff
            std::cout << "Result is True";
        }
        else
        {
            // Do some different stuff
            std::cout << "Result is False";
        }

        delete m_usedBar;
        delete m_usedFizz;
    }

private:
    Fizz* m_usedFizz;
    Bar* m_usedBar;
};

int main(int argc, char* argv[])
{
    Foo foo1 = Foo();
    foo1.RunCalculations();
    std::cout << "Done";
}

I'm not sure if that's something that's ok over vs having Bar be something more like:

class Bar
{
public:
    Bar(Fizz* _givenFizz)
        : m_heldFizz(_givenFizz)
    {
    }

    void StartRunningThingsAsync()
    {
        // Run calculations with m_heldFizz.m_results asyncronously and then
        //    return from the other thread using the signal
        {
            m_heldFizz.m_finalResult = m_heldFizz.m_results[0];
            emit SignalStuffIsDone();
        }
    }

Q_SIGNALS:
    void SignalStuffIsDone();

private:
    Fizz* m_heldFizz;
};

How do i sort the words in a vector in alphabetical order?, (all letters in each word need to be accounted for)

Im trying to make a function that sorts the words in a vector an puts them in alphabetical order, and if the letters are all the same letters the word with fewest letters ends up higher in the vector.

Right now everything seems to work except when words with all the same letters end up in a random order.

For examlpe the words a, aaa and aaaa would end up in a random order but i would want a to be at the top of the list and aaaa at the bottom.

void sortWords()
{
    for (int i = 0; i < wordList.size(); i++)
    {
        for (int j = 0; j < wordList.size(); j++)
        {
            string temp;
            for (int y = 0; y < wordList[i].size(); y++)
            {
                if (wordList[i][y] < wordList[j][y] && i != j) 
                {
                    temp = wordList[i];
                    wordList[i] = wordList[j];
                    wordList[j] = temp;
                    break;
                }
                else if (wordList[i][y] > wordList[j][y] && i != j)
                {
                    break;
                }

            }
                
        }
    }
}

samedi 15 avril 2023

Why we need to use QOverload in connect two signal and slot?

I saw an example for running a TCP Server with Qt. In this example a class was created(class name is Client) and in constructor of this class there is 5 connection between signals and slots of QTcpSocket and Client class. In one of connection this code was writed: connect(&socket,QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::errorOccurred),this,&Client::error); I am familiar with signal and slot mechanism and how to connect. Now my questions are:
1-What is the role of "of" in above code?
2-According to that 'errorOccurred' signal exist in 'QAbstractSocket', why we use QOverload?
3-If it is possible some one explian part of QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::errorOccurred). This Part with this format is ambiguous for me. Thanks a lot.

vendredi 14 avril 2023

reference of global functions not deduced correctly

I am using gcc12.2 and find that the following code compiles and produces wierd results try it in godbolt. (PS: Switching to clang shows the same result)

#include <iostream>
void global() { /*std::cout << "global()" << std::endl;*/ }

template <typename T> // universal reference
void invoke(T&& func, const std::string& tag) { 
    if constexpr (std::is_rvalue_reference_v<T>) {
        std::cout << "rvalue reference " << tag << std::endl;
    }
    else if constexpr (std::is_lvalue_reference_v<T>) {
        std::cout << "lvalue reference " << tag << std::endl;
    }
    else {
        std::cout << "non-reference " << tag << std::endl;
    }
    func(); 
}

template <typename T>
struct Test {
    Test(T&& x, const std::string& tag) // rvalue reference, not universal reference 
    {
        if constexpr (std::is_rvalue_reference_v<T>) {
            std::cout << "rvalue reference " << tag << std::endl;
        }
        else if constexpr (std::is_lvalue_reference_v<T>) {
            std::cout << "lvalue reference " << tag << std::endl;
        }
        else {
            std::cout << "non-reference " << tag << std::endl;
        }
    }
};

int main() {
    int && x = 3;
    using RRef = void (&&)();
    RRef rref = global;
    using LRef = void (&)();
    LRef lref = global;

    std::cout << "RRef       is rvalue reference " << std::is_rvalue_reference_v<RRef> << std::endl;
    std::cout << "rref       is rvalue reference " << std::is_rvalue_reference_v<decltype(rref)> << std::endl;
    std::cout << "move(rref) is rvalue reference " << std::is_rvalue_reference_v<decltype(std::move(rref))> << std::endl;
    std::cout << "x          is rvalue reference " << std::is_rvalue_reference_v<decltype(x)> << std::endl;
    std::cout << "move(x)    is rvalue reference " << std::is_rvalue_reference_v<decltype(std::move(x))> << std::endl;

    std::cout << "==== invoke ==== " << std::endl;
    invoke(global, "global");
    invoke(rref, "rref");
    invoke(std::move(rref), "rref2");
    invoke(lref, "lref");
    invoke(std::move(lref), "lref2");

    std::cout << "==== Test ==== " << std::endl;
    Test(global, "global");
    Test(rref, "rref");
    Test(std::move(rref), "rref2");
    Test(lref, "lref");
    Test(std::move(lref), "lref2");

    std::cout << "==== Test int ==== " << std::endl;
    // Test(x, "x");  // cannot bind lvalue to rvalue-reference
    Test(std::move(x), "move(x)");
}

The output is as following for gcc 12.2:

RRef       is rvalue reference 1
rref       is rvalue reference 1
move(rref) is rvalue reference 0   // why is this no longer rvalue reference
x          is rvalue reference 1
move(x)    is rvalue reference 1
==== invoke ==== 
lvalue reference global  // why are they all lvalue reference
lvalue reference rref
lvalue reference rref2
lvalue reference lref
lvalue reference lref2
==== Test ==== 
non-reference global  // why they are non-reference
non-reference rref
non-reference rref2
non-reference lref
non-reference lref2
==== Test int ==== 
non-reference move(x)

Could you please explain why we get the following output:

  1. std::move(rref) is an lvalue reference while std::move(x) is an rvalue reference
  2. when passing the functions to invoke, which accepts universal reference, the deduced type are all lvalue-reference, indicating lvalue references are passed to the invoke
  3. when passing the functions to Test, which accepts only rvalue references, the various inputs are all accepted, indicating they are all rvalue references.

Passing reference of int behaves normal, while passing reference of function behaves quite wierd.

Using a member std::tuple to iterate through an object's member vectors

I'm trying to iterate through an object's member std::vectors, using a member std::tuple that contains the references of the member vectors.

A simple example would be like this:

#include <iostream>
#include <vector>
#include <tuple>
struct S {
    std::vector<int> a;
    std::vector<double> b;
    std::tuple<std::vector<int>&, std::vector<double>&> tup{a, b};
};
int main() {
    S s; 
    s.a = {2, 3};
    s.b = {5.1, 6.1};
    std::apply([&](auto&... v){
        ((std::cout << v.size()), ...);
    }, s.tup);
}

This works, but the problem is that if I assign the object s to an std container, the references tup is holding can be dangling references. Such as:

    std::map<int, S> myMap;
    myMap[3] = s; // s.a and s.b has been copied to different addresses.
    auto& v = std::get<0>(myMap.at(3).tup); // -> still refers to the previous s.a, not the copied one.

Is there any decent way to solve this problem? I want the references to refer to the newly copied members, not the original ones so that the member vectors of the new object can be iterated through using the member tuple.

(This question is being written after asking this question.)

jeudi 13 avril 2023

Insert in std::map without default empty constructor

I have instances of std::map<std::string,Foo> where I insert and fill data. The class Foo is default-constructible, default-copyable. Then I do it by this (simple) way:

std::map<std::string,Foo> data;
for(std::string const& key : keys)
{
  assert(data.count(key) == 0); // it's assumed that the keys not already exist
  Foo& foo = data[key];
  foo.fill(blahblah);
}

After refactoring, the class Foo lost the default empty constructor. What are the (simple) alternatives to insert and fill data ? For the moment, I replaced by this but I don't know if it's the best/simplier way to refactor the code:

std::map<std::string,Foo> data;
for(std::string const& key : keys)
{
  assert(data.count(key) == 0); // it's assumed that the keys not already exist
  Foo& foo = data.emplace(key, Foo(requirement)).first->second;
  foo.fill(blahblah);
}

I also think it could be possible with insert, insert_or_assign, emplace, emplace_hint, try_emplace. I'm a little bit lost with all the possibilities...

I'm interested in solutions for C++11 or C++17.

C++ How to Programatically Change a Call Instruction at Runtime

Before getting into the details of the problem, I would like to disclose that this was handed to me as a research task, so it may or may not be possible. Simply, the end goal will be to have a class, that is able to call one of two functions based on a runtime condition, with minimal overhead. Our class will have two main methods:

(1) set_direction(bool) : here, we want to programatically change the call instruction in the next method. We can employ any methods to do so here, some of which I explored are binary editing, hooking, or even changing the contents of a defined executable buffer.

(2) branch() : here we will call one of two of the functions, selected by the above method. The key part is we want to do this with minimal overhead. That means, no pointer dereferencing and conditionals, just simply a CALL (or JMP) to an absolute address.

Our code will look something like this:

class BranchChanger
{
   private:
       func if_branch_func;
       func else_branch_func;
       /* possibly other stuff here as well */

   public:
       BranchChanger(func if_branch, func else_branch);
       void set_direction(bool); // change method called by 'branch' programatically
       auto branch(); // call either if_branch or else_branch directly with minimal overhead
}

Our main program should look like this:

#include <branch.h>

int add(int a, int b) { return a + b; }

int sub(int a, int b) { return a - b; }

int main() {
   BranchChanger branch = BranchChanger(&add, &sub);
   bool condition = rand() % 2; // our runtime condition
   branch.set_direction(condition);
   branch.branch(); // call either add or sub with minimal overhead
}

The problem is, what we want to happen when branch is called is this:

CALL <some_address>

But in reality, what always happens is this:

CALL QWORD PTR [<some_address>]

Due to how function pointers work, we cannot obtain the address of the function this way, because dereferencing function pointers just decay back to a pointer to the function. If we define an executable buffer with bytecode that we can edit, which we can allocate with some neat linux system calls, even this would need to be accessed through a pointer which we do not want. I have tried function hooking (including trampolines, detours ect), inline asm, indirect function compiler attributes, and even trying to stuff with symbols. However I have had no success because the branch() method will always involve some sort of indirection due to pointer dereferencing.

A really brute force idea I had would be to modify the current ELF in place, however I am not sure how feasible this is. What I wanted to do is manually copy the address of either of functions in the ELF, paste it within the body of branch, when set_direction is called. As you can see I am running out of ideas and I would appreciate some fresh eyes to look at the problem, maybe I am missing something (or maybe this is not possible at all).

Note, consider the desired syntax of the class as a placeholder, it may not be possible to actually do what we want using it, but its something we are aiming for.

All responses will be appreciated.

mercredi 12 avril 2023

How do I create a static member variable of an object that has static variables itself? [duplicate]

Is there a robust way to write a class that has a static member variable when that object itself has static variables of its own? In this example provided below, where Bar has a static variable of type Foo, and Foo has a static variable of type string, I am getting a seg fault when bar.cpp is compiled before foo.cpp. How could I structure this so that it works no matter the order in which the files are provided?

foo.h

#ifndef FOO
#define FOO
#include <string>

class Foo {
public:
  static const std::string STATIC_FOO
  Foo(): m_foo(STATIC_FOO) {};
  std::string m_foo;
};

#endif

foo.cpp

#include <string>
#include "foo.h"
const std::string Foo::STATIC_FOO = "foo";

bar.h

#ifndef BAR
#define BAR
#include "foo.h"

class Bar {
public:
  static Foo s_foo;
};

#endif

bar.cpp

#include "foo.h"
#include "bar.h"
Foo Bar::s_foo;

main.cpp

#include <iostream>
#include "bar.h"
int main() {
  Bar b;
  std::cout << b.s_foo.m_foo << std::endl;
}

This compiles fine when I specify foo.cpp before bar.cpp.

$ g++ -std=c++11 main.cpp foo.cpp bar.cpp -o main
$ ./main
Foo!

But if bar.cpp is compiled first, I get a segmentation fault.

$ g++ -std=c++11 main.cpp bar.cpp foo.cpp -o main  # note bar.cpp comes before foo.cpp here
$ ./main
Segmentation fault (core dumped)

I am getting error LNK2019: : unresolved external symbol for my TEST project which is testing a project of .dll type

I am using Microsoft Native Visual C++ unit test (.NET frame work 4.5). I am creating TEST project in visual studio 2012 for my "xyz project", which has a configuration type Dynamic library(Properties->Configuration Properties->General). I am calling methods from TEST project which are defined in "xyz project". I am adding the proper header file ,in test.cpp and xyz.dll in Linker->Input->Additional Dependencies for TEST project.

The problem will arise only when I build my TEST project. The error says "error LNK2019: unresolved external symbol "public: bool __thiscall xyz_comm::send(void *,class xyz_Node *,int *). As far as I understand this error should not come as I already added xyz.dll( path is proper and there is no spelling or syntax issue).

My solution: After scratching my head a lot, I find out a work around. When I change the configuration (Properties->Configuration Properties->General) of test project from Dynamic library(.dll) to static library (.lib) shockingly this issue is resolved.

My Question:

  1. How can I resolve my error by keeping the configuration as Dynamic library(.dll) and build it without error.
  2. Does Microsoft Native Visual C++ unit test support testing for .dll project or not? If not which C++ test frameworks support .dll project testing

mardi 11 avril 2023

how to find date for previous day in c++? [duplicate]

I was using std::time_t t = std::time(0) for current time, however i also need the previous day date. I don't want to use the approach where we get the current time and then convert it to previous day using basic year/month/day logic.

Using a variadic template template, itself with with variadic parameters?

Could one make a variadic template template, itself with variadic parameters?
How would one explicitly/partially specialize this template?

//E.g. something where the following would be valid:

template <template <typename...> typename... Containers>
    class SomeClass {};

SomeClass <int, std::vector<int>, std::tuple<int, char, float, double, short>> var;

I get as far as

template <template <typename...> typename... Tuples>
    class CVarMap : public CVarMap<Tuples>
    {};

template <template <typename...> typename Tuple, template <typename...> typename... Tuples>
    class CVarMap : public CVarMap<Tuple, Tuples...>
    {};

but any attempt to unpack the "inner" variadic args results in a template with multiple variadic parameters. Yet in the answer for this question there are multiple variadic parameters, which is valid.

What am I missing here?

Cleanly Passing a Dependency Using Smart Pointer

I am in the early stages of learning "modern" C++ and would like to ask what the "best-practice" is for providing a dependency to a consumer whilst using smart pointers for management.

I would like it to be the case that a change to the object state referenced by the smart pointer, is reflected in the consumer class.

I also don't want the consumer class to know about the smart pointer as I feel this makes the interface/constructor less clear. However maybe this is misinformed?

The example below does what I want using aliases, but is it the "right" way to achieve my goals using "modern" C++? Are there alternative approaches / idioms I could be aware of?

Header

class Widget {
public:
    int cost { 0 };
    virtual ~Widget();
};

class WidgetConsumer {
public:
    Widget& _widget;
    explicit WidgetConsumer(Widget&  widget);
    virtual ~WidgetConsumer();
};

Source

#include <iostream>
#include "widgets.h"

int main() {
    std::unique_ptr<Widget> widgetB = std::make_unique<Widget>();
    WidgetConsumer widgetConsumerB(*widgetB);
    widgetB->cost = 23;
    std::cout << "widget.cost=" << widgetB->cost << std::endl;
    std::cout << "widgetConsumer._widget.cost=" << widgetConsumerB._widget.cost << std::endl;
}

WidgetConsumer::WidgetConsumer(Widget &widget) : _widget(widget) {
}

WidgetConsumer::~WidgetConsumer() {
    std::cout << "WidgetConsumer destroyed" << std::endl;
}

Widget::~Widget() {
    std::cout << "Widget destroyed" << std::endl;
}

Output

widget.cost=23
widgetConsumer._widget.cost=23
WidgetConsumer destroyed
Widget destroyed

Parameter packs unable to resolve overloaded function

#include <iostream>
#include <algorithm>
#include <memory>
#include <mutex>
#include <vector>
template <typename Observer>
class ObsNoti {
public:
    template <
            typename Ret,
            typename Class,
            typename... Args,
            typename = std::enable_if_t<std::is_same<Observer, Class>::value>>
    void notifyEveryone(Ret Class::*func, Args&&... args) {
        (obs.*func)(std::forward<Args>(args)...);
    }
    Observer obs;
};

class ContactObserver {
    public:
    virtual int onContactRetrieved() {
        std::cout<<"onContactRetrieved\n";
        return 0;
    }
    
    virtual int onContactRetrieved(bool bSucess) {
        std::cout<<"onContactRetrieved sucessfully\n";
        return 0;
    }
};

class MyClass : public ObsNoti<ContactObserver> {
    public:
    template<typename Func, bool,  typename... Args>
    inline void notifyObserver(Func &&func, bool b, Args&&... args) {
        ObsNoti<ContactObserver>::notifyEveryone(func , b, std::forward<Args>(args)...);
    }
    
    template<typename Func, typename... Args>
    inline void notifyObserver(Func &&func, Args&&... args) {
        ObsNoti<ContactObserver>::notifyEveryone(func , std::forward<Args>(args)...);
    }
};



int main() {
    MyClass my;
    my.notifyObserver(&ContactObserver::onContactRetrieved, true);
    return 0;
}

I am getting the following error:

/tmp/w7Rta4F1cT.cpp:53:22: error: no matching function for call to 'MyClass::notifyObserver(<unresolved overloaded function type>, bool)'
   53 |     my.notifyObserver(&ContactObserver::onContactRetrieved, true);
      |     ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/tmp/w7Rta4F1cT.cpp:37:17: note: candidate: 'template<class Func, bool <anonymous>, class ... Args> void MyClass::notifyObserver(Func&&, bool, Args&& ...)'
   37 |     inline void notifyObserver(Func &&func, bool b, Args&&... args) {
      |                 ^~~~~~~~~~~~~~
/tmp/w7Rta4F1cT.cpp:37:17: note:   template argument deduction/substitution failed:
/tmp/w7Rta4F1cT.cpp:53:22: note:   couldn't deduce template parameter 'Func'
   53 |     my.notifyObserver(&ContactObserver::onContactRetrieved, true);
      |     ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/tmp/w7Rta4F1cT.cpp:42:17: note: candidate: 'template<class Func, class ... Args> void MyClass::notifyObserver(Func&&, Args&& ...)'
   42 |     inline void notifyObserver(Func &&func, Args&&... args) {
      |                 ^~~~~~~~~~~~~~
/tmp/w7Rta4F1cT.cpp:42:17: note:   template argument deduction/substitution failed:
/tmp/w7Rta4F1cT.cpp:53:22: note:   couldn't deduce template parameter 'Func'
   53 |     my.notifyObserver(&ContactObserver::onContactRetrieved, true);
      |     ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I understand the problem here is that template is unable to resolve the function at compile time because of overloading. But, I am not sure of a correct way to implement it.

Any way to resolve this?

How does this simple multithread code lead to memory corruption?

The following code reliably produces a segfault.

#include <vector>
#include <thread>

class Class {
public:
    Class(const int integer)
        : cinteger(integer), carray(std::array<int, 1>{0})
    {}

   const int operator()() 
   {
    carray[cinteger] = 0;
        return cinteger;
    }
    
private:
    int cinteger;
    std::array<int, 1> carray;
};

class Worker{
    public:
        Worker( Class iClass): 
            wClass(iClass),
            thread(&Worker::thread_main, this)
            {}
        
        void join(){thread.join();}     

    private:
        Class wClass;
        std::thread thread;
        void thread_main(){
            for(int i = 0; i < 50000; i++)
            wClass();
        }
};

int main()
{
    std::vector<Worker> Workers;
    for(int i = 0; i < 4; i++)
        Workers.emplace_back(Class(0));
    for(int i = 0; i < 4; i++)
        Workers[i].join();
    return 0;
}

For some reason, I do not understand, the cinteger variable of Class seems to get changed unexpectedly. This problem arises every time I run the code. It does not arise if I only generate 3 workers. Also, at 1000 iterations in the Worker class the problem does not appear.

TBH I am a bit out of ideas of where this problem could come from.

dimanche 9 avril 2023

Random number generator in C++ using rand_r function [duplicate]

I have been trying to generate random number in C++ using rand_r, while using multiple threads for parallel implementation in a pretty big code, which utilizes a lot of seeds. Also, I need to run my simulation multiple times. I want a different random number generated for the same seed in a particular node. However, I keep getting the same sequence (which is understandable due to same initialization of the random generator). Any ideas to reset the random generator? I have explained the question using an example below. I cannot use rand() as it is not thread safe, and I am using an older version of c++ (4.4.7). Also, I generate a hell lot of seeds in one simulation, so kindly do not suggest using a different seed in every simulation.

Example Code:

#include <stdio.h>
#include <mpi.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdlib.h>
using namespace std;

 int main(int argc, char** argv) {
   int rank;
   MPI_Init(&argc, &argv);
   MPI_Comm_rank(MPI_COMM_WORLD, &rank);
   unsigned int rank2 = rank;
   int random_n = rand_r(&rank2);
   cout << "Random number is: " << random_n << " in node: " << rank << endl;
   return MPI_Finalize();
 }

The result generated is:

Random number is: 1012484 in node: 0
Random number is: 476707713 in node: 1
Random number is: 952403967 in node: 2
Random number is: 1430195325 in node: 3

Upon executing the simulation again, I want different random number in the nodes. However, the result I get is:

Random number is: 1012484 in node: 0
Random number is: 476707713 in node: 1
Random number is: 952403967 in node: 2
Random number is: 1430195325 in node: 3

Any help on this would be appreciated!!

C2665 none of the 2 overloads could convert all the argument type [duplicate]

I am trying to create a static member to a class that will contain every object of that class. I created another class called Map and it has only a map variable and 2 methods: Insert. But when i tried to use the Insert method on the static var in my constructor it gave me the C2665 Error: None of the 2 overloads could convert all the argument types.

I have read many posts and the Microsoft documentation about this error but I could not find the difference between the definition and the argument list.

This is Map class def:

template <typename _Tv>
class Map
{
public:
    std::map<std::string, _Tv> myMap;
    std::pair<typename std::map<std::string, _Tv>::iterator, bool> Insert(_Tv&);
    std::pair<typename std::map<std::string, _Tv>::iterator, bool> Insert(std::pair<std::string&, _Tv>&); 
}

This is the static member:

public:
    static Map<VideoSource*> videoSources;

The definition in the same file:

extern Map<VideoSource*> videoSources;

And in the source file:

Map<VideoSource*> VideoSource::videoSources;

VideoSource::VideoSource(std::string path, std::string name) : ISource(path), IImg(), IPlayable()
{
    VideoSource::videoSources.Insert(std::make_pair(name, this)); // returns error from the compiler
}

This is the error message:

1>D:\C++\VideoEditor\VideoEditor\Map.h(11,65): message : could be 'std::pair<std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,_Tv>>>>,bool> Map<_Tv>::Insert(std::pair<std::string &,_Tv> &)'
1>        with
1>        [
1>            _Tv=VideoSource *
1>        ]
1>D:\C++\VideoEditor\VideoEditor\Map.h(10,65): message : or       'std::pair<std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,_Tv>>>>,bool> Map<_Tv>::Insert(_Tv &)'
1>        with
1>        [
1>            _Tv=VideoSource *
1>        ]
1>D:\C++\VideoEditor\VideoEditor\VideoSource.cpp(12,27): message : 'std::pair<std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,_Tv>>>>,bool> Map<_Tv>::Insert(_Tv &)': cannot convert argument 1 from 'std::pair<std::basic_string<char,std::char_traits<char>,std::allocator<char>>,VideoSource>' to '_Tv &'
1>        with
1>        [
1>            _Tv=VideoSource *
1>        ]
1>D:\C++\VideoEditor\VideoEditor\Map.h(10,65): message : see declaration of 'Map<VideoSource *>::Insert'
1>D:\C++\VideoEditor\VideoEditor\VideoSource.cpp(12,64): message : while trying to match the argument list '(std::pair<std::basic_string<char,std::char_traits<char>,std::allocator<char>>,VideoSource>)'

Can someone please help me? I have no idea what i did wrong

Why does variable value not change giving std::move as function argument? [duplicate]

I have looked at other posts regarding std::move but those examples were a bit complicated for me to understand so I will try to explain my problem with a very simple example here.

void increaseNum(int num) {
    num += 1;
}

int main() {
    int myNum {5};
    increaseNum(myNum); // Case-1
    increaseNum(std::move(myNum)) // Case-2
}

In Case-1 it does not change the value of myNum because I am passing it by value. It creates a copy of myNum inside increaseNum and changes the value of copy there. However, in Case-2 what I would expect is that I am saying to increaseNum "Hey, do not create a copy of myNum, instead take the ownership of that variable and change it, like pass by reference". When I print out myNum after Case-2, it is still 5 which confuses me.

Could someone please help me what I am missing here? Is giving std::move(variable) as function argument not the same as pass by reference? If not then why do we give std::move(variable) as function argument?

samedi 8 avril 2023

Catching an abort signal

I am working on one of my assignments (recursion) and testing. I've run into a problem when trying to test a specific function. The function is called Ramanujan() https://math.stackexchange.com/questions/2381181/ramanujans-infinite-root. I was reading online on ways to test functions and found some very useful tricks (such as the google test library) but after trying to implement it I found out that it goes way above my level of knowledge. I settled for the old-fashioned "math by hand" testing, where I compare the output of the function with my calculations.

That worked for the 4 functions but I got stuck at the 5th one. I decide to use cassert and assert that the output of the ramanujan() function would always be less or equal to 4, because the series converges to 4. ( The constant is set to 3 because of testing).

While doing that I read that assert raised a SIGABRT signal upon failure, because my professors submission script won't accept that for some reason I had to come up with a signla_handler.

The signal handler works, but this gets printed to the console

prog: main.cpp:413: bool runTest5(): Assertion `output <= OUT' failed.

Is there a way to print out TEST5 FAILED instead of this?

Here is my code:

/**
 * @author Jakob Balkovec
 * @file main.cpp [Driver code]
 * @brief This assignment focuses on using recursion to solve various
 *        problems are given in the description [pdf]
 * @name Assignment 2
 */

#include <iostream> //std::cin, std::cout
#include <stdexcept> //try catch throw blocks
#include <string> // std::string lib for decToBase2()
#include <limits> //limts for int overflow
#include <cmath> //std::sqrt()
#include <unistd.h> //usleep
#include <csignal> //signal handler
#include <cassert> //assert library

#pragma message ("Compiling main.cpp")
#pragma message ("Last modified on 4/8/2023")

int const CONVERGE = 18; //ramanujan const for the series
long int const PAUSE = 1000000;
/**
 * @invariant The user will always provide an integer upon calling any of the 5 functions
 */

/**
 * @note typedefing it for better readbility
 */
typedef std::numeric_limits<int32_t> limits;

/**
 * @brief Upper and lower limits for 32bit (4Byte) intiger
 */
const int32_t MAX = limits::max();


/** @name printMenu()
 * @brief The function prints a menu for the user
 * @remark Handles UI
 * @return void-type
 */
void printMenu() {
  std::cout << "\n\nWelcome to the recursion assigment. What would you like to test?\n"
            << "[1] mysterySequence\n"
            << "[2] tennisBalls\n"
            << "[3] decToBase2\n"
            << "[4] isDivisibleBy7\n"
            << "[5] ramanjuan\n"
            << "[6] Run tests\n"
            << "[7] Exit\n\n";
  return;
}

/** @name goodbye()
 * @brief The function prompts the user goodbye
 * @remark Handles UI
 * @return void-type
 */
void goodbye() {
  std::cout << "Goodbye!\n\n";
}

/** @name getInput()
 * @brief The function prompts the user to enter a number corresponding to the menu
 * @return int choice (0 < choice < 8)
 */
int getInput() {
  int choice = 0;
  std::cout << "\n[Enter]: ";
  
  while (true) {
    try {
      std::cin >> choice;
      if (std::cin.fail()) { //std::cin.fail() if the input is not an intiger returns true
        /// @link https://cplusplus.com/forum/beginner/2957/
        
        std::cin.clear(); // clear error flags
        std::cin.ignore(10000, '\n'); // ignore up to 10000 characters or until a newline is encountered
        throw std::invalid_argument("[Invalid input]");
      }
      else if (choice < 1 || choice > 7) {
        throw std::out_of_range("Input out of range. Please enter an integer between 1 and 7.");
      }
      else {
        return choice;
      }
    }
    catch (const std::exception& error) {
      std::cout << error.what() << std::endl;
      std::cout << "[Re-enter]: ";
    }
  }
}

/** @name mysterySequence()
 * @brief Calculates the n-th term of the mystery sequence.
 * The sequence is defined recursively as follows:
 * 
 * @note Computed using a simple math formula
 * a[0] = 2
 * a[n] = a[n-1] * 3n for n >= 1
 * @note Computed using a simple math formula
 * 
 * @param n The term number to calculate.
 * @return The value of the n-th term of the sequence.
 */
int mysterySequence(int n) {
  if (n == 0) { /// @brief base case: the first term of the sequence is 2
    return 2; //a[1]
  } else if (n == 1) {
    return 3;
  } else {
    return mysterySequence(n-1) * mysterySequence(n-2); /// @brief recursive call to get the next term
  }
}

/** @name mysterySequenceFunc()
 * @brief Prompts the user for an input n and calls the mysterySequence function 
 * with n as the argument. 
 * @throw overflow_error
 * @return void-type
 */
void mysterySequenceFunc() {
  int n = 0;
  std::cout << "\n[Enter an index]: ";
  std::cin >> n;
  
  try {
    if (n < 0) {
      throw std::out_of_range("\nIndex should be positive\n");
    } else if (n > 46340) {
      throw std::overflow_error("\nInteger Overflow is bound to happen\n");
    } else {
      int index = mysterySequence(n);
      std::cout << "\nThe [" << n << "th] link in the sequence is " << index << "\n\n";
    }
  } catch (const std::exception& error) {
    std::cout << error.what() << std::endl;
  }
}

/** @name tennisBalls()
 * @brief Calculates the total number of tennis balls in a pyramid of tennis ball cans.
 * @param n The number of levels
 * @return The total number of tennis balls in the pyramid.
 */
int tennisBalls(int n) {
  if(n == 0) { /// @brief base case
    return 0;
  } else { /// @brief recursive case
    int balls = n*n;
    return balls + tennisBalls(n-1);
  }
}

/** @name tennisBallsFunc()
 * @brief Prompts the user to enter the number of cans in the base of a pyramid and 
 *        calculates the total
 *        number of tennis balls in the pyramid.
 * @throw std::overflow_error If n is greater than 46340, which can cause an integer overflow.
 * @return void-type
 */
void tennisBallsFunc() {
  int n = 0;
  std::cout << "\n[Enter the height of the pyramid]: ";
  std::cin >> n;
  
  try {
    if (n > 46340) {
      throw std::overflow_error("\nIntiger Overflow is bound to happen\n");
    } else if(n < 0) {
      throw std::out_of_range("\nHeight should be positive\n");
    }else {
      int result = tennisBalls(n);
      std::cout << "\nA pyramid with " << n << " levels holds " << result << " balls\n\n";
    }
  } catch (const std::exception& error) {
    std::cout << error.what() << std::endl;
  }
}

/** @name decToBase2()
 * @brief Converts an integer to its binary representation as a string. 
 * @param n The integer to convert to binary.
 * @return The binary representation of n as a string.
 */
std::string decToBase2(int n) {
  if (n == 0) { /// @brief base case
    return "0";
  } else if (n == 1) {
    return "1";
  } else { /// @brief recursive case
    int remainder = n % 2;
    return decToBase2(n / 2) + std::to_string(remainder);
    //std::to_string() returns a string with the representation of a value
    /// @link https://cplusplus.com/reference/string/to_string/
  }
}

/** @name decToBase2Func()
 * @brief Converts an integer to its binary representation.
 * @details Uses the decToBase2() function to convert the integer to binary, and prints the result.
 * @throws std::overflow_error If the integer is outside the range of a signed 32-bit integer.
 * @return void-type
 */
void decToBase2Func() {
  int n = 0;
  std::cout << "\n[Enter an integer]: ";
  std::cin >> n;
  
  try {
    if(n > MAX) { //int is defined as a 32 bit int (pre installed compiler on cs1)
      throw std::overflow_error("\nIntiger Overflow\n");
    } else if( n < 0) {
      throw std::out_of_range("\nThe intiger should be positive\n");   
    }else {
      std::cout << "\nThe integer " << n << " as binary: [" << decToBase2(n) << "]\n\n";
    }
  } catch(const std::exception &error) {
    std::cout << error.what() << std::endl;
  }
}

/** @name isDivisibleBy7()
 * @brief Check if an integer is divisible by 7
 * @param n The integer to check
 * @return true if n is divisible by 7, false otherwise
 */
bool isDivisibleBy7(int n) {
  if (n < 0) {
    n = abs(-n); // make n positive
  }
  
  if (n == 0 || n == 7) { //base case
    return true; // base case
    
  } else if (n < 10) {
    return false; // base case
    
  } else { //recursive case
    int lastDigit = n % 10;
    int remaining = n / 10;
    int doubled = lastDigit * 2;
    int newNumber = remaining - doubled;
    return isDivisibleBy7(newNumber); // recursive case
  }
}

/** @name isDivisibleBy7Func()
 * @brief This function takes an integer input from the user and checks if it is divisible by 7
 * calling the isDivisibleBy7() function.
 * @throw overflow_error error.
 * @return void-type
 */
void isDivisibleBy7Func() {
  int n = 0;
  std::cout << "\n[Enter an integer]: ";
  std::cin >> n;
  
  try{
    if(n > MAX) {
      throw std::overflow_error("\nInteger Overflow\n");
    } else if( n < 0) {
      throw std::out_of_range("\nThe intiger should be positive\n");   
    } else{
      bool isDivisible = isDivisibleBy7(n);
      if(isDivisible) {
        std::cout << "\nThe integer " << n << " is divisible by 7\n\n";
        }else {
        std::cout << "\nThe integer " << n << " is not divisible by 7\n\n";
      }
    }
  } catch(const std::exception &error) {
    std::cout << error.what() << std::endl;
  }
}

/** @name ramanujan()
 * @brief Calculates the value of the Ramanujan series to a specified depth using recursion.
 * @param depth The depth of the Ramanujan series.
 * @param current The current depth of the recursion. Defaults to 0.
 * @return The value of the Ramanujan series at the specified depth.
*/
double ramanujan(int depth, int current = 0){ //current passed as default argument
  if(current > depth) {// base case
    return 0;
  }else { //recursive case
    return (current + 1) * sqrt(6 + current + ramanujan(depth, current + 1));
  }
}

/** @name ramanujanFunc()
 * @brief Computes the value of the Ramanujan series with the given depth using recursion.
 * @param depth The depth of the Ramanujan series to compute.
 * @return The value of the Ramanujan series with the given depth.
 * @throw std::overflow_error If the depth is too large to compute.
 * @throw std::out_of_range If the depth is negative.
 */
void ramanujanFunc() {
  int n = 0;
  std::cout << "\n[Enter the depth of the series]: ";
  std::cin >> n;
  
  try {
    if(n > MAX) {
      throw std::overflow_error("\nInteger Overflow\n");
    } else if(n < 0) {
      throw std::logic_error("\nThe depth should be positive\n"); //if n < 0 we need complex nums
    }else {
      std::cout << "\nResult at depth [" << n << "] is " << ramanujan(n) << "\n";
      std::cout << "\nResult at infinte depth is " << ramanujan(100) << "\n"; //int overflow
      std::cout << "\n";
    }
  }catch (const std::exception &error) {
    std::cout << error.what() << std::endl;
  }
}

/** @name runTest1()
 * @brief Runs the test for mysterySequence() using comparison with expected output and the actual output
 * @return booleans wheter the output mathes (false || true)
 */
bool runTest1() {

  int expectedOutput[] = {2, 3, 6, 18, 108, 1944, 209952, 408146688};

  int input[] = {0, 1, 2, 3, 4, 5, 6, 7};
  int numTests = sizeof(expectedOutput) / sizeof(expectedOutput[0]);

  for (auto i = 0; i < numTests; i++) {
    if (mysterySequence(input[i]) != expectedOutput[i]) {
      std::cout << "*** For " << input[i] << " expected " << expectedOutput[i] << " but got " << mysterySequence(input[i]) << std::endl << std::endl;
      return false;
    }
  }
  return true;
}

/** @name runTest1()
 * @brief Runs the test for tennisBalls() using comparison with expected output and the actual output
 * @return booleans wheter the output mathes (false || true)
 */
bool runTest2(){
  int expectedOutput[] = {0, 1, 14, 385, 650, 5525};

  int input[] = {0, 1, 3, 10, 12, 25};
  int numTests = sizeof(expectedOutput) / sizeof(expectedOutput[0]);

  for(auto i = 0; i < numTests; i++) {
    if(tennisBalls(input[i]) != expectedOutput[i]) {
      std::cout << "*** For " << input[i] << " expected " << expectedOutput[i] << " but got " << tennisBalls(input[i]) << std::endl << std::endl;
      return false; //test failed
    }
  }
  return true;
}

/** @name runTest1()
 * @brief Runs the test for decToBase2() using comparison with expected output and the actual output
 * @return booleans wheter the output mathes (false || true)
 */
bool runTest3(){
  typedef std::string string;
  string expectedOutput[] = {"0", "1", "1101", "100000", "101000001", "10000010000100"};

  int input[] = {0, 1, 13, 32, 321, 8324};
  int numTests = sizeof(expectedOutput) / sizeof(expectedOutput[0]);

  for(auto i = 0; i < numTests; i++) {
    if(decToBase2(input[i]) != expectedOutput[i]) {
      std::cout << "*** For " << input[i] << " expected " << expectedOutput[i] << " but got " << decToBase2(input[i]) << std::endl << std::endl;
      return false; //test failed
    }
  }
  return true;
}

/** @name runTest1()
 * @brief Runs the test for isDivisbleBy7() using comparison with expected output and the actual output
 * @return booleans wheter the output mathes (false || true)
 */
bool runTest4(){
  bool expectedOutput[] = {false, true, false, false, true, true, false};

  int input[] = {1, 7, 31, 1073, 1729, 5838, 151932};
  int numTests = sizeof(expectedOutput) / sizeof(expectedOutput[0]);

  for(auto i = 0; i < numTests; i++) {
    if(isDivisibleBy7(input[i] != expectedOutput[i])) {
      std::cout << "*** For " << input[i] << " expected " << expectedOutput[i] << " but got " << isDivisibleBy7(input[i]) << std::endl << std::endl;
      return false; //test failed
    }
  }
  return true;
}

/** @name runTest1()
 * @brief Runs the test for ramanujan() using assertion 
 * (asserts the output is always less than or equal to 4)
 * @return useless boolean...assert calls abort() upon failure
 */
bool runTest5() {
  int const OUT = 3; //const for testing

  int input[] {1, 3, 7, 23, 10, 34, 55, 12};
  float output; //declare var for output
  bool test = true;

  int numTests = sizeof(input) / sizeof(input[0]);
  for(auto i = 0; i < numTests; i++) {
    output = ramanujan(input[i]);
    assert(output <= OUT);
  }
  //create a singal handler for assert
  return test;
}

void signal_handler(int signal) {
    if (signal == SIGABRT) {
        std::exit(EXIT_FAILURE); //std::exit(signal)
    }
}
 
void runTestsFunc() {
  #define FAIL false
  #define PASS true
  
  bool test1 = runTest1();
  if(test1 == PASS) {
    std::cout << "\n*** TEST1 PASSED\n";
    usleep(PAUSE);
  }else if(test1 == FAIL) {
    std::cout << "\n*** TEST1 FAILED\n";
    usleep(PAUSE);
  }

  bool test2 = runTest2();
  if(test2 == PASS) {
    std::cout << "*** TEST2 PASSED\n";
    usleep(PAUSE);
  }else if(test2 == FAIL) {
    std::cout << "*** TEST2 FAILED\n";
    usleep(PAUSE);
  }

  bool test3 = runTest3();
  if(test3 == PASS) {
    std::cout << "*** TEST3 PASSED\n";
    usleep(PAUSE);
  }else if(test3 == FAIL) {
    std::cout << "*** TEST3 FAILED\n";
    usleep(PAUSE);
  }

  bool test4 = runTest4();
  if(test4 == PASS) {
    std::cout << "*** TEST4 PASSED\n";
    usleep(PAUSE);
  }else if(test4 == FAIL) {
    std::cout << "*** TEST4 FAILED\n";
    usleep(PAUSE);
  }

  std::signal(SIGABRT, signal_handler);
  bool test5 = runTest5();

  if (test5 == PASS) {
      std::cout << "*** TEST5 PASSED\n";
      usleep(PAUSE);
  } else {
      std::cout << "*** TEST5 FAILED\n";
      usleep(PAUSE);
  }
    

bool allPassed = test1 && test2 && test3 && test4 && test5;

try {
    if (allPassed) {
        std::cout << "*** ALL TEST CASES PASSED\n";
    } else {
        // throw an exception if any test case failed
        throw std::runtime_error("FAIL -> COMPILATION TERMINATED");
    }
} catch (const std::exception& error) {
    std::cout << "*** ERROR: " << error.what() << "\n";
    exit(EXIT_FAILURE);
}
}

int main () {
  while(1) { //change back to while true
    printMenu();
    switch(getInput()) {
    case 1: {
      mysterySequenceFunc();
      break;
    }
    case 2: {
      tennisBallsFunc();
      break;
    }
    case 3: {
      decToBase2Func();
      break;
    }
    case 4: {
      isDivisibleBy7Func();
      break;
    }
    case 5: {
      ramanujanFunc();
      break;
    }
    case 6: {
      runTestsFunc();
      break;
    }
    case 7: {
      goodbye();
      exit(EXIT_FAILURE);
      break;
    }
    default:  {
      /**
       * @brief add more or edit
       */
      std::cout << "In default";
      break;
    }
    }
  }
}

I would be very grateful for any response I could get and any style and formatting tips. My professor requires a quite "harsh and heavy" function decomposition that's why my main is so short. I am also not allowed to work with classes and multiple files for this assignment.

Thank you!

how to process in debugging gdb trace

I am new to gdb. I found a below crash while running a process (written in c++) under gdb. I do not know from where I have to start understanding this backtrack to get the root cause. can any one help me with this?

(gdb) bt
#0  0x0000555555611560 in std::atomic<double>::load(std::memory_order) const ()
#1  0x000055555561130d in prometheus::Gauge::Change(double) ()
#2  0x0000555555611240 in prometheus::Gauge::Increment(double) ()
#3  0x0000555555611212 in prometheus::Gauge::Increment() ()
#4  0x00005555555f8356 in prometheus::Counter::Increment() ()
#5  0x000055555559dee6 in asnInitiatingRequest (pdu=0x7fffd800e4d0, sctpMap=0x5555557261a0, message=..., rmrMessageBuffer=..., streamId=0) at /opt/e2/RIC-E2-TERMINATION/sctpThread.cpp:2198
#6  0x000055555559eda8 in receiveDataFromSctp (events=0x7fffd8000e40, sctpMap=0x5555557261a0, numOfMessages=@0x7fffedd79fbc: 6, rmrMessageBuffer=..., ts=...) at /opt/e2/RIC-E2-TERMINATION/sctpThread.cpp:1509
#7  0x000055555559f698 in listener (params=0x7fffffff7460) at /opt/e2/RIC-E2-TERMINATION/sctpThread.cpp:972
#8  0x00007ffff7850de4 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
#9  0x00007ffff7964609 in start_thread (arg=<optimized out>) at pthread_create.c:477
#10 0x00007ffff7558133 in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
(gdb) 




(gdb) f 5
#5  0x000055555559dee6 in asnInitiatingRequest (pdu=0x7fffe015ccf0, sctpMap=0x5555557261a0, message=..., rmrMessageBuffer=..., streamId=0) at /opt/e2/RIC-E2-TERMINATION/sctpThread.cpp:2198
2198    /opt/e2/RIC-E2-TERMINATION/sctpThread.cpp: No such file or directory.



(gdb) p pdu
$1 = (E2AP_PDU_t *) 0x7fffe015ccf0
(gdb) p sctpMap
$2 = (Sctp_Map_t *) 0x5555557261a0
(gdb) p message
$3 = (ReportingMessages_t &) <error reading variable>
(gdb) p rmrMessageBuffer
$4 = (RmrMessagesBuffer_t &) @0x7fffee57b1b0: {ka_message = "{\"address\": \"127.0.0.1:38000\",\"fqdn\": \"e2t.com\",\"pod_name\": \"e2term\"}", '\000' <repeats 1978 times>, ka_message_len = 69, rmrCtx = 0x5555556fdd80, 
  sendMessage = 0x7fffe00014b0, rcvMessage = 0x7fffdc102a70}
(gdb) p streamId
$5 = 0
(gdb) 

Why do I have std::list element declaration errors?

I am writing a program in c++ (for a list) where an element that is smaller than the one before is deleted. I declared 2 elements- current and next but i get declaration errors and have no idea why. I checked the syntax, it is correct.

My code:

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

void deleteFromSTLList(list<int> &numbers) {
    auto curr = numbers.begin();
    auto next = ++numbers.begin();
    while (next != numbers.end()) {
        if (*curr < *next) {
            next = numbers.erase(next);
            continue;
        }
        curr = next;
        next++;
    }
}

I am getting an error that my variables curr and next ar not declared in this scope and do not name a type.

vendredi 7 avril 2023

C++ Sheffer functions (How the Boolean EXOR function can be composed entirely from NAND gates)

I am a first-year computer engineering student using C++ for one of my modules. We have an assignement due in a few days, and I would really appreciate if someone could help me check if my code is correct according to the given Requirements Specification. Also I don not know how to implement the requirement in the "my_EXOR_implementation" which says that truth values may not be represented numerically. (We are marked out of 1, so we will either get 1 or 0; and NULL marks are given to any submission that violates any of the given requirements).

I will place the Scenario and the requirements Specification below and then what I have so far.

Scenario: An undergraduate student of Electronic Engineering, Emily Esterhuizen, is currently learning that Sheffer functions are universal Boolean functions by means of which all other Boolean functions can be composed. Moreover, Emily has also already learned that the NAND function is indeed one of such Sheffer functions. Normally such Boolean functions are implemented in hardware (where they are also known as “gates”), but as an undergraduate student there is no way for Emily to make hardware gates. For this reason, Emily would like to simulate such gates in software, such that she will be able to study how such functional compositions are made and how they work. Unfortunately Emily is not very good at C++ programming, such that she is hoping for your help in this matter: she would like to see how the Boolean EXOR function can be composed entirely from NAND gates (which is certainly possible because NAND is a Sheffer function).

Your Task: Help Emily Esterhuizen to implement in C++ the following Requirements Specification:

MAIN Program • declares two Boolean variables: b1, b2 • asks the user to input truth-values for b1, b2 • calls the function my_EXOR_implementation with b1, b2 as its two actual parameters • outputs the truth-value which my_EXOR_implementation returns.

Boolean Function my_EXOR_implementation(Boolean input1, Boolean input2) • must return the correct truth-value of EXOR(input1,input2) • must utilize for this purpose a correct combination of several calls to the underlying Sheffer function my_NAND_implementation • May not contain any built-in logical C++ operators && (conjunction), || (disjunction), or ! (negation) • May not contain any mathematical-arithmetic operators (like + or −) for mimicking Boolean typed truth-values as numbers (0,1): the truth-values may not be represented numerically. • May not contain any if-statements, if-else-statements, nor switch-case statements.

Boolean Function my_NAND_implementation(Boolean input1, Boolean input2) • must return the correct truth-value of NAND(input1,input2) • must utilize for this purpose a suitable algorithmic combination of several if-statements or if-else-statements, • May not contain any built-in logical C++ operators && (conjunction), || (disjunction), or ! (negation) • May not contain any mathematical-arithmetic operators (like + or −) for mimicking Boolean typed truth-values as numbers (0,1): the truth-values may not be represented numerically.

`#include <iostream>

using namespace std;

bool my_NAND_implementation(bool input1, bool input2) {
  bool result = true;
  if (input1 == true) {
    if (input2 == true) {
      result = false;
    }
  }
  return result;
}

bool my_EXOR_implementation(bool input1, bool input2) {
  bool nand1 = my_NAND_implementation(input1, input2);
  bool nand2 = my_NAND_implementation(input1, nand1);
  bool nand3 = my_NAND_implementation(input2, nand1);
  bool nand4 = my_NAND_implementation(nand2, nand3);
  return nand4;
}

int main() {
  bool b1, b2;
  cout << "Enter truth value for b1 (0 or 1): ";
  cin >> b1;
  cout << "Enter truth value for b2 (0 or 1): ";
  cin >> b2;
  bool exor_result = my_EXOR_implementation(b1, b2);
  cout << "The result of EXOR(" << b1 << ", " << b2 << ") is: " << exor_result << endl;
  
return 0;
}`
`

How to design sequence lock API

#include "seqlock.h"
typedef struct {
    unsigned seq;
    pthread_mutex_t lock;
} seqlock_t;
int pthread_seqlock_init(pthread_seqlock_t *seqlock);
int pthread_rwlock_destroy(pthread_seqlock_t *seqlock);

I try to understand sequence lock but sequence lock API to new for me

How to fix "cmake_pch.hxx" issue occurred from stdafx.h precompilation

There are two projects in my C++ solution. So, resultant of one project is the dependency for other project.

I have placed "ProjectA/src/Include" in ProjectB as ProjectA is a dependency for ProjectB. In "ProjectB/Src/stdafx.h" I have included that header file from "ProjectA/src/Include".

I have included the "ProjectA/src/Include" in CMAke file as well and my CMake file of ProjectB look like

include_directories(${PROJECT_SOURCE_DIR}/Dependencies/ProjectA/include)
target_link_directories(ProjectB PRIVATE ${PROJECT_SOURCE_DIR}/Dependencies/ProjectA/lib)
target_link_libraries(ProjectB PRIVATE ProjectA)

I get the issue from this line

target_precompile_headers(ProjectB PRIVATE
    "$<$<COMPILE_LANGUAGE:CXX>:${CMAKE_CURRENT_SOURCE_DIR}/stdafx.h>"
)

Issue: "Defs.h" is from "ProjectA/src/Include" and included in "ProjectB/Src/stdafx.h"

In file included from /home/vsts/work/1/s/ProjectB/out/build/Linux-GCC-Debug/Debug/Source/CMakeFiles/ProjectB.dir/cmake_pch.hxx:5, from <command-line>:/home/vsts/work/1/s/ProjectB/Source/stdafx.h:18:10: fatal error: Defs.h: No such file or directory

18 | #include "Defs.h" | ^~~~~~~~~~~ compilation terminated. gmake[2]: *** [Source/CMakeFiles/ProjectB.dir/build.make:77: Source/CMakeFiles/ProjectB.dir/cmake_pch.hxx.gch] Error 1 gmake[1]: *** [CMakeFiles/Makefile2:98: Source/CMakeFiles/ProjectB.dir/all] Error 2 gmake: *** [Makefile:91: all] Error 2 ##[error]The process '/usr/local/bin/cmake' failed with exit code 2 ##[error]CMake failed with error: The process '/usr/local/bin/cmake' failed with exit code 2

Building in azure devops in Linux envireonment: Ubuntu: 22.04 Cmake: 3.26 The C compiler identification is GNU 11.3.0 The CXX compiler identification is GNU 11.3.0 Ninja for build

  1. I tried adding /Yc and /Yu compiler options for stdafx.cpp and stdafx.h