for Robot Artificial Inteligence

4. Google tests, Namespaces, Classes

|

Use GTest(Google Test) to test your functions

  • Catch bugs early to fix them with less pain
  • Testing is crucial to catch bugs early
  • Tested functions are easier to trust
  • For every function write at least two tests
    • One for normal cases
    • One for extreme cases
  • Make writing tests a habit

How do tests look?

  • A single dummy Google test:
    TEST(TestModule , FunctionName ) {
    EXPECT_EQ (4, FunctionName ());
    }
    
  • Successful output:

Add GTests with CMake

  • Install GTest source files (build them later):
    • sudo apt install libgtest-dev
  • Add folder tests to your CMake project:
    # Must be in the top-most CMakeLists.txt file
    enable_testing ()
    # Outsource tests to another folder
    add_subdirectory(tests)
    

Configure tests

# Add gtest sources folder. Provides gtest , gtest_main.
add_subdirectory(/usr/src/gtest
                ${PROJECT_BINARY_DIR}/gtest)
include(CTest) # Include testing cmake package.
# Set binary name for convenience.
set( TEST_BINARY ${PROJECT_NAME}_test)
# This is an executable that runs the tests.
add_executable(${TEST_BINARY} test_tools.cpp)
# Link the executable to needed libraries.
target_link_libraries(${TEST_BINARY}
  tools # Library we are testing
  gtest gtest_main # GTest libraries
)
# Add gtest to be able to run ctest
add_test(
  NAME ${TEST_BINARY}
  COMMAND ${EXECUTABLE_OUTPUT_PATH}/${TEST_BINARY})

Run your tests

  • Build your code just like before
  • Add one additional step after building
    cd <project_folder>
    mkdir build
    cd build
    cmake ..
    make
    ctest -VV
    

Namespaces

  • Helps avoiding name conflicts
  • Group the project into logical modules

Namespaces example

#include <iostream>

namespace boring{
  int GetMeaningOfLife() {return 0;}
}

namespace fun{
  int GetMeaningOfLife() {return 42;}
}

int main () {
  std :: cout << "The answer to everything is not "
              << boring :: GetMeaningOfLife () << " but "
              << fun :: GetMeaningOfLife () << std :: endl;
  return 0;
}

Avoid using namespace

#include <cmath >
#include <iostream >
using namespace std; // std namespace is used
// Self -defined function power shadows std::pow
double pow(double x, int exp) {
  double res = 1.0;
  for (int i = 0; i < exp; i++) { res * = x; }
  cout << "Our cool power function\n";
  return (res);
}
int main () {
  double x = 2.0;
  int power = 2;
  double res = pow(x, power);
  cout << x << " ^ " << power << " = " << res << endl;
  return 0;
}

Namespace error

Only use what you need

#include <cmath >
#include <iostream >
using std::cout; // Explicitly use cout, std 네임스페이스에서 오직 cout만 쓰게한다
using std::endl; // Explicitly use cout, std 네임스페이스에서 오직 endl만 쓰게한다
// Self -defined function power shadows std::pow
double pow(double x, int exp) {
  double res = 1.0;
  for (int i = 0; i < exp; i++) { res * = x; }
  cout << "Our cool power function\n";
  return (res);
}
int main () {
  double x = 2.0;
  int power = 2;
  double res = pow(x, power);
  cout << x << " ^ " << power << " = " << res << endl;
  return 0;
}

Namespaces Wrap Up

Use namespaces to avoid name conflicts

namespace some_name {
  <your_code >
  } // namespace some_name

Use using correctly

  • [good]
    • using my_namespace::myFunc;
    • my_namespace::myFunc(…);
  • Never use using namespace name in * .h files
  • Prefer using explicit using even in * .cpp files

Nameless namespaces

  • If you find yourself relying on some contstants in a file and these constants should not be seen in any other file, put them into a nameless namespace on the top of this file(Local variable of certain file)
namespace {
  const int kLocalImportantInt = 13;
  const float kLocalImportantFloat = 13.0f;
}

Create new types with classes and structs

  • Classes are used to encapsulate data along with methods to process them
  • Every class or struct defines a new type
  • Terminology:
    • Type or class to talk about the defined type
    • A variable of such type is an instance of class or an object
  • asses allow C++ to be used as an Object Oriented Programming language
  • string, vector, etc. are all classes

Example Class definition

class Image{
  public:
    Image(const std::string& file_name);
    void Draw();
  private:
    int rows_ = 0;
    int cols_ = 0;
}
int main () {
  Image image("some_image.pgm");
  image.Draw ();
  return 0;
}

Classes syntax

  • Definition starts with the keyword class
  • Classes have three access modifiers: private, protected and public
  • By default everything is private
  • Classes can contain data and functions
  • Access members with a “.”
  • Have two types of special functions:
    • Contructors: called upon creation of an instance of the class in stack memory
    • Destructor: called upon destruction of an instance of the class in stack memory
  • GOOGLE-STYLE Use CamelCase for class name

What about structs?

  • Definition starts with the keyword struct:
    struct ExampleStruct {
    Type value;
    Type value;
    Type value;
    // No functions!
    };
    
  • struct is a class where everything is public
  • GOOGLE-STYLE Use struct as a simple data container, if it needs a function it should be a class instead

