understand C compilers and build system and debugers

  • CMake — build system generator
    • You use this define how to compile your code
  • gcc/g++/clang/clang++ — compilers
    • compilers turn your code into binaries
    • gcc and g++ are the GNU C and C++ compilers, respectively
    • clang and clang++ are the LLVM compilers, respectively
    • Use CMake to define how to invoke compilers on the source code files
  • gdb/lldb — debuggers
    • gdb is a debugger provided by GNU
    • lldb is a debugger provided by LLVM
    • Use these to detect issues when running your binaries
    • It generally does not matter which compiler was used to generate the binary, i.e. you can use LLDB to debug a code compiled with a GNU compiler or vice versa

diffrence between make and cmake

Make (or rather a Makefile) is a buildsystem – it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

cmake -G"MSYS Makefiles"  when compiling for MinGW
cmake -G "Visual Studio 16 2019" -A Win32  when compiling for vs
cmake -G "Visual Studio 16 2019" -A x64 when compiling for vs

for more about cmake

GCC and G++

The GNU C and C++ compiler are called gcc and g++, respectively.

// Compile and link source file hello.c into executable a.exe (Windows) or a (Unixes)
> gcc hello.c
  
// (Unixes / Mac OS X) In Bash shell
$ gcc -o hello hello.c
$ chmod a+x hello
$ ./hello

// (Windows) In CMD shell
> g++ -o hello.exe hello.cpp
   // Compile and link source hello.cpp into executable hello.exe
> hello
// Execute under CMD shell

// (Unixes / Mac OS X) In Bash shell
$ g++ -o hello hello.cpp
$ chmod a+x hello
$ ./hello
$ g++ -Wall -g -o Hello.exe Hello.cpp
-o: specifies the output executable filename.
-Wall: prints "all" Warning messages.
-g: generates additional symbolic debuggging information for use with gdb debugger.
// Compile-only with -c option
> g++ -c -Wall -g Hello.cpp
// Link object file(s) into an executable
> g++ -g -o Hello.exe Hello.o
-c: Compile into object file "Hello.o". By default, the object file has the same name as the source file with extension of ".o" (there is no need to specify -o option). No linking with other object files or libraries.
Linking is performed when the input file are object files ".o" (instead of source file ".cpp" or ".c"). GCC uses a separate linker program (called ld.exe) to perform the linking.

Suppose that your program has two source files: file1.cppfile2.cpp. You could compile all of them in a single command:

g++ -o myprog.exe file1.cpp file2.cpp 

However, we usually compile each of the source files separately into object file, and link them together in the later stage. In this case, changes in one file does not require re-compilation of the other files.

> g++ -c file1.cpp
> g++ -c file2.cpp
> g++ -o myprog.exe file1.o file2.o
gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3 // link dynamic and static filels and object to executable file
> cpp hello.c > hello.i //preprocessing 
> gcc -S hello.i //compilation generate assembly code
> as -o hello.o hello.s //assembler generate machine code 
> ld -o hello.exe hello.o ...libraries... linker and generate excutable machine code
g++ --std=c++2a test2.cpp -o test2 //select c++ version

GNU Make

First Makefile By Example

// hello.c
#include <stdio.h>
 
int main() {
    printf("Hello, world!\n");
    return 0;
}
all: hello.exe

hello.exe: hello.o
	 gcc -o hello.exe hello.o

hello.o: hello.c
	 gcc -c hello.c
     
clean:
	 rm hello.o hello.exe

Run the “make” utility as follows:

> make
gcc -c hello.c
gcc -o hello.exe hello.o

Boost Libraries

Windows Install
Ubuntu Install C++
Ubuntu Install

boost tutorial

coroutine

With Boost.Coroutine it is possible to use coroutines in C++. Coroutines are a feature of other programming languages, which often use the keyword yield for coroutines. In these programming languages, yield can be used like return. However, when yield is used, the function remembers the location, and if the function is called again, execution continues from that location.

#include <boost/coroutine/all.hpp>
#include <iostream>

using namespace boost::coroutines;

void cooperative(coroutine<void>::push_type &sink)
{
  std::cout << "Hello";
  sink();
  std::cout << "world";
}

int main()
{
  coroutine<void>::pull_type source{cooperative};
  std::cout << ", ";
  source();
  std::cout << "!\n";
}
using namespace boost::coroutines;
void cooperative(coroutine<int>::push_type &sink)
{
    int i=0;
  sink(++i);
  sink(++i);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    coroutine<int>::pull_type source{cooperative};
    qDebug()<<source.get();
    if(source){
        qDebug()<<source().get();
    }
    return a.exec();
}
//1 2
#include <boost/coroutine/all.hpp>
#include <stdexcept>
#include <iostream>

using boost::coroutines::coroutine;

void cooperative(coroutine<void>::push_type &sink)
{
  sink();
  throw std::runtime_error("error");
}

