├── Cpp ├── asioTcpServer │ ├── build │ │ ├── CMakeFiles │ │ │ ├── progress.marks │ │ │ ├── server.dir │ │ │ │ ├── progress.make │ │ │ │ ├── depend.make │ │ │ │ ├── link.txt │ │ │ │ ├── depend.internal │ │ │ │ ├── flags.make │ │ │ │ ├── cmake_clean.cmake │ │ │ │ ├── CXX.includecache │ │ │ │ └── DependInfo.cmake │ │ │ ├── cmake.check_cache │ │ │ ├── feature_tests.bin │ │ │ ├── 3.13.4 │ │ │ │ ├── CompilerIdC │ │ │ │ │ └── a.out │ │ │ │ ├── CompilerIdCXX │ │ │ │ │ └── a.out │ │ │ │ ├── CMakeDetermineCompilerABI_C.bin │ │ │ │ ├── CMakeDetermineCompilerABI_CXX.bin │ │ │ │ ├── CMakeSystem.cmake │ │ │ │ └── CMakeCCompiler.cmake │ │ │ ├── TargetDirectories.txt │ │ │ ├── CMakeDirectoryInformation.cmake │ │ │ ├── feature_tests.c │ │ │ └── Makefile.cmake │ │ └── cmake_install.cmake │ ├── CMakeLists.txt │ └── server.cpp ├── QtOpenCV │ ├── staticTest │ │ ├── my_math.cpp │ │ ├── my_math.h │ │ ├── .qmake.stash │ │ ├── staticTest.pro │ │ └── main.cpp │ ├── QtOpencvQml │ │ ├── qml.qrc │ │ ├── qmlType.h │ │ ├── main.qml │ │ ├── qmlType.cpp │ │ ├── .qmake.stash │ │ ├── QtOpencvQml.pro │ │ └── main.cpp │ ├── Editor │ │ ├── main.cpp │ │ ├── editor.pro │ │ └── mainwindow.h │ └── Viewer │ │ ├── main.cpp │ │ ├── .qmake.stash │ │ ├── viewer.pro │ │ └── mainwindow.h ├── reverserInt.cpp ├── nonDerived.cpp ├── findSubstringInString.cpp ├── socketExample │ ├── main.cpp │ ├── myserver.h │ ├── myserver.cpp │ ├── myclient.h │ ├── mytask.h │ ├── mytask.cpp │ ├── socketExample.pro │ ├── socketExample.uml │ └── myclient.cpp ├── firstNonRepeatingChar.cpp ├── findMinReturnType.cpp ├── CustomAllocator.cpp ├── reverseWordsInSentence.cpp ├── openCVExample.cpp ├── maxSubArray.cpp ├── minMove3Consecutive.cpp ├── majorityElementII.cpp ├── conversionOperator.cpp ├── twoSum.cpp ├── numIslandsDFS.cpp ├── RTTI.cpp ├── lambdaOutOfScope.cpp ├── framebuffer1.c ├── nonAutoDuration.cpp ├── partialMocking.cpp ├── asyncProcess.cpp ├── stockPair.cpp ├── longestPalindrome.cpp ├── LongetCommonSubsequence.cpp ├── server.cpp ├── twoOutOfThreef.cpp ├── LongestCommonSubsDynamic.cpp ├── findDuplicate.cpp ├── numberOfIslands_dfs.cpp ├── forSum2.cpp ├── threadLimitTest.cpp ├── stockPair2.cpp ├── travellingSalesMan.cpp ├── FirstUniqueCharacterInaString.cpp ├── minTimeToCompleteTrip.cpp ├── maxArea.cpp ├── nestedStructExample.cpp ├── subtractMin.cpp ├── LongestCommonSubsequence.cpp ├── stringToInt.cpp ├── async_server.cpp ├── forSum22.cpp ├── client.cpp ├── swapNodes.cpp ├── numberOfMoves.cpp ├── stackWithMaxElement.cpp ├── 3sum.cpp ├── longestPalindromeManacher.cpp ├── updateTime.cpp ├── getFramebuffer.cpp ├── addTowNumbers.cpp ├── minimumSwap.cpp ├── async_server2.cpp ├── mergeSortedLinkedLists.cpp ├── BFS.cpp ├── zigzag-conversion.cpp ├── LCS.cpp ├── MinNumberSwapAnagram2.cpp ├── circleGlfw.cpp ├── linkedListCycle2.cpp ├── rangeExpressionLifeTime.cpp ├── superReducedString.cpp ├── productExceptItself.cpp ├── index.html ├── numberOfIslands.cpp ├── zigzag-conversion2.cpp ├── Knapsack.cpp ├── minAbsoluteSumDiff.cpp ├── maxProfit.cpp ├── quickSort.cpp ├── maximumStock.cpp ├── LcsDynamicTable.cpp ├── faceDetection_opencv_cuda.cpp ├── RecorderDataInLogs2.cpp ├── longestPalindromicString.cpp ├── RecorderDataInLogs.cpp ├── largestKthElement.cpp ├── countProtifMonths.cpp ├── LinkedListExample.cpp └── zipDataList.cpp ├── cmakeExample ├── app │ ├── CMakeLists.txt │ └── main.cpp ├── CMakeLists.txt └── lib │ ├── src │ └── lib.cpp │ ├── include │ └── lib │ │ └── lib.h │ └── CMakeLists.txt ├── LinkTimeSubstitution ├── Data.cpp ├── example.cpp ├── include │ ├── Data.h │ └── MockData.h ├── MockData.cpp ├── example_test.cpp └── CMakeLists.txt ├── googleTest ├── linecoverage.png ├── src │ ├── foo.cpp │ ├── dummy.cpp │ └── example.cpp ├── include │ ├── foo.hpp │ ├── foo_if.hpp │ ├── dummy.hpp │ └── mock_foo.hpp └── test.puml ├── CmakeExample2 ├── src │ ├── Example.cpp │ ├── Formula.cpp │ ├── main.cpp │ ├── Example.h │ ├── Formula.h │ └── CMakeLists.txt ├── tst │ ├── main.cpp │ ├── Formula-test.cpp │ ├── Example-text.h │ ├── include │ │ └── Example-text.h │ ├── CMakeLists.txt │ └── Example-text.cpp └── CMakeLists.txt ├── Py ├── regressionTf.py ├── InteractWithBinance.py ├── runVideo.py ├── ex.py ├── pythonGstreamer.py ├── recordVideo.py ├── gstreamerPython.py ├── drawSingleRect.py ├── FaceDetection.py ├── clientWebsocket.py ├── piCameraVideo.py ├── DrawCircle.py ├── numberOfIslands.py ├── drawRect.py ├── regressinTf.py ├── gstExample.py ├── cameraJetsonNanoGst3.py └── gradientDescent.py ├── protoExamples ├── test.proto ├── example.proto ├── test.cpp ├── socket_server_json.py └── socket_server.py ├── sharedCallbackExample ├── exampleAInt.h ├── exampleBInt.h ├── exampleB.cpp ├── main.cpp ├── exampleB.h ├── exampleA.h └── exampleA.cpp ├── gtestExample ├── example.cpp └── exampleTest.cpp └── bash └── brihtPi.sh /Cpp/asioTcpServer/build/CMakeFiles/progress.marks: -------------------------------------------------------------------------------- 1 | 2 2 | -------------------------------------------------------------------------------- /cmakeExample/app/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_executable(app main.cpp) 2 | 3 | target_link_libraries(app lib) -------------------------------------------------------------------------------- /LinkTimeSubstitution/Data.cpp: -------------------------------------------------------------------------------- 1 | #include "Data.h" 2 | 3 | int Data::call() { 4 | return 42; 5 | } 6 | -------------------------------------------------------------------------------- /googleTest/linecoverage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhysicsX/ExampleCode/HEAD/googleTest/linecoverage.png -------------------------------------------------------------------------------- /CmakeExample2/src/Example.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Example.h" 3 | 4 | int Example::foo() 5 | { 6 | 7 | return 1; 8 | } -------------------------------------------------------------------------------- /CmakeExample2/src/Formula.cpp: -------------------------------------------------------------------------------- 1 | #include "Formula.h" 2 | 3 | int Formula::bla(int arg1) { 4 | return arg1 * 2; 5 | } -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/progress.make: -------------------------------------------------------------------------------- 1 | CMAKE_PROGRESS_1 = 1 2 | CMAKE_PROGRESS_2 = 2 3 | 4 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/staticTest/my_math.cpp: -------------------------------------------------------------------------------- 1 | #include "my_math.h" 2 | 3 | double reciprocal(double d) { 4 | return 1.0 / d; 5 | } 6 | -------------------------------------------------------------------------------- /Py/regressionTf.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib.pyplot as plt 4 | import tensorflow as tf 5 | 6 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/QtOpencvQml/qml.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | main.qml 4 | 5 | 6 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/cmake.check_cache: -------------------------------------------------------------------------------- 1 | # This file is generated by cmake for dependency checking of the CMakeCache.txt file 2 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/staticTest/my_math.h: -------------------------------------------------------------------------------- 1 | #ifndef H_MY_MATH 2 | #define H_MY_MATH 3 | 4 | double reciprocal(double d); 5 | 6 | #endif // H_MY_MATH 7 | -------------------------------------------------------------------------------- /cmakeExample/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | 3 | project(cmakeExample) 4 | 5 | add_subdirectory(lib) 6 | add_subdirectory(app) 7 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/feature_tests.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhysicsX/ExampleCode/HEAD/Cpp/asioTcpServer/build/CMakeFiles/feature_tests.bin -------------------------------------------------------------------------------- /cmakeExample/lib/src/lib.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "lib/lib.h" 4 | 5 | void lib::foo() 6 | { 7 | std::cout<<"hello from foo"< 2 | #include "lib/lib.h" 3 | 4 | int main() 5 | { 6 | 7 | lib lib; 8 | lib.foo(); 9 | return 0; 10 | } -------------------------------------------------------------------------------- /CmakeExample2/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Formula.h" 3 | 4 | int main() { 5 | std::cout << "Bla: " << Formula::bla(2) << std::endl; 6 | return 0; 7 | } -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CompilerIdC/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhysicsX/ExampleCode/HEAD/Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CompilerIdC/a.out -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CompilerIdCXX/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhysicsX/ExampleCode/HEAD/Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CompilerIdCXX/a.out -------------------------------------------------------------------------------- /CmakeExample2/tst/main.cpp: -------------------------------------------------------------------------------- 1 | #include "gtest/gtest.h" 2 | 3 | int main(int argc, char **argv) { 4 | ::testing::InitGoogleTest(&argc, argv); 5 | return RUN_ALL_TESTS(); 6 | } -------------------------------------------------------------------------------- /protoExamples/test.proto: -------------------------------------------------------------------------------- 1 | 2 | syntax = "proto3"; 3 | 4 | message Test { 5 | 6 | uint64 number = 1; 7 | 8 | string name = 2; 9 | 10 | repeated int64 id = 3; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /CmakeExample2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | project(ExampleProject) 3 | 4 | set(CMAKE_CXX_STANDARD 14) 5 | 6 | add_subdirectory(tst) 7 | add_subdirectory(src) 8 | 9 | -------------------------------------------------------------------------------- /LinkTimeSubstitution/example.cpp: -------------------------------------------------------------------------------- 1 | #include "Data.h" 2 | 3 | class Example { 4 | Data data; 5 | 6 | public: 7 | int foo() { 8 | return data.call(); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CMakeDetermineCompilerABI_C.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhysicsX/ExampleCode/HEAD/Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CMakeDetermineCompilerABI_C.bin -------------------------------------------------------------------------------- /sharedCallbackExample/exampleAInt.h: -------------------------------------------------------------------------------- 1 | #ifndef _EXAMPLEAINT_H_ 2 | #define _EXAMPLEAINT_H_ 3 | 4 | class interfaceA 5 | { 6 | public: 7 | virtual void foo() = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /CmakeExample2/src/Example.h: -------------------------------------------------------------------------------- 1 | #ifndef EXAMPLE_H 2 | #define EXAMPLE_H 3 | 4 | class Example 5 | { 6 | public: 7 | int foo(); 8 | 9 | }; 10 | 11 | 12 | #endif //EXAMPLEPROJECT_FORMULA_H -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CMakeDetermineCompilerABI_CXX.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhysicsX/ExampleCode/HEAD/Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CMakeDetermineCompilerABI_CXX.bin -------------------------------------------------------------------------------- /LinkTimeSubstitution/include/Data.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Data { 4 | public: 5 | virtual int call(); 6 | virtual ~Data() = default; // Add a virtual destructor for good measure 7 | 8 | }; 9 | -------------------------------------------------------------------------------- /sharedCallbackExample/exampleBInt.h: -------------------------------------------------------------------------------- 1 | #ifndef _EXAMPLEBINT_H_ 2 | #define _EXAMPLEBINT_H_ 3 | 4 | class interfaceB 5 | { 6 | public: 7 | virtual void fooB() = 0; 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /cmakeExample/lib/include/lib/lib.h: -------------------------------------------------------------------------------- 1 | #ifndef LIB_H 2 | #define LIB_H 3 | 4 | #include 5 | 6 | class lib{ 7 | 8 | public: 9 | void foo(); 10 | }; 11 | 12 | 13 | #endif //#ifndef LIB_H -------------------------------------------------------------------------------- /CmakeExample2/src/Formula.h: -------------------------------------------------------------------------------- 1 | #ifndef EXAMPLEPROJECT_FORMULA_H 2 | #define EXAMPLEPROJECT_FORMULA_H 3 | 4 | class Formula { 5 | public: 6 | static int bla(int arg1); 7 | }; 8 | 9 | #endif //EXAMPLEPROJECT_FORMULA_H -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/depend.make: -------------------------------------------------------------------------------- 1 | # CMAKE generated file: DO NOT EDIT! 2 | # Generated by "Unix Makefiles" Generator, CMake Version 3.13 3 | 4 | CMakeFiles/server.dir/server.cpp.o: ../server.cpp 5 | 6 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/link.txt: -------------------------------------------------------------------------------- 1 | /usr/bin/c++ -rdynamic CMakeFiles/server.dir/server.cpp.o -o server -lboost_system -lboost_thread -lpthread -lboost_chrono -lboost_date_time -lboost_atomic -lpthread 2 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/depend.internal: -------------------------------------------------------------------------------- 1 | # CMAKE generated file: DO NOT EDIT! 2 | # Generated by "Unix Makefiles" Generator, CMake Version 3.13 3 | 4 | CMakeFiles/server.dir/server.cpp.o 5 | /home/pi/ExampleCode/Cpp/asioTcpServer/server.cpp 6 | -------------------------------------------------------------------------------- /CmakeExample2/src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(BINARY ${CMAKE_PROJECT_NAME}) 2 | 3 | file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp) 4 | 5 | set(SOURCES ${SOURCES}) 6 | 7 | add_executable(${BINARY}_run ${SOURCES}) 8 | 9 | add_library(${BINARY}_lib STATIC ${SOURCES}) -------------------------------------------------------------------------------- /cmakeExample/lib/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(lib SHARED src/lib.cpp) 2 | 3 | message("${CMAKE_CURRENT_SOURCE_DIR} is the current source") 4 | set(CMAKE_SHARED_LIBRARY_PREFIX "s") # change prefix 5 | 6 | target_include_directories(lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/TargetDirectories.txt: -------------------------------------------------------------------------------- 1 | /home/pi/ExampleCode/Cpp/asioTcpServer/build/CMakeFiles/rebuild_cache.dir 2 | /home/pi/ExampleCode/Cpp/asioTcpServer/build/CMakeFiles/server.dir 3 | /home/pi/ExampleCode/Cpp/asioTcpServer/build/CMakeFiles/edit_cache.dir 4 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/flags.make: -------------------------------------------------------------------------------- 1 | # CMAKE generated file: DO NOT EDIT! 2 | # Generated by "Unix Makefiles" Generator, CMake Version 3.13 3 | 4 | # compile CXX with /usr/bin/c++ 5 | CXX_FLAGS = 6 | 7 | CXX_DEFINES = 8 | 9 | CXX_INCLUDES = 10 | 11 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/Editor/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mainwindow.h" 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | QApplication app(argc, argv); 7 | MainWindow window; 8 | window.setWindowTitle("Viewer"); 9 | window.show(); 10 | return app.exec(); 11 | } 12 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/Viewer/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mainwindow.h" 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | QApplication app(argc, argv); 7 | MainWindow window; 8 | window.setWindowTitle("Viewer"); 9 | window.show(); 10 | return app.exec(); 11 | } 12 | -------------------------------------------------------------------------------- /sharedCallbackExample/exampleB.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "exampleB.h" 4 | #include "exampleA.h" 5 | 6 | 7 | B::B(std::shared_ptr Aptr) 8 | { 9 | std::cout<<"B const"<Acallback(); 11 | } 12 | 13 | void B::fooB() 14 | { 15 | 16 | } -------------------------------------------------------------------------------- /CmakeExample2/tst/Formula-test.cpp: -------------------------------------------------------------------------------- 1 | #include "gtest/gtest.h" 2 | #include "Formula.h" 3 | 4 | TEST(blaTest, test1) { 5 | //arrange 6 | //act 7 | //assert 8 | EXPECT_EQ (Formula::bla (0), 0); 9 | EXPECT_EQ (Formula::bla (10), 20); 10 | EXPECT_EQ (Formula::bla (50), 100); 11 | } -------------------------------------------------------------------------------- /LinkTimeSubstitution/MockData.cpp: -------------------------------------------------------------------------------- 1 | #include "Data.h" 2 | #include "MockData.h" 3 | #include 4 | 5 | MockData::Ptr global_mock_data_ptr = std::make_shared(); 6 | 7 | #include 8 | int Data::call() { 9 | std::cout<<__LINE__<call(); 11 | } 12 | -------------------------------------------------------------------------------- /LinkTimeSubstitution/include/MockData.h: -------------------------------------------------------------------------------- 1 | #include "Data.h" 2 | #include 3 | 4 | 5 | class MockData { 6 | public: 7 | MOCK_METHOD(int, call, ()); 8 | using Ptr = std::shared_ptr; 9 | }; 10 | 11 | // Declare the global pointer to MockData 12 | extern MockData::Ptr global_mock_data_ptr; 13 | -------------------------------------------------------------------------------- /gtestExample/example.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Example{ 6 | 7 | public: 8 | 9 | int ctr = 0; 10 | 11 | void increase(int value) 12 | { 13 | ctr += value; 14 | } 15 | 16 | void decrease(int value) 17 | { 18 | ctr -= value; 19 | } 20 | }; -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/cmake_clean.cmake: -------------------------------------------------------------------------------- 1 | file(REMOVE_RECURSE 2 | "CMakeFiles/server.dir/server.cpp.o" 3 | "server.pdb" 4 | "server" 5 | ) 6 | 7 | # Per-language clean rules from dependency scanning. 8 | foreach(lang CXX) 9 | include(CMakeFiles/server.dir/cmake_clean_${lang}.cmake OPTIONAL) 10 | endforeach() 11 | -------------------------------------------------------------------------------- /sharedCallbackExample/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include "exampleA.h" 6 | 7 | //g++ -std=c++17 main.cpp exampleA.cpp exampleB.cpp -lpthread 8 | 9 | int main() 10 | { 11 | std::shared_ptr Aptr { std::make_shared() }; 12 | Aptr->foo(); 13 | 14 | while(1); 15 | } -------------------------------------------------------------------------------- /Cpp/asioTcpServer/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(server) 3 | 4 | 5 | find_package(Boost REQUIRED COMPONENTS system thread) 6 | 7 | if(Boost_FOUND) 8 | include_directories(${Boost_INCLUDE_DIR}) 9 | add_executable(server server.cpp) 10 | target_link_libraries(server ${Boost_LIBRARIES} pthread) 11 | endif() 12 | -------------------------------------------------------------------------------- /Py/InteractWithBinance.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | import pprint 4 | 5 | logger = logging.getLogger() 6 | 7 | def get_contracts(): 8 | response_object = requests.get("https://fapi.binance.com/fapi/v1/exchangeInfo") 9 | print(response_object.status_code) 10 | pprint.pprint(response_object.json()) 11 | 12 | get_contracts() -------------------------------------------------------------------------------- /googleTest/src/foo.cpp: -------------------------------------------------------------------------------- 1 | #include "foo.hpp" 2 | 3 | int foo::fooInt(std::string& str) 4 | { 5 | return str.size(); 6 | } 7 | 8 | void foo::fooStr(std::string& str) 9 | { 10 | str = "ExampleStr"; 11 | } 12 | 13 | void foo::fooThrow() 14 | { 15 | // throw runtime error 16 | } 17 | 18 | void foo::callbackMethod(std::function& callback) 19 | { 20 | callback(); 21 | } -------------------------------------------------------------------------------- /googleTest/include/foo.hpp: -------------------------------------------------------------------------------- 1 | #ifndef FOO_HPP 2 | #define FOO_HPP 3 | 4 | #include "foo_if.hpp" 5 | #include 6 | #include 7 | 8 | class foo : public fooIf 9 | { 10 | public: 11 | int fooInt(std::string& str); 12 | void fooStr(std::string& str); 13 | void fooThrow(); 14 | void callbackMethod(std::function& callback); 15 | }; 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /googleTest/include/foo_if.hpp: -------------------------------------------------------------------------------- 1 | #ifndef FOO_IF_HPP 2 | #define FOO_IF_HPP 3 | #include 4 | #include 5 | 6 | class fooIf 7 | { 8 | public: 9 | virtual int fooInt(std::string& str) = 0; 10 | virtual void fooStr(std::string& str) = 0; 11 | virtual void fooThrow() = 0; 12 | virtual void callbackMethod(std::function& callback) = 0; 13 | }; 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /Cpp/reverserInt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int reverseInteger(int n) 4 | { 5 | int reversed {0}; 6 | 7 | while(n) 8 | { 9 | int reminder = n%10; 10 | 11 | reversed = reversed * 10 + reminder; 12 | n /= 10; 13 | } 14 | 15 | return reversed; 16 | } 17 | 18 | 19 | int main() 20 | { 21 | int n = 12345; 22 | std::cout< 4 | #include 5 | #include "foo_if.hpp" 6 | 7 | class dummy 8 | { 9 | public: 10 | dummy(fooIf& f):mfoo(f){} 11 | int dummyInt(std::string& str); 12 | void dummyStr(std::string& str); 13 | void dummyThrow(); 14 | void dummyCallback(std::function callback); 15 | 16 | fooIf& mfoo; 17 | }; 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /sharedCallbackExample/exampleB.h: -------------------------------------------------------------------------------- 1 | #ifndef _EXAMPLEB_H_ 2 | #define _EXAMPLEB_H_ 3 | 4 | #include 5 | #include 6 | #include "exampleBInt.h" 7 | #include "exampleA.h" 8 | 9 | class B : public interfaceB, public std::enable_shared_from_this 10 | { 11 | public: 12 | B(std::shared_ptr Aptr); 13 | void fooB() override; 14 | 15 | std::shared_ptr mAptr; 16 | 17 | }; 18 | 19 | #endif -------------------------------------------------------------------------------- /googleTest/include/mock_foo.hpp: -------------------------------------------------------------------------------- 1 | #include "foo_if.hpp" 2 | #include 3 | #include 4 | 5 | class mockFoo : public fooIf 6 | { 7 | public: 8 | MOCK_METHOD(int, fooInt, (std::string& str), (override)); 9 | MOCK_METHOD(void, fooStr, (std::string& str), (override)); 10 | MOCK_METHOD(void, fooThrow, (), (override)); 11 | MOCK_METHOD(void, callbackMethod, (std::function&),(override)); 12 | 13 | }; 14 | -------------------------------------------------------------------------------- /Cpp/nonDerived.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //without final keyword inheritance 4 | 5 | class A 6 | { 7 | 8 | 9 | private: 10 | A(){}; 11 | friend class B; 12 | 13 | }; 14 | 15 | class B : virtual public A 16 | { 17 | 18 | 19 | }; 20 | 21 | class C : public B 22 | { 23 | 24 | 25 | }; 26 | 27 | int main() 28 | { 29 | 30 | C c; 31 | 32 | return 0; 33 | 34 | } -------------------------------------------------------------------------------- /googleTest/src/dummy.cpp: -------------------------------------------------------------------------------- 1 | #include "dummy.hpp" 2 | 3 | int dummy::dummyInt(std::string& str) 4 | { 5 | return mfoo.fooInt(str); 6 | } 7 | 8 | void dummy::dummyStr(std::string& str) 9 | { 10 | mfoo.fooStr(str); 11 | //str = "ExampleStr"; 12 | } 13 | 14 | void dummy::dummyThrow() 15 | { 16 | mfoo.fooThrow(); 17 | } 18 | 19 | void dummy::dummyCallback(std::function callback){ 20 | mfoo.callbackMethod(callback); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /CmakeExample2/tst/Example-text.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Example.h" 3 | 4 | 5 | class TestBase : public ::testing::Test 6 | { 7 | public: 8 | TestBase(void); 9 | virtual ~TestBase(void); 10 | static void SetUpTestCase(); 11 | static void TearDownTestCase(); 12 | virtual void SetUp(void); 13 | virtual void TearDown(void); 14 | 15 | public: 16 | static int mArgc; 17 | static char** mArgs; 18 | 19 | static Example* pSC; 20 | 21 | }; -------------------------------------------------------------------------------- /CmakeExample2/tst/include/Example-text.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Example.h" 3 | 4 | 5 | class TestBase : public ::testing::Test 6 | { 7 | public: 8 | TestBase(void); 9 | virtual ~TestBase(void); 10 | static void SetUpTestCase(); 11 | static void TearDownTestCase(); 12 | virtual void SetUp(void); 13 | virtual void TearDown(void); 14 | 15 | public: 16 | static int mArgc; 17 | static char** mArgs; 18 | 19 | static Example* pSC; 20 | 21 | }; -------------------------------------------------------------------------------- /Cpp/findSubstringInString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int main() 5 | { 6 | std::string str = "hello world"; 7 | std::string str2 = "l"; 8 | 9 | std::size_t pos = str.find(str2); 10 | 11 | while(pos != std::string::npos) 12 | { 13 | std::cout<<"found"< 5 | #include 6 | #include "exampleAInt.h" 7 | #include "exampleBInt.h" 8 | 9 | class A : public std::enable_shared_from_this, public interfaceA 10 | { 11 | public: 12 | A(); 13 | 14 | void foo() ; 15 | 16 | void Acallback(); 17 | 18 | std::shared_ptr Bptr; 19 | 20 | }; 21 | 22 | #endif -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/CXX.includecache: -------------------------------------------------------------------------------- 1 | #IncludeRegexLine: ^[ ]*[#%][ ]*(include|import)[ ]*[<"]([^">]+)([">]) 2 | 3 | #IncludeRegexScan: ^.*$ 4 | 5 | #IncludeRegexComplain: ^$ 6 | 7 | #IncludeRegexTransform: 8 | 9 | /home/pi/ExampleCode/Cpp/asioTcpServer/server.cpp 10 | iostream 11 | - 12 | boost/asio.hpp 13 | - 14 | boost/beast/core.hpp 15 | - 16 | boost/beast/websocket.hpp 17 | - 18 | boost/asio/dispatch.hpp 19 | - 20 | boost/asio/strand.hpp 21 | - 22 | 23 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/QtOpencvQml/qmlType.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | 11 | class qmlType : public QQuickPaintedItem 12 | { 13 | Q_OBJECT 14 | public: 15 | 16 | qmlType(QQuickItem *parent = nullptr); 17 | void paint(QPainter *painter) override; 18 | 19 | void updateImage(const QImage& img); 20 | 21 | QImage *image; 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CMakeSystem.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_HOST_SYSTEM "Linux-4.19.118-v7l+") 2 | set(CMAKE_HOST_SYSTEM_NAME "Linux") 3 | set(CMAKE_HOST_SYSTEM_VERSION "4.19.118-v7l+") 4 | set(CMAKE_HOST_SYSTEM_PROCESSOR "armv7l") 5 | 6 | 7 | 8 | set(CMAKE_SYSTEM "Linux-4.19.118-v7l+") 9 | set(CMAKE_SYSTEM_NAME "Linux") 10 | set(CMAKE_SYSTEM_VERSION "4.19.118-v7l+") 11 | set(CMAKE_SYSTEM_PROCESSOR "armv7l") 12 | 13 | set(CMAKE_CROSSCOMPILING "FALSE") 14 | 15 | set(CMAKE_SYSTEM_LOADED 1) 16 | -------------------------------------------------------------------------------- /CmakeExample2/tst/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(BINARY ${CMAKE_PROJECT_NAME}_tst) 2 | 3 | file(GLOB_RECURSE TEST_SOURCES LIST_DIRECTORIES false ../src/Formula.cpp ../src/Example.cpp *.cpp) 4 | 5 | set(SOURCES ${TEST_SOURCES}) 6 | set(THREADS_PREFER_PTHREAD_FLAG ON) 7 | find_package(Threads REQUIRED) 8 | 9 | include_directories(../src include) 10 | 11 | add_executable(${BINARY} ${TEST_SOURCES}) 12 | 13 | add_test(NAME ${BINARY} COMMAND ${BINARY}) 14 | 15 | target_link_libraries(${BINARY} PUBLIC Threads::Threads gtest) -------------------------------------------------------------------------------- /Cpp/QtOpenCV/QtOpencvQml/main.qml: -------------------------------------------------------------------------------- 1 | import QtQuick 2.12 2 | import QtQuick.Window 2.12 3 | import QtQuick.Controls 2.0 4 | import Painter 1.0 5 | 6 | Window { 7 | width: Screen.width 8 | height: Screen.height 9 | visible: true 10 | title: qsTr("OpencvToQml") 11 | 12 | 13 | QmlType { 14 | objectName: "inputCamera" 15 | id: inputView 16 | //streamerThreadSlot: VideoStreamer 17 | width: parent.width 18 | height: parent.height 19 | 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Cpp/socketExample/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myserver.h" 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | QCoreApplication a(argc, argv); 7 | 8 | // Create an instance of a server and then start it. 9 | MyServer server; 10 | server.startServer(); 11 | 12 | return a.exec(); 13 | } 14 | 15 | // while true; do echo "ulas" | netcat localhost 1234 -w 1; sleep 0.1; done; 16 | // echo "ulas" | netcat localhost 1234 -w 1 17 | 18 | // stress test 19 | // while true; do echo "ulas" | netcat localhost 1234 & disown; done; 20 | 21 | -------------------------------------------------------------------------------- /Py/ex.py: -------------------------------------------------------------------------------- 1 | #connect to camera and record it 2 | 3 | import cv2 4 | cap = cv2.VideoCapture(0) 5 | 6 | width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 7 | height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 8 | 9 | output = cv2.VideoWriter('myVideo.mkv', cv2.VideoWriter_fourcc(*'XVID'),20,(width, height)) 10 | 11 | while True: 12 | ret, frame = cap.read() 13 | 14 | output.write(frame) 15 | 16 | cv2.imshow('frame', frame) 17 | if cv2.waitKey(5) & 0xFF == 27: 18 | break 19 | 20 | 21 | cap.release() 22 | output.release() 23 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /Py/pythonGstreamer.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | print(cv2.__version__) 3 | 4 | 5 | # Cam properties 6 | fps = 30. 7 | frame_width = 1920 8 | frame_height = 1080 9 | 10 | 11 | 12 | dispW=640 13 | dispH=480 14 | flip=2 15 | #Uncomment These next Two Line for Pi Camera 16 | camSet = ('videotestsrc ! videoconvert ! appsink') 17 | 18 | cam= cv2.VideoCapture(camSet) 19 | 20 | 21 | 22 | while True: 23 | ret, frame = cam.read() 24 | cv2.imshow('nanoCam',frame) 25 | if cv2.waitKey(1)==ord('q'): 26 | break 27 | cam.release() 28 | cv2.destroyAllWindows() 29 | -------------------------------------------------------------------------------- /Py/recordVideo.py: -------------------------------------------------------------------------------- 1 | #connect to camera and record it 2 | 3 | import cv2 4 | cap = cv2.VideoCapture(0) 5 | 6 | width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 7 | height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 8 | 9 | output = cv2.VideoWriter('myVideo.mkv', cv2.VideoWriter_fourcc(*'XVID'),20,(width, height)) 10 | 11 | while True: 12 | ret, frame = cap.read() 13 | 14 | output.write(frame) 15 | 16 | cv2.imshow('frame', frame) 17 | if cv2.waitKey(5) & 0xFF == 27: 18 | break 19 | 20 | 21 | cap.release() 22 | output.release() 23 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /Py/gstreamerPython.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | print(cv2.__version__) 3 | 4 | 5 | # Cam properties 6 | fps = 30. 7 | frame_width = 1920 8 | frame_height = 1080 9 | 10 | 11 | 12 | dispW=640 13 | dispH=480 14 | flip=2 15 | #Uncomment These next Two Line for Pi Camera 16 | camSet = ('videotestsrc ! videoconvert ! appsink') 17 | 18 | cam= cv2.VideoCapture(camSet) 19 | 20 | 21 | 22 | while True: 23 | ret, frame = cam.read() 24 | cv2.imshow('nanoCam',frame) 25 | if cv2.waitKey(1)==ord('q'): 26 | break 27 | cam.release() 28 | cv2.destroyAllWindows() 29 | 30 | -------------------------------------------------------------------------------- /googleTest/test.puml: -------------------------------------------------------------------------------- 1 | @startuml 2 | 3 | class fooIf<> 4 | { 5 | + {abstract} fooStr(std::string&): void 6 | } 7 | 8 | class foo 9 | { 10 | + fooStr(std::string&): void 11 | } 12 | 13 | class mockFoo 14 | { 15 | + fooStr(std::string&): void 16 | } 17 | 18 | class dummy 19 | { 20 | + dummy(fooIf&) 21 | # fooIf foo 22 | } 23 | 24 | class test 25 | { 26 | # mockFoo fooMock 27 | # unique_ptr testDummy 28 | } 29 | 30 | 31 | 32 | fooIf <|.. foo 33 | fooIf <|.. mockFoo 34 | dummy -right-> fooIf 35 | 36 | test *-- dummy 37 | test *-- mockFoo 38 | 39 | @enduml 40 | -------------------------------------------------------------------------------- /Py/drawSingleRect.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | cap = cv2.VideoCapture(0) 4 | 5 | width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 6 | height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 7 | 8 | x = width // 2 9 | y = height // 2 10 | 11 | w = width // 4 12 | h = height // 4 13 | 14 | while True: 15 | ret, frame = cap.read() 16 | 17 | cv2.rectangle(frame, (x,y), (x+w, y+h), color=(255,0,255), thickness=5) 18 | 19 | cv2.imshow('frame', frame) 20 | 21 | if cv2.waitKey(3) & 0xFF == 27: 22 | break 23 | 24 | 25 | cap.release() 26 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /Cpp/firstNonRepeatingChar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char firstNonRepeatingChar(const std::string& str) 6 | { 7 | std::unordered_map map; 8 | 9 | for(const auto& c : str) 10 | { 11 | map[c] ++; 12 | } 13 | 14 | for(const auto& c : str) 15 | { 16 | if(map[c] == 1) 17 | { 18 | return c; 19 | } 20 | } 21 | 22 | return '\0'; 23 | } 24 | 25 | int main() 26 | { 27 | std::string s = "helloFromGithub"; 28 | std::cout<fill(QColor("yellow")); 7 | 8 | // If camera is open here, it is not possible to send the frames. 9 | // need another thread to send the frames over this class 10 | } 11 | 12 | void qmlType::paint(QPainter *painter) { 13 | painter->drawImage(this->boundingRect(), *image); 14 | } 15 | 16 | void qmlType::updateImage(const QImage& img) 17 | { 18 | *image = img; 19 | update(); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /LinkTimeSubstitution/example_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "example.cpp" 4 | #include "MockData.h" 5 | 6 | extern std::shared_ptr global_mock_data_ptr; 7 | 8 | class testFixture : public testing::Test 9 | { 10 | public: 11 | testFixture() 12 | { 13 | } 14 | ~testFixture() 15 | { 16 | global_mock_data_ptr.reset(); // delete the global mock 17 | } 18 | }; 19 | 20 | 21 | TEST_F(testFixture, FooReturnsMockedValue) { 22 | 23 | EXPECT_CALL(*global_mock_data_ptr, call()).WillOnce(::testing::Return(99)); 24 | 25 | Example ex; 26 | ASSERT_EQ(99, ex.foo()); 27 | } 28 | -------------------------------------------------------------------------------- /LinkTimeSubstitution/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | set(CMAKE_CXX_STANDARD 14) 3 | 4 | project(ExampleGtest LANGUAGES CXX) 5 | 6 | include(FetchContent) 7 | FetchContent_Declare( 8 | googletest 9 | GIT_REPOSITORY https://github.com/google/googletest.git 10 | GIT_TAG bf66935e07825318ae519675d73d0f3e313b3ec6 11 | ) 12 | FetchContent_MakeAvailable(googletest) 13 | 14 | add_executable(${PROJECT_NAME} example_test.cpp MockData.cpp) 15 | 16 | target_link_libraries(${PROJECT_NAME} gtest_main gmock_main) 17 | 18 | include(GoogleTest) 19 | gtest_discover_tests(${PROJECT_NAME}) 20 | 21 | #include headers 22 | include_directories(include) -------------------------------------------------------------------------------- /Cpp/findMinReturnType.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | auto findMin(A a, B b) -> decltype( (a < b) ? a: b) // decltype is not necessary for c++14 8 | { 9 | return (a < b) ? a : b; 10 | } 11 | 12 | auto foo(int a, double b) 13 | { 14 | return (a < b) ? a : b; 15 | } 16 | 17 | int main() 18 | { 19 | 20 | std::cout<::value<::value< 2 | 3 | auto allocated = size_t{0}; 4 | // Overload operator new and delete to track allocations 5 | auto operator new(size_t size) -> void* { 6 | void* p = std::malloc(size); 7 | allocated += size; 8 | return p; 9 | } 10 | 11 | auto operator delete(void* p) noexcept -> void { 12 | return std::free(p); 13 | } 14 | 15 | auto main() -> int { 16 | allocated = 0; 17 | auto s = std::string{"12345678901234567890123"}; 18 | //auto s = std::string{"1234"}; 19 | 20 | std::cout << "stack space = " << sizeof(s) 21 | << ", heap space = " << allocated 22 | << ", capacity = " << s.capacity() << '\n'; 23 | } -------------------------------------------------------------------------------- /Cpp/reverseWordsInSentence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | std::string reverseWords(std::string str) 6 | { 7 | std::stringstream ss(str); 8 | std::string word; 9 | 10 | std::deque words; 11 | 12 | while(ss>>word) 13 | { 14 | words.push_front(word); 15 | } 16 | 17 | std::string result; 18 | while(!words.empty()) 19 | { 20 | result += words.front() + " "; 21 | words.pop_front(); 22 | } 23 | 24 | result.pop_back(); 25 | 26 | return result; 27 | } 28 | 29 | int main() 30 | { 31 | std::string str = "Electric cars are cool"; 32 | std::cout< 2 | #include 3 | 4 | // sudo apt install libopencv-dev 5 | // g++ openCVExample.cpp `pkg-config --libs --cflags opencv4` -o example 6 | // g++ openCVExample.cpp $(pkg-config --libs --cflags opencv4) -o example 7 | 8 | using namespace cv; 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | std::cout<<"Example"< 7 | #include 8 | #include 9 | #include 10 | 11 | #include "myclient.h" 12 | 13 | class MyServer : public QTcpServer 14 | { 15 | // Q_OBJECT is the base class for all qt libraries 16 | Q_OBJECT 17 | QThreadPool *pool; // this can be used also global isntead of dependency injection 18 | public: 19 | explicit MyServer(QObject *parent = 0); 20 | void startServer(); 21 | 22 | protected: 23 | void incomingConnection(qintptr socketDescriptor); 24 | 25 | signals: 26 | 27 | public slots: 28 | 29 | }; 30 | 31 | #endif // MYSERVER_H 32 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/server.dir/DependInfo.cmake: -------------------------------------------------------------------------------- 1 | # The set of languages for which implicit dependencies are needed: 2 | set(CMAKE_DEPENDS_LANGUAGES 3 | "CXX" 4 | ) 5 | # The set of files for implicit dependencies of each language: 6 | set(CMAKE_DEPENDS_CHECK_CXX 7 | "/home/pi/ExampleCode/Cpp/asioTcpServer/server.cpp" "/home/pi/ExampleCode/Cpp/asioTcpServer/build/CMakeFiles/server.dir/server.cpp.o" 8 | ) 9 | set(CMAKE_CXX_COMPILER_ID "GNU") 10 | 11 | # The include file search paths: 12 | set(CMAKE_CXX_TARGET_INCLUDE_PATH 13 | ) 14 | 15 | # Targets to which this target links. 16 | set(CMAKE_TARGET_LINKED_INFO_FILES 17 | ) 18 | 19 | # Fortran module output directory. 20 | set(CMAKE_Fortran_TARGET_MODULE_DIR "") 21 | -------------------------------------------------------------------------------- /Cpp/maxSubArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | class Solution { 7 | public: 8 | int maxSubArray(std::vector& nums) { 9 | 10 | int largestSum = nums[0]; //SHRT_MIN; 11 | int sum = nums[0]; //SHRT_MIN; 12 | 13 | for(int i=0; i vec {-2,1,-3,4,-1,2,1,-5,4}; 29 | 30 | std::cout<setMaxThreadCount(5); 10 | 11 | } 12 | 13 | void MyServer::startServer() 14 | { 15 | if(listen(QHostAddress::Any, 1234)) 16 | { 17 | qDebug() << "Server: started"; 18 | } 19 | else 20 | { 21 | qDebug() << "Server: not started!"; 22 | } 23 | } 24 | 25 | void MyServer::incomingConnection(qintptr socketDescriptor) 26 | { 27 | // At the incoming connection, make a client 28 | // and set the socket 29 | MyClient *client = new MyClient(this, pool); 30 | client->setSocket(socketDescriptor); 31 | } 32 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/CMakeDirectoryInformation.cmake: -------------------------------------------------------------------------------- 1 | # CMAKE generated file: DO NOT EDIT! 2 | # Generated by "Unix Makefiles" Generator, CMake Version 3.13 3 | 4 | # Relative path conversion top directories. 5 | set(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/pi/ExampleCode/Cpp/asioTcpServer") 6 | set(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/pi/ExampleCode/Cpp/asioTcpServer/build") 7 | 8 | # Force unix paths in dependencies. 9 | set(CMAKE_FORCE_UNIX_PATHS 1) 10 | 11 | 12 | # The C and CXX include file regular expressions for this directory. 13 | set(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") 14 | set(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") 15 | set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) 16 | set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN}) 17 | -------------------------------------------------------------------------------- /Cpp/minMove3Consecutive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution 5 | { 6 | public: 7 | int minMoves(const std::string& str) 8 | { 9 | int res{0}; 10 | size_t size = str.size(); 11 | 12 | for(size_t i = 0; i < size;) 13 | { 14 | int next = i + 1; 15 | 16 | while( (next < size) && (str[i] == str[next])) {next ++;} 17 | // next - i is the length of the sequence 18 | // Each third letter should be changed to remove 19 | // too long sequenes 20 | res += (next-i)/3; 21 | i = next; 22 | } 23 | 24 | return res; 25 | } 26 | }; 27 | 28 | int main() 29 | { 30 | std::cout< 7 | #include 8 | #include 9 | #include 10 | #include "mytask.h" 11 | 12 | class MyClient : public QObject 13 | { 14 | QThreadPool *pool; 15 | Q_OBJECT 16 | public: 17 | explicit MyClient(QObject *parent = 0, QThreadPool *pool = 0); 18 | void setSocket(qintptr Descriptor); 19 | 20 | signals: 21 | 22 | public slots: 23 | void connected(); 24 | void disconnected(); 25 | void readyRead(); 26 | 27 | // make the server fully ascynchronous 28 | // by doing time consuming task 29 | void TaskResult(int Number); 30 | 31 | private: 32 | QTcpSocket *socket; 33 | 34 | }; 35 | 36 | #endif // MYCLIENT_H 37 | -------------------------------------------------------------------------------- /Cpp/socketExample/mytask.h: -------------------------------------------------------------------------------- 1 | // mytask.h 2 | 3 | #ifndef MYTASK_H 4 | #define MYTASK_H 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // Q_OBJECT missing in the original file generated by class wizard. 11 | // because we set this class with base class QRunnable 12 | // with no inheritance in the class wizard 13 | // We do not have this. So, we cannot use signal/slot 14 | // But we need them. 15 | // Thus, we should use multiple inheritance: QObject inserted here 16 | 17 | class MyTask : public QObject, public QRunnable 18 | { 19 | Q_OBJECT 20 | public: 21 | MyTask(); 22 | 23 | signals: 24 | // notify to the main thread when we're done 25 | void Result(int Number); 26 | 27 | protected: 28 | void run(); 29 | }; 30 | 31 | #endif // MYTASK_H 32 | -------------------------------------------------------------------------------- /Cpp/majorityElementII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | std::vector majorityElement(std::vector& nums) { 8 | std::unordered_map map; 9 | for(auto num : nums) 10 | { 11 | map[num] ++; 12 | } 13 | 14 | std::vector result; 15 | result.reserve(map.size()); 16 | for(const std::pair& p : map) 17 | { 18 | if(p.second > nums.size()/3) 19 | result.push_back(p.first); 20 | } 21 | return result; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | std::vector vec {3,2,3}; 28 | 29 | for(auto v : Solution{}.majorityElement(vec)) 30 | std::cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | class example 7 | { 8 | public: 9 | int foo() 10 | { 11 | return 1; 12 | } 13 | 14 | }; 15 | 16 | class exampleFixture : public testing::Test 17 | { 18 | public: 19 | exampleFixture(){ 20 | testExPtr = new example(); 21 | } 22 | ~exampleFixture() 23 | { 24 | delete testExPtr; 25 | } 26 | 27 | void SetUp(){} 28 | void TearDown(){} 29 | 30 | example* testExPtr; 31 | }; 32 | 33 | TEST_F(exampleFixture, test1) 34 | { 35 | ASSERT_EQ(1,testExPtr->foo()); 36 | } 37 | 38 | TEST_F(exampleFixture, test2) 39 | { 40 | ASSERT_NE(0,testExPtr->foo()); 41 | } 42 | 43 | int main(int argc, char **argv) 44 | { 45 | testing::InitGoogleTest(&argc, argv); 46 | return RUN_ALL_TESTS(); 47 | } 48 | -------------------------------------------------------------------------------- /Cpp/conversionOperator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | //how to use conversion operator 5 | class smart; 6 | class dummy 7 | { 8 | dummy()=default; 9 | public: 10 | friend class smart; 11 | }; 12 | 13 | class smart 14 | { 15 | public: 16 | dummy d; 17 | 18 | // conversion operator overloading 19 | operator dummy() 20 | { 21 | return d; 22 | } 23 | }; 24 | 25 | int main() 26 | { 27 | 28 | // possible usages 29 | // each line call the operator dummy() method 30 | dummy d = smart(); 31 | 32 | smart s2; 33 | dummy d2 = s2; 34 | 35 | dummy d3 = smart().operator dummy(); 36 | 37 | smart s3; 38 | dummy d5 = s3.operator dummy(); 39 | 40 | auto s4 = smart(); 41 | 42 | } -------------------------------------------------------------------------------- /CmakeExample2/tst/Example-text.cpp: -------------------------------------------------------------------------------- 1 | #include "Example-text.h" 2 | 3 | int TestBase::mArgc = 0; 4 | char** TestBase::mArgs = NULL; 5 | 6 | Example* TestBase::pSC = NULL; 7 | 8 | TestBase::TestBase(void) 9 | { 10 | 11 | } 12 | 13 | TestBase::~TestBase(void) 14 | { 15 | 16 | } 17 | 18 | void TestBase::SetUpTestCase() 19 | { 20 | std::cout << "Set up test cases." << std::endl; 21 | 22 | if ( pSC != NULL ) 23 | { 24 | delete pSC; 25 | } 26 | 27 | pSC = new Example; 28 | } 29 | 30 | void TestBase::TearDownTestCase() 31 | { 32 | std::cout << "Tear down test cases." << std::endl; 33 | 34 | delete pSC; pSC = NULL; 35 | } 36 | 37 | void TestBase::SetUp(void) 38 | { 39 | 40 | } 41 | 42 | void TestBase::TearDown(void) 43 | { 44 | 45 | } 46 | 47 | TEST_F(TestBase, tmp) 48 | { 49 | Example a; 50 | int tmp = pSC->foo(); 51 | EXPECT_EQ(tmp,1); 52 | } -------------------------------------------------------------------------------- /Cpp/QtOpenCV/Viewer/.qmake.stash: -------------------------------------------------------------------------------- 1 | QMAKE_CXX.INCDIRS = \ 2 | /usr/include/c++/7 \ 3 | /usr/include/aarch64-linux-gnu/c++/7 \ 4 | /usr/include/c++/7/backward \ 5 | /usr/lib/gcc/aarch64-linux-gnu/7/include \ 6 | /usr/local/include \ 7 | /usr/lib/gcc/aarch64-linux-gnu/7/include-fixed \ 8 | /usr/include/aarch64-linux-gnu \ 9 | /usr/include 10 | QMAKE_CXX.LIBDIRS = \ 11 | /usr/lib/gcc/aarch64-linux-gnu/7 \ 12 | /usr/lib/aarch64-linux-gnu \ 13 | /usr/lib \ 14 | /lib/aarch64-linux-gnu \ 15 | /lib 16 | QMAKE_CXX.QT_COMPILER_STDCXX = 201402L 17 | QMAKE_CXX.QMAKE_GCC_MAJOR_VERSION = 7 18 | QMAKE_CXX.QMAKE_GCC_MINOR_VERSION = 5 19 | QMAKE_CXX.QMAKE_GCC_PATCH_VERSION = 0 20 | QMAKE_CXX.COMPILER_MACROS = \ 21 | QT_COMPILER_STDCXX \ 22 | QMAKE_GCC_MAJOR_VERSION \ 23 | QMAKE_GCC_MINOR_VERSION \ 24 | QMAKE_GCC_PATCH_VERSION 25 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/QtOpencvQml/.qmake.stash: -------------------------------------------------------------------------------- 1 | QMAKE_CXX.QT_COMPILER_STDCXX = 201402L 2 | QMAKE_CXX.QMAKE_GCC_MAJOR_VERSION = 7 3 | QMAKE_CXX.QMAKE_GCC_MINOR_VERSION = 5 4 | QMAKE_CXX.QMAKE_GCC_PATCH_VERSION = 0 5 | QMAKE_CXX.COMPILER_MACROS = \ 6 | QT_COMPILER_STDCXX \ 7 | QMAKE_GCC_MAJOR_VERSION \ 8 | QMAKE_GCC_MINOR_VERSION \ 9 | QMAKE_GCC_PATCH_VERSION 10 | QMAKE_CXX.INCDIRS = \ 11 | /usr/include/c++/7 \ 12 | /usr/include/aarch64-linux-gnu/c++/7 \ 13 | /usr/include/c++/7/backward \ 14 | /usr/lib/gcc/aarch64-linux-gnu/7/include \ 15 | /usr/local/include \ 16 | /usr/lib/gcc/aarch64-linux-gnu/7/include-fixed \ 17 | /usr/include/aarch64-linux-gnu \ 18 | /usr/include 19 | QMAKE_CXX.LIBDIRS = \ 20 | /usr/lib/gcc/aarch64-linux-gnu/7 \ 21 | /usr/lib/aarch64-linux-gnu \ 22 | /usr/lib \ 23 | /lib/aarch64-linux-gnu \ 24 | /lib 25 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/staticTest/staticTest.pro: -------------------------------------------------------------------------------- 1 | ###################################################################### 2 | # Automatically generated by qmake (3.1) Mon Nov 7 14:39:27 2022 3 | ###################################################################### 4 | 5 | TEMPLATE = app 6 | TARGET = staticTest 7 | INCLUDEPATH += . 8 | LIBS += -L/home/ulas/staticTest -lmy_math 9 | # You can make your code fail to compile if you use deprecated APIs. 10 | # In order to do so, uncomment the following line. 11 | # Please consult the documentation of the deprecated API in order to know 12 | # how to port your code away from it. 13 | # You can also select to disable deprecated APIs only up to a certain version of Qt. 14 | #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 15 | 16 | # Input 17 | # HEADERS += my_math.h 18 | SOURCES += main.cpp 19 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/feature_tests.c: -------------------------------------------------------------------------------- 1 | 2 | const char features[] = {"\n" 3 | "C_FEATURE:" 4 | #if (__GNUC__ * 100 + __GNUC_MINOR__) >= 304 5 | "1" 6 | #else 7 | "0" 8 | #endif 9 | "c_function_prototypes\n" 10 | "C_FEATURE:" 11 | #if (__GNUC__ * 100 + __GNUC_MINOR__) >= 304 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L 12 | "1" 13 | #else 14 | "0" 15 | #endif 16 | "c_restrict\n" 17 | "C_FEATURE:" 18 | #if (__GNUC__ * 100 + __GNUC_MINOR__) >= 406 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201000L 19 | "1" 20 | #else 21 | "0" 22 | #endif 23 | "c_static_assert\n" 24 | "C_FEATURE:" 25 | #if (__GNUC__ * 100 + __GNUC_MINOR__) >= 304 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L 26 | "1" 27 | #else 28 | "0" 29 | #endif 30 | "c_variadic_macros\n" 31 | 32 | }; 33 | 34 | int main(int argc, char** argv) { (void)argv; return features[argc]; } 35 | -------------------------------------------------------------------------------- /protoExamples/example.proto: -------------------------------------------------------------------------------- 1 | // See README.txt for information and build instructions. 2 | // 3 | // Note: START and END tags are used in comments to define sections used in 4 | // tutorials. They are not part of the syntax for Protocol Buffers. 5 | // 6 | // To get an in-depth walkthrough of this file and the related examples, see: 7 | // https://developers.google.com/protocol-buffers/docs/tutorials 8 | 9 | // [START declaration] 10 | syntax = "proto3"; 11 | 12 | // [START messages] 13 | message Person { 14 | 15 | optional uint32 id = 1; 16 | optional string number = 2; // Unique ID number for this person. 17 | optional uint32 anotherId = 3; 18 | optional uint32 aid = 4; 19 | optional uint32 bid = 5; 20 | optional uint32 cid = 6; 21 | optional uint32 did = 7; 22 | optional uint32 eid = 8; 23 | optional uint32 fid = 9; 24 | optional uint32 gid = 10; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Cpp/twoSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | // 1. Two Sum 6 | 7 | class Solution { 8 | public: 9 | std::vector twoSum(std::vector& nums, int target) { 10 | 11 | std::unordered_map map; 12 | 13 | for(size_t i{0}; i{static_cast(i), it->second}; 18 | 19 | map[nums[i]] = i; 20 | } 21 | return std::vector{}; 22 | } 23 | }; 24 | 25 | int main(){ 26 | std::vector vec{2,7,11,15}; 27 | auto res = Solution{}.twoSum(vec, 9); 28 | std::copy(res.begin(),res.end(),std::ostream_iterator(std::cout, " " )); 29 | 30 | } -------------------------------------------------------------------------------- /Py/clientWebsocket.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import asyncio 4 | import websockets 5 | import threading 6 | import sys 7 | 8 | async def hello(): 9 | for x in range(100000): 10 | async with websockets.connect("ws://localhost:8083") as websocket: 11 | await websocket.send(str(x)) 12 | name = await websocket.recv() 13 | #print("< {}".format(name)) 14 | print(name,end = ' ', flush=True) 15 | sys.stdout.flush() 16 | 17 | #asyncio.run(hello()) 18 | 19 | 20 | async def main(): 21 | 22 | await asyncio.wait([ 23 | hello(), 24 | hello(), 25 | hello(), 26 | hello(), 27 | hello(), 28 | hello(), 29 | hello(), 30 | hello(), 31 | hello(), 32 | hello(), 33 | hello() 34 | ]) 35 | 36 | loop = asyncio.get_event_loop() 37 | loop.run_until_complete(main()) -------------------------------------------------------------------------------- /Cpp/numIslandsDFS.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIslands(vector>& grid) { 4 | int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0; 5 | for (int i = 0; i < m; i++) { 6 | for (int j = 0; j < n; j++) { 7 | if (grid[i][j] == '1') { 8 | islands++; 9 | eraseIslands(grid, i, j); 10 | } 11 | } 12 | } 13 | return islands; 14 | } 15 | private: 16 | void eraseIslands(vector>& grid, int i, int j) { 17 | int m = grid.size(), n = grid[0].size(); 18 | if (i < 0 || i == m || j < 0 || j == n || grid[i][j] == '0') { 19 | return; 20 | } 21 | grid[i][j] = '0'; 22 | eraseIslands(grid, i - 1, j); 23 | eraseIslands(grid, i + 1, j); 24 | eraseIslands(grid, i, j - 1); 25 | eraseIslands(grid, i, j + 1); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Cpp/RTTI.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // to disable the RTTI -fno-rtti 3 | // g++ -fno-rtti RTTI.cpp -o RTTI 4 | class Animal{ 5 | //virtual void dummy(){} 6 | }; 7 | 8 | class StrayCat : public Animal 9 | { 10 | public: 11 | void meow(){std::cout<<"meoww"<(animalPtr); 20 | //if(catPtr) 21 | catPtr->meow(); 22 | //else{std::cout<<"Related instance "<< 23 | // "has no meow"< 2 | #include 3 | #include 4 | 5 | // Example of passing this to lambda expression 6 | // that is not working for out of scope case for 7 | // dummy foo object 8 | 9 | // should be used *this. It is available after c++17 10 | 11 | // note: with this (without *this) example will NOT work with x86-64 gcc 11.2 12 | // but it will work with x86-64 clang 13.0.0 13 | 14 | struct foo 15 | { 16 | int id; 17 | std::string name; 18 | //std::function run() 19 | auto run() 20 | { 21 | return[this]{ std::cout << id << ' ' << name << '\n'; }; 22 | //return[*this]{ std::cout << id << ' ' << name << '\n'; }; 23 | } 24 | }; 25 | 26 | //std::function boo() 27 | auto boo() 28 | { 29 | return foo{ 42, "john" }.run(); 30 | } 31 | 32 | int main() 33 | { 34 | auto l = boo(); 35 | l(); // does not print 42 john 36 | } 37 | -------------------------------------------------------------------------------- /Cpp/socketExample/mytask.cpp: -------------------------------------------------------------------------------- 1 | // mytask.cpp 2 | 3 | #include "mytask.h" 4 | #include 5 | #include 6 | #include 7 | 8 | MyTask::MyTask() 9 | { 10 | qDebug() << "MyTask()"; 11 | } 12 | 13 | // When the thread pool kicks up 14 | // it's going to hit this run, and it's going to do this time consuming task. 15 | // After it's done, we're going to send the results back to our main thread. 16 | // This runs in the separate thread, and we do not have any control over this thread, 17 | // but Qt does. 18 | // This may just stay in the queue for several ms depending on how busy the server is. 19 | 20 | void MyTask::run() 21 | { 22 | // time consumer 23 | 24 | qDebug() << "Task started"; 25 | 26 | int iNumber = 0; 27 | for(int i = 0; i < 100; i++) 28 | { 29 | iNumber += 1; 30 | } 31 | std::this_thread::sleep_for(std::chrono::milliseconds(2000)); 32 | 33 | 34 | qDebug() << "Task done"; 35 | emit Result(iNumber); 36 | } 37 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/QtOpencvQml/QtOpencvQml.pro: -------------------------------------------------------------------------------- 1 | ###################################################################### 2 | # Automatically generated by qmake (3.1) Sat Sep 3 21:58:11 2022 3 | ###################################################################### 4 | 5 | QT += quick 6 | 7 | CONFIG += c++11 8 | 9 | CONFIG += link_pkgconfig 10 | PKGCONFIG += opencv4 11 | 12 | TEMPLATE = app 13 | TARGET = QtOpencvQml 14 | INCLUDEPATH += . 15 | 16 | RESOURCES += qml.qrc 17 | 18 | 19 | # You can make your code fail to compile if you use deprecated APIs. 20 | # In order to do so, uncomment the following line. 21 | # Please consult the documentation of the deprecated API in order to know 22 | # how to port your code away from it. 23 | # You can also select to disable deprecated APIs only up to a certain version of Qt. 24 | #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 25 | 26 | # Input 27 | SOURCES += main.cpp qmlType.cpp 28 | 29 | HEADERS += qmlType.h 30 | -------------------------------------------------------------------------------- /Cpp/framebuffer1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | // application entry point 10 | int main(int argc, char* argv[]) 11 | { 12 | int fbfd = 0; // framebuffer filedescriptor 13 | struct fb_var_screeninfo var_info; 14 | 15 | // Open the framebuffer device file for reading and writing 16 | fbfd = open("/dev/fb0", O_RDWR); 17 | if (fbfd == -1) { 18 | printf("Error: cannot open framebuffer device.\n"); 19 | return(1); 20 | } 21 | printf("The framebuffer device opened.\n"); 22 | 23 | // Get variable screen information 24 | if (ioctl(fbfd, FBIOGET_VSCREENINFO, &var_info)) { 25 | printf("Error reading variable screen info.\n"); 26 | } 27 | printf("Display info %dx%d, %d bpp\n", 28 | var_info.xres, var_info.yres, 29 | var_info.bits_per_pixel ); 30 | 31 | // close file 32 | close(fbfd); 33 | 34 | return 0; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Cpp/nonAutoDuration.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // g++ nonAutoDuration.cpp -o example -lpthread 5 | // valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./example 6 | class Example 7 | { 8 | public: 9 | int a = 1; 10 | }; 11 | 12 | void foo() 13 | { 14 | static Example ex; 15 | 16 | ex.a = 1; 17 | 18 | std::thread t([&ex]()mutable{ 19 | 20 | std::cout< 2 | #include 3 | // https://godbolt.org/z/jqEhvo13Y 4 | 5 | class Concrete { 6 | public: 7 | int NonMockedMethod() { 8 | return 42; 9 | } 10 | 11 | virtual int MockedMethod() { 12 | return 43; 13 | } 14 | }; 15 | 16 | class MockConcrete : public Concrete { 17 | public: 18 | MOCK_METHOD(int, MockedMethod, (), (override)); 19 | 20 | MockConcrete() { 21 | // Call the real implementation by default 22 | ON_CALL(*this, MockedMethod()) 23 | .WillByDefault([this]() { return Concrete::MockedMethod(); }); 24 | } 25 | }; 26 | 27 | TEST(MockConcreteTest, CanMockConcrete) { 28 | MockConcrete obj; 29 | 30 | // When we call NonMockedMethod, we call the real implementation 31 | EXPECT_EQ(42, obj.NonMockedMethod()); 32 | 33 | EXPECT_EQ(43, obj.MockedMethod()); 34 | 35 | // We can still override MockedMethod to return a different value 36 | EXPECT_CALL(obj, MockedMethod()).WillOnce(::testing::Return(44)); 37 | EXPECT_EQ(44, obj.MockedMethod()); 38 | } -------------------------------------------------------------------------------- /Py/DrawCircle.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | 4 | def draw_circle(event, 5 | x, 6 | y, 7 | flags, 8 | param): 9 | global center, clicked 10 | 11 | # get the mouse click down & up 12 | # and Track the center 13 | if event == cv2.EVENT_LBUTTONDOWN: 14 | center = (x, y) 15 | clicked = False 16 | 17 | if event == cv2.EVENT_LBUTTONUP: 18 | clicked = True 19 | 20 | 21 | # zero drawing of the circle 22 | center = (0, 0) 23 | clicked = False 24 | 25 | # Take a video 26 | cap = cv2.VideoCapture(0) 27 | 28 | # Create a Named Window for the Connections 29 | cv2.namedWindow('Testing') 30 | 31 | # Bind Our Function with mouse click 32 | cv2.setMouseCallback('Testing', draw_circle) 33 | 34 | while True: 35 | ret, frame = cap.read() 36 | 37 | if clicked: 38 | cv2.circle(frame, center=center, radius=50, color=(255, 255, 255), thickness=3) 39 | 40 | cv2.imshow('Testing', frame) 41 | 42 | if cv2.waitKey(3) & 0xFF == 27: 43 | break 44 | 45 | cap.release() 46 | cv2.destroyAllWindows() 47 | -------------------------------------------------------------------------------- /Cpp/QtOpenCV/Viewer/viewer.pro: -------------------------------------------------------------------------------- 1 | ###################################################################### 2 | # Automatically generated by qmake (3.1) Thu Aug 18 22:08:08 2022 3 | ###################################################################### 4 | 5 | TEMPLATE = app 6 | TARGET = viewer 7 | INCLUDEPATH += . 8 | greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 9 | 10 | # The following define makes your compiler warn you if you use any 11 | # feature of Qt which has been marked as deprecated (the exact warnings 12 | # depend on your compiler). Please consult the documentation of the 13 | # deprecated API in order to know how to port your code away from it. 14 | DEFINES += QT_DEPRECATED_WARNINGS 15 | 16 | # You can also make your code fail to compile if you use deprecated APIs. 17 | # In order to do so, uncomment the following line. 18 | # You can also select to disable deprecated APIs only up to a certain version of Qt. 19 | #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 20 | 21 | # Input 22 | SOURCES += main.cpp mainwindow.cpp 23 | 24 | HEADERS += mainwindow.h 25 | 26 | 27 | -------------------------------------------------------------------------------- /gtestExample/exampleTest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "example.cpp" 4 | 5 | using namespace std; 6 | // g++ -Wall -g -pthread exampleTest.cpp example.cpp -lgtest_main -lgtest -lpthread -o test 7 | // test fixture 8 | class ExampleTest : public testing::Test 9 | { 10 | protected: 11 | Example *ex; 12 | void SetUp() 13 | { 14 | ex = new Example; 15 | cout<<"Created"<increase(100); 28 | EXPECT_EQ(100,ex->ctr); 29 | } 30 | 31 | TEST(Example, test1) 32 | { 33 | Example inst; 34 | inst.increase(100); 35 | EXPECT_EQ(100, inst.ctr); 36 | } 37 | 38 | TEST(Example, test2) 39 | { 40 | Example inst; 41 | inst.increase(100); 42 | ASSERT_EQ(500, inst.ctr); 43 | 44 | inst.decrease(50); 45 | EXPECT_EQ(100, inst.ctr); 46 | } 47 | 48 | int main(int argc, char **argv) 49 | { 50 | testing::InitGoogleTest(&argc, argv); 51 | 52 | return RUN_ALL_TESTS(); 53 | } -------------------------------------------------------------------------------- /Cpp/asyncProcess.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() 8 | { 9 | 10 | std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); 11 | 12 | //int cnt{0}; 13 | std::atomic cnt{0}; 14 | int iterator{1'000'000}; 15 | std::mutex lockMutex; 16 | 17 | 18 | std::future obj1 = std::async(std::launch::async, [&]() 19 | { 20 | //std::lock_guard guardMutex(lockMutex); //RAII style mechanism 21 | // lockMutex automatically released when guardMutex is out of scope 22 | for(int i{0}; i guardMutex(lockMutex); 29 | for(int i{0}; i(end-begin).count()<<"[us]"< 2 | #include 3 | #include 4 | 5 | class Solution 6 | { 7 | public: 8 | int stockPairs(std::vector stocksProfit, 9 | long target) 10 | { 11 | int result {0}; 12 | std::unordered_map m; 13 | for(size_t i{0}; i vec {5, 7, 9, 9, 13, 11, 6, 6, 3, 3}; 39 | int target = 12; 40 | 41 | std::cout< 2 | #include 3 | 4 | class Solution 5 | { 6 | public: 7 | std::string longestPalindrome(const std::string& s) 8 | { 9 | size_t size {s.size()}; 10 | 11 | unsigned int max_length {0}; 12 | unsigned int min_start {0}; 13 | 14 | for(unsigned int i{0}; i < size;) 15 | { 16 | if((size-i) <= max_length/2) break; 17 | unsigned int k {i}, j {i}; 18 | 19 | while( k 0 && (s[k+1] == s[j-1])) // expand 23 | { 24 | ++k; 25 | --j; 26 | } 27 | 28 | unsigned int new_length {k-j+1}; 29 | if(new_length > max_length){ max_length = new_length; min_start=j;} 30 | } 31 | 32 | return size ? size==1 ? s : s.substr(min_start,max_length) : ""; 33 | } 34 | }; 35 | 36 | int main() 37 | { 38 | const std::string str = "asddabbasswe"; 39 | 40 | std::cout< 2 | 3 | //A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Longest common subsequence (LCS) of 2 sequences is a subsequence, with maximal length, which is common to both the sequences. 4 | 5 | 6 | using namespace std; 7 | 8 | using iter = string::const_iterator; 9 | 10 | int MaxChildRanges(iter b1, iter e1, iter b2, iter e2) 11 | { 12 | 13 | if(b1==e1 || b2==e2) 14 | return 0; 15 | 16 | if(*b1 == *b2) 17 | return 1 + MaxChildRanges(next(b1), e1, next(b2), e2); 18 | 19 | return max( MaxChildRanges(next(b1), e1, b2, e2), 20 | MaxChildRanges(b1, e1, next(b2), e2)); 21 | } 22 | 23 | int commonChild(const string& s1, const string& s2) { 24 | 25 | return MaxChildRanges(s1.begin(), s1.end(), s2.begin(), s2.end()); 26 | 27 | } 28 | 29 | int main() 30 | { 31 | 32 | std::string str1 {"SHINCHAN"}; 33 | std::string str2 {"NOHARAAA"}; 34 | 35 | int result = commonChild(str1, str2); 36 | 37 | cout << result << "\n"; 38 | 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /sharedCallbackExample/exampleA.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "exampleB.h" 7 | #include "exampleA.h" 8 | 9 | 10 | A::A() 11 | { 12 | std::cout<<"A cons"<(shared_from_this()); // can not be called inside of the constructor 14 | 15 | // std::thread([this](){ 16 | 17 | // std::this_thread::sleep_for (std::chrono::seconds(1)); 18 | // Bptr = std::make_shared(shared_from_this()); 19 | 20 | // }).detach(); 21 | 22 | //std::this_thread::sleep_for (std::chrono::seconds(3)); 23 | 24 | } 25 | 26 | void A::foo() 27 | { 28 | Bptr = std::make_shared(shared_from_this()); // can not be called inside of the constructor 29 | //It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr (in particular, shared_from_this cannot be called during construction of *this). 30 | // terminate called after throwing an instance of 'std::bad_weak_ptr 31 | } 32 | 33 | void A::Acallback() 34 | { 35 | std::cout<<"Acallback"< 6 | #include 7 | 8 | //using namespace boost::asio 9 | //using ip::tcp 10 | 11 | using std::string; 12 | using std::cout; 13 | using std::endl; 14 | 15 | int main() 16 | { 17 | boost::asio::io_service io_service; 18 | //listen for new connection 19 | boost::system::error_code ec; 20 | boost::asio::ip::tcp::acceptor acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 1234 )); 21 | boost::asio::ip::tcp::socket socket_(io_service);//socket creation 22 | acceptor_.accept(socket_);//waiting for connection 23 | //read operation 24 | boost::asio::streambuf buf; 25 | boost::asio::read_until( socket_, buf, "\n",ec); 26 | if(ec){std::cout<(buf.data()); 28 | cout << data << endl; 29 | //write operation 30 | boost::asio::write( socket_, boost::asio::buffer(data) ,ec); 31 | if(ec){std::cout< 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | std::vector twoOutOfThree(std::vector& nums1, std::vector& nums2, std::vector& nums3) { 8 | struct found 9 | { 10 | bool n1; 11 | bool n2; 12 | bool n3; 13 | }; 14 | 15 | std::unordered_map map; 16 | for(auto n : nums1) map[n].n1 = true; 17 | for(auto n : nums2) map[n].n2 = true; 18 | for(auto n : nums3) map[n].n3 = true; 19 | 20 | std::vector result; 21 | result.reserve(map.size()); 22 | 23 | for(const auto x : map) 24 | { 25 | if(x.second.n1 + x.second.n2 + x.second.n3 >= 2) 26 | result.push_back(x.first); 27 | } 28 | 29 | return result; 30 | } 31 | }; 32 | 33 | int main() 34 | { 35 | std::vector vec1 {3,1}; 36 | std::vector vec2 {2,3}; 37 | std::vector vec3 {1,2}; 38 | 39 | for(const auto v : Solution{}.twoOutOfThree(vec1, vec2, vec3)) 40 | std::cout< 2 | 3 | //A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Longest common subsequence (LCS) of 2 sequences is a subsequence, with maximal length, which is common to both the sequences. 4 | 5 | 6 | using namespace std; 7 | 8 | using iter = string::const_iterator; 9 | 10 | int MaxChildRanges(iter b1, iter e1, iter b2, iter e2) 11 | { 12 | 13 | int result; 14 | if(b1==e1 || b2==e2) 15 | result = 0; 16 | else if(*b1 == *b2) 17 | result = 1 + MaxChildRanges(next(b1), e1, next(b2), e2); 18 | else 19 | result = max(MaxChildRanges(next(b1), e1, b2, e2), 20 | MaxChildRanges(b1, e1, next(b2), e2)); 21 | 22 | return result; 23 | } 24 | 25 | int commonChild(const string& s1, const string& s2) { 26 | 27 | return MaxChildRanges(s1.begin(), s1.end(), s2.begin(), s2.end()); 28 | 29 | } 30 | 31 | int main() 32 | { 33 | 34 | std::string str1 {"SHINCHAN"}; 35 | std::string str2 {"NOHARAAA"}; 36 | 37 | int result = commonChild(str1, str2); 38 | 39 | cout << result << "\n"; 40 | 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /protoExamples/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "test.pb.h" 5 | #include "google/protobuf/io/zero_copy_stream_impl.h" 6 | #include "google/protobuf/text_format.h" 7 | 8 | using ::google::protobuf::RepeatedField; 9 | using ::google::protobuf::int64; 10 | 11 | int main() 12 | { 13 | Test test; 14 | test.add_id(10); 15 | test.add_id(20); 16 | test.add_id(30); 17 | 18 | std::cout<& id_vec = test.id(); 23 | for(auto a : id_vec) 24 | { 25 | // *itr += 1000; // this will throw an compiler error. It is not mutable. 26 | std::cout<< "id: "<* mut_vec = test.mutable_id(); 34 | 35 | for(auto itr = mut_vec->begin(); itr != mut_vec->end(); ++itr) 36 | { 37 | *itr += 1000; // this will throw an compiler error. It is not mutable. 38 | std::cout<< "id: "<<*itr< 2 | #include 3 | 4 | 5 | /* 6 | * It is like finding a start point of circle in linked list 7 | * Start point of the circle is the first repeated number 8 | * Lets define array like linked list with using index 9 | * 1 3 4 2 2 (vector itself) 10 | * 0 1 2 3 4 (index) 11 | * 12 | * 0 goes to 1, 1 goies to 3, 3 goes to 2, 13 | * 0 -> 1 -> 3 -> 2 -> 4 14 | * 4 -> 2, as it is seen there is a loop between 2 and 4. 15 | * And the 2 is the start point of the circle which is 16 | * first repeated number in the array/vector. 17 | * 18 | * 19 | */ 20 | 21 | class Solution { 22 | public: 23 | int findDuplicate(std::vector& nums) { 24 | int slow = nums[0]; 25 | int fast = nums[nums[0]]; 26 | 27 | while(slow != fast) 28 | { 29 | slow = nums[slow]; 30 | fast = nums[nums[fast]]; 31 | } 32 | 33 | slow = 0; 34 | while(slow != fast) 35 | { 36 | slow = nums[slow]; 37 | fast = nums[fast]; 38 | } 39 | 40 | return slow; 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | std::vector vec {1,3,4,2,2}; 47 | std::cout< 2 | #include 3 | 4 | class Solution 5 | { 6 | public: 7 | void dfs(std::vector> &map, int x, int y) 8 | { 9 | if(x < 0 || y < 0 || x >= map.size() || y >= map[0].size() || map[x][y] == '0') 10 | return; 11 | 12 | map[x][y] = '0'; 13 | dfs(map, x + 1, y); 14 | dfs(map, x - 1, y); 15 | dfs(map, x, y + 1); 16 | dfs(map, x, y - 1); 17 | } 18 | int numberOfIslands(std::vector> &map) 19 | { 20 | int result = 0; 21 | 22 | if(map.size() == 0) 23 | return result; 24 | 25 | for(int i = 0; i < map.size(); i++) 26 | { 27 | for(int j = 0; j < map[0].size(); j++) 28 | { 29 | if(map[i][j] == '1') 30 | { 31 | result ++; 32 | 33 | dfs(map,i,j); 34 | } 35 | } 36 | } 37 | 38 | 39 | return result; 40 | } 41 | }; 42 | 43 | 44 | int main() 45 | { 46 | 47 | std::vector> map 48 | { 49 | {'1','0','1','0','1'}, 50 | {'1','0','1','0','1'}, 51 | {'1','0','1','0','1'}, 52 | {'1','0','1','0','1'}, 53 | {'1','0','0','0','0'}, 54 | {'1','0','1','0','1'}, 55 | {'1','0','0','0','1'}, 56 | {'1','0','0','0','1'}, 57 | {'1','0','0','0','1'}, 58 | {'1','0','1','1','1'} 59 | }; 60 | 61 | Solution s; 62 | std::cout<= 0 and nr < m and nc >= 0 and nc < n and grid[nr][nc] == '1': 23 | queue.append((nr, nc)) 24 | grid[nr][nc] = '0' 25 | return count 26 | 27 | 28 | tmp = Solution() 29 | grid = [ 30 | ['1', '0', '1', '0', '1', '0', '1'], 31 | ['1', '0', '0', '0', '0', '0', '1'], 32 | ['0', '0', '0', '1', '0', '0', '1'], 33 | ['1', '0', '1', '0', '1', '1', '1'], 34 | ['1', '0', '1', '0', '1', '0', '1'], 35 | ['1', '0', '1', '0', '1', '0', '1'] 36 | ] 37 | print(tmp.numOfIslands(grid)) 38 | -------------------------------------------------------------------------------- /protoExamples/socket_server_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import socket 4 | from time import sleep 5 | import json 6 | import sys 7 | 8 | HOST = '127.0.0.1' # Standard loopback interface address (localhost) 9 | PORT = 2389 # Port to listen on (non-privileged ports are > 1023) 10 | 11 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 12 | s.bind((HOST, PORT)) 13 | s.listen() 14 | conn, addr = s.accept() 15 | with conn: 16 | print('Connected by', addr) 17 | while True: 18 | data = conn.recv(172) 19 | if not data: 20 | break 21 | 22 | data = data.decode('utf-8') 23 | #print(data) 24 | d = json.dumps(data) 25 | 26 | send_data = {} 27 | send_data['id'] = '5001' 28 | send_data['id2'] = '5001' 29 | send_data['id3'] = '5001' 30 | send_data['id4'] = '5001' 31 | send_data['id5'] = '5001' 32 | send_data['id6'] = '5001' 33 | send_data['id7'] = '5001' 34 | send_data['id8'] = '5001' 35 | send_data['id9'] = '5001' 36 | send_data['id10'] = '5001' 37 | 38 | json_data = json.dumps(send_data) 39 | #print(sys.getsizeof(json_data)) 40 | 41 | conn.sendall(bytes(json_data,encoding="utf-8")) 42 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/server.cpp: -------------------------------------------------------------------------------- 1 | //simple tcp socket server example with boost asio 2 | //sudo apt install libboost-dev 3 | //g++ -lpthread -lboost_system server.cpp -o server 4 | 5 | #include 6 | #include 7 | 8 | 9 | //using namespace boost::asio 10 | //using ip::tcp 11 | 12 | int main(int argc, char* argv[]) 13 | { 14 | 15 | if(argc != 3) 16 | { 17 | std::cout<<"Wrong parameter\n"<<"Example usage 127.0.0.1 1234"<(buf.data()); 35 | std::cout << data << std::endl; 36 | //write operation 37 | boost::asio::write( socket_, boost::asio::buffer(data) ,ec); 38 | if(ec){std::cout< 2 | #include 3 | #include 4 | 5 | // leetcode 454. 4Sum II 6 | // Given four integer arrays v1, v2, v3, and v4 all of length n, return the number of tuples (i, j, k, l) such that: 7 | // 0 <= i, j, k, l < n 8 | // nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 9 | 10 | class Solution 11 | { 12 | using vec = const std::vector; 13 | public: 14 | int fourSumCount(vec& v1, vec& v2, vec& v3, vec& v4) 15 | { 16 | unsigned int result {0}; 17 | 18 | std::unordered_map map; 19 | 20 | const size_t size {v1.size()}; 21 | // nums1[i] + nums2[j] = -(nums3[k] + nums4[l]) 22 | for(int i{0}; i vec1 {1,2}; 37 | std::vector vec2 {-2,-1}; 38 | std::vector vec3 {-1,2}; 39 | std::vector vec4 {0,2}; 40 | 41 | std::cout< 3 | #include 4 | #include // std::chrono::seconds 5 | #include 6 | //g++ -std=c++17 threadLimitTest.cpp -lpthread -o binary 7 | 8 | int main() { 9 | unsigned int n = std::thread::hardware_concurrency(); 10 | std::cout << n << " concurrent threads are supported.\n"; 11 | std::atomic a {1}; 12 | //for(int i = 0; i<100000; i++) 13 | try 14 | { 15 | while(a > 0) 16 | { 17 | 18 | std::thread([&](){ 19 | 20 | 21 | while(1) 22 | { 23 | //a ++; 24 | //std::cout< 2 | #include 3 | #include 4 | 5 | // Function to find the number of distinct pairs of stocks that sum to the target profit 6 | class Solution 7 | { 8 | public: 9 | int stockPairs(std::vector& profits, int target) { 10 | // Initialize a hash set to store the profits that have been seen 11 | std::unordered_set seen; 12 | 13 | // Initialize a counter to keep track of the number of pairs 14 | int count = 0; 15 | 16 | // Iterate through the array of profits 17 | for (int profit : profits) { 18 | // Check if the target profit minus the current profit has been seen before 19 | if (seen.count(target - profit)) { 20 | // If it has, increment the counter 21 | count++; 22 | } 23 | // Add the current profit to the hash set 24 | seen.insert(profit); 25 | } 26 | 27 | // Return the number of pairs found 28 | return count; 29 | } 30 | }; 31 | 32 | int main() { 33 | // Define the array of profits and the target profit 34 | std::vector profits = {5, 7, 9, 9, 13, 11, 6, 6, 3, 3}; 35 | int target = 12; 36 | 37 | std::cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int tsp(int mask, int pos, 8 | std::vector>& vec, 9 | std::vector>& dp) 10 | { 11 | 12 | const int size {vec.size()}; 13 | 14 | if(mask == ((1<>& vec) 39 | { 40 | std::vector> dp(vec.size()*vec.size(),std::vector(vec.size(),-1)); 41 | return tsp(1,0,vec,dp); 42 | } 43 | 44 | 45 | int main() 46 | { 47 | 48 | std::vector> dist{ 49 | {0,20,42,25}, 50 | {20,0,30,34}, 51 | {42,30,0,10}, 52 | {25,34,10,0}, 53 | }; 54 | 55 | std::cout< 2 | #include 3 | #include 4 | 5 | /* 6 | * 7 | * Given string find firt non repeating unique character if there is none return -1 8 | * 9 | * leetcode returns 0 10 | * loveleetcode returns 2 11 | * 12 | * */ 13 | 14 | 15 | using namespace std; 16 | 17 | class Solution 18 | { 19 | 20 | public: 21 | int firstUniqueCharacterInString(string &str) 22 | { 23 | 24 | std::unordered_map map; 25 | int ans = INT_MAX; 26 | 27 | for(int i=0; i 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | class MainWindow : public QMainWindow 15 | { 16 | Q_OBJECT 17 | 18 | public: 19 | explicit MainWindow(QWidget *parent=nullptr); 20 | ~MainWindow(); 21 | 22 | private: 23 | void initUI(); 24 | void createActions(); 25 | void showImage(QString); 26 | void setupShortcuts(); 27 | 28 | private slots: 29 | void openImage(); 30 | void zoomIn(); 31 | void zoomOut(); 32 | void prevImage(); 33 | void nextImage(); 34 | void saveAs(); 35 | 36 | private: 37 | QMenu *fileMenu; 38 | QMenu *viewMenu; 39 | 40 | QToolBar *fileToolBar; 41 | QToolBar *viewToolBar; 42 | 43 | QGraphicsScene *imageScene; 44 | QGraphicsView *imageView; 45 | 46 | QStatusBar *mainStatusBar; 47 | QLabel *mainStatusLabel; 48 | 49 | QAction *openAction; 50 | QAction *saveAsAction; 51 | QAction *exitAction; 52 | QAction *zoomInAction; 53 | QAction *zoomOutAction; 54 | QAction *prevAction; 55 | QAction *nextAction; 56 | 57 | QString currentImagePath; 58 | QGraphicsPixmapItem *currentImage; 59 | }; 60 | 61 | #endif // MAINWINDOW_H 62 | -------------------------------------------------------------------------------- /Cpp/minTimeToCompleteTrip.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // 2187. Minimum Time to Complete Trips 5 | 6 | class Solution { 7 | 8 | using lng = long long int; 9 | public: 10 | 11 | long long minimumTime(std::vector& arr , int totalTrips) { 12 | lng lowestTime = 1; 13 | lng highestTime = 1e14; 14 | while(lowestTime 3 + 1 + 1 = 5 Trips 23 | 24 | lng totalTrips = 0; 25 | for(const auto& x : arr) 26 | { 27 | // convert it to long long int 28 | lng val = x; 29 | 30 | totalTrips += (mid / val); 31 | } 32 | return totalTrips; 33 | }() >= totalTrips) 34 | highestTime = mid; 35 | else 36 | lowestTime = mid+1; 37 | } 38 | return lowestTime; 39 | } 40 | }; 41 | 42 | int main () 43 | { 44 | std::vector vec {1,2,3}; 45 | int totalTrips {5}; 46 | 47 | std::cout< 2 | #include 3 | #include 4 | 5 | // 11. Container With Most Water 6 | // if height[left] < height[right] then 7 | // move forward from left to right. Because you have 8 | // already the area which is bigger then right ones. 9 | // if(height[i] < height[j]) 10 | // A = A(i,j) = (j-i)*min(height[i], height[j]) 11 | // A' = A(i, j-1) = (j-1-i)*(min(height[i], height[j])) 12 | // for if height[i] < height [j-1] 13 | // A' = (j-1-i)*height[i] which is smaller than (j-i)*height[i] = A 14 | // A' < A 15 | 16 | class Solution { 17 | public: 18 | int maxArea(std::vector& height) { 19 | 20 | int result {0}; 21 | int area {0}; 22 | int minHeight {0}; 23 | size_t l {0}; 24 | size_t r {height.size()-1}; 25 | 26 | while(l < r) 27 | { 28 | minHeight = std::min(height[l], height[r]); 29 | area = (r-l)*minHeight; 30 | 31 | result = std::max(area, result); 32 | 33 | if(height[l] vec {1,8,6,2,5,4,8,3,7}; 47 | 48 | std::cout< 2 | #include 3 | #include 4 | 5 | typedef struct value_tag 6 | { 7 | int x; 8 | int y; 9 | }value; 10 | 11 | typedef struct st1_tag 12 | { 13 | unsigned int size; 14 | value* array; 15 | }st1; 16 | 17 | typedef struct st2_tag 18 | { 19 | unsigned int size; 20 | st1* array; 21 | }st2; 22 | 23 | st2 foo(int size) 24 | { 25 | st2 st2Struct; 26 | st2Struct.size = size; 27 | st2Struct.array = (st1*)malloc(size*sizeof(st1)); 28 | 29 | for(int i = 0; i < size; ++i) 30 | { 31 | st1 st1Struct; 32 | st1Struct.size = size; 33 | st1Struct.array = (value*)malloc(size*sizeof(value)); 34 | 35 | for(int j = 0; j < size; ++j) 36 | { 37 | value val; 38 | val.x = j; 39 | val.y = j+1; 40 | st1Struct.array[j] = val; 41 | } 42 | st2Struct.array[i] = st1Struct; 43 | } 44 | 45 | return st2Struct; 46 | } 47 | 48 | int main() 49 | { 50 | 51 | st2 st = foo(10); 52 | 53 | for(int i = 0; i < 10; ++i) 54 | { 55 | for(int j = 0; j < 10; ++j) 56 | { 57 | printf("%d ",st.array[i].array[j].x); 58 | } 59 | std::endl(std::cout); 60 | } 61 | 62 | // free the memory 63 | for(int i = 0; i < 10; ++i) 64 | { 65 | free(st.array[i].array); 66 | } 67 | free(st.array); 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Cpp/subtractMin.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | std::vector vec; 9 | int size = 10000000; 10 | for(int i=0; i(end-begin).count()<<" [ns]"<(end-begin).count()<<" [ns]"< 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | //A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Longest common subsequence (LCS) of 2 sequences is a subsequence, with maximal length, which is common to both the sequences. 8 | 9 | using iter = std::string::const_iterator; 10 | using doubleMap = std::vector>; 11 | 12 | int maxChildRanges(iter b1, iter e1, iter b2, iter e2, doubleMap& map) 13 | { 14 | auto& mem {map[e1-b1][e2-b2]}; 15 | int result {0}; 16 | 17 | if(mem != -1) 18 | result = mem; 19 | else if(b1==e1 || b2==e2) 20 | mem = 0; 21 | else if(*b1 == *b2) 22 | result = mem = 1 + maxChildRanges(next(b1), e1, next(b2), e2, map); 23 | else 24 | result = mem = std::max(maxChildRanges(next(b1), e1, b2, e2, map), 25 | maxChildRanges(b1, e1, next(b2), e2, map)); 26 | 27 | return result; 28 | } 29 | 30 | int commonChild(const std::string str1, const std::string str2) 31 | { 32 | doubleMap map{str1.size()+1,std::vector(str2.size()+1, -1)}; 33 | return maxChildRanges(str1.begin(), str1.end(), str2.begin(), str2.end(), map); 34 | } 35 | 36 | int main() 37 | { 38 | std::string str1{"SHINCHAN"}; 39 | std::string str2{"NOHARAAA"}; 40 | 41 | std::cout< 2 | #include 3 | #include 4 | 5 | int stringToInteger(const std::string& str) 6 | { 7 | int result = 0; 8 | bool isNegative = false; 9 | int i = 0; 10 | 11 | //check str is negative or not 12 | if(str[0] == '-') 13 | { 14 | isNegative = true; 15 | i++; 16 | } 17 | 18 | for(; i (result * 10 + (str[i] - '0')) then there is a overflow 25 | // if(result * 10 + (str[i] - '0') > INT_MAX) // but this will not work 26 | // because result * 10 + (str[i] - '0') if result is cause overflow then there 27 | // will be undefined behaviour so it is good idea to compare it with result 28 | 29 | if(result > (INT_MAX - (str[i] - '0')) / 10) 30 | { 31 | std::cout<<"overflow detected"< 2 | #include 3 | #include 4 | #include 5 | 6 | //using namespace boost::asio 7 | //using ip::tcp 8 | 9 | typedef std::shared_ptr socket_ptr; 10 | 11 | boost::asio::io_service io_service; 12 | boost::asio::ip::tcp::acceptor acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 1234 )); 13 | 14 | void handle_accept(socket_ptr sock, const boost::system::error_code & err); 15 | 16 | void start_accept(socket_ptr sock) { 17 | acceptor_.async_accept(*sock, boost::bind( handle_accept, sock, _1) ); 18 | } 19 | 20 | void handle_accept(socket_ptr sock, const boost::system::error_code & err) { 21 | if ( err) return; 22 | // at this point, you can read/write to the socket 23 | 24 | boost::system::error_code ec; 25 | boost::asio::streambuf buf; 26 | char data[10]; 27 | size_t len = sock->read_some(boost::asio::buffer(data),ec); 28 | 29 | if (len > 0) 30 | { 31 | std::cout << "received " << len << " bytes\n"; 32 | write(*sock, boost::asio::buffer(data),ec); 33 | 34 | if(ec)std::cout< 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | class MainWindow : public QMainWindow 15 | { 16 | Q_OBJECT 17 | 18 | public: 19 | explicit MainWindow(QWidget *parent=nullptr); 20 | ~MainWindow(); 21 | 22 | private: 23 | void initUI(); 24 | void createActions(); 25 | void showImage(QString); 26 | void setupShortcuts(); 27 | 28 | private slots: 29 | void openImage(); 30 | void zoomIn(); 31 | void zoomOut(); 32 | void prevImage(); 33 | void nextImage(); 34 | void saveAs(); 35 | void blurImage(); 36 | 37 | private: 38 | QMenu *fileMenu; 39 | QMenu *viewMenu; 40 | 41 | QToolBar *fileToolBar; 42 | QToolBar *viewToolBar; 43 | 44 | QGraphicsScene *imageScene; 45 | QGraphicsView *imageView; 46 | 47 | QStatusBar *mainStatusBar; 48 | QLabel *mainStatusLabel; 49 | 50 | QAction *openAction; 51 | QAction *saveAsAction; 52 | QAction *exitAction; 53 | QAction *zoomInAction; 54 | QAction *zoomOutAction; 55 | QAction *prevAction; 56 | QAction *nextAction; 57 | 58 | QString currentImagePath; 59 | QGraphicsPixmapItem *currentImage; 60 | 61 | QMenu *editMenu; 62 | QToolBar *editToolBar; 63 | QAction *blurAction; 64 | }; 65 | 66 | #endif // MAINWINDOW_H 67 | -------------------------------------------------------------------------------- /Cpp/forSum22.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int minimizeTheDifference(vector>& mat, int target) { 11 | bitset<4901> p(1); 12 | 13 | // this will create bitset which has all possibilities 14 | // of the additions from each row of the elements. 15 | // first row is shifted to left then in the second 16 | // iteration this bitset is used as default to be shifted 17 | // to the left according the next vector content. 18 | // at the end, each bitset position shows the addition 19 | // of all possibilities. 20 | for (auto& r : mat) { 21 | bitset<4901> tmp; 22 | for (int i : r) { 23 | tmp = tmp | (p << i); 24 | } 25 | swap(p, tmp); 26 | } 27 | 28 | int result {INT_MAX}; 29 | for (int i {0}; i < 4901; ++i) { 30 | if (p[i]) { 31 | int distance = abs(i - target); 32 | result = min(result, distance); 33 | } 34 | } 35 | 36 | return result; 37 | } 38 | }; 39 | 40 | int main() 41 | { 42 | vector> vec{ {1,2,3},{4,5,6},{7,8,9} }; 43 | 44 | std::cout< 2 | #include 3 | 4 | //using namespace boost::asio; 5 | //using ip::tcp; 6 | 7 | int main(int argc, char* argv[]) 8 | { 9 | 10 | if(argc != 4) 11 | { 12 | std::cout<<"Wrong parameter\n"<<"Example usage ./client 127.0.0.1 1234 hello"<(receive_buffer.data()); 45 | std::cout << data << std::endl; 46 | } 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Cpp/swapNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // leetcode 24. Swap Nodes in Pairs 4 | 5 | struct ListNode { 6 | int val; 7 | ListNode *next; 8 | ListNode() : val(0), next(nullptr) {} 9 | ListNode(int x) : val(x), next(nullptr) {} 10 | ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | ListNode* swapPairs(ListNode* head) { 16 | 17 | if(head==NULL) 18 | return head; 19 | 20 | ListNode* dummy = new ListNode(-1); 21 | dummy->next = head; 22 | ListNode* prev = dummy; 23 | 24 | while(head != NULL && head->next!=NULL) 25 | { 26 | ListNode *firstNode = head; 27 | ListNode *secondNode = head->next; 28 | 29 | prev->next = secondNode; 30 | firstNode->next = secondNode->next; 31 | secondNode->next = firstNode; 32 | 33 | prev = firstNode; 34 | head = firstNode->next; 35 | } 36 | 37 | return dummy->next; 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | ListNode* tmp; 44 | ListNode* list = new ListNode(0); 45 | tmp = list; 46 | 47 | for(int i = 1; i<6; i++) 48 | { 49 | tmp->next = new ListNode(i); 50 | tmp = tmp->next; 51 | } 52 | 53 | ListNode* res = Solution{}.swapPairs(list); 54 | 55 | tmp = res; 56 | 57 | while(tmp != NULL) 58 | { 59 | std::cout<val; 60 | tmp = tmp->next; 61 | } 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /Py/drawRect.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | def draw_rectangle(event, 4 | x, 5 | y, 6 | flags, 7 | param): 8 | 9 | global pt1, pt2, top_left_clicked, bottom_right_clicked 10 | 11 | # create an event for left button down and assigned it to event 12 | if event == cv2.EVENT_LBUTTONDOWN: 13 | # reset your rect 14 | if top_left_clicked == True and bottom_right_clicked == True: 15 | 16 | pt1 = (0,0) 17 | pt2 = (0,0) 18 | 19 | top_left_clicked = False 20 | bottom_right_clicked = False 21 | 22 | 23 | if top_left_clicked == False: 24 | pt1 = (x, y) 25 | top_left_clicked = True 26 | 27 | elif bottom_right_clicked == False: 28 | pt2 = (x, y) 29 | bottom_right_clicked = True 30 | 31 | 32 | pt1 = (0, 0) 33 | pt2 = (0, 0) 34 | 35 | top_left_clicked = False 36 | bottom_right_clicked = False 37 | 38 | cap = cv2.VideoCapture(0) 39 | 40 | cv2.namedWindow('Test') 41 | 42 | cv2.setMouseCallback('Test', draw_rectangle) 43 | 44 | while True: 45 | ret, frame = cap.read() 46 | 47 | if top_left_clicked == True: 48 | cv2.circle(frame, center=pt1, radius=5, color=(255, 0, 255), thickness=-1) 49 | 50 | if top_left_clicked == True and bottom_right_clicked == True: 51 | cv2.rectangle(frame, pt1, pt2, (0, 0, 255), 3) 52 | 53 | cv2.imshow('Test', frame) 54 | 55 | if cv2.waitKey(3) & 0xFF == 27: 56 | break 57 | 58 | cap.release() 59 | cv2.destroyAllWindows() 60 | 61 | 62 | -------------------------------------------------------------------------------- /Cpp/numberOfMoves.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | 6 | std::vector> numberOfMoves( 7 | std::vector> &mat, 8 | int x, 9 | int y 10 | ) 11 | { 12 | std::vector> result; 13 | 14 | 15 | std::vector X = {2, 1, -1, -2, -2, -1, 1, 2}; 16 | std::vector Y = {1, 2, 2, 1, -1, -2, -2, -1}; 17 | 18 | int numberOfRows = mat.size(); 19 | int numberOfColumns = mat[0].size(); 20 | 21 | for(int i=0; i=0 && y>=0) 27 | { 28 | if(mat[p][q] == 0) 29 | { 30 | 31 | result.push_back({p,q}); 32 | } 33 | } 34 | 35 | 36 | } 37 | 38 | 39 | 40 | return result; 41 | } 42 | 43 | 44 | int main() 45 | { 46 | 47 | std::vector> mat = { 48 | {0, 1, 0, 1, 1, 0,}, 49 | {0, 1, 0, 0, 0, 0,}, 50 | {0, 1, 0, 0, 0, 0,}, 51 | {0, 1, 0, 0, 0, 0,}, 52 | {0, 1, 0, 1, 1, 0,}, 53 | {0, 1, 0, 0, 0, 0,}, 54 | {0, 1, 0, 1, 0, 0,}, 55 | }; 56 | 57 | int x = 3; 58 | int y = 4; 59 | 60 | std::vector> res = numberOfMoves(mat,x,y); 61 | 62 | for(auto s : res) 63 | { 64 | std::cout< QTcpServer 60 | MyClient -down-|> QObject 61 | 62 | MyServer -down-> MyClient 63 | 64 | MyTask -right-|> QObject 65 | MyTask -left-|> QRunnable 66 | 67 | MyClient -down-> MyTask 68 | 69 | @enduml 70 | -------------------------------------------------------------------------------- /Cpp/stackWithMaxElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class StackWithMaxElement 6 | { 7 | private: 8 | std::stack mainStack; 9 | std::stack maxStack; 10 | 11 | public: 12 | void push(int i) 13 | { 14 | mainStack.push(i); 15 | 16 | if(maxStack.empty() || i >= maxStack.top()) 17 | { 18 | maxStack.push(i); 19 | } 20 | } 21 | 22 | void pop() 23 | { 24 | if(mainStack.empty()) 25 | { 26 | throw std::runtime_error("Stack is empty"); 27 | } 28 | 29 | if(mainStack.top() == maxStack.top()) 30 | maxStack.pop(); 31 | 32 | mainStack.pop(); 33 | } 34 | 35 | int top() 36 | { 37 | if(mainStack.empty()) 38 | { 39 | throw std::runtime_error("Stack is empty"); 40 | } 41 | 42 | return mainStack.top(); 43 | } 44 | 45 | int max() 46 | { 47 | if(maxStack.empty()) 48 | { 49 | throw std::runtime_error("Stack is empty"); 50 | } 51 | 52 | return maxStack.top(); 53 | } 54 | 55 | bool empty() 56 | { 57 | return mainStack.empty(); 58 | } 59 | }; 60 | 61 | int main() 62 | { 63 | StackWithMaxElement stack; 64 | 65 | stack.push(1); 66 | stack.push(5); 67 | stack.push(4); 68 | 69 | std::cout< 2 | #include 3 | #include 4 | 5 | // 15. 3Sum 6 | class Solution { 7 | public: 8 | std::vector> threeSum(std::vector& nums) { 9 | 10 | std::vector> result; 11 | 12 | std::sort(nums.begin(), nums.end()); 13 | 14 | for(size_t i {0}; i < nums.size(); i++) 15 | { 16 | int front = i + 1; 17 | int back = nums.size() - 1; 18 | 19 | while(i+1 < nums.size() && nums[i+1] == nums[i]) 20 | i++; 21 | 22 | while(front < back) 23 | { 24 | int sum = nums[i] + nums[front] + nums[back]; 25 | 26 | if(sum < 0) 27 | front ++; 28 | else if(sum > 0) 29 | back --; 30 | else 31 | { 32 | result.push_back({nums[i], nums[front], nums[back]}); 33 | while(front vec {-1,0,1,2,-1,-4}; 46 | 47 | for(auto s: Solution{}.threeSum(vec)) 48 | { 49 | for(auto c : s) 50 | std::cout< 2 | #include 3 | #include 4 | #include 5 | 6 | class Solution 7 | { 8 | public: 9 | std::string longestPalindrome(std::string s) 10 | { 11 | 12 | if(s.empty()) return ""; 13 | if(s.size() == 1) return s; 14 | 15 | std::vector vec2; 16 | vec2.push_back('$'); 17 | 18 | for(int i = 1, j = 0; i < (s.size()*2 + 1); i++) 19 | { 20 | if(i % 2 == 0) 21 | vec2.push_back(s[j++]); 22 | else 23 | vec2.push_back('#'); 24 | } 25 | 26 | vec2.push_back('#'); 27 | vec2.push_back('@'); 28 | 29 | std::vector P(vec2.size(),0); 30 | int C = 0; 31 | int R = 0; 32 | 33 | for(int i = 1; i < vec2.size()-1; i++) 34 | { 35 | int mirr = 2*C - i; 36 | if(i < R) 37 | P[i] = std::min((R-i), P[mirr]); 38 | 39 | while( vec2[i + 1 + P[i]] == vec2[i - 1 - P[i]] ) 40 | P[i]++; 41 | 42 | if((i + P[i]) > R) 43 | { 44 | C = i; 45 | R = i + P[i]; 46 | } 47 | } 48 | 49 | int max = *std::max_element(P.begin(), P.end()); 50 | std::vector::iterator it = std::find(P.begin(), P.end(), max); 51 | int index = std::distance(P.begin(), it); 52 | int init = 0; 53 | 54 | if(index % 2 == 0) 55 | init = std::abs((max / 2)- ( index / 2 - 1)); 56 | else 57 | init = std::abs((max / 2)- ( index / 2 )); 58 | 59 | 60 | return s.substr(init,max); 61 | } 62 | }; 63 | 64 | int main(int argc, char **argv) 65 | { 66 | const std::string str = "acbbabad"; 67 | 68 | Solution s; 69 | std::cout< 2 | #include 3 | #include 4 | 5 | class Solution 6 | { 7 | public: 8 | int updateTimes(std::vector signalOne, 9 | std::vector signalSecond) 10 | { 11 | 12 | const auto signalOneSize = signalOne.size(); 13 | const auto signalSecondSize = signalSecond.size(); 14 | 15 | const auto size = std::min(signalOneSize, signalSecondSize); 16 | 17 | unsigned int counter {0}; 18 | int max = 0; 19 | 20 | for(int i=0; i max) 28 | { 29 | max = signalOneValue; 30 | counter ++; 31 | } 32 | } 33 | } 34 | 35 | return counter; 36 | } 37 | }; 38 | 39 | int main() { 40 | 41 | std::vector signalOne = {1,2,3,3,3,5,4}; 42 | std::vector signalSecond = {1,2,3,4,3,5,4}; 43 | 44 | 45 | std::cout< signalOne2 = {1,2,3,4,1}; 48 | std::vector signalSecond2 = {5,4,3,4,1}; 49 | 50 | 51 | std::cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | // g++ framebuffer2.c -lX11 -lopencv_core -lopencv_highgui -o frame2 11 | // sudo apt install libopencv-dev 12 | void ImageFromDisplay(std::vector& Pixels, int& Width, int& Height, int& BitsPerPixel) 13 | { 14 | Display* display = XOpenDisplay(nullptr); 15 | Window root = DefaultRootWindow(display); 16 | 17 | XWindowAttributes attributes = {0}; 18 | XGetWindowAttributes(display, root, &attributes); 19 | 20 | Width = attributes.width; 21 | Height = attributes.height; 22 | 23 | XImage* img = XGetImage(display, root, 0, 0 , Width, Height, AllPlanes, ZPixmap); 24 | BitsPerPixel = img->bits_per_pixel; 25 | Pixels.resize(Width * Height * 4); 26 | 27 | memcpy(&Pixels[0], img->data, Pixels.size()); 28 | 29 | XDestroyImage(img); 30 | XCloseDisplay(display); 31 | } 32 | 33 | int main() 34 | { 35 | int Width = 0; 36 | int Height = 0; 37 | int Bpp = 0; 38 | std::vector Pixels; 39 | ImageFromDisplay(Pixels, Width, Height, Bpp); 40 | 41 | if (Width && Height) 42 | { 43 | cv::Mat img = cv::Mat(Height, Width, Bpp > 24 ? CV_8UC4 : CV_8UC3, &Pixels[0]); //Mat(Size(Height, Width), Bpp > 24 ? CV_8UC4 : CV_8UC3, &Pixels[0]); 44 | 45 | namedWindow("WindowTitle", cv::WINDOW_AUTOSIZE); 46 | imshow("Display window", img); 47 | 48 | // cv::waitKey(0); 49 | } 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Cpp/addTowNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // leetcode 2. Add Two Numbers 4 | 5 | struct ListNode { 6 | int val; 7 | ListNode *next; 8 | ListNode() : val(0), next(nullptr) {} 9 | ListNode(int x) : val(x), next(nullptr) {} 10 | ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | }; 12 | 13 | class Solution 14 | { 15 | public: 16 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 17 | { 18 | ListNode* dummy{new ListNode()}; 19 | ListNode* temp{dummy}; 20 | 21 | int carry{0}; 22 | while(l1!=NULL || l2!=NULL || carry){ 23 | int sum=0; 24 | if(l1!=NULL){ 25 | sum+=l1->val; 26 | l1=l1->next; 27 | } 28 | if(l2!=NULL){ 29 | sum+=l2->val; 30 | l2=l2->next; 31 | } 32 | sum+=carry; 33 | carry=sum/10; 34 | ListNode* newnode=new ListNode(sum%10); 35 | temp->next=newnode; 36 | temp=temp->next; 37 | } 38 | return dummy->next; 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | ListNode* l1 = new ListNode(2); 45 | l1->next = new ListNode(4); 46 | l1->next->next = new ListNode(3); 47 | 48 | ListNode* l2 = new ListNode(5); 49 | l2->next = new ListNode(6); 50 | l2->next->next = new ListNode(4); 51 | 52 | ListNode* res = Solution{}.addTwoNumbers(l1, l2); 53 | 54 | ListNode* tmp; 55 | tmp = res; 56 | 57 | while(tmp != NULL) 58 | { 59 | std::cout<val; 60 | tmp = tmp->next; 61 | } 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /Cpp/QtOpenCV/staticTest/main.cpp: -------------------------------------------------------------------------------- 1 | // #include "my_math.h" 2 | #include 3 | 4 | extern double reciprocal(double d); 5 | 6 | int main(){ 7 | std::cout << reciprocal(2.0) << std::endl; 8 | return 0; 9 | } 10 | 11 | /* 12 | 13 | g++ -c main.cpp -o main.o 14 | 15 | ulas@ulas:~/staticTest$ cat my_math.cpp 16 | #include "my_math.h" 17 | 18 | double reciprocal(double d) { 19 | return 1.0 / d; 20 | } 21 | 22 | g++ -c my_math.cpp -o my_math.o 23 | g++ main.o my_math.o -o a.out 24 | 25 | ar cr libmy_math.a my_math.o 26 | g++ -static -static-libgcc -static-libstdc++ main.o libmy_math.a -o a.out 27 | 28 | ulas@ulas:~/staticTest$ ldd staticTest 29 | linux-vdso.so.1 (0x00007ffc4c5d0000) 30 | libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fac8f1af000) 31 | libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fac8ef87000) 32 | libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fac8eea0000) 33 | /lib64/ld-linux-x86-64.so.2 (0x00007fac8f3fd000) 34 | libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fac8ee80000) 35 | 36 | 37 | g++ -shared -o libmy_math.so my_math.o 38 | export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/ulas/staticTest/ 39 | ulas@ulas:~/staticTest$ ldd staticTest 40 | linux-vdso.so.1 (0x00007ffd5ece8000) 41 | libmy_math.so => not found 42 | libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f3f17796000) 43 | libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3f1756e000) 44 | libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f3f17487000) 45 | /lib64/ld-linux-x86-64.so.2 (0x00007f3f179e4000) 46 | libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f3f17467000) 47 | 48 | */ 49 | -------------------------------------------------------------------------------- /Cpp/minimumSwap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // to order the array/vector in descending order calculate necessary minimum swap number 7 | 8 | int numberOfSwap(const std::vector& vec) 9 | { 10 | unsigned int result{0}; 11 | const size_t size{vec.size()}; 12 | 13 | std::vector> p(size); 14 | for(size_t i{0}; i &p1, const std::pair &p2){ 23 | return (p1.first > p2.first); 24 | }); 25 | 26 | // keep visited nodes in deque 27 | std::deque visited(size, false); 28 | 29 | // find cycle in vector/array 30 | // (edge number of the cycle - 1) is the minimum swap number 31 | // if there is a back edge that means there is a cycle in the directed graph 32 | for(size_t i{0}; i(i)) 35 | continue; 36 | 37 | int edgeNumber{0}; 38 | size_t j {i}; 39 | while(!visited[j]) 40 | { 41 | visited[j] = true; 42 | j = p[j].second; 43 | edgeNumber++; 44 | } 45 | 46 | if(edgeNumber > 0) 47 | result += (edgeNumber - 1); 48 | } 49 | 50 | return result; 51 | } 52 | 53 | int main() 54 | { 55 | std::vector vec{2, 4, 5, 1, 3}; 56 | std::cout< 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | 12 | //using namespace boost::asio 13 | //using ip::tcp 14 | 15 | using std::string; 16 | using std::cout; 17 | using std::endl; 18 | 19 | int main() 20 | { 21 | int port = 1233; 22 | boost::asio::io_service io_service_; 23 | boost::asio::ip::tcp::acceptor acceptor_(io_service_, 24 | boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)); 25 | 26 | char packet_type[4]; 27 | 28 | boost::asio::ip::tcp::socket socket_(io_service_); 29 | 30 | std::function fun2; 31 | std::function asyn_acc; 32 | 33 | fun2 = [&](boost::system::error_code ec){}; 34 | 35 | asyn_acc = [&,&asyn_acc](boost::asio::ip::tcp::socket socket_) 36 | { 37 | 38 | acceptor_.async_accept(socket_, [&](boost::system::error_code ec){ 39 | 40 | boost::asio::async_read(socket_, boost::asio::buffer(packet_type, 4), 41 | [&](boost::system::error_code ec, std::size_t N) 42 | { 43 | std::cout << "Received: '"; 44 | std::cout.write(packet_type, sizeof(packet_type)) << "'\n"; 45 | write(socket_, boost::asio::buffer(packet_type),ec); 46 | }); 47 | 48 | 49 | }); 50 | //boost::asio::ip::tcp::socket socket(io_service_); 51 | //asyn_acc(std::move(socket)); 52 | }; 53 | 54 | asyn_acc(std::move(socket_)); 55 | 56 | //auto fun2 = [&](boost::system::error_code ec){}; 57 | 58 | 59 | io_service_.run(); 60 | 61 | return 0; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/cmake_install.cmake: -------------------------------------------------------------------------------- 1 | # Install script for directory: /home/pi/ExampleCode/Cpp/asioTcpServer 2 | 3 | # Set the install prefix 4 | if(NOT DEFINED CMAKE_INSTALL_PREFIX) 5 | set(CMAKE_INSTALL_PREFIX "/usr/local") 6 | endif() 7 | string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") 8 | 9 | # Set the install configuration name. 10 | if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) 11 | if(BUILD_TYPE) 12 | string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" 13 | CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") 14 | else() 15 | set(CMAKE_INSTALL_CONFIG_NAME "") 16 | endif() 17 | message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") 18 | endif() 19 | 20 | # Set the component getting installed. 21 | if(NOT CMAKE_INSTALL_COMPONENT) 22 | if(COMPONENT) 23 | message(STATUS "Install component: \"${COMPONENT}\"") 24 | set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") 25 | else() 26 | set(CMAKE_INSTALL_COMPONENT) 27 | endif() 28 | endif() 29 | 30 | # Install shared libraries without execute permission? 31 | if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) 32 | set(CMAKE_INSTALL_SO_NO_EXE "1") 33 | endif() 34 | 35 | # Is this installation the result of a crosscompile? 36 | if(NOT DEFINED CMAKE_CROSSCOMPILING) 37 | set(CMAKE_CROSSCOMPILING "FALSE") 38 | endif() 39 | 40 | if(CMAKE_INSTALL_COMPONENT) 41 | set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") 42 | else() 43 | set(CMAKE_INSTALL_MANIFEST "install_manifest.txt") 44 | endif() 45 | 46 | string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT 47 | "${CMAKE_INSTALL_MANIFEST_FILES}") 48 | file(WRITE "/home/pi/ExampleCode/Cpp/asioTcpServer/build/${CMAKE_INSTALL_MANIFEST}" 49 | "${CMAKE_INSTALL_MANIFEST_CONTENT}") 50 | -------------------------------------------------------------------------------- /protoExamples/socket_server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import socket 4 | from time import sleep 5 | import example_pb2 6 | 7 | HOST = '127.0.0.1' # Standard loopback interface address (localhost) 8 | PORT = 2389 # Port to listen on (non-privileged ports are > 1023) 9 | 10 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 11 | s.bind((HOST, PORT)) 12 | s.listen() 13 | conn, addr = s.accept() 14 | with conn: 15 | print('Connected by', addr) 16 | while True: 17 | data = conn.recv(30) # fix for size of the protobuf message 18 | if not data: 19 | break 20 | 21 | example = example_pb2.Person() 22 | example.ParseFromString(data) 23 | # print ("Person ID:", example.id) 24 | # print ("Person ID:", example.number) 25 | # print ("Person ID:", example.anotherId) 26 | # print ("Person ID:", example.aid) 27 | # print ("Person ID:", example.bid) 28 | # print ("Person ID:", example.cid) 29 | # print ("Person ID:", example.did) 30 | # print ("Person ID:", example.eid) 31 | # print ("Person ID:", example.fid) 32 | # print ("Person ID:", example.gid) 33 | 34 | write = example_pb2.Person() 35 | write.id = 5001 36 | write.number = 5001 37 | write.anotherId = 5001 38 | write.aid = 5001 39 | write.bid = 5001 40 | write.cid = 5001 41 | write.did = 5001 42 | write.eid = 5001 43 | write.fid = 5001 44 | write.gid = 5001 45 | out = write.SerializeToString() 46 | 47 | conn.sendall(out) 48 | -------------------------------------------------------------------------------- /Cpp/mergeSortedLinkedLists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // merge sorted linked-list example 4 | // recursive approach 5 | 6 | struct ListNode{ 7 | int val; 8 | ListNode* next; 9 | ListNode():val(0),next(nullptr){} 10 | ListNode(int x):val(x), next(nullptr){} 11 | ListNode(int x, ListNode* next):val(x),next(next){} 12 | }; 13 | 14 | 15 | class Solution 16 | { 17 | public: 18 | ListNode* mergeTwoList(ListNode* list1, ListNode* list2) 19 | { 20 | 21 | if(list1 == nullptr) return list2; 22 | if(list2 == nullptr) return list1; 23 | 24 | if(list1->val < list2->val) 25 | { 26 | list1->next = mergeTwoList(list1->next, list2); 27 | return list1; 28 | } 29 | else 30 | { 31 | list2->next = mergeTwoList(list1, list2->next); 32 | return list2; 33 | } 34 | } 35 | }; 36 | 37 | int main() 38 | { 39 | ListNode* lastNode = new ListNode(22); 40 | ListNode* secondNode = new ListNode(12, lastNode); 41 | ListNode* firstNode = new ListNode(3, secondNode); 42 | 43 | ListNode* list1 = firstNode; 44 | 45 | ListNode* list2LastNode = new ListNode(16); 46 | ListNode* list2secondNode = new ListNode(6, list2LastNode); 47 | ListNode* list2firstNode = new ListNode(1, list2secondNode); 48 | 49 | ListNode* list2 = list2firstNode; 50 | 51 | ListNode* resultList = Solution().mergeTwoList(list1, list2); 52 | 53 | ListNode* node; 54 | node = resultList; 55 | for(int i{0}; i<6; i++) 56 | { 57 | std::cout<val<<" "; 58 | node = node->next; 59 | } 60 | 61 | } 62 | 63 | -------------------------------------------------------------------------------- /Cpp/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node* next; 8 | }; 9 | 10 | struct Node* front = NULL; 11 | struct Node* rear = NULL; 12 | 13 | void enqueue(int x) 14 | { 15 | 16 | struct Node* t = (struct Node*)malloc(sizeof(struct Node)); 17 | 18 | if(t==NULL) 19 | printf("memory problem"); 20 | else 21 | { 22 | t->data = x; 23 | t->next = NULL; 24 | if(front == NULL) //empty 25 | { 26 | front = rear = t; 27 | } 28 | else 29 | { 30 | rear->next = t; 31 | rear = t; 32 | } 33 | } 34 | } 35 | 36 | int dequeue() 37 | { 38 | int x; 39 | struct Node* t; 40 | 41 | if(front == NULL) 42 | { 43 | printf("queue is empty"); 44 | return -1; 45 | } 46 | else 47 | { 48 | t = front; 49 | x = t->data; 50 | front = front->next; 51 | free(t); 52 | } 53 | 54 | return x; 55 | 56 | } 57 | 58 | int isEmpty() 59 | { 60 | return front == NULL; 61 | } 62 | 63 | 64 | void BFS(int G[][7], int start, int n) 65 | { 66 | int i = start; 67 | int visited[n] = {0}; 68 | printf("%d ",i); 69 | enqueue(i); 70 | visited[i] = 1; 71 | 72 | while(!isEmpty()) 73 | { 74 | 75 | i = dequeue(); 76 | 77 | for(int j = 0; j 30 | #include 31 | #include 32 | 33 | class Solution { 34 | public: 35 | std::string convert(std::string s, int numRows) { 36 | if(numRows <= 1) return s; 37 | 38 | std::vector vec(numRows); // if array is used memory usage will be low 39 | 40 | bool flag = true; 41 | int y = 0; 42 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | std::string longestCommonSubsequence(const std::string s1, std::string s2) 6 | { 7 | int n = s1.size(); 8 | int m = s2.size(); 9 | 10 | std::vector> dp(n+1, std::vector(n+1, 0)); 11 | 12 | for(int i=1; i0 && j>0) 38 | { 39 | if(s1[i-1] == s2[j-1]) 40 | { 41 | lcs = s1[i-1] + lcs; 42 | --i; --j; 43 | } 44 | else if(dp[i-1][j] > dp[i][j-1]) 45 | { 46 | --i; 47 | } 48 | else 49 | { 50 | --j; 51 | } 52 | } 53 | return lcs; 54 | } 55 | 56 | int main() 57 | { 58 | std::string s1 = "ABCBDAB"; 59 | std::string s2 = "BDCABA"; 60 | std::string lcs = longestCommonSubsequence(s1, s2); 61 | std::cout << "Longest common subsequence: " << lcs << std::endl; // Output: "BCBA" 62 | return 0; 63 | 64 | } -------------------------------------------------------------------------------- /Cpp/QtOpenCV/QtOpencvQml/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | #include 12 | #include 13 | #include "qmlType.h" 14 | 15 | 16 | int main(int argc, char *argv[]) 17 | { 18 | QGuiApplication app(argc, argv); 19 | 20 | qRegisterMetaType("cv::Mat"); 21 | qmlRegisterType("Painter", 1, 0, "QmlType"); 22 | 23 | QQmlApplicationEngine engine; 24 | 25 | const QUrl url(QStringLiteral("qrc:/main.qml")); 26 | 27 | engine.load(url); 28 | QObject *object = engine.rootObjects()[0]; 29 | 30 | QObject *inputCamera = object->findChild("inputCamera"); 31 | 32 | qmlType *ptrQmlType = qobject_cast(inputCamera); 33 | 34 | QTimer timer; 35 | 36 | cv::VideoCapture cap("/home/b.mp4"); 37 | 38 | QObject::connect(&timer, &QTimer::timeout, [&]() 39 | { 40 | 41 | cv::Mat frame; 42 | cap >> frame; 43 | 44 | if(frame.empty()) 45 | { 46 | // to clean lsat frame 47 | int width = 100; 48 | int height = 200; 49 | QImage image = QPixmap(width, height).toImage(); 50 | 51 | ptrQmlType->updateImage(image); 52 | timer.stop(); 53 | return; 54 | } 55 | // Opencv use BGR but QImage use RGB so color information 56 | // should be swapped for this case Mat->QImage 57 | // no need to swap when Mat->QImage->Mat 58 | cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB); 59 | QImage imgIn= QImage((uchar*) frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888); 60 | //.rgbSwapped(); 61 | 62 | ptrQmlType->updateImage(imgIn); 63 | 64 | } 65 | ); 66 | timer.start(60); 67 | 68 | return app.exec(); 69 | } 70 | -------------------------------------------------------------------------------- /Cpp/MinNumberSwapAnagram2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // 2186. Minimum Number of Steps to Make Two Strings Anagram II 6 | 7 | class Solution { 8 | public: 9 | int minSteps(std::string s, std::string t) { 10 | 11 | std::map m; 12 | for(int i=0; isecond); 32 | } 33 | 34 | return cnt; 35 | } 36 | }; 37 | 38 | // faster one 39 | class Solution2 40 | { 41 | public: 42 | int minSteps(const std::string& s, const std::string& t) { 43 | 44 | // Initialize the counts of each letter to 0 45 | std::array sCount{}; 46 | std::array tCount{}; 47 | 48 | // Count the number of occurrences of each letter in s and t 49 | for (char c : s) { 50 | sCount[c - 'a']++; 51 | } 52 | 53 | for (char c : t) { 54 | tCount[c - 'a']++; 55 | } 56 | 57 | int steps = 0; 58 | 59 | // Count the number of characters in s that are not in t, or the number of extra 60 | // occurrences of a character in s 61 | for (int i = 0; i < 26; i++) { 62 | steps += std::abs(sCount[i] - tCount[i]); 63 | } 64 | 65 | return steps; 66 | } 67 | 68 | }; 69 | 70 | int main () 71 | { 72 | std::string s1 {"leetcode"}; 73 | std::string s2 {"coats"}; 74 | 75 | std::cout< 2 | #include 3 | #include 4 | 5 | // sudo apt-get install libglfw3 6 | // sudo apt-get install libglfw3-dev 7 | // check related dependencies with pkg-config --static --libs glfw3. 8 | // g++ -pthread -o circle circleGlfw.cpp -lglfw -lGLU -lGL -lXrandr -lXi -lX11 -lrt -ldl 9 | // or 10 | // g++ -pthread -o circle circleGlfw.cpp -lGLU -lGL -lXrandr -lXi -lX11 `pkg-config --static --libs glfw3` 11 | 12 | const int steps = 100; 13 | const float angle = 3.1415926 * 2.f / steps; 14 | 15 | int main() { 16 | GLFWwindow * window; 17 | 18 | if (!glfwInit()) { 19 | std::cout << "Init error"; 20 | return -1; 21 | } 22 | 23 | window = glfwCreateWindow(800,600,"Circle",0,0); 24 | if (!window) { 25 | std::cout << "Window creation error"; 26 | glfwTerminate(); 27 | return -1; 28 | } 29 | 30 | glfwMakeContextCurrent(window); 31 | 32 | float xPos = 0; 33 | float yPos = 0; 34 | float radius = 1.0f; 35 | 36 | // render loop 37 | while (!glfwWindowShouldClose(window)) 38 | { 39 | glClearColor(1.0,1.0,1.0,0); 40 | glClear(GL_COLOR_BUFFER_BIT); 41 | 42 | float prevX = xPos; 43 | float prevY = yPos - radius; 44 | 45 | for (int i=0;i<=1;i++) { 46 | float newX = radius * sin(angle*i); 47 | float newY = -radius * cos(angle*i); 48 | 49 | glBegin(GL_TRIANGLES); 50 | glColor3f(0,0.5f,0); 51 | glVertex3f(0.0f,0.0f,0.0f); 52 | glVertex3f(prevX,prevY,0.0f); 53 | glVertex3f(newX,newY,0.0f); 54 | glEnd(); 55 | 56 | prevX = newX; 57 | prevY = newY; 58 | } 59 | 60 | glfwSwapBuffers(window); 61 | glfwPollEvents(); 62 | } 63 | glfwTerminate(); 64 | } 65 | -------------------------------------------------------------------------------- /Cpp/linkedListCycle2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode(int x) : val(x), next(NULL) {} 7 | }; 8 | // 142. Linked List Cycle || 9 | // return start point of the cycle in linked list 10 | // Floyd`s algorithm is used 11 | // there are two pointer slow and fast. Fast is 2x faster than slow. 12 | // Meeting point in the circle(if it is exist) for fast a+b+c+b and for slow 13 | // a+b, 2*d = (a+b+c+b), d = (a+b) 14 | // 2a+2b = a+b+c+b 15 | // a=c that means distance from beginning to start point is same with where 16 | // slow and fast pointer is met to start point. 17 | // 18 | 19 | class Solution { 20 | public: 21 | ListNode *detectCycle(ListNode *head) { 22 | 23 | ListNode* slow = head; 24 | ListNode* fast = head; 25 | 26 | if(head == NULL || head->next == NULL) 27 | return NULL; 28 | 29 | slow = slow->next; 30 | fast = fast->next->next; 31 | 32 | while(fast && fast->next) 33 | { 34 | if(fast == slow) 35 | break; 36 | 37 | slow = slow->next; 38 | fast = fast->next->next; 39 | } 40 | 41 | if (slow != fast) 42 | return NULL; 43 | 44 | slow = head; 45 | 46 | while(fast != slow) 47 | { 48 | slow = slow->next; 49 | fast = fast->next; 50 | } 51 | 52 | return slow; 53 | } 54 | }; 55 | 56 | int main() 57 | { 58 | ListNode* node = new ListNode(0); 59 | 60 | ListNode* tmp; 61 | tmp = node; 62 | 63 | for(int i = 1; i < 10; i++) 64 | { 65 | tmp->next = new ListNode(i); 66 | tmp = tmp->next; 67 | } 68 | // create a cycle from 3 as a start point 69 | tmp->next = node->next->next->next; 70 | 71 | ListNode* res = Solution{}.detectCycle(node); 72 | std::cout<val< 2 | #include 3 | #include 4 | 5 | std::shared_ptr> foo() 6 | { 7 | std::shared_ptr> ptrVec; 8 | 9 | ptrVec = std::make_shared>(); 10 | 11 | for(int i = 0; i < 100; ++i) 12 | ptrVec->push_back(i); 13 | 14 | return ptrVec; 15 | } 16 | 17 | int main() 18 | { 19 | const auto vec = *foo(); 20 | for(const auto& x : vec) //it is okay. 21 | std::cout< > >::__normal_iterator(int* const&) (in /home/jnano/files/ExampleCode/Cpp/a.out) 37 | ==4767== by 0x109C3B: std::vector >::end() (in /home/jnano/files/ExampleCode/Cpp/a.out) 38 | ==4767== by 0x10950C: main (in /home/jnano/files/ExampleCode/Cpp/a.out) 39 | ==4767== Address 0x4dc3928 is 24 bytes inside a block of size 40 free'd 40 | ==4767== at 0x483CFBF: operator delete(void*) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) 41 | ==4767== by 0x10B4D7: __gnu_cxx::new_allocator >, std::allocator > >, (__gnu_cxx::_Lock_policy)2> >::deallocate(std::_Sp_counted_ptr_inplace >, std::allocator > >, (__gnu_cxx::_Lock_policy)2>*, unsigned long) (in /home/jnano/files/ExampleCode/Cpp/a.out) 42 | 43 | */ -------------------------------------------------------------------------------- /Cpp/superReducedString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // super reduced string hackerRank 7 | // Reduce a string of lowercase characters in 8 | // range ascii[‘a’..’z’]by doing a series of operations. In each operation, select a pair of adjacent letters that match, and delete them. 9 | // aab shortens to b in one operation: remove the adjacent a characters. 10 | // abccbd => ad 11 | 12 | using namespace std; 13 | 14 | // custom char inherited stack to use protected member c 15 | class customCharStack : public std::stack> 16 | { 17 | public: 18 | const std::deque& get_underlying_container() const 19 | { 20 | return this->c; // c is protected in std::stack 21 | } 22 | }; 23 | 24 | string superReducedString(string str) { 25 | 26 | customCharStack stackStr; 27 | 28 | for(const auto s : str) 29 | { 30 | if(!stackStr.empty() && s == stackStr.top()) 31 | stackStr.pop(); 32 | else 33 | stackStr.push(s); 34 | } 35 | 36 | const std::deque& underlying_container = stackStr.get_underlying_container(); 37 | 38 | std::string result; 39 | 40 | for(auto it = underlying_container.rbegin(); it != underlying_container.rend(); ++it) 41 | { 42 | result += *it; 43 | } 44 | 45 | if(result.empty()) 46 | return "Empty String"; 47 | 48 | return result; 49 | } 50 | 51 | 52 | 53 | int main() { 54 | 55 | std::string str("acdqglrfkqyuqfjkxyqvnrtysfrzrmzlygfveulqfpdbhlqdqrrqdqlhbdpfqluevfgylzmrzrfsytrnvqyxkjfquyqkfrlacdqj"); 56 | 57 | const auto result = superReducedString(str); 58 | 59 | std::cout< 2 | #include 3 | 4 | class Solution 5 | { 6 | public: 7 | std::vector productExceptSelf(const std::vector& vec) 8 | { 9 | size_t size = vec.size(); 10 | std::vector result(size,1); 11 | 12 | int first {1}; 13 | int last {1}; 14 | 15 | for(size_t i {0}; i productExceptSelf3For(std::vector& vec) { 28 | 29 | std::vector result; 30 | 31 | std::vector left; 32 | std::vector right; 33 | 34 | int leftSum {1}; 35 | for(size_t i{0}; i0; i--) 43 | { 44 | right.push_back(rightSum); 45 | rightSum = rightSum * vec[i-1]; 46 | } 47 | 48 | for(size_t i {0}; i 2 | 9 |