Always initialize structs using braced initialization

#include <iostream>
#include <string>
using namespace std;
// Define a structure.
struct NamedInt {
  int num;
  string name;
};
void PrintStruct (const NamedInt& s) {
  cout << s.name << " " << s.num << endl;
}
int main(int argc , char const* argv []) {
  NamedInt var = {1, "hello"};
  PrintStruct (var);
  PrintStruct ({10 , "world"});
  return 0;
}

Data stored in a class

  • Classes can store data of any type
  • GOOGLE-STYLE All data must be private
  • GOOGLE-STYLE Use snake_case_ with a trailing “_ “ for private data members
  • Data should be set in the Constructor
  • Cleanup data in the Destructor if needed

Constructors and Destructor

  • Classes always have at least one Constructor and exactly one Destructor
  • Constructors crash course:
    • Are functions with no return type
    • Named exactly as the class
    • There can be many constructors
    • If there is no explicit constructor an implicit default constructor will be generated
  • Destructor for class SomeClass:
    • Is a function named ~SomeClass()
    • Last function called in the lifetime of an object
    • Generated automatically if not explicitly defined

Many ways to create instances

class SomeClass {
  public:
    SomeClass (); // Default constructor.
    SomeClass (int a); // Custom constructor.
    SomeClass (int a, float b); // Custom constructor.
    ~ SomeClass (); // Destructor.
};
// How to use them?
 int main () {
   SomeClass var_1; // Default constructor
   SomeClass var_2 (10); // Custom constructor
   // Type is checked when using {} braces. Use them!
   SomeClass var_3 {10}; // Custom constructor
   SomeClass var_4 = {10}; // Same as var_3
   SomeClass var_5 {10, 10.0}; // Custom constructor
   SomeClass var_6 = {10, 10.0}; // Same as var_5
   return 0;
 }

Setting and getting data

  • Use initializer list to initialize data
  • Name getter functions as the private member they return
  • Make getters const
  • Avoid setters, set data in the constructor
class Student {
  public:
    Student(int id , string name): id_{id}, name_{name} {} //initilized
    int id() const { return id_; }//input parameter convert into data variable of class
    const string& name () const { return name_; }
  private:
    int id_;
    string name_;

Const correctness

  • const after function states that this function does not change the object
  • Mark all functions that should not change the state of the object as const
  • Ensures that we can pass objects by a const reference and still call their functions
  • Substantially reduces number of errors

Typical const error

Declaration and definition

  • Data members belong to declaration
  • Class methods can be defined elsewhere
  • Class name becomes part of function name
// Declare class.
class SomeClass {
  public:
    SomeClass ();
    int var () const;
  private:
    void DoSmth ();
    int var_ = 0;
};
// Define all methods.
SomeClass :: SomeClass () {}
int SomeClass :: var () const { return var_; }
void SomeClass :: DoSmth () {}

Always initialize members for classes

  • C++11 allows to initialize variables in-place
  • Do not initialize them in the constructor
  • No need for an explicit default constructor
    class Student {
    public:
      // No need for default constructor.
      // Getters and functions omitted.
    private:
      int earned_points_ = 0;
      float happiness_ = 1.0f;
    };
    
  • Note: Leave the members of structs uninitialized as defining them forbids using brace initialization

Classes as modules

  • Prefer encapsulating information that belongs together into a class
  • Separate declaration and definition of the class into header and source files
  • Typically, class SomeClass is declared in some_class.h and is defined in some_class.cpp

Reference

https://www.ipb.uni-bonn.de/teaching/modern-cpp/

Cpp Core Guidelines: https://github.com/isocpp/CppCoreGuidelines

Git guide: http://rogerdudler.github.io/git-guide/

C++ Tutorial: http://www.cplusplus.com/doc/tutorial/

Book: Code Complete 2 by Steve McConnell

Modern CMake Tutorial https://www.youtube.com/watch?v=eC9-iRN2b04

Compiler Explorer: https://godbolt.org/ Gdbgui: https://www.gdbgui.com/ CMake website: https://cmake.org/ Gdbgui tutorial: https://www.youtube.com/watch?v=em842geJhfk

Comment  Read more

3.Compilation, Functions, Source, Library and Cmake

|

Compilation flags

  • There is a lot of flags that can be passed while compiling the code
    • -std=c++11, -o, etc

Other useful options:

  • Enable all warnings, treat them as errors:
    • -Wall, -Wextra, -Werror
  • Optimization options:
    • -O0 - no optimizations
    • -O3 or -Ofast - full optimizations(Best)
  • Keep debugging symbols: -g

Debugging tools