int main()
{
  coroutine<void>::pull_type source{cooperative};
  try
  {
    source();
  }
  catch (const std::runtime_error &e)
  {
    std::cerr << e.what() << '\n';
  }
}

Rotation Transform

basic 2D Rotation

Rotation About an Arbitrary Axis

Homogeneous Coordinates

Four-Dimensional Transforms

Transforming Normal Vectors

Quaternion Mathematics

rotation with quaternion

Spherical Linear Interpolation

Most UBUNTU Commands

File System

cp originalFile newFile : copy original to new
rm file : remove file
rm -rf directory : remove non-empty directory
rm -r directory : clean directory
rmdir directory : remove empty directories
mkdir directory : create directory
mv fileFrom fileTo : move file from to
ls director : display all directory content
dir directory : diplay all directories inside directory
ls -l file : file create date and owner and mod
cat file.txt file2.txt : display file content
pwd : get current path
cd path: set the current path
chmod {options} filename : change permision of file
chown USERNAME:GROUPNAME path : change owner
chown -R USERNAME:GROUPNAME path : change owner recursive
chgrp group file1 file2 dir1 : change group of file
touch file : create file
zip|unzip file

cat ./file.txt | grep "^hello .*ld.*$"
user@host:/home/user$ chmod ugo+rwx file4 #add read and write and execute permision for owner and group and others

System

lspci : pci hardware info
inxi : hardware info more readable need to install
free : memory size and how much used and free
dmesg : debug all devices
lsusb : all serial devices connected
top : monitor all processors
kill -9 pid : force kill for proccesor

Users

sudo : play command as root
sudo -i : always as root
adduser userName : add user
su : change user
usermod -aG group user : add user to group
deluser user group : remove user from group
groups : display groups of current user
exit : logout
passwd : change passward of current user
adduser –system userName : add system user
addgroup group : add new group

MongoDB

RDBMSMongoDB
DatabaseDatabase
TableCollection
Tuple/RowDocument
columnField
Table JoinEmbedded Documents
Primary KeyPrimary Key (Default key _id provided by MongoDB itself)
{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100, 
   comments: [	
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2011,1,20,2,15),
         like: 0 
      },
      {
         user:'user2',
         message: 'My second comments',
         dateCreated: new Date(2011,1,25,7,45),
         like: 5
      }
   ]
}

Embedded Data Model

In this model, you can have (embed) all the related data in a single document, it is also known as de-normalized data model.

For example, assume we are getting the details of employees in three different documents namely, Personal_details, Contact and, Address, you can embed all the three documents in a single one

{
	_id: ,
	Emp_ID: "10025AE336"
	Personal_details:{
		First_Name: "Radhika",
		Last_Name: "Sharma",
		Date_Of_Birth: "1995-09-26"
	},
	Contact: {
		e-mail: "radhika_sharma.123@gmail.com",
		phone: "9848022338"
	},
	Address: {
		city: "Hyderabad",
		Area: "Madapur",
		State: "Telangana"
	}
}

Normalized Data Model

In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as:

Employee:

{
	_id: <ObjectId101>,
	Emp_ID: "10025AE336"
}

Personal_details:

{
	_id: <ObjectId102>,
	empDocID: " ObjectId101",
	First_Name: "Radhika",
	Last_Name: "Sharma",
	Date_Of_Birth: "1995-09-26"
}

Contact:

{
	_id: <ObjectId103>,
	empDocID: " ObjectId101",
	e-mail: "radhika_sharma.123@gmail.com",
	phone: "9848022338"
}

Address:

{
	_id: <ObjectId104>,
	empDocID: " ObjectId101",
	city: "Hyderabad",
	Area: "Madapur",
	State: "Telangana"
}
show dbs; //show all databases
use db;//select database
db;//current database
db.movie.insert({"name":"tutorials point"})//insert document to collection
db.dropDatabase()//remove database
db.createCollection("mycollection")//create collection
db.COLLECTION_NAME.drop()//remove collection
show databases // display all databases
use database //select or create database
show collections // display all collections
db.post.insert([
	{
		title: "MongoDB Overview",
		description: "MongoDB is no SQL database",
		by: "tutorials point",
		url: "http://www.tutorialspoint.com",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 100
	},
	{
	title: "NoSQL Database",
	description: "NoSQL database doesn't have tables",
	by: "tutorials point",
	url: "http://www.tutorialspoint.com",
	tags: ["mongodb", "database", "NoSQL"],
	likes: 20,
	comments: [
		{
			user:"user1",
			message: "My first comment",
			dateCreated: new Date(2013,11,10,2,35),
			like: 0
		}
	]
}
])
db.empDetails.find(
	{
		$nor:[
			40
			{"First_Name": "Radhika"},
			{"Last_Name": "Christopher"}
		]
	}
)
db.COLLECTION_NAME.find(
	{
		$NOT: [
			{key1: value1}, {key2:value2}
		]
	}
)
db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
OperationSyntaxExampleRDBMS Equivalent
Equality{<key>:{$eg;<value>}}db.mycol.find({“by”:”tutorials point”}).pretty()where by = ‘tutorials point’
Less Than{<key>:{$lt:<value>}}db.mycol.find({“likes”:{$lt:50}}).pretty()where likes < 50
Less Than Equals{<key>:{$lte:<value>}}db.mycol.find({“likes”:{$lte:50}}).pretty()where likes <= 50
Greater Than{<key>:{$gt:<value>}}db.mycol.find({“likes”:{$gt:50}}).pretty()where likes > 50
Greater Than Equals{<key>:{$gte:<value>}}db.mycol.find({“likes”:{$gte:50}}).pretty()where likes >= 50
Not Equals{<key>:{$ne:<value>}}db.mycol.find({“likes”:{$ne:50}}).pretty()where likes != 50
Values in an array{<key>:{$in:[<value1>, <value2>,……<valueN>]}}db.mycol.find({“name”:{$in:[“Raj”, “Ram”, “Raghu”]}}).pretty()Where name matches any of the value in :[“Raj”, “Ram”, “Raghu”]
Values not in an array{<key>:{$nin:<value>}}db.mycol.find({“name”:{$nin:[“Ramu”, “Raghav”]}}).pretty()Where name values is not in the array :[“Ramu”, “Raghav”] or, doesn’t exist at all
{"x":{"$exists":true}} // = {"x":{"$ne":null}}

update and Save()

db.mycol.update({'title':'MongoDB Overview'},
   {$set:{'title':'New MongoDB Tutorial'}},{multi:true})
>db.mycol.save( //for insert or update
   {
      "_id" : ObjectId("507f191e810c19729de860ea"), 
		"title":"Tutorials Point New Topic",
      "by":"Tutorials Point"
   }
)
WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("507f191e810c19729de860ea")
})
>db.mycol.find()
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic",
   "by":"Tutorials Point"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"}
db.empDetails.updateOne(
	{First_Name: 'Radhika'},
	{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }
db.empDetails.updateMany(
	{Age:{ $gt: "25" }},
	{ $set: { Age: '00'}}
)
db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})
db.mycol.find()
{"_id" : ObjectId("507f191e810c19729de860e2"), "title" : "NoSQL Overview" }
{"_id" : ObjectId("507f191e810c19729de860e3"), "title" : "Tutorials Point Overview" }

limit and sort

db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
db.COLLECTION_NAME.find().sort({KEY:1})

indexing

db.mycol.createIndex({"title":1,"description":-1})
db.mycol.dropIndexes({"title":1,"description":-1})
db.members.createIndex( { "user_id": 1 }, { unique: true } )
db.COLLECTION_NAME.getIndexes()
db.COLLECTION_NAME.dropIndexes()
ParameterTypeDescription
backgroundBooleanBuilds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
uniqueBooleanCreates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
namestringThe name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
sparseBooleanIf true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false.
expireAfterSecondsintegerSpecifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection.
weightsdocumentThe weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score.
default_languagestringFor a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is English.
language_overridestringFor a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is language.

projection

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("customers").find({}, { projection: { _id: 0, name: 1, address: 1 } }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

aggregate() Method

{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 10
},
{
   _id: ObjectId(7df78ad8902e)
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j', 'database', 'NoSQL'],
   likes: 750
}

//similar to count method
db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{ "_id" : "tutorials point", "num_tutorial" : 2 }
{ "_id" : "Neo4j", "num_tutorial" : 1 }

Following are the possible stages in aggregation framework −

  • $project − Used to select some specific fields from a collection.
  • $match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.
  • $group − This does the actual aggregation as discussed above.
  • $sort − Sorts the documents.
  • $skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.
  • $limit − This limits the amount of documents to look at, by the given number starting from the current positions.
  • $unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.
ExpressionDescriptionExample
$sumSums up the defined value from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$sum : “$likes”}}}])
$avgCalculates the average of all given values from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$avg : “$likes”}}}])
$minGets the minimum of the corresponding values from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$min : “$likes”}}}])
$maxGets the maximum of the corresponding values from all documents in the collection.db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$max : “$likes”}}}])
$pushInserts the value to an array in the resulting document.db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$push: “$url”}}}])
$addToSetInserts the value to an array in the resulting document but does not create duplicates.db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$addToSet : “$url”}}}])
$firstGets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycol.aggregate([{$group : {_id : “$by_user”, first_url : {$first : “$url”}}}])
$lastGets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycol.aggregate([{$group : {_id : “$by_user”, last_url : {$last : “$url”}}}])

distinct query

db.Files.distinct("originalName",{"filament":"PLA"})