WebSocket Test

10 | 11 | 12 |
13 | -------------------------------------------------------------------------------- /Cpp/numberOfIslands.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // g++ -std=c++14 numberOfIslands.cpp -o numberOfIslands 6 | 7 | using namespace std; 8 | 9 | class Solution 10 | { 11 | public: 12 | int numOfIsland(vector> vec) 13 | { 14 | 15 | int result = 0; // number of islands 16 | if(vec.size() == 0) 17 | return result; 18 | 19 | int numberOfRows = vec.size(); 20 | int numberOfColumns = vec.at(0).size(); 21 | vector> neighborCorr = {{0,1},{1,0},{0,-1},{-1,0}}; 22 | 23 | for(int i=0; i> que; 31 | que.push({i,j}); 32 | vec[i][j] = '0'; 33 | 34 | while(!que.empty()) 35 | { 36 | auto p = que.front(); 37 | que.pop(); 38 | 39 | for(const auto& coor : neighborCorr) 40 | { 41 | 42 | int x = p.first + coor.first; 43 | int y = p.second + coor.second; 44 | 45 | if(x>=0 && x=0 && y> grid = { 68 | 69 | {'0','1','0','1','1','1','0'}, 70 | {'0','1','0','1','1','1','0'}, 71 | {'1','1','0','1','1','1','0'}, 72 | {'0','1','0','1','1','1','0'}, 73 | {'1','0','0','0','0','0','0'}, 74 | {'0','1','0','1','1','1','0'}, 75 | {'0','1','0','1','1','1','0'}, 76 | {'0','1','0','1','1','1','0'} 77 | 78 | }; 79 | 80 | cout< 30 | #include 31 | #include 32 | #include 33 | 34 | class Solution { 35 | public: 36 | std::string convert(std::string s, int numRows) { 37 | 38 | if(numRows == 1) 39 | return s; 40 | 41 | std::vector> vec(numRows); 42 | 43 | int j=0; bool flag = 0; 44 | for(int i=0; i=0; i--) 61 | { 62 | while(!vec[i].empty()) 63 | { 64 | result[j-1] = vec[i].top(); 65 | vec[i].pop(); 66 | j--; 67 | } 68 | } 69 | 70 | return result; 71 | 72 | } 73 | }; 74 | 75 | int main() 76 | { 77 | Solution s; 78 | std::string str = "PAYPALISHIRING"; 79 | std::string result = s.convert(str,4); 80 | std::cout< 2 | 3 | 4 | // the idea is that first begin from first light element to put in bag in a way that calculate every each size for bag. 5 | // for instance have a 3 kg object, 8 kg bag, there will be 8 iterations for 3 kg object. 6 | // for w = 1 -> bag is 1 kg, object is greater than the bag so we can not put anything K[0][0] = 0; 7 | // for w = 2 -> bag is 2 kg, object is greater than the bag so we can not put anything K[0][1] = 0; // bag is empty 8 | // for w = 3 -> bag is 3 kg, object is same with bag capacity for right now so K[0][2] = val_of_3kg_object; 9 | // for other cases there is no object so between w = 3 and w = 8 there will be 3 kg object in the bag, 10 | // after for second object calculate that if current bag size is greater or equal then the object weight, then 11 | // check the remaning size in the bag, what was the value before ? so add with current object value and compare 12 | // it with before object with exact index, if it is greater than save it to map K[i][w] 13 | // finally K[n][W] will be the result. 14 | 15 | 16 | int knapsack(int W, int wt[], int val[], int n) 17 | { 18 | int K[n+1][W+1]; 19 | 20 | for(int i=0; i<=n; i++) 21 | { 22 | for(int w=0; w<=W; w++) 23 | { 24 | 25 | int prev = K[i-1][w]; 26 | 27 | if( i == 0 || w == 0) 28 | K[i][w] = 0; 29 | else if(wt[i-1] <= w) 30 | { 31 | int remainWeight = val[i-1] + K[i-1][w-wt[i-1]]; 32 | K[i][w] = (prev <= remainWeight) ? remainWeight : prev; 33 | } 34 | else 35 | { 36 | K[i][w] = prev; 37 | } 38 | } 39 | } 40 | 41 | return K[n][W]; 42 | } 43 | 44 | 45 | 46 | 47 | int main() 48 | { 49 | 50 | 51 | int val[] = {1,2,5,6}; 52 | int wt[] = {2,3,4,5}; 53 | 54 | int W = 8; 55 | int n = sizeof(val)/sizeof(val[0]); 56 | std::cout< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // find the element to swap in the first array to make absolute sum diff minimum. 8 | // To point which element is swapped, check closest element to the element with same 9 | // index in the second array, To do this, copy first array and sort it, use binary 10 | // search to find closest or same number to swap, keep gain for each iteration. 11 | 12 | class Solution { 13 | public: 14 | int minAbsoluteSumDiff(const vector& nums1, const vector& nums2) { 15 | 16 | long res = 0, gain = 0; 17 | set s(nums1.begin(), nums1.end()); 18 | for(int i=0; i vec1 {53,48,14,71,31,55,6,80,28,19,15,40,7,21,69,15,5,42,86,15,11,54,44,62,9,100,2,26,81,87,87,18,45,29,46,100,20,87,49,86,14,74,74,52,52,60,8,25,21,96,7,90,91,42,32,34,55,20,66,36,64,67,44,51,4,46,25,57,84,23,10,84,99,33,51,28,59,88,50,41,59,69,59,65,78,50,78,50,39,91,44,78,90,83,55,5,74,96,77,46}; 43 | 44 | std::vector vec2 {39,49,64,34,80,26,44,3,92,46,27,88,73,55,66,10,4,72,19,37,40,49,40,58,82,32,36,91,62,21,68,65,66,55,44,24,78,56,12,79,38,53,36,90,40,73,92,14,73,89,28,53,52,46,84,47,51,31,53,22,24,14,83,75,97,87,66,42,45,98,29,82,41,36,57,95,100,2,71,34,43,50,66,52,6,43,94,71,93,61,28,84,7,79,23,48,39,27,48,79}; 45 | std::cout< 2 | #include 3 | #include 4 | #include 5 | 6 | /* 7 | 121. Best Time to Buy and Sell Stock 8 | 9 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 10 | 11 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 12 | 13 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 14 | 15 | */ 16 | 17 | class Solution { 18 | public: 19 | int maxProfit(std::vector& prices) { 20 | 21 | int maxPro{0}, mn{INT_MAX}; 22 | 23 | for(size_t i{0};i& prices) 32 | { 33 | int currentMax {0}, max{0}; 34 | 35 | for(int i=0; i prices {7,1,5,3,6,4}; 57 | std::cout< prices2 {1,2}; 60 | std::cout< 2 | #include 3 | #include 4 | 5 | /* 6 | idea is that choose a pivot (can be done randomly or choosing from left/right) 7 | define left and right element. In the beginning left is 0 and right is size of the vector 8 | Iterate through left to right. according to pivot elements value, swap the iterated element such that 9 | if it is greater than the pivot value the swap with index which can be choosen from left or right. 10 | The idea is to collect the elements which are greater than the pivot to the right and smaller than to 11 | left. 12 | Recursion can be used to make continue this process. Pivot should be replacted at the end when iteration 13 | is finished for each partioning. 14 | */ 15 | 16 | int partition(std::vector& vec, int left, int right) 17 | { 18 | int pivot = vec[left]; 19 | int index = left + 1; 20 | 21 | for(int i = left + 1; i <= right; i++) 22 | { 23 | if(vec[i] < pivot) // condition for descending or ascanding order 24 | { 25 | std::swap(vec[i], vec[index++]); 26 | } 27 | } 28 | std::swap(vec[left], vec[index - 1]); 29 | return index - 1; 30 | } 31 | 32 | int partition2(std::vector& vec, int left, int right) 33 | { 34 | int pivot = vec[right]; 35 | int index = left - 1; 36 | 37 | for(int i=left; i < right; ++i) // pivot is excluded intentionally i < right not i <= right. (both conditions are corrects) 38 | { 39 | if(vec[i] < pivot) 40 | { 41 | index ++; 42 | std::swap(vec[index], vec[i]); 43 | } 44 | } 45 | 46 | std::swap(vec[right], vec[index + 1]); 47 | 48 | return index + 1; 49 | } 50 | 51 | void quickSort(std::vector& vec, int low, int high) 52 | { 53 | if(low < high) 54 | { 55 | int pivotIndex = partition2(vec, low, high); 56 | quickSort(vec, low, pivotIndex - 1); 57 | quickSort(vec, pivotIndex + 1, high); 58 | } 59 | } 60 | 61 | int main() 62 | { 63 | std::vector nums = {3,1,4,2,9,5,6,7}; 64 | 65 | quickSort(nums, 0, nums.size() - 1); 66 | 67 | std::cout << "Sorted array: "; 68 | for (int i = 0; i < nums.size(); i++) { 69 | std::cout << nums[i] << " "; 70 | } 71 | 72 | } -------------------------------------------------------------------------------- /Cpp/socketExample/myclient.cpp: -------------------------------------------------------------------------------- 1 | // myclient.cpp 2 | 3 | #include "myclient.h" 4 | 5 | MyClient::MyClient(QObject *parent, QThreadPool* _pool) : 6 | QObject(parent) 7 | { 8 | pool = _pool; 9 | //QThreadPool::globalInstance()->setMaxThreadCount(5); 10 | } 11 | 12 | void MyClient::setSocket(qintptr descriptor) 13 | { 14 | // make a new socket 15 | socket = new QTcpSocket(this); 16 | 17 | qDebug() << "A new socket created!"; 18 | 19 | connect(socket, SIGNAL(connected()), this, SLOT(connected())); 20 | connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected())); 21 | connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); 22 | 23 | socket->setSocketDescriptor(descriptor); 24 | 25 | qDebug() << " Client connected at " << descriptor; 26 | } 27 | 28 | 29 | // asynchronous - runs separately from the thread we created 30 | void MyClient::connected() 31 | { 32 | qDebug() << "Client connected event"; 33 | } 34 | 35 | // asynchronous 36 | void MyClient::disconnected() 37 | { 38 | qDebug() << "Client disconnected"; 39 | } 40 | 41 | // Our main thread of execution 42 | // This happening via main thread 43 | // Our code running in our current thread not in another QThread 44 | // That's why we're getting the thread from the pool 45 | 46 | void MyClient::readyRead() 47 | { 48 | qDebug() << "MyClient::readyRead()"; 49 | qDebug() << socket->readAll(); 50 | 51 | // Time consumer 52 | MyTask *mytask = new MyTask(); 53 | // mytask->setAutoDelete(true); 54 | 55 | // using queued connection 56 | connect(mytask, SIGNAL(Result(int)), this, SLOT(TaskResult(int)), Qt::QueuedConnection); 57 | 58 | qDebug() << "Starting a new task using a thread from the QThreadPool"; 59 | 60 | // QThreadPool::globalInstance() returns global QThreadPool instance 61 | // QThreadPool::globalInstance()->start(mytask); 62 | pool->start(mytask); 63 | 64 | } 65 | 66 | // After a task performed a time consuming task, 67 | // we grab the result here, and send it to client 68 | void MyClient::TaskResult(int Number) 69 | { 70 | QByteArray Buffer; 71 | Buffer.append("\r\nTask result = "); 72 | Buffer.append(QString::number(Number)); 73 | 74 | socket->write(Buffer); 75 | socket->flush(); 76 | socket->deleteLater(); 77 | } 78 | -------------------------------------------------------------------------------- /Cpp/maximumStock.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* 6 | Each day, you can either buy one share of WOT, sell any number of shares 7 | of WOT that you own, or not make any transaction at all. What is the 8 | maximum profit you can obtain with an optimum trading strategy? 9 | 10 | - For each share profit is independent. Means that for instance 11 | array = 1,2,100; then for first day buy, second day buy then 12 | sell the shares in third day -> (100-2) + (100-1) = 197 13 | - Iterate reversely 14 | 15 | only difference between maxStock and maxProfit is that for maxStock 16 | profit is added (stock). For maxProfit, it is needed to keep only maximum one 17 | profit. 18 | */ 19 | 20 | class Solution 21 | { 22 | public: 23 | long maxStock(const std::vector& prices) 24 | { 25 | const size_t size {prices.size()}; 26 | long profit {0}; 27 | int peak {0}; 28 | 29 | for(int i = size-1; i > -1; i--) 30 | { 31 | if(prices[i] >= peak) 32 | peak = prices[i]; 33 | 34 | profit += peak - prices[i]; 35 | } 36 | 37 | return profit; 38 | } 39 | 40 | // 121. Best Time to Buy and Sell Stock - leetcode 41 | long maxProfit(std::vector& prices) { 42 | 43 | const size_t size {prices.size()}; 44 | int profit {0}; 45 | int peak {INT_MIN}; 46 | 47 | // if iteration is from left to right then instead of peak, min value 48 | // should be kept (int min{INT_MAX}) 49 | // min = std::min(prices[i],min); 50 | // profit = std::max(profit, prices[i]-min); 51 | // because first it is needed to buy the share to sell later 52 | for(int i = size-1; i>-1; i--) 53 | { 54 | peak = std::max(prices[i], peak); 55 | profit = std::max(profit, peak - prices[i]); 56 | } 57 | 58 | return profit; 59 | 60 | } 61 | 62 | }; 63 | 64 | int main() 65 | { 66 | std::vector stocks{1,2,100}; 67 | std::cout< 2 | #include 3 | #include 4 | #include 5 | 6 | class Solution 7 | { 8 | public: 9 | std::vector> vec; 10 | std::string str1; 11 | std::string str2; 12 | 13 | Solution(std::string str1_, std::string str2_): 14 | str1(str1_), str2(str2_) 15 | {} 16 | 17 | int longestCommonSubsequence() 18 | { 19 | const size_t firstStrSize {str1.size()}; 20 | const size_t secondStrSize {str2.size()}; 21 | 22 | std::vector> vec(firstStrSize+1, 23 | std::vector(secondStrSize+1,0)); 24 | 25 | for(int i = 1; i <= firstStrSize; i++) 26 | for(int j = 1; j <= secondStrSize; j++) 27 | if(str1[i-1] == str2[j-1]) 28 | vec[i][j] = 1 + vec[i-1][j-1]; 29 | else 30 | vec[i][j] = std::max(vec[i-1][j], vec[i][j-1]); 31 | 32 | int result = vec[firstStrSize][secondStrSize]; 33 | this->vec = std::move(vec); 34 | 35 | return result; 36 | } 37 | 38 | std::string returnLCSstring() 39 | { 40 | for(auto v : vec) 41 | { for(auto z : v) 42 | { 43 | std::cout< result; 51 | 52 | while(y >= 1 && x >= 1) 53 | { 54 | if(vec[x][y] == vec[x-1][y]) 55 | { 56 | x -= 1; 57 | } 58 | else if(vec[x][y] == vec[x][y-1]) 59 | { 60 | y -= 1; 61 | } 62 | else 63 | { 64 | y -= 1; 65 | x -= 1; 66 | result.push_back(str1[x]); // or str2[y] 67 | } 68 | } 69 | 70 | std::reverse(result.begin(), result.end()); 71 | 72 | return std::string(result.begin(), result.end()); 73 | 74 | } 75 | 76 | 77 | }; 78 | 79 | int main() { 80 | 81 | std::string str1 {"SHINCHAN"}; 82 | std::string str2 {"NOHARAAA"}; 83 | 84 | Solution s(str1, str2); 85 | std::cout< 2 | #include 3 | #include 4 | #include 5 | 6 | // g++ face_detection_opencv_cuda.cpp -o faceDetectionOpencvCuda `pkg-config opencv4 --cflags --libs` 7 | 8 | using namespace cv; 9 | using namespace std; 10 | 11 | std::string get_tegra_pipeline(int width, int height, int fps) { 12 | return "nvarguscamerasrc ! video/x-raw(memory:NVMM), width=(int)" + std::to_string(width) + ", height=(int)" + 13 | std::to_string(height) + ", format=(string)NV12, framerate=(fraction)" + std::to_string(fps) + 14 | "/1 ! nvvidconv flip-method=0 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink"; 15 | } 16 | 17 | int main() { 18 | 19 | 20 | std::cout << "OpenCV version : " << CV_VERSION << std::endl; 21 | std::cout << "Major version : " << CV_MAJOR_VERSION << std::endl; 22 | std::cout << "Minor version : " << CV_MINOR_VERSION << std::endl; 23 | std::cout << "Subminor version : " << CV_SUBMINOR_VERSION << std::endl; 24 | 25 | // Options 26 | int WIDTH = 800; 27 | int HEIGHT = 600; 28 | int FPS = 60; 29 | 30 | // Define the gstream pipeline 31 | std::string pipeline = get_tegra_pipeline(WIDTH, HEIGHT, FPS); 32 | std::cout << "Using pipeline: \n\t" << pipeline << "\n"; 33 | 34 | // Create OpenCV capture object, ensure it works. 35 | cv::VideoCapture cap(pipeline, cv::CAP_GSTREAMER); 36 | 37 | if (!cap.isOpened()) { 38 | cerr << "Can not open video source"; 39 | return -1; 40 | } 41 | std::vector h_found; 42 | cv::Ptr cascade = cv::cuda::CascadeClassifier::create("haarcascade_frontalface_default.xml"); 43 | cv::cuda::GpuMat d_frame, d_gray, d_found; 44 | while(1) 45 | { 46 | Mat frame; 47 | 48 | if ( !cap.read(frame) ) { 49 | cerr << "Can not read frame from webcam"; 50 | return -1; 51 | } 52 | 53 | d_frame.upload(frame); 54 | cv::cuda::cvtColor(d_frame, d_gray, cv::COLOR_BGR2GRAY); 55 | cascade->detectMultiScale(d_gray, d_found); 56 | cascade->convert(d_found, h_found); 57 | 58 | for(int i = 0; i < h_found.size(); ++i) 59 | { 60 | rectangle(frame, h_found[i], Scalar(0,255,255), 5); 61 | } 62 | 63 | imshow("Result", frame); 64 | 65 | if (waitKey(1) == 'q') { 66 | break; 67 | } 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Py/gradientDescent.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | xPrimeData = [] 5 | yPrimeData = [] 6 | 7 | xData = [] 8 | yData = [] 9 | 10 | xDataB = [] 11 | yDataB = [] 12 | 13 | f, (ax1, ax2, ax3) = plt.subplots(1, 3) 14 | 15 | x_old = 0 16 | x_new = 6 17 | 18 | eps = 0.00009 19 | precision = 0.00000001 20 | 21 | ax1.set_xlim(-100, 6000) 22 | ax1.set_ylim(-0.001, 0.050) 23 | line, = ax1.plot(xPrimeData, yPrimeData, 'r-') 24 | 25 | ax2.set_xlim(0, 6) 26 | ax2.set_ylim(-10, 600) 27 | line2, = ax2.plot(xData, yData, 'r-') 28 | 29 | # maximize the window 30 | manager = plt.get_current_fig_manager() 31 | manager.full_screen_toggle() 32 | 33 | # f(x) = x^{4}-3x^{3} 34 | def f(x): 35 | return x**4 - 3*x**3 36 | 37 | ax3.set_xlim(0, 6) 38 | ax3.set_ylim(-10, 600) 39 | xDataB = np.linspace(0,6,1000, endpoint=False) 40 | 41 | for a in xDataB: 42 | yDataB.append(f(a)) 43 | 44 | line3, = ax3.plot(xDataB, yDataB, linewidth=3, color='red') 45 | 46 | def f_prime(x): 47 | return 4 * x**3 - 9 * x**2 48 | 49 | it = 0 50 | while abs(x_new - x_old) > precision: 51 | x_old = x_new 52 | x_new = x_old - eps * f_prime(x_old) 53 | it = it + 1 54 | #print(x_old, " ",x_new, " ",f_prime(x_old)," ",eps*f_prime(x_old), " ",abs(x_new - x_old)) 55 | #print(x_new, " ", f(x_new)) 56 | xPrimeData.append(it) 57 | yPrimeData.append(abs(x_new - x_old)) 58 | line.set_xdata(xPrimeData) 59 | line.set_ydata(yPrimeData) 60 | 61 | xData.append(x_new) 62 | yData.append(f(x_new)) 63 | line2.set_xdata(x_new) 64 | line2.set_ydata(f(x_new)) 65 | 66 | ax1.plot(xPrimeData, yPrimeData, linewidth=3, color='red') 67 | ax1.title.set_text('iteration vs abs(xNew -xOld) \n xNew = xOld - eps * fPrime(xOld) \n cost function') 68 | ax1.set_xlabel("iteration") 69 | ax1.set_ylabel("difference - abs(xNew - xOld)") 70 | 71 | ax2.plot(xData, yData, linewidth=3, color='red') 72 | ax2.title.set_text('Function iteration - x vs y') 73 | ax2.set_xlabel("x") 74 | ax2.set_ylabel("y") 75 | 76 | ax3.plot(xData, yData, marker=".", markersize=6 , linestyle='',color='black') 77 | ax3.title.set_text('Function iteration on the \n drawn function with dots \n f(x) = x^4-3x^3') 78 | ax3.set_xlabel("x") 79 | ax3.set_ylabel("y") 80 | 81 | # to see the process in animation uncomment these 82 | #plt.draw() 83 | #plt.pause(0.000001) 84 | 85 | print("local minimum occurs at", x_new ," ", it) 86 | 87 | plt.show() 88 | -------------------------------------------------------------------------------- /Cpp/asioTcpServer/build/CMakeFiles/3.13.4/CMakeCCompiler.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_C_COMPILER "/usr/bin/cc") 2 | set(CMAKE_C_COMPILER_ARG1 "") 3 | set(CMAKE_C_COMPILER_ID "GNU") 4 | set(CMAKE_C_COMPILER_VERSION "8.3.0") 5 | set(CMAKE_C_COMPILER_VERSION_INTERNAL "") 6 | set(CMAKE_C_COMPILER_WRAPPER "") 7 | set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "11") 8 | set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert") 9 | set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") 10 | set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") 11 | set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") 12 | 13 | set(CMAKE_C_PLATFORM_ID "Linux") 14 | set(CMAKE_C_SIMULATE_ID "") 15 | set(CMAKE_C_SIMULATE_VERSION "") 16 | 17 | 18 | 19 | set(CMAKE_AR "/usr/bin/ar") 20 | set(CMAKE_C_COMPILER_AR "/usr/bin/gcc-ar-8") 21 | set(CMAKE_RANLIB "/usr/bin/ranlib") 22 | set(CMAKE_C_COMPILER_RANLIB "/usr/bin/gcc-ranlib-8") 23 | set(CMAKE_LINKER "/usr/bin/ld") 24 | set(CMAKE_COMPILER_IS_GNUCC 1) 25 | set(CMAKE_C_COMPILER_LOADED 1) 26 | set(CMAKE_C_COMPILER_WORKS TRUE) 27 | set(CMAKE_C_ABI_COMPILED TRUE) 28 | set(CMAKE_COMPILER_IS_MINGW ) 29 | set(CMAKE_COMPILER_IS_CYGWIN ) 30 | if(CMAKE_COMPILER_IS_CYGWIN) 31 | set(CYGWIN 1) 32 | set(UNIX 1) 33 | endif() 34 | 35 | set(CMAKE_C_COMPILER_ENV_VAR "CC") 36 | 37 | if(CMAKE_COMPILER_IS_MINGW) 38 | set(MINGW 1) 39 | endif() 40 | set(CMAKE_C_COMPILER_ID_RUN 1) 41 | set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) 42 | set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) 43 | set(CMAKE_C_LINKER_PREFERENCE 10) 44 | 45 | # Save compiler ABI information. 46 | set(CMAKE_C_SIZEOF_DATA_PTR "4") 47 | set(CMAKE_C_COMPILER_ABI "ELF") 48 | set(CMAKE_C_LIBRARY_ARCHITECTURE "arm-linux-gnueabihf") 49 | 50 | if(CMAKE_C_SIZEOF_DATA_PTR) 51 | set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") 52 | endif() 53 | 54 | if(CMAKE_C_COMPILER_ABI) 55 | set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") 56 | endif() 57 | 58 | if(CMAKE_C_LIBRARY_ARCHITECTURE) 59 | set(CMAKE_LIBRARY_ARCHITECTURE "arm-linux-gnueabihf") 60 | endif() 61 | 62 | set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") 63 | if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) 64 | set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") 65 | endif() 66 | 67 | 68 | 69 | 70 | 71 | set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "gcc;gcc_s;c;gcc;gcc_s") 72 | set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/usr/lib/gcc/arm-linux-gnueabihf/8;/usr/lib/arm-linux-gnueabihf;/usr/lib;/lib/arm-linux-gnueabihf") 73 | set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "") 74 | -------------------------------------------------------------------------------- /Cpp/RecorderDataInLogs2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Recorder Data in Log Files 3 | You have an array of logs. Each log is a space deliminated string of words. 4 | For each log, the fisrt word in each log is an alphanumeric identifier. Then, either; 5 | - Each word after the identifier will consist only of lowercase letters, or; 6 | - Each word after the identifier will consist only of digits. 7 | We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier. 8 | Recorder the logs so that all of the letter logs come before any digt-log. The letter-logs are orderedd lexicographically ignoring identifier, with the 9 | identifier used in case of ties. The digit-logs should be put in their original order. 10 | Return the final order of the logs. 11 | Example 12 | Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] 13 | output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"] 14 | */ 15 | //Runtime: 12 ms, faster than 96.91% of C++ online submissions for Reorder Data in Log Files. 16 | //Memory Usage: 11.2 MB, less than 100.00% of C++ online submissions for Reorder Data in Log Files. 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | 24 | using namespace std; 25 | 26 | class Solution { 27 | public: 28 | vector reorderLogFiles(vector& logs) { 29 | 30 | 31 | vector resLet; 32 | vector resDig; 33 | 34 | for(std::string &s : logs) 35 | { 36 | if(std::string::npos != ((s.substr(s.find_first_of(" ")+1)).find_first_of("0123456789"))) 37 | resDig.push_back(s); 38 | else 39 | resLet.push_back(s.substr(s.find_first_of(" ")+1) + " " + s.substr(0,s.find_first_of(" "))); 40 | 41 | } 42 | 43 | std::sort(resLet.begin(), resLet.end()); 44 | 45 | for(std::string &s : resLet) 46 | s = s.substr(s.find_last_of(" ")+1) + " " + s.substr(0,s.find_last_of(" ")); 47 | 48 | for(std::string &s : resDig) resLet.push_back(s); 49 | 50 | return resLet; 51 | } 52 | }; 53 | 54 | int main() 55 | { 56 | vector log = {"dig1 8 1 5 1", "let1 art can", "dig2 3 6","let2 own kit dig","let3 art zero"}; 57 | 58 | 59 | Solution s; 60 | 61 | vector res = s.reorderLogFiles(log); 62 | 63 | for( auto s : res ) 64 | cout< 2 | #include 3 | #include 4 | 5 | int lngPalindromicString(std::string str) 6 | { 7 | size_t size {str.size()}; 8 | 9 | std::vector> vec(size, std::vector(size,0)); 10 | 11 | // fill diagonally with 1 (base case) 12 | for(size_t i {0}; i 21 | #include 22 | #include 23 | #include 24 | 25 | 26 | using namespace std; 27 | 28 | 29 | class Solution 30 | { 31 | 32 | public: 33 | static bool compareFunc(std::string s1, std::string s2) 34 | { 35 | std::size_t found = s1.find_first_of(" "); 36 | std::size_t found2 = s2.find_first_of(" "); 37 | 38 | std::string subs1 = s1.substr(0,found); 39 | std::string subs2 = s2.substr(0,found2); 40 | 41 | s1.erase(0,found); 42 | s2.erase(0,found2); 43 | 44 | if(s1 == s2) 45 | { 46 | //in case of ties 47 | return subs1 < subs2; 48 | } 49 | 50 | return s1 reorderLogFiles(vector& logs) 54 | { 55 | vector resLet; 56 | vector resDig; 57 | 58 | for(int i=0; i 1) 66 | resDig.push_back(logs[i]); 67 | else 68 | resLet.push_back(logs[i]); 69 | 70 | } 71 | 72 | 73 | std::sort(resLet.begin(), resLet.end(), compareFunc); 74 | resLet.insert(resLet.end(), resDig.begin(), resDig.end()); 75 | 76 | return resLet; 77 | 78 | } 79 | }; 80 | 81 | 82 | 83 | int main() 84 | { 85 | vector log = {"dig1 8 1 5 1", "let1 art can", "dig2 3 6","let2 own kit dig","let3 art zero"}; 86 | 87 | 88 | Solution s; 89 | 90 | vector res = s.reorderLogFiles(log); 91 | 92 | for( auto s : res ) 93 | cout< 2 | #include 3 | #include 4 | 5 | // finding kth largest element is based on quick select 6 | // algorithm which is based on quick sort algorithm 7 | // The idea is to repeadetly partition the input array and 8 | // narrow down the search space based on kth largest elements 9 | // position relative to the partition index. 10 | 11 | /* 12 | 1. choose pivot element. In this example, the pivot element is 13 | always the first element of the current search space(nums[left]) 14 | 2. Perform a partition operation. Rearrange the elements in the search 15 | space such that elements greater than the pivot come before the pivot, 16 | and the elements less than the pivot come after it. The partition funciton 17 | returns the final index of the pivot element. 18 | 3. Compare the returned pivot index to k-1: 19 | a. if the pivot index is equal to k-1, we found kth largest 20 | element and the algortihm terminates. 21 | b. If the pivot index is less than k-1, the kth largest eleemnt 22 | lies in the right partition. Update the left pointer to idx+1 and 23 | repeat the process. 24 | c. If the pivot index is greater than k-1, the kth largest element 25 | lies in the left partition. Update the left pointer to idx-1 and 26 | repeat the process. 27 | */ 28 | 29 | class Solution { 30 | public: 31 | int findKthLargest(std::vector& nums, int k) 32 | { 33 | int left = 0, right = nums.size() - 1, kth; 34 | while(true) 35 | { 36 | int idx = partition(nums, left, right); 37 | if(idx == k - 1) 38 | { 39 | kth = nums[idx]; 40 | break; 41 | } 42 | if(idx < k - 1) 43 | { 44 | left = idx + 1; 45 | } 46 | else 47 | { 48 | right = idx - 1; 49 | } 50 | } 51 | return kth; 52 | } 53 | 54 | private: 55 | int partition(std::vector& nums, int left, int right) 56 | { 57 | int pivot = nums[left], l = left + 1, r = right; 58 | while(l <= r) 59 | { 60 | if(nums[l] < pivot && nums[r] > pivot) 61 | { 62 | std::swap(nums[l], nums[r]); 63 | } 64 | 65 | if(nums[l] >= pivot) 66 | l++; 67 | 68 | if(nums[r] <= pivot) 69 | r--; 70 | } 71 | std::swap(nums[left], nums[r]); 72 | return r; 73 | } 74 | 75 | 76 | }; 77 | 78 | int main() 79 | { 80 | std::vector vec{3,4,5,1,2,0,3,12,3,4,5,6,8,7,4}; 81 | 82 | std::cout< 2 | #include 3 | #include 4 | 5 | // find the number of months for k number which is used to count 6 | // the number of months that are increased consecutively 7 | 8 | class Solution 9 | { 10 | public: 11 | int countProfitableMonths(std::vector& vec, int k) 12 | { 13 | int result {0}; 14 | size_t size {vec.size()}; 15 | 16 | int cnt {0}; 17 | for(size_t i=1; i 0) 22 | { 23 | cnt ++; 24 | unsigned int l = i+1; 25 | if( l >= size) 26 | { 27 | if(k == 2) 28 | { 29 | result++; 30 | break; 31 | } 32 | } 33 | while(1) 34 | { 35 | int tempDiff {vec[l] - vec[l-1]}; 36 | if( tempDiff > 0) 37 | { 38 | l++; 39 | cnt++; 40 | 41 | if(k == 2) 42 | { 43 | if(cnt == k) 44 | { 45 | result ++; 46 | cnt = 0; 47 | break; 48 | } 49 | } 50 | else if( k > 2) 51 | { 52 | if(cnt == k-1) 53 | { 54 | result ++; 55 | cnt = 0; 56 | break; 57 | } 58 | } 59 | } 60 | else 61 | { 62 | cnt = 0; 63 | break; 64 | } 65 | } 66 | } 67 | else 68 | cnt = 0; 69 | } 70 | return result; 71 | } 72 | }; 73 | 74 | int main() 75 | { 76 | std::vector vec {5, 3, 5, 7, 8, 9, 10, 11}; 77 | //std::vector vec {5, 3, 5, 7, 8}; 78 | //std::vector vec { 1, 5, 2, 3, 7, 6, 4, 5 }; 79 | std::cout< 2 | #include 3 | #include 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node* next; 9 | }; 10 | 11 | struct Node* first = NULL; 12 | struct Node* last = NULL; 13 | 14 | void create(int A[], int n) 15 | { 16 | if(first) 17 | return; 18 | 19 | Node* t = (struct Node*)malloc(sizeof(struct Node)); 20 | first = t; 21 | t->data = A[0]; 22 | t->next = NULL; 23 | last = first; 24 | 25 | for(int i = 1; i < n; i++) 26 | { 27 | t = (struct Node*)malloc(sizeof(struct Node)); 28 | t->data = A[i]; 29 | t->next = NULL; 30 | last->next = t; 31 | last = t; 32 | } 33 | } 34 | 35 | 36 | void print() 37 | { 38 | if(first == NULL) 39 | return; 40 | 41 | struct Node* p; 42 | p = first; 43 | 44 | while(p) 45 | { 46 | std::cout<data<<" "; 47 | p = p->next; 48 | } 49 | 50 | } 51 | 52 | 53 | void pushLast(int value) 54 | { 55 | if(last == NULL) 56 | return; 57 | 58 | Node* t = (struct Node*)malloc(sizeof(struct Node)); 59 | t->data = value; 60 | t->next = NULL; 61 | last->next = t; 62 | last = t; 63 | } 64 | 65 | void pushFirst(int value) 66 | { 67 | if(first == NULL) 68 | return; 69 | 70 | Node* t = (struct Node*)malloc(sizeof(struct Node)); 71 | t->data = value; 72 | t->next = first; 73 | first = t; 74 | } 75 | 76 | void findPalindrome(std::vector &vec) 77 | { 78 | 79 | if(first == NULL) 80 | return; 81 | 82 | struct Node* p; 83 | p = first; 84 | 85 | int n,d,s; 86 | 87 | while(p) 88 | { 89 | n = p->data; 90 | d = 0; 91 | s = 0; 92 | while(n > 0) 93 | { 94 | d = n % 10; 95 | s = s*10 + d; 96 | n = n / 10; 97 | } 98 | 99 | if(s == p->data) 100 | vec.push_back(p->data); 101 | 102 | p = p->next; 103 | } 104 | } 105 | 106 | int main(int argc, char **argv) 107 | { 108 | 109 | int A[] = {11,223,323,414,52}; 110 | int n ; // sizeof(A)/sizeof(A[0]); 111 | n = sizeof(A)/sizeof(A[0]); 112 | 113 | pushLast(12); 114 | print(); 115 | pushFirst(12); 116 | print(); 117 | 118 | create(A,n); 119 | 120 | print(); 121 | std::cout< vec; 129 | findPalindrome(vec); 130 | for(auto s : vec) 131 | std::cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | 11 | // firstList = {{1, 'a'},{3, 'a'},{4, 'a'}}; 12 | // secondList = {{2, 7.6},{1, 2.8},{4, 5.3}}; 13 | 14 | // combine these two lists such as (sorted): {{1, 'a', 2.8}, {2, ,7.6}, {3, 'a', }, {4, 'a', 5.3}} 15 | // there will not be same key in one list two times, there can be only one or none. 16 | 17 | using data = std::tuple, std::optional>; 18 | 19 | std::vector foo(const std::vector>>& vec1, 20 | const std::vector>>& vec2) 21 | { 22 | std::unordered_map, std::optional>> map; 23 | 24 | for(const auto& v : vec1) 25 | { 26 | if(v.second != std::nullopt) 27 | map[v.first] = {v.second, std::nullopt}; 28 | } 29 | 30 | for(const auto& v : vec2) 31 | { 32 | if(v.second != std::nullopt) 33 | { 34 | if(map[v.first].first != std::nullopt) 35 | { 36 | map[v.first] = {map[v.first].first, v.second}; 37 | } 38 | else 39 | { 40 | map[v.first] = {std::nullopt, v.second}; 41 | } 42 | } 43 | } 44 | 45 | std::vector result; 46 | 47 | for(const auto& m : map) 48 | { 49 | result.push_back({m.first, m.second.first, m.second.second}); 50 | } 51 | 52 | 53 | std::sort(result.begin(), result.end(), [&](data lhs, data rhs) 54 | { 55 | return lhs < rhs; 56 | }); 57 | 58 | return result; 59 | } 60 | 61 | int main() 62 | { 63 | std::vector>> vec1{ 64 | {1, 'a'}, 65 | {2, 'c'}, 66 | {4, 'd'}, 67 | {3, 'b'}, 68 | }; 69 | 70 | std::vector>> vec2{ 71 | {6, 1.0}, 72 | {3, 2.34}, 73 | {4, 3.23}, 74 | {1, 1.23}, 75 | }; 76 | 77 | auto result = foo(vec1, vec2); 78 | 79 | for(const auto& tuple : result) 80 | { 81 | int i = std::get<0>(tuple); 82 | std::optional c = std::get<1>(tuple); 83 | std::optional d = std::get<2>(tuple); 84 | 85 | std::cout<