  • The best option is to use gdb
chan@chan~acer:/temp$ c++ -std=c++11 -g test.cpp
chan@chan~acer:/temp$ gdb a.out

Quit anyway? (y or n) y
chan@chan~acer:/temp$ gdb a.out
  • Insanely popular and powerful
  • No build-in gui
  • Use gdbgui for a user-friendly interface
  • Install gdbgui from pip:
    • sudo pip3 install –upgrade gdbgui

Functions

ReturnType FuncName(ParamType1 in_1 , ParamType2 in_2){
  // Some awesome code here.
  return return_value;
}
  • Code can be organized into functions
  • Functions create a scope
  • Single return value from a function
  • Any number of input variables of any types
  • Should do only one thing and do it right
  • Name must show what the function does
  • GOOGLE-STYLE name functions in CamelCase
  • GOOGLE-STYLE write small functions

Example in GOOGLE-STYLE Function

#include <vector>
using namespace std;
vector<int> CreateVectorOfFullSquares(int size){ // vecotr<int>는 데이터 타입이다. 모든 펑션에는 데이터 타입이 필요하다 like void, int, float, double 등등
  vector<int> result(size);
  for (int i=0; i<size; ++i) { result[i] = i * i; }
  return result;
}
int main(){
  auto squares = CreateVectorOfFullSquares(10);
  return 0;
}

  • Is small enough to see all the code at once
  • Name clearly states what the function does
  • Function does a single thing

Declaration and definition

  • Function declaration can be separated from the implementation details
  • Function declaration sets up an interface
void FuncName(int param);
  • Function definition holds the implementation of the function that can even be hidden from the user

void FuncName(int param){
  // Implementation details.
  cout<<"This function is called FuncName! ";
  cout<<"Did you expect anything useful from it?";
}

Passing big objects

  • By default in C++, objects are copied when passed into functions
  • If objects are big it might be slow
  • Pass by reference to avoid copy

void DoSmth(std::string huge_string); // Slow.
void DoSmth(std::string& huge_string); // Faster.

  • Is the string still the same?

string hello="some_important_long_string";
DoSmth(hello);

  • Unknown without looking into DoSmth()!

    Pass by reference Intuition

Pass by reference:

  • void fillCup(Cup &cup);
  • cup is full

    Pass by value:

  • void fillCup(Cup cup);
  • A copy of cup is full
  • cup is still empty

Example


#include <iostream>
using namespace std;
int sum(int& a, int b)
{
  a = 10;
  return a + b;
}
int main()
{
  int blah = 1;
  int a = sum(blah,2);
  cout<<a<<endl;
  return 0;
}
// output 12

Solution : use const references

  • 그냥 Reference만 붙여도 되지만 어차피 똑같은 결과 속도를 더 높이기 위해서 const int& 와 같은 데이터 타입에 const를 넣는다.
  • Pass const reference to the function
  • Great speed as we pass a reference
  • Passed object stays intact(完好)

void DoSmth(const std::string& huge_string);

  • Use snake_case for all function arguments
  • Non-const refs are mostly used in older code written before C++11
  • They can be useful but destroy readability
  • GOOGLE-STYLE Avoid using non-const refs

Function overloading

  • Compiler infers( 暗示) a function from arguments
  • Cannot overload based on return type
  • Return type plays no role at all
  • GOOGLE-STYLE Avoid non-obvious overloads

#include <iostream>
#include <string>
using namespace std;
string Func(int num) { return "int"; }
string Func(const string& str) { return "string"; }
int main (){
  cout<<Func(1)<< endl;
  cout<<Func("hello")<< endl;
  return 0;
}
// output int, hello

default arguments

  • Functions can accept default arguments
  • Only set in declaration not in definition
  • Pro: simplify function calls
  • Cons:
    • Evaluated upon every call
    • Values are hidden in declaration
    • Can lead to unexpected behavior when overused
  • GOOGLE-STYLE Only use them when readability gets much better

Example: default arguments


#include <iostream> // std::cout , std::endl
using namespace std;
string SayHello(const string& to_whom = "world") {
  return "Hello " + to_whom + "!";
}
int main () {
  cout<<SayHello()<< endl;
  cout<<SayHello("students")<<endl;
  return 0;
}

Don’t reinvent(以新形式出现) the wheel

  • When using std::vector, std::array, etc. try to avoid writing your own functions.
  • Use #include
  • There is a lot of functions in std which are at least as fast as hand-written ones:

std::vector<float> v;
// Filling the vector omitted here.
std::sort(v.begin (), v.end ()); // Sort ascending.
float sum = std::accumulate(v.begin(), v.end(), 0.0f);
float product = std::accumulate(v.begin(), v.end(), 1.0f, std::multiplies<float>());

Header / Source Separation

  • Move all declarations to header files (* .h)
  • implementation goes to * .cpp or * .cc

// some_file.h
Type SomeFunc(... args ...);

// some_file.cpp
#include "some_file.h"
Type SomeFunc(... args ...) { /* code * / }

// program.cpp
#include "some_file.h"
int main(){
  SomeFunc(/* args */);
  return 0;
}

How to build this?

folder/
    --- tools.h
    --- tools.cpp
    --- main.cpp

Short: we separate the code into modules

Declaration: tools.h


#pragma once // Ensure file is included only once
void MakeItSunny();
void MakeItRain();

  • #pragma once <- 중복 declaration을 방지

Definition: tools.cpp


#include <iostream>
#include "tools.h"
void MakeItRain(){
  // important weather manipulation code
  std::cout<<"Here! Now it rains! Happy?\n";
}
void MakeItSunny(){ std::cerr<<"Not available\n"; }

Calling : main.cpp


#include "tools.h"
int main (){
  MakeItRain();
  MakeItSunny();
  return 0;
}

Just build it as before?

c++ -std=c++11 main.cpp -o main

Error:

/tmp/tools_main -0 eacf5.o: In function `main ':
tools_main .cpp: undefined reference to `makeItRain ()'
tools_main .cpp: undefined reference to `makeItSunny ()'
clang: error: linker command failed with exit code 1
(use -v to see invocation )

Use modules and libraries

1. Compile modules:

c++ -std=c++11 -c tools.cpp -o tools.o

  • o is a compiled binary file for machine code(instrument) [ it called object files]

2. Organize modules into libraries:

ar rcs libtools.a tools.o

c++ -std=c++11 main.cpp -L . -ltools -o main

4. Run the Code:

./main

Libraries

  • Library: multiple object files that are logically connected
  • Types of libraries:
    • Static: faster, take a lot of space, become part of the end binary, named: lib*.a
    • Dynamic: slower, can be copied, referenced by a program, named lib*.so
  • Create a static library with
    • ar rcs libname.a module.o module.o …
  • Static libraries are just archives just like
    • zip/tar/…

What is linking?

  • The library is a binary object that contains the compiled implementation of some methods
  • Linking maps a function declaration to its compiled implementation
  • To use a library we need a header and the compiled library object

Use CMake to simplify the build

  • One of the most popular build tools
  • Does not build the code, generates files to eed into a build system
  • Cross-platform
  • Very powerful, still build receipt is readable
  • The library creation and linking can be rewritten as follows:
    add_library(tools tools.cpp)
    add_executable(main main.cpp)
    target_link_libraries(main tools)
    

Typical project structure

<a href=”https://postimg.cc/Jy2GgqgD>

Build process of CMAKE

  • CMakeLists.txt defines the whole build
  • CMake reads CMakeLists.txt sequentially
  • Build process:
    cd <project_folder>
    mkdir build
    cd build
    cmake ..
    make -j2 # pass your number of cores here
    

First working CMakeLists.txt

project( first_project ) # Mandatory.
cmake_minimum_required(VERSION 3.1) # Mandatory.
set( CMAKE_CXX_STANDARD 11) # Use c++11
# tell cmake to output binaries here:
set( EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
set( LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
# tell cmake where to look for *.h files
include_directories(${PROJECT_SOURCE_DIR}/src)
# create library "libtools"
add_library(tools src/tools.cpp)
# add executable main
add_executable(main src/ tools_main .cpp)
# tell the linker to bind these objects together
target_link_libraries(main tools)

Useful commands in CMake

  • Just a scripting language
  • Has features of a scripting language, i.e.
    • functions, control structures, variables, etc.
  • All variables are string
  • Set variables with set(VAR VALUE)
  • Get value of a variable with ${VAR}
  • Show a message message(STATUS “message”)
  • Also possible WARNING, FATAL_ERROR

Use CMake in your builds

  • Build process is standard and simple
  • No need to remember sequence of commands
  • All generated build files are in one place
  • CMake detects changes to the files
  • Do this after changing files:
    cd project/build
    make -j2 # pass your number of cores here
    

Set compilation options in CMake

set ( CMAKE_CXX_STANDARD 14)
# Set build type if not set.
if(NOT CMAKE_BUILD_TYPE )
  set( CMAKE_BUILD_TYPE Release) //debug: we don't want optimization
endif ()
# Set additional flags.
set( CMAKE_CXX_FLAGS "-Wall -Wextra ")
set( CMAKE_CXX_FLAGS_DEBUG "-g -O0")
set( CMAKE_CXX_FLAGS_RELEASE "-O3")
  • -Wall -Wextra: show all warnings
  • -g: keep debug information in binary
  • -O: optimization level in {0, 1, 2, 3}
    • 0: no optimization
    • 3: full optimization

Remove build folder for performing a clean build

  • Sometimes you want a clean build
  • It is very easy to do with CMake
cd project/build
make clean [remove generated binaries]
rm -r * [make sure you are in build folder]

Use pre-compiled library

  • Sometimes you get a compiled library
  • You can use it in your build
  • For example, given libtools.so it can be used in the project as follows:
find_library(TOOLS
            NAMES tools
            PATHS ${LIBRARY_OUTPUT_PATH})
# Use it for linking:
target_link_libraries(<some_binary > ${TOOLS})

Reference

https://www.ipb.uni-bonn.de/teaching/modern-cpp/

Cpp Core Guidelines: https://github.com/isocpp/CppCoreGuidelines

Git guide: http://rogerdudler.github.io/git-guide/

C++ Tutorial: http://www.cplusplus.com/doc/tutorial/

Book: Code Complete 2 by Steve McConnell

Modern CMake Tutorial https://www.youtube.com/watch?v=eC9-iRN2b04

Compiler Explorer: https://godbolt.org/ Gdbgui: https://www.gdbgui.com/ CMake website: https://cmake.org/ Gdbgui tutorial: https://www.youtube.com/watch?v=em842geJhfk

Comment  Read more

Jekyll markdown

|

블로그가 Jekyll로 만들어져있어 게시물을 게시할때 깔끔하게 정리할 수 있는 markdown을 정리해보았다.

1. Header & Sub-Header

- Header

Syntax

이것은 헤더입니다.
===

Example

이것은 헤더입니다.

- sub-Header

Syntax

이것은 부제목입니다.
---

Example

이것은 부제목입니다.

- H1 ~ H6 Tags

Syntax

 # H1
 ## H2
 ### H3
 #### H4
 ##### H5
 ###### H6

Example

H1

H2

H3

H4

H5
H6

2. Links

링크를 넣고 싶은 경우는 2가지 방법이 있다.

Syntax

Link: [참조 키워드][링크변수]
[링크변수]: WebAddress "Descriptions"

Example

Link : [Google][https://google.com]

Syntax

Link: [Google](https://google.com)

Example

Link: Google

3. BlockQuote

Syntax

 >이것은 Block Quote
 >이것은 Block Quote
  >이것은 Block Quote
  >이것은 Block Quote

Example

이것은 Block Quote 이것은 Block Quote 이것은 Block Quote 이것은 Block Quote

4. Ordered List

Syntax

 1. 순서가 있는 목록
 2. 순서가 있는 목록
 3. 순서가 있는 목록

Example

  1. 순서가 있는 목록
  2. 순서가 있는 목록
  3. 순서가 있는 목록

5. Unordered list

Syntax

 - 순서가 없는 목록
 - 순서가 있는 목록
 - 순서가 있는 목록

Example

  • 순서가 없는 목록
  • 순서가 있는 목록
  • 순서가 있는 목록

6. Code Block

- General

Syntax

 <pre> Code block open
 <code> write a code here</code>
 code block close</pre>

Example

 Code block open
 write a code here
code block close

- python

Syntax

  ```python
     # This program adds up integers in the command line
  import sys
  try:
      total = sum(int(arg) for arg in sys.argv[1:])
      print 'sum =', total
  except ValueError:
      print 'Please supply integer arguments'

Example

   # This program adds up integers in the command line
import sys
try:
    total = sum(int(arg) for arg in sys.argv[1:])
    print 'sum =', total
except ValueError:
    print 'Please supply integer arguments'

Ruby

Syntax

  ```ruby
  a = [ 45, 3, 19, 8 ]
  b = [ 'sam', 'max', 56, 98.9, 3, 10, 'jill' ]
  print (a + b).join(' '), "\n"
  print a[2], " ", b[4], " ", b[-2], "\n"
  print a.sort.join(' '), "\n"
  a << 57 << 9 << 'phil'
  print "A: ", a.join(' '), "\n"

Example

a = [ 45, 3, 19, 8 ]
b = [ 'sam', 'max', 56, 98.9, 3, 10, 'jill' ]
print (a + b).join(' '), "\n"
print a[2], " ", b[4], " ", b[-2], "\n"
print a.sort.join(' '), "\n"
a << 57 << 9 << 'phil'
print "A: ", a.join(' '), "\n"

C++

Syntax

  ```c++
  int str_equals(char *equal1, char *eqaul2)
  {
     while(*equal1==*eqaul2)
     {
        if ( *equal1 == '\0' || *eqaul2 == '\0' ){break;}
        equal1++;
        eqaul2++;
     }
     if(*eqaul1 == '\0' && *eqaul2 == '\0' ){return 0;}
     else {return -1};
  }

Example

int str_equals(char *equal1, char *eqaul2)
{
   while(*equal1==*eqaul2)
   {
      if ( *equal1 == '\0' || *eqaul2 == '\0' ){break;}
      equal1++;
      eqaul2++;
   }
   if(*eqaul1 == '\0' && *eqaul2 == '\0' ){return 0;}
   else {return -1};
}

C#

Syntax

  ```c#
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  namespace Inheritance
  {

      class Program
      {
          static void Main(string[] args)
          {
              Teacher d = new Teacher();
              d.Teach();
              Student s = new Student();
              s.Learn();
              s.Teach();
              Console.ReadKey();
          }

          class Teacher
          {
              public void Teach()
              {
                  Console.WriteLine("Teach");
              }
          }

          class Student : Teacher
          {
              public void Learn()
              {
                  Console.WriteLine("Learn");
              }
          }
      }
  }

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inheritance
{

    class Program
    {
        static void Main(string[] args)
        {
            Teacher d = new Teacher();
            d.Teach();
            Student s = new Student();
            s.Learn();
            s.Teach();
            Console.ReadKey();
        }

        class Teacher
        {
            public void Teach()
            {
                Console.WriteLine("Teach");
            }
        }

        class Student : Teacher
        {
            public void Learn()
            {
                Console.WriteLine("Learn");
            }
        }
    }
}

JABA

Syntax

  ```go
  package main

  import "fmt"

  func main() {
     var greeting =  "Hello world!"

     fmt.Printf("normal string: ")
     fmt.Printf("%s", greeting)
     fmt.Printf("\n")
     fmt.Printf("hex bytes: ")

     for i := 0; i < len(greeting); i++ {
         fmt.Printf("%x ", greeting[i])
     }

     fmt.Printf("\n")
     const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"

     /*q flag escapes unprintable characters, with + flag it escapses non-ascii
     characters as well to make output unambigous */
     fmt.Printf("quoted string: ")
     fmt.Printf("%+q", sampleText)
     fmt.Printf("\n")  
  }

Example

package main

import "fmt"

func main() {
   var greeting =  "Hello world!"

   fmt.Printf("normal string: ")
   fmt.Printf("%s", greeting)
   fmt.Printf("\n")
   fmt.Printf("hex bytes: ")

   for i := 0; i < len(greeting); i++ {
       fmt.Printf("%x ", greeting[i])
   }

   fmt.Printf("\n")
   const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"

   /*q flag escapes unprintable characters, with + flag it escapses non-ascii
   characters as well to make output unambigous */
   fmt.Printf("quoted string: ")
   fmt.Printf("%+q", sampleText)
   fmt.Printf("\n")  
}

Swift

Syntax


  ```swift
  let password = "HelloWorld"
  let repeatPassword = "HelloWorld"
  if ((password.elementsEqual(repeatPassword)) == true)
  {
     print("Passwords are equal")
  } else {
     print("Passwords are not equal")
  }

Example

let password = "HelloWorld"
let repeatPassword = "HelloWorld"
if ((password.elementsEqual(repeatPassword)) == true)
{
   print("Passwords are equal")
} else {
   print("Passwords are not equal")
}

7. Strketthrough(취소선)

Syntax

  ~~ 이것은 취소선 입니다. ~~

Example

~~ 이것은 취소선 입니다. ~~

8. Bold, Italic

Syntax

  [Italic]          * 기울임 *
  [Bold]           ** 강조 **
  [Bold & Italic] *** 강조와 기울임 ***

Example

기울임 강조 강조와 기울임

9. Image

Syntax

  <a href="https://postimg.cc/Kkz1fJFW"><img src="https://i.postimg.cc/9MPyWnkc/Capture.jpg" width="700px" title="source: imgur.com" /><a>

Example

Comment  Read more

2.Modern C++ and git

|

Outline

  1. Variables and baisc types
    • built-in types
    • Strings
    • Vector and array
  2. Control structures
    • If statement
    • Switch statement
    • Loops

Declaring variables

Variable declaration always follows pattern:

  • [ = ];
  • Every variable has a type
  • Variables cannot change their type
  • Always initialize variables if you can
int sad_uninitialized_var;
 bool initializing_is_good = true;

Naming variables

  • Name must start with a letter
  • Give variables meaningful names
  • Don’t be afraid to use longer names
  • Don’t include type in the name
  • Don’t use negation in the name
  • GOOGLE-STYLE name variables in snake_case all lowercase, underscores separate words
  • C++ is case sensitive:
    • some_var is different from some_Var

Built-in types

“Out of the box” types in C++:

Operations on arithmetic types

  • All character, integer and floating point types are arithmetic
  • Arithmetic operations: +, -, * , /
  • Comparisons <, >, <=, >=, == return bool
  • a += 1 ⇔ a = a + 1, same for -=, * =, /=, etc
  • Avoid == for floating point types

Some additional operations

  • Boolean variables have logical operations
    • or:   , and: &&, not: !
bool is_happy = (!is_hungry && is_warm) || is_rich
  • Additional operations on integer variables:
    • / is integer division: i.e. 7 / 3 == 2
    • % is modulo division: i.e. 7 / 3 == 1
    • Increment operator: a++ ⇔ ++a ⇔ a += 1
    • Decrement operator: a– ⇔ –a ⇔ a -= 1
    • Do not use de- increment operators within another expression, i.e. a = (a++) + ++b

Strings

  • #include to use std::string
  • Concatenate strings with +
  • Check if str is empty with str.empty()
  • Works out of the box with I/O streams
#include <iostream>
#include <string>
int main() {
  std::string hello = "Hello";
  std::cout << "Type your name:" << std::endl;
  std::string name = ""; // Init empty.
  std::cin >> name; // Read name.
  std::cout << hello + ", " + name + "!" << std::endl;
  return 0;
}

Use std::array for fixed size collections of items(allocate stack memory as static programming)

  • #include to use std::array
  • Store a collection of items of same type
  • Create from data:
    • array<float, 3> arr = {1.0f, 2.0f, 3.0f};
  • Access items with arr[i]
    • indexing starts with 0
  • Number of stored items: arr.size()
  • Useful access aliases:
    • First item: arr.front() == arr[0]
    • Last item: arr.back() == arr[arr.size() - 1]

Use std::vector when number of items is unknown before-wise(allocated heap memory as dynamic programming)

  • #include to use std::vector
  • Vector is implemented as a dynamic table
  • Access stored items just like in std::array
  • Remove all elements: vec.clear()
  • Add a new item in one of two ways:
    • vec.emplace_back(value) [preferred, c++11]
    • vec.push_back(value) [historically better known]
  • Use it! It is fast and flexible!
    • Consider it to be a default container to store collections of items of any same type

Optimize vector resizing

  • Many push_back/emplace_back operations force vector to change its size many times
  • reserve(n) ensures that the vector has enough memory to store n items
  • The parameter n can even be approximate
  • This is a very important optimization
std::vector <std::string > vec;
const int kIterNum = 100;
// Always call reserve when you know the size.
for (int i = 0; i < kIterNum; ++i) {
  vec.emplace_back("hello");
}

Example Vector

#include <string >
#include <vector >
#include <iostream >
using namespace std;
int main() {
  vector <int> numbers = {1, 2, 3};
  vector <string > names = {"Igor", "Cyrill"};
  names.push_back("another_string");
  cout << "First name: " << names.front() << endl;
  cout << "Last number: " << numbers.back() << endl;
  return 0;
}

Variables live in scopes

  • There is a single global scope
  • Local scopes start with { and ends with }
  • All variables belong to the scope where they have been declared
  • All variables die in the end of their scope
  • This is the core of C++ memory system
int main()// Start of main scope.
{
  float some_float = 13.13f; // Create variable.
  {
    // New inner scope
    auto another_float = some_float; // Copy variable.
  } // another_float dies
  return 0;
}// some_float dies.

Any variable can be const

  • Use const to declare a constant
  • The compiler will guard it from any changes
  • Keyword const can be used with any type
  • GOOGLE-STYLE name constants in CamelCase starting with a small letter k:
    • const float kImportantFloat = 20.0f;
    • const int kSomeInt = 20;
    • const std::string kHello = “hello”;
  • const is part of type:
    • variable kSomeInt has type const int
  • Tip: declare everything const unless it must be changed

References to variables

  • We can create a reference to any variable
  • Use & to state that a variable is a reference
    • float& ref = original_variable;
    • std::string& hello_ref = hello;
  • Reference is part of type: variable ref has type float&
  • Whatever happens to a reference happens to the variable and vice versa
  • Yields performance gain as references avoid copying data

Const with references

  • References are fast but reduce control
  • To avoid unwanted changes use const
    • const float& ref = original_variable;
    • const std::string& hello_ref = hello;
#include <iostream >
using namespace std;
int main() {
  int num = 42; // Name has to fit on slides
  int& ref = num;
  const int& kRef = num;
  ref = 0;
  cout << ref << " " << num << " " << kRef << endl; // output 0 0 0
  num = 42;
  cout << ref << " " << num << " " << kRef << endl; // output 42 42 42
  return 0;
}

If statement

if (STATEMENT) {
// This is executed if STATEMENT == true
} else if (OTHER_STATEMENT) {
// This is executed if:
// (STATEMENT == false) && (OTHER_STATEMENT == true)
} else {
// This is executed if neither is true
}
  • Used to conditionally execute code
  • All the else cases can be omitted if needed
  • STATEMENT can be any boolean expression

Switch Statement

switch(STATEMENT) {
  case CONST_1:
    // This runs if STATEMENT == CONST_1.
    break;
  case CONST_2:
    // This runs if STATEMENT == CONST_2.
    break;
  default:
    // This runs if no other options worked.
}
  • Used to conditionally execute code
  • Can have many case statements
  • break exits the switch block
  • STATEMENT usually returns int or enum value

While loop

while (STATEMENT) {
  // Loop while STATEMENT == true.
}

Example while loop:

bool condition = true;
while (condition) {
  condition = /* Magically update condition. * /
}

  • Usually used when the exact number of iterations is unknown before-wise
  • Easy to form an endless loop by mistake

For loop

for (INITIAL_CONDITION; END_CONDITION; INCREMENT) {
  // This happens until END_CONDITION == false
}

Example for Loop

for (int i = 0; i < COUNT; ++i) {
  // This happens COUNT times.
}
  • In C++ for loops are very fast. Use them!
  • Less flexible than while but less error-prone
  • Use for when number of iterations is fixed and while otherwise

Range for loop

  • Iterating over a standard containers like array or vector has simpler syntax
  • Avoid mistakes with indices
  • Show intent with the syntax
  • Has been added in C++11
for (const auto& value : container) {
  // This happens for each value in the container.
}

Exit loops and iterations

  • We have control over loop iterations
  • Use break to exit the loop
  • Use continue to skip to next iteration
while (true) {
  int i = /* Magically get new int. *
  if (i % 2 == 0) {
    cerr << i << endl;
  }
  else{
    break;
  }
}

Git

  • Free software for distributed version control
  • synchronizes local and remote files
  • stores a history of all changes

What is synchronized?

  • Local files on a computer
  • Remote Files in the repository
  • We are using a Gitlab server

Typical workflow

Cloning a repository:

  • git clone In :
  • Change files
  • git add
  • git commit -am ‘descriptive message’
  • git push origin master

Reference

https://www.ipb.uni-bonn.de/teaching/modern-cpp/

Cpp Core Guidelines: https://github.com/isocpp/CppCoreGuidelines

Git guide: http://rogerdudler.github.io/git-guide/

C++ Tutorial: http://www.cplusplus.com/doc/tutorial/

Book: Code Complete 2 by Steve McConnell

Comment  Read more

1.Modern C++ Introduction

|

Outline

  1. Linux Introduction

  2. C++ syntax

what we will learn

  • how to work in Linux
  • How to write software with modern c++
  • core software development techniques
  • how to work with image using OpenCV
  • how to implement inverse image search

Check out Google Image search for example: https://images.google.come/

why C++? why Linux? Why?

  • over 50000 developers surveyed
  • nearly half of them use linux
  • C++ is the most used systems language(4.5 million users in 2015)
  • All companies want C++ in our field.

What is Linux?

  • Linux is a free Unix-like OS
  • Linux kernel implemented by Linus Torvalds.
  • Extremely popular: Android, ChromeOS, servers, supercomputers.
  • use any distribution if we have preference

Linux Directory tree

  • Tree organization starting with root: /
  • There are no volume letters, e.g. C:, D:
  • User can only access his/her own folder

Understanding files and folders

  • Folders end with / e.g. /path/folder/
  • Everything else is files, e.g. /path/file
  • Absolute paths start with / while all other paths are relative:
    • /home/igor/folder/ — absolute path to a folder
    • /home/igor/file.cpp — absolute path to a file
    • folder/file — relative path to a file
  • Paths are case sensitive:
    • filename is different from FileName
  • Extension is part of a name:
    • filename.cpp is different from filename.png

Linux Terminal

  • Press Ctrl + Alt + T to open terminal
  • Linux terminal is a very powerful tool
  • Most tasks can be done faster from the terminal than from the GUI

Navigating tree from terminal

  • Terminal is always in some folder
  • pwd: print working directory
  • cd : change directory to
  • ls : list contents of a directory
  • Special folders:
    • / — root folder
    • ~ — home folder
    • . — current folder
    • .. — parent folder

Structure of Linux commands

Typical structure

${PATH}/command [ options ] [ parameters ]

  • ${PATH}/command: absolute or relative path to the program binary
    • e.g. -h, or –help
    • e.g. input files, etc.

Use help with Linux programs

  • man — manual
    • exhaustive(철저한) manual on program usage
  • command -h
  • command –help
    • usually shorter help message

Using command completion

Pressing [tab] while typing:

  • completes name of a file, folder or program
  • “beeps” if current text does not match any file or folder uniquely Pressing [tab] + [tab] shows all potential matches

Example :

Creating and manipulating files and folders

  • mkdir [-p] — make directory
    • Create a folder (with all parent folders [-p])
  • rm [-r] — remove [recursive]
    • Remove file or folder (With folder contents [-r])
  • cp [-r] — copy
    • Copy file or folder from to
  • mv — move
    • Move file or folder from to

Using placeholders

  • Can be used with most of terminal commands: ls, rm, mv etc.

Example

Standard input/output channels

  • Single input channel: stdin
  • Two output channels:
    • stdout: Standard output: channel 1
    • stderr: Standard error output: channel 2
  • Redirecting stdout
    • command 1> out.txt
    • command » out.txt
  • Redirecting stderr
    • command 2> out.txt
  • Redirect stdout and stderr into a file
    • progamm > out.txt 2>&1
  • Write stdout and stderr into different files
    • progamm 1>stdout.txt 2>stderr.txt

Working with files

  • more/less/cat
    • Most of the time using cat if enough
  • find -name
    • Search for file in folder
    • , allows wildcards
  • grep
    • Search for a string in a file

Chaining commands

  • command1; command2; command3
    • Calls commands one after another
  • command1 && command2 && command3
    • Same as above but fails if any of the commands returns a non-zero code
  • command1 command2 command3
    • Pipe stdout of command1 to stdin of command2 and stdout of command2 to stdin of command3
  • Piping commonly used with grep:
    • ls grep smth look for smth in output of ls

Canceling commands

  • CTRL + C
    • Cancel currently running command
  • kill -9
    • Kill the process with id pid
  • killall
    • Kill all processes with name pname
  • htop (top)
    • Shows an overview of running processes
    • Allows to kill processes by pressing F9

      Command history

  • The shell saves the history of commands in the ~/.bash_history file

Installing software

Most of the software is available in the system repository. To install a program in Ubuntu type this into terminal:

  • sudo apt update to update information about available packages
  • **sudo apt install ** to install the program that you want
  • **Use apt search ** to find all packages that provide
  • Same for any library, just with lib prefix

where to write C++ code

Good code style

Programs are meant to be read by humans and only incidentally for computers to execute. - Donald Knuth

  • Use clang_format to format your code
  • use cpplint to check the style
  • Following a style guide will save you time and make the code more readable
  • We use Google Code Style Sheet
  • Naming and style recommendations will be marked by GOOGLE-STYLE tag in slides

Everything starts with main

  • Every C++ program starts with main
  • main is a function that returns an error code
  • Error code 0 means OK
  • Error code can be any number in [1, 255]

#include directive

Two variants:

  • #include — system include files
  • #include “file” — local include files
    • Copies the content of file into the current file

I/O streams for simple input and output

  • Handle stdin, stdout and stderr:
    • std::cin — maps to stdin
    • std::cout — maps to stdout
    • std::cerr — maps to stderr
  • #include to use I/O streams
  • #include <bits/strc++> to use I/O streams
  • Part of C++ standard library

Compile and run Hello World!

  • We understand text
  • Computer understands machine code
  • Compilation is translation from text to machine code
  • Compilers we can use on Linux:
    • GCC
    • Clang [*] [used in examples]
  • Compile and run Hello World example:

Reference

https://www.ipb.uni-bonn.de/teaching/modern-cpp/

Cpp Core Guidelines: https://github.com/isocpp/CppCoreGuidelines

Git guide: http://rogerdudler.github.io/git-guide/

C++ Tutorial: http://www.cplusplus.com/doc/tutorial/

Book: Code Complete 2 by Steve McConnell

Comment  Read more