#include<math.h>
#include<stdio.h>
/*#include<iostream>

using namespace std;*/

int isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	double sqroot_x;
	sqroot_x = sqrt (x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return 0;
	}
	return 1;
}

int main(int argc, char* argv[])
{
	int result;
/*	int number;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if (result) {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}*/
	result = isPrimeBruteForce(37);
	printf("Is 37 a prime number? %i", result);
	return 0;
}

#include <iostream>
#include <cmath>
//using namespace std;

int isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	double sqroot_x;
	double square = x;
	sqroot_x = std::sqrt(square);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return 0;
	}
	return 1;
}

int main(int argc, char* argv[])
{
	int result;
	int number;
	std::cout << "Enter number to test if it's prime: " << std::endl;
	std::cin >> number;
	result = isPrimeBruteForce(number);
	std::cout << std::endl;
	if (result == 1) {
		std::cout << number << " is a prime number." << std::endl;
	} else {
		std::cout << number << " is not a prime number." << std::endl;
	}
/*	result = isPrimeBruteForce(37);
	printf("Is 37 a prime number? %i", result);*/
	return 0;
}

Change preprocessors and namespaces to c++ std library; make data types consistent (at least trying to)


/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/platform/cuda_libdevice_path.h"

#include <stdlib.h>
#include <vector>

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

std::vector<string> CandidateCudaRoots() {
  VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
  return {TF_CUDA_TOOLKIT_PATH};
}

}  // namespace tensorflow

/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/platform/cuda_libdevice_path.h"

#include <stdlib.h>
#include <vector>

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

std::vector<string> CandidateCudaRoots() {
  VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
  return {TF_CUDA_TOOLKIT_PATH, string("/usr/local/cuda")};
}

}  // namespace tensorflow

Add /usr/local/cuda to the list of CUDA data directories that XLA searches by default.


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

using namespace std;
/* So I guess I should use arrays? Seems like quite good idea, hopefully it'll work as intended.
 * Also I'm still not sure how to avoid duplicates...
*/

void lotto::lotek(){
    for(int i = 0; i < 6; i++) {
        int a = rand()%49+1;
        cout << '\t' << a << " " << endl;
    }
}

void lotto::multilotek() {
    for(int i = 0; i < 20; i++) {
        int a = rand()%80+1;
        cout << a << endl;
    }
}

void lotto::simpleMenu() {
    cout << "Bardzo prosty program używający generator liczb pseudolosowych.\n" << endl;
    cout << "1. Lotto (bez plusa i innych super szans)\n2. Multi multi (bez plusa i super szansy)\n3. Koniec (kończy program)" << endl;
}

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

using namespace std;
/* So I guess I should use arrays? Seems like quite good idea, hopefully it'll work as intended.
 * Also I'm still not sure how to avoid duplicates...
*/

void lotto::lotek(){
   int lotteryPool[50];
   for(int x = 0; x < 50; x++) {
       lotteryPool[x] = x + 1;
   }
   srand (time(NULL));
   int random;
   int y = 0;
   while(y < 6) {
       random = rand()%50;
       if(lotteryPool[random] != 0) {
           cout << lotteryPool[random] << " ";
           lotteryPool[random] = 0;
           y++;
       }
   }

}

void lotto::multilotek() {
    for(int i = 0; i < 20; i++) {
        int a = rand()%80+1;
        cout << a << endl;
    }
}

void lotto::simpleMenu() {
    cout << "Bardzo prosty program używający generator liczb pseudolosowych.\n" << endl;
    cout << "1. Lotto (bez plusa i innych super szans)\n2. Multi multi (bez plusa i super szansy)\n3. Koniec (kończy program)" << endl;
}

Add changes to first option


/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "halfling/halfling_engine.h"

#include "deferred_shading_demo/graphics_manager.h"
#include "deferred_shading_demo/game_state_manager.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	DeferredShadingDemo::GameStateManager gameStateManager;
	DeferredShadingDemo::GraphicsManager graphicsManager(&gameStateManager);

	Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager);

	engine.Initialize(L"Lighting Demo", 800, 600, false);
	engine.Run();

	engine.Shutdown();

	return 0;
}

/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "halfling/halfling_engine.h"

#include "deferred_shading_demo/graphics_manager.h"
#include "deferred_shading_demo/game_state_manager.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	DeferredShadingDemo::GameStateManager gameStateManager;
	DeferredShadingDemo::GraphicsManager graphicsManager(&gameStateManager);

	Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager);

	engine.Initialize(L"Deferred Shading Demo", 800, 600, false);
	engine.Run();

	engine.Shutdown();

	return 0;
}

Change the title bar caption


/*
Author: vpetrigo
Task:

  0.
     ,
,   ,
   .

   ,
 0 (  0    ,      ).

   .

Sample Input 1:
4
4
2
3
0
Sample Output 1:
4

Sample Input 2:
2
1
0
Sample Output 2:
1

*/

#include <iostream>

using namespace std;

int main() {
    int n;
    int max = -1;
    int s_max = -1;

    while (cin >> n && n != 0) {
        if (max < n) {
            max = n;
        }

        if (n <= max && s_max < n) {
            s_max = n;
        }
    }

    cout << s_max;

    return 0;
}

/*
Author: vpetrigo
Task:

  0.
     ,
,   ,
   .

   ,
 0 (  0    ,      ).

   .

Sample Input 1:
4
4
2
3
0
Sample Output 1:
4

Sample Input 2:
2
1
0
Sample Output 2:
1

*/

#include <iostream>

using namespace std;

int main() {
    int n;
    int max = -1;
    int s_max = -1;

    while (cin >> n && n != 0) {
        if (max <= n) {
            s_max = max;
            max = n;
        }
        else if (s_max < n) {
            s_max = n;
        }
    }

    cout << s_max;

    return 0;
}

Revert "Revert "Solution for week 3, task 9""


/*
 * Copyright (c) 2015 Roc authors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <CppUTest/CommandLineArguments.h>
#include <CppUTest/CommandLineTestRunner.h>

#include "roc_core/crash.h"
#include "roc_core/exit.h"
#include "roc_core/log.h"

int main(int argc, const char** argv) {
    roc::core::CrashHandler crash_handler;

    CommandLineArguments args(argc, argv);

    if (args.parse(NULL) && args.isVerbose()) {
        roc::core::Logger::instance().set_level(roc::LogDebug);
    } else {
        roc::core::Logger::instance().set_level(roc::LogNone);
    }

    MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();

    const int code = CommandLineTestRunner::RunAllTests(argc, argv);
    if (code != 0) {
        roc::core::fast_exit(code);
    }

    return 0;
}

/*
 * Copyright (c) 2015 Roc authors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <CppUTest/CommandLineArguments.h>
#include <CppUTest/CommandLineTestRunner.h>

#include "roc_core/colors.h"
#include "roc_core/crash.h"
#include "roc_core/exit.h"
#include "roc_core/log.h"

int main(int argc, const char** argv) {
    roc::core::CrashHandler crash_handler;

    CommandLineArguments args(argc, argv);

    if (args.parse(NULL) && args.isVerbose()) {
        roc::core::Logger::instance().set_level(roc::LogDebug);
    } else {
        roc::core::Logger::instance().set_level(roc::LogNone);
    }

    roc::core::Logger::instance().set_colors(roc::core::colors_available()
                                                 ? roc::core::ColorsEnabled
                                                 : roc::core::ColorsDisabled);

    MemoryLeakWarningPlugin::turnOffNewDeleteOverloads();

    const int code = CommandLineTestRunner::RunAllTests(argc, argv);
    if (code != 0) {
        roc::core::fast_exit(code);
    }

    return 0;
}

Enable colorful logs in tests


#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "pattern_posture_generator");
  ros::NodeHandle nh;

  PatternPostureGenerator ppg(nh);

  ros::spin();
  return 0;
}

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  return true;
}

#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "pattern_posture_generator");
  ros::NodeHandle nh;

  PatternPostureGenerator ppg(nh);

  ros::spin();
  return 0;
}

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  std::copy(posture_datas[req.name].begin(), posture_datas[req.name].end(), std::back_inserter(res.posture));
  return true;
}

Implement getPostureKey of PPG node.


#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  return true;
}

int main(int argc, char* argv[]) {
  return 0;
}

#include "ros/ros.h"

#include "pattern_posture_generator_node.hpp"

int main(int argc, char* argv[]) {
  ros::init(argc, argv, "pattern_posture_generator");
  ros::NodeHandle nh;

  PatternPostureGenerator ppg(nh);

  ros::spin();
  return 0;
}

PatternPostureGenerator::PatternPostureGenerator(){}

PatternPostureGenerator::PatternPostureGenerator(ros::NodeHandle& nh) {
  if (!nh.getParam("pattern", pattern_names)) return;
  for (std::map<std::string, std::string >::iterator it = pattern_names.begin();
       it != pattern_names.end();
       it++) {
    std::vector<double> posture;
    if (!nh.getParam(std::string("pattern/").append(it->second), posture)) return;
    std::copy(posture.begin(), posture.end(), std::back_inserter(posture_datas[it->second]));
  }
  key_srv = nh.advertiseService("getPostureKey", &PatternPostureGenerator::getPostureKey, this);
}

bool PatternPostureGenerator::getPostureKey(pattern_posture_generator::PatternKeyPosture::Request&  req,
                                            pattern_posture_generator::PatternKeyPosture::Response& res) {
  return true;
}

Implement main func of PPG.


/*
 * Copyright 2014-2015 Adam Chyła, adam@chyla.org
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "../config.h"

#if defined(HAVE_GTEST) && defined(HAVE_GMOCK)

#include <gtest/gtest.h>

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);

    return RUN_ALL_TESTS();
}

#else

#error Cannot make tests. Google Test or Google Mock library not found.

#endif // HAVE_BOOST_UNIT_TEST_FRAMEWORK

/*
 * Copyright 2014-2015 Adam Chyła, adam@chyla.org
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "../config.h"

#if defined(HAVE_GTEST) && defined(HAVE_GMOCK)

#include <boost/log/common.hpp>
#include <gtest/gtest.h>

int main(int argc, char **argv) {
  boost::log::core::get()->set_logging_enabled(false);

  testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}

#else

#error Cannot make tests. Google Test or Google Mock library not found.

#endif // HAVE_BOOST_UNIT_TEST_FRAMEWORK

Disable logging in agent tests


#include <cstring>
#include "board.h"
#include <aery32/all.h>

using namespace aery;

int main(void)
{
	int errno;
	uint16_t page = FLASH_LAST_PAGE;
	char buf[512] = {'\0'};

	init_board();
	gpio_init_pin(LED, GPIO_OUTPUT|GPIO_HIGH);

	/* If page is empty, write "foo". Else read page. */
	if (flashc_page_isempty(page)) {
		strcpy(buf, "foo");
		errno = flashc_save_page(page, buf);

		switch (errno) {
		case EFLASH_PAGE_LOCKED:
			/* Page was locked */
			break;
		case EFLASH_PROG_ERR:
			/* Programming error was accured */
			break;
		}
	} else {
		flashc_read_page(page, buf);
	}

	for(;;) {
		/* Put your application code here */

	}

	return 0;
}

#include <cstring>
#include "board.h"
#include <aery32/all.h>

using namespace aery;

void lock_flash_programspace(void)
{
	int i = FLASH_LAST_PAGE;
	for (; flashc_page_isempty(i); i--);
	for (; i >= 0; i--) {
		flashc_lock_page(i);
	}
}

int main(void)
{
	int errno;
	uint16_t page = FLASH_LAST_PAGE;
	char buf[512] = {'\0'};

	init_board();
	gpio_init_pin(LED, GPIO_OUTPUT|GPIO_HIGH);

	/* Lock flash region for the uploaded program. Just to be in safe. */
	lock_flash_programspace();

	/* If page is empty, write "foo". Else read page. */
	if (flashc_page_isempty(page)) {
		strcpy(buf, "foo");
		errno = flashc_save_page(page, buf);

		switch (errno) {
		case EFLASH_PAGE_LOCKED:
			/* Page was locked */
			break;
		case EFLASH_PROG_ERR:
			/* Programming error was accured */
			break;
		}
	} else {
		flashc_read_page(page, buf);
	}

	for(;;) {
		/* Put your application code here */

	}

	return 0;
}

Enhance example to write flash


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <random>

// template<class RealType = double>
// class piecewise_linear_distribution

// param_type param() const;

#include <random>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 10};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        P pa(b, b+Np+1, p);
        D d(pa);
        assert(d.param() == pa);
    }
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <random>

// template<class RealType = double>
// class piecewise_linear_distribution

// param_type param() const;

#include <random>
#include <cassert>

int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 10};
        const size_t Np = sizeof(p) / sizeof(p[0]);
        P pa(b, b+Np, p);
        D d(pa);
        assert(d.param() == pa);
    }
}

Fix bug in test; found by AddressSanitizer


#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>

int main() {
  size_t T;
  std::cin >> T;
  for (auto testCase{1u}; testCase <= T; ++testCase) {
    size_t N;
    std::cin >> N;
    std::string beautyScores;
    std::cin >> beautyScores;
    std::transform(beautyScores.begin(), beautyScores.end(), beautyScores.begin(),
                   [](const auto &score) { return char{score - '0'}; });
    const size_t windowSize = (N + 1) / 2;
    size_t numberOfWindows = N - windowSize + 1;
    auto sum = std::accumulate(beautyScores.begin(), beautyScores.begin() + windowSize, 0u);
    auto max = sum;
    for (auto i{0u}; i < numberOfWindows; ++i) {
      sum -= beautyScores[i];
      sum += beautyScores[i + windowSize];
      max = std::max(max, sum);
    }
    std::cout << "Case #" << testCase << ": " << max << std::endl;
  }
}

#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>

int main() {
  size_t T;
  std::cin >> T;
  for (auto testCase{1u}; testCase <= T; ++testCase) {
    size_t N;
    std::cin >> N;
    std::string beautyScores;
    std::cin >> beautyScores;
    std::transform(beautyScores.begin(), beautyScores.end(), beautyScores.begin(),
                   [](const auto &score) { return static_cast<char>(score - '0'); });
    const size_t windowSize = (N + 1) / 2;
    size_t numberOfWindows = N - windowSize + 1;
    auto sum = std::accumulate(beautyScores.begin(), beautyScores.begin() + windowSize, 0u);
    auto max = sum;
    for (auto i{0u}; i < numberOfWindows; ++i) {
      sum -= beautyScores[i];
      sum += beautyScores[i + windowSize];
      max = std::max(max, sum);
    }
    std::cout << "Case #" << testCase << ": " << max << std::endl;
  }
}

Fix compilation on clang and gcc


// Tests -fsanitize-coverage=inline-8bit-counters
//
// REQUIRES: has_sancovcc,stable-runtime
// UNSUPPORTED: i386-darwin, x86_64-darwin
//
// RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1

#include <stdio.h>
#include <assert.h>

const char *first_counter;

extern "C"
void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) {
  printf("INIT: %p %p\n", start, end);
  assert(end - start > 1);
  first_counter = start;
}

int main() {
  assert(first_counter);
  assert(*first_counter == 1);
}

// Tests -fsanitize-coverage=inline-8bit-counters
//
// REQUIRES: has_sancovcc,stable-runtime
// UNSUPPORTED: i386-darwin, x86_64-darwin, x86_64h-darwin
//
// RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1

#include <stdio.h>
#include <assert.h>

const char *first_counter;

extern "C"
void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) {
  printf("INIT: %p %p\n", start, end);
  assert(end - start > 1);
  first_counter = start;
}

int main() {
  assert(first_counter);
  assert(*first_counter == 1);
}

Mark a sancov test as unsupported on x86_64h-darwin


#include "configs/includes.h"
#include "power/gb_abstract_battery.h"
#include "power/gb_battery.h"
#include "utilities/gb_utility.h"
#include <Arduino.h>

class FakeBattery : public GbAbstractBattery {
public:
  FakeBattery() : GbAbstractBattery(1, 3.4, 3.5, 3){};
  float GetVoltage() {
    return (sin(millis()/10000.0)/2.0) + 3.7;
  }
};

static const int BATTERY_WAIT_TIME = 4;
FakeBattery battery1 = FakeBattery();
FakeBattery battery2 = FakeBattery();

void setup() {
  Serial.begin(115200);
  Serial.println(F("Wait_for_batteries test starting..."));
}

void loop() {
  GbUtility::WaitForBatteries(BATTERY_WAIT_TIME, battery1, battery2);
  Serial.print("battery1 voltage: ");
  Serial.print(battery1.GetVoltage());
  Serial.print(" | battery1 status: ");
  Serial.println(battery1.Status());
  Serial.print("battery2 voltage: ");
  Serial.print(battery2.GetVoltage());
  Serial.print(" | battery2 status: ");
  Serial.println(battery2.Status());
  Serial.println("*******************************************");
  delay(500);
}

#include "configs/includes.h"
#include "power/gb_abstract_battery.h"
#include "power/gb_battery.h"
#include "utilities/gb_utility.h"
#include <Arduino.h>

class FakeBattery : public GbAbstractBattery {
private:
  char _scheme;
public:
  FakeBattery(char scheme) : GbAbstractBattery(1, 3.4, 3.5, 3), _scheme(scheme) {};
  float GetVoltage() {
    float voltage;
    switch (_scheme) {
      case 's':
        voltage = (sin(millis()/10000.0)/2.0) + 3.7;
        break;
      case 'a':
        voltage = (sin(millis()/5000.0)/2.0) + 3.7;
        break;
      default:
        voltage = 3.89;
        break;
    }
    return voltage;
  }
};

static const int BATTERY_WAIT_TIME = 4;
FakeBattery battery1 = FakeBattery('s');
FakeBattery battery2 = FakeBattery('a');

void setup() {
  Serial.begin(115200);
  Serial.println(F("Wait_for_batteries test starting..."));
}

void loop() {
  GbUtility::WaitForBatteries(BATTERY_WAIT_TIME, battery1, battery2);
  Serial.print("battery1 voltage: ");
  Serial.print(battery1.GetVoltage());
  Serial.print(" | battery1 status: ");
  Serial.println(battery1.Status());
  Serial.print("battery2 voltage: ");
  Serial.print(battery2.GetVoltage());
  Serial.print(" | battery2 status: ");
  Serial.println(battery2.Status());
  Serial.println("*******************************************");
  delay(500);
}

Add fake voltage decay schemes


#include "Thread/Unix/ThreadImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  ThreadImpl::ThreadImpl(Thread *thread)
  {
    this->_isActive = pthread_create(&this->_thread, NULL,
        &ThreadImpl::entryPoint, thread) == 0;
    if (!this->_isActive)
      throw ThreadException("Thread Exception: "
          "Error while creating the Thread.");
  }

  ThreadImpl::~ThreadImpl()
  {
    if (this->_isActive)
      terminate();
  }

  void ThreadImpl::wait()
  {
    if (this->_isActive)
    {
      if (pthread_equal(pthread_self(), this->_thread) != 0)
        throw ThreadException("Thread Exception: "
            "A thread cannot wait for itself.");
      if (pthread_join(this->_thread, NULL) != 0)
        throw ThreadException("Thread Exception: "
            "Error while waiting for the thread to finish.");
    }
  }

  void ThreadImpl::terminate()
  {
    if (this->_isActive)
      if (pthread_cancel(this->_thread) != 0)
        throw ThreadException("Thread Exception: "
            "Error while canceling the thread.");
    this->_isActive = false;
  }

  void *ThreadImpl::entryPoint(void *data)
  {
    Thread *self = static_cast<Thread *>(data);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    self->run();
    return (NULL);
  }
}

#include "Thread/Unix/ThreadImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  ThreadImpl::ThreadImpl(Thread *thread)
  {
    this->_isActive = pthread_create(&this->_thread, NULL,
        &ThreadImpl::entryPoint, thread) == 0;
    if (!this->_isActive)
      throw ThreadException("Thread Exception: "
          "Error while creating the Thread.");
  }

  ThreadImpl::~ThreadImpl()
  {
    if (this->_isActive)
      terminate();
  }

  void ThreadImpl::wait()
  {
    if (this->_isActive)
    {
      if (pthread_equal(pthread_self(), this->_thread) != 0)
        throw ThreadException("Thread Exception: "
            "A thread cannot wait for itself.");
      if (pthread_join(this->_thread, NULL) != 0)
        throw ThreadException("Thread Exception: "
            "Error while waiting for the thread to finish.");
    }
    this->_isActive = false;
  }

  void ThreadImpl::terminate()
  {
    if (this->_isActive)
      if (pthread_cancel(this->_thread) != 0)
        throw ThreadException("Thread Exception: "
            "Error while canceling the thread.");
    this->_isActive = false;
  }

  void *ThreadImpl::entryPoint(void *data)
  {
    Thread *self = static_cast<Thread *>(data);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    self->run();
    return (NULL);
  }
}

Set the thread to non active after waiting for it.


// RUN: clang-cc -fsyntax-only -pedantic -std=c++0x -verify %s

void foo();

void bar() { };

void wibble();

;

namespace Blah {
  void f() { };

  void g();
}

Improve top-level-semicolon test a bit


/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas);
}

/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas(0,0));
}

Fix SkNWayCanvas cons call when creating null canvas.


/*
The MIT License (MIT)

Copyright (c) 2013-2019 Winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_utest_http.hpp>

#include <srs_http_stack.hpp>

VOID TEST(ProtoStackTest, StatusCode2Text)
{
    EXPECT_STREQ(SRS_CONSTS_HTTP_OK_str, srs_generate_http_status_text(SRS_CONSTS_HTTP_OK).c_str());
    EXPECT_STREQ("Status Unknown", srs_generate_http_status_text(999).c_str());
}

Improve test coverage of status for HTTP.


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Summon.hpp>
#include <Rosetta/Games/Game.hpp>

namespace RosettaStone::Generic
{
void Summon(Player& player, Minion* minion, int fieldPos)
{
    player.GetField().AddMinion(*minion, fieldPos);
}
}  // namespace RosettaStone::Generic

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Summon.hpp>
#include <Rosetta/Games/Game.hpp>

namespace RosettaStone::Generic
{
void Summon(Player& player, Minion* minion, int fieldPos)
{
    player.GetField().AddMinion(*minion, fieldPos);

    player.GetGame()->UpdateAura();

    player.GetGame()->summonedMinions.emplace_back(minion);
}
}  // namespace RosettaStone::Generic

Add code to update aura and minion to summoned minions


#include "sleepy_discord/sleepy_discord.h"

class myClientClass : public SleepyDiscord::DiscordClient {
public:
	using SleepyDiscord::DiscordClient::DiscordClient;
	void onMessage(SleepyDiscord::Message message) {
		if (message.startsWith("whcg hello"))
			sendMessage(message.channelID, "Hello " + message.author.username);
	}
};

int main() {
	myClientClass client("token", SleepyDiscord::BaseDiscordClient::USER_CONTROLED_THREADS);
	client.run();
}

#include "sleepy_discord/sleepy_discord.h"

class myClientClass : public SleepyDiscord::DiscordClient {
public:
	using SleepyDiscord::DiscordClient::DiscordClient;
	void onMessage(SleepyDiscord::Message message) {
		if (message.startsWith("whcg hello"))
			sendMessage(message.channelID, "Hello " + message.author.username);
	}
};

int main() {
	myClientClass client("token", SleepyDiscord::USER_CONTROLED_THREADS);
	client.run();
}

Fix hello example, variable not defined


/*
 * var_len_pool_test.cpp - Test suite for varrable lengthed allocation pool
 */

#include "test_suite.h"

/*
 * VarLenPoolBasicTest() - This function allocates a series of memory
 *                         using an increasing sequence and then check
 *                         for correctness
 */
void VarLenPoolBasicTest() {
  PrintTestName("VarLenPoolBasicTest");

  static const iter = 10;

  void *p_list[iter];

  // Chunk size = 64
  VarLenPool vlp{64};
  for(int i = 1;i <= 10;i++) {
    p_list[i - 1] = vlp.Allocate(i);
    memset(p_list[i - 1], i, i);
  }

  // Verify for correctness
  for(int i = 1;i <= 10;i++) {
    char *p = reinterpret_cast<char *>(p_list[i - 1]);
    for(int j = 0;j < i;j++) {
      assert(p[j] == static_cast<char>(i));
    }
  }

  return;
}

int main() {
  VarLenPoolBasicTest();

  return;
}

/*
 * var_len_pool_test.cpp - Test suite for varrable lengthed allocation pool
 */

#include "test_suite.h"
#include "../src/VarLenPool.h"

/*
 * VarLenPoolBasicTest() - This function allocates a series of memory
 *                         using an increasing sequence and then check
 *                         for correctness
 */
void VarLenPoolBasicTest() {
  PrintTestName("VarLenPoolBasicTest");

  static const int iter = 10;

  void *p_list[iter];

  // Chunk size = 64
  VarLenPool vlp{64};
  for(int i = 1;i <= 10;i++) {
    p_list[i - 1] = vlp.Allocate(i);
    memset(p_list[i - 1], i, i);
  }

  // Verify for correctness
  for(int i = 1;i <= 10;i++) {
    char *p = reinterpret_cast<char *>(p_list[i - 1]);
    for(int j = 0;j < i;j++) {
      assert(p[j] == static_cast<char>(i));
    }
  }

  return;
}

int main() {
  VarLenPoolBasicTest();

  return 0;
}

Fix test case compilation problem


// Copyright (C) 2011-2012, Zeex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include "timers.h"

namespace sampgdk {

int GetTickCount() {
	return GetTickCount();
}

} // namespace sampgdk

// Copyright (C) 2011-2012, Zeex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include "timers.h"

namespace sampgdk {

int GetTickCount() {
	return ::GetTickCount();
}

} // namespace sampgdk

Fix infinite recursion in GetTickCount() on Windows


#include "compress.hpp"
#include "huffman.hpp"

std::string compress(const std::string& data) {
	using uch = unsigned char;

	std::array<uint64_t, BYTES_COUNT> freq_table;
	freq_table.fill(0);
	for(uch c : data) ++freq_table[c];
	auto root = buildHuffmanTree(freq_table);
	auto table = buildCompressTable(root);

	std::string compressed;

	uint64_t index = 0;
	for(uch c : data) {
		for(unsigned f : table[c]) {
			if((index & 7) == 0)
				compressed.push_back(0);
			compressed.back() |= f << (~index & 7);
			++index;
		}
	}

	return compressed;
}

#include "compress.hpp"
#include "huffman.hpp"

std::string compress(const std::string& data) {
	using uch = unsigned char;

	std::array<uint64_t, BYTES_COUNT> freq_table;
	freq_table.fill(0);
	for(uch c : data) ++freq_table[c];
	auto root = buildHuffmanTree(freq_table);
	auto table = buildCompressTable(root);

	std::string compressed((char*)freq_table.data(), sizeof(freq_table));

	uint64_t index = 0;
	for(uch c : data) {
		for(unsigned f : table[c]) {
			if((index & 7) == 0)
				compressed.push_back(0);
			compressed.back() |= f << (~index & 7);
			++index;
		}
	}

	return compressed;
}

Add frequency table to output


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "CreationRules.h"
#include <cstdlib>

void* autowiring::aligned_malloc(size_t ncb, size_t align) {
  void* pRetVal;
  if(posix_memalign(&pRetVal, ncb, align))
    return nullptr;
  return pRetVal;
}

void autowiring::aligned_free(void* ptr) {
  free(ptr);
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "CreationRules.h"
#include <cstdlib>

void* autowiring::aligned_malloc(size_t ncb, size_t align) {
  void* pRetVal;
  if(posix_memalign(&pRetVal, align, ncb))
    return nullptr;
  return pRetVal;
}

void autowiring::aligned_free(void* ptr) {
  free(ptr);
}

Fix an issue with the call to posix_memalign


#include "shape.hpp"

Shape::Shape():
        name_{},
        color_{0.0, 0.0, 0.0}
        {}

Shape::Shape(std::string const& name):
        name_{name},
        color_{1.0, 1.0, 1.0}
        {}

Shape::Shape(Color const& color):
        name_{},
        color_{color}
        {}

Shape::Shape(std::string const& name, Color const& color):
        name_{name},
        color_{color}
        {}

std::string Shape::getName() const {
        return name_;
}

Color Shape::getColor() const {
        return color_;
}

std::ostream& Shape::print(std::ostream& os) const {
        os << "Shape " << name_ << ", RGB: {" << color_.r << ", " << color_.g
        << ", " << color_.b << "}";
        return os;
}

std::ostream& operator<<(std::ostream& os, Shape const& s) {
        s.print(os);
        return os;
}

#include "shape.hpp"

Shape::Shape():
        name_{},
        color_{0.0, 0.0, 0.0}
        {}

Shape::Shape(std::string const& name):
        name_{name},
        color_{1.0, 1.0, 1.0}
        {}

Shape::Shape(Color const& color):
        name_{},
        color_{color}
        {}

Shape::Shape(std::string const& name, Color const& color):
        name_{name},
        color_{color}
        {}

std::string Shape::getName() const {
        return name_;
}

Color Shape::getColor() const {
        return color_;
}

std::ostream& Shape::print(std::ostream& os) const {
        os << "Shape " << name_ << ", RGB: " << color_;
        return os;
}

/* virtual */ std::ostream& operator<<(std::ostream& os, Shape const& s) {
        s.print(os);
        return os;
}

Switch to predefined color output.


#define CATCH_CONFIG_MAIN

#include "../catch.hpp"
#include "../../NumberTheory/Fibonacci.cpp"

TEST_CASE("Base cases", "[fibonacci]") {
    REQUIRE(fibonacci(0) == 0);
    REQUIRE(fibonacci(1) == 1);
}

TEST_CASE("Normal cases", "[fibonacci]") {
    REQUIRE(fibonacci(2) == 1);
    REQUIRE(fibonacci(7) == 13);
    REQUIRE(fibonacci(15) == 610);
    REQUIRE(fibonacci(18) == 2584);
    REQUIRE(fibonacci(23) == 28657);
    REQUIRE(fibonacci(50) == 12586269025);
    REQUIRE(fibonacci(93) == 12200160415121876738U);
}

TEST_CASE("Overflow cases", "[fibonacci]") {
    REQUIRE(fibonacci(94) == 1293530146158671551U);
    REQUIRE(fibonacci(1500) == 13173307912845686352U);
}

#define CATCH_CONFIG_MAIN
#define TEST

#include "../catch.hpp"
#include "../../NumberTheory/Fibonacci.cpp"

TEST_CASE("Base cases", "[fibonacci]") {
    REQUIRE(fibonacci(0) == 0);
    REQUIRE(fibonacci(1) == 1);
}

TEST_CASE("Normal cases", "[fibonacci]") {
    REQUIRE(fibonacci(2) == 1);
    REQUIRE(fibonacci(7) == 13);
    REQUIRE(fibonacci(15) == 610);
    REQUIRE(fibonacci(18) == 2584);
    REQUIRE(fibonacci(23) == 28657);
    REQUIRE(fibonacci(50) == 12586269025);
    REQUIRE(fibonacci(93) == 12200160415121876738U);
}

TEST_CASE("Overflow cases", "[fibonacci]") {
    REQUIRE(fibonacci(94) == 1293530146158671551U);
    REQUIRE(fibonacci(1500) == 13173307912845686352U);
}

Add a define to simplify compilation


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t s) {
  return HeapAlloc(win_heap, 0, s);
}

void* win_heap_realloc(void* p, size_t s) {
  if (!p)
    return win_heap_malloc(s);
  return HeapReAlloc(win_heap, 0, p, s);
}

void win_heap_free(void* s) {
  HeapFree(win_heap, 0, s);
}

size_t win_heap_msize(void* p) {
  return HeapSize(win_heap, 0, p);
}

}  // extern "C"

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t size) {
  return HeapAlloc(win_heap, 0, size);
}

void win_heap_free(void* size) {
  HeapFree(win_heap, 0, size);
}

void* win_heap_realloc(void* ptr, size_t size) {
  if (!ptr)
    return win_heap_malloc(size);
  if (!size) {
    win_heap_free(ptr);
    return NULL;
  }
  return HeapReAlloc(win_heap, 0, ptr, size);
}

size_t win_heap_msize(void* ptr) {
  return HeapSize(win_heap, 0, ptr);
}

}  // extern "C"

Fix the windows allocator to behave properly on realloc.


#pragma push_macro("N")
#undef N
#include <llvm/IR/IRBuilder.h>
#pragma pop_macro("N")
namespace eosio { namespace chain { namespace eosvmoc {
namespace LLVMJIT {

llvm::Value* CreateInBoundsGEPWAR(llvm::IRBuilder<>& irBuilder, llvm::Value* Ptr, llvm::Value* v1, llvm::Value* v2) {
   if(!v2)
      return irBuilder.CreateInBoundsGEP(Ptr, v1);
   else
      return irBuilder.CreateInBoundsGEP(Ptr, {v1, v2});
}

}

}}}

#include <llvm/IR/IRBuilder.h>
namespace eosio { namespace chain { namespace eosvmoc {
namespace LLVMJIT {

llvm::Value* CreateInBoundsGEPWAR(llvm::IRBuilder<>& irBuilder, llvm::Value* Ptr, llvm::Value* v1, llvm::Value* v2) {
   if(!v2)
      return irBuilder.CreateInBoundsGEP(Ptr, v1);
   else
      return irBuilder.CreateInBoundsGEP(Ptr, {v1, v2});
}

}

}}}

Revert "Attempt to fix unity builds."


#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>

#include "sailfishapplication.h"
#include "servercomm.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
    QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));

    ServerComm sc;
    view->rootContext()->setContextProperty("serverComm", &sc);

    Sailfish::showView(view.data());

    return app->exec();
}

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQuickWindow>

#include "sailfishapplication.h"
#include "servercomm.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QQuickWindow::setDefaultAlphaBuffer(true);
    QScopedPointer<QGuiApplication> app(Sailfish::createApplication(argc, argv));
    QScopedPointer<QQuickView> view(Sailfish::createView("main.qml"));

    ServerComm sc;
    view->rootContext()->setContextProperty("serverComm", &sc);

    Sailfish::showView(view.data());

    return app->exec();
}

Add trasparency support for the app cover


#include <ncurses.h>

#include "print.hpp"
#include "lightsout.hpp"
using namespace roadagain;

int main()
{
    initscr();
    cbreak();
    noecho();
    start_color();
    init_colors();

    board b(5, 5);
    while (!b.is_perfect()){
        char c = getch();

        switch (c){
        case 'h':
            b.move_board(0, -1);
            break;
        case 'j':
            b.move_board(1, 0);
            break;
        case 'k':
            b.move_board(-1, 0);
            break;
        case 'l':
            b.move_board(0, 1);
            break;
        case '\n':
            b.turn();
            break;
        }
    }

    endwin();
    return 0;
}

#include <ncurses.h>
#include <cstring>
#include <cstdlib>

#include "print.hpp"
#include "lightsout.hpp"
using namespace roadagain;

int main(int argc, char** argv)
{
    initscr();
    cbreak();
    noecho();
    start_color();
    init_colors();

    int width = 5;
    int height = 5;
    for (int i = 1; i < argc; i++){
        if (std::strncmp("--width=", argv[i], 8) == 0){
            width = std::atoi(argv[i] + 8);
        }
        else if (std::strncmp("--height=", argv[i], 9) == 0){
            height = std::atoi(argv[i] + 9);
        }
    }

    board b(width, height);
    while (!b.is_perfect()){
        char c = getch();

        switch (c){
        case 'h':
            b.move_board(0, -1);
            break;
        case 'j':
            b.move_board(1, 0);
            break;
        case 'k':
            b.move_board(-1, 0);
            break;
        case 'l':
            b.move_board(0, 1);
            break;
        case '\n':
            b.turn();
            break;
        }
    }

    endwin();
    return 0;
}

Add getting width and height from argv


#include <iostream>

using namespace std;

int week_day(int day, int month, int year) {
    int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};

    year -= month < 3;
    return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;
}

int main() {
    int y, m, count = 0;
    for (y = 1901; y <= 2000; y++) {
        for (m = 1; m <= 12; m++) {
            if (week_day(1, m, y) == 0) count++;
        }
    }

    cout << count << endl;
    return 0;
}

Remove espaço no fim da linha.


#include <iostream>
#include <vector>
#include <string>
using namespace std;

class StringBuilder {
    vector<string> _buffer;

    StringBuilder() {
//        this._buffer = new List();
    }

    public:
    StringBuilder append(string text) {
        _buffer.push_back(text);
        return *this;
    }
/*
    StringBuilder insert(index, text) {
        _buffer.insert(index, text);
        return *this;
    }

    int length() {
        return toString().length();
    }

    StringBuilder deleteCharAt(index) {
        var str = this.toString();
        this._buffer = new List();
        append(str.substring(0, index));
        return this;
    }

    String toString() {
        return _buffer.join("");
    }
*/
};

int main(){
    vector<string> strings;
    strings.push_back("string 1");
    strings.push_back("string 2");
    vector<string>::const_iterator strIter;
    string result("");
    for (strIter=strings.begin(); strIter!=strings.end(); strIter++) {
        cout << *strIter << endl;
        result = result + *strIter;
    }
    cout << "Basic list programm!" << endl;
    cout << "Together: " << result << endl;
    return 0;
}

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class StringBuilder {
    vector<string> _buffer;

    public:
    StringBuilder() {
    }

    StringBuilder append(string text) {
        _buffer.push_back(text);
        return *this;
    }

    StringBuilder insert(int index, string text) {
        _buffer.insert(_buffer.begin() + index, text);
        return *this;
    }

    int length() {
        return toString().length();
    }

    StringBuilder deleteCharAt(int index) {
        string str = toString();
        _buffer.clear();
        append(str.substr(0, index));
        return *this;
    }

    string toString() {
        string result("");
        for (vector<string>::const_iterator strIter = _buffer.begin(); strIter != _buffer.end(); strIter++) {
            result = result + *strIter;
        }
        return result;
    }
};

class MoneyToStr {
    public:
    MoneyToStr(string currency, string language, string pennies) {
        if (currency == "") {
            throw std::invalid_argument("currency is null");
        }
        if (language == "") {
            throw std::invalid_argument("language is null");
        }
        if (pennies == "") {
            throw std::invalid_argument("pennies is null");
        }
    }
};

int main(int argc, char *argv[]) {
    string amount = "123.25";
    string language = "ENG";
    string currency = "USD";
    string pennies = "TEXT";
    if (argc == 1) {
        cout << "Usage: MoneyToStr --amount=123.25 --language=rus|ukr|eng --currency=rur|uah|usd --pennies=text|number" << endl;
    }
    return 0;
}

Improve c++ version of thr converter


#include "gamescreen.hpp"
#include "ui/menu.hpp"
#include "ui/event.hpp"
#include "world.hpp"
#include "player.hpp"
#include "scenery.hpp"
namespace Space {

void GameScreen::handleEvent(UI::Event const &evt)
{
    switch (evt.type) {
    case UI::KeyDown:
    case UI::KeyUp:
        handleKey(evt.keyEvent());
        break;
    default:
        break;
    }
}

void GameScreen::handleKey(UI::KeyEvent const &evt)
{
    // bool state = evt.type == UI::KeyDown;
    switch (evt.key) {
    case UI::KEscape:
        setActive(new UI::Menu);
        break;
    case UI::KUp:

        break;
    case UI::KDown:
        break;
    case UI::KLeft:
        break;
    case UI::KRight:
        break;
    case UI::KSelect:
        break;
    default:
        break;
    }
}

void GameScreen::update(unsigned int ticks)
{
    if (!world_) {
        world_ = new World;

        player_ = new Player();
        world_->addThinker(player_);
        world_->setPlayer(player_);

        Scenery *s = new Scenery;
        s->radius = 32.0f;
        world_->addEntity(s);
    }
    world_->update(ticks);
}

void GameScreen::draw()
{
    glClear(GL_COLOR_BUFFER_BIT);
    world_->draw();
}

}

#include "gamescreen.hpp"
#include "ui/menu.hpp"
#include "ui/event.hpp"
#include "world.hpp"
#include "player.hpp"
#include "scenery.hpp"
namespace Space {

void GameScreen::handleEvent(UI::Event const &evt)
{
    switch (evt.type) {
    case UI::KeyDown:
    case UI::KeyUp:
        handleKey(evt.keyEvent());
        break;
    default:
        break;
    }
}

void GameScreen::handleKey(UI::KeyEvent const &evt)
{
    // bool state = evt.type == UI::KeyDown;
    switch (evt.key) {
    case UI::KEscape:
        setActive(new UI::Menu);
        break;
    case UI::KUp:

        break;
    case UI::KDown:
        break;
    case UI::KLeft:
        break;
    case UI::KRight:
        break;
    case UI::KSelect:
        break;
    default:
        break;
    }
}

void GameScreen::update(unsigned int ticks)
{
    if (!world_) {
        world_ = new World;

        Scenery *s = new Scenery;
        s->radius = 32.0f;
        world_->addEntity(s);

        player_ = new Player();
        world_->addThinker(player_);
        world_->setPlayer(player_);
    }
    world_->update(ticks);
}

void GameScreen::draw()
{
    glClear(GL_COLOR_BUFFER_BIT);
    world_->draw();
}

}

Change order of entities in space game


#include <bitcoin/utility/timed_section.hpp>

#include <bitcoin/utility/logger.hpp>

namespace libbitcoin {

timed_section::timed_section(
    const std::string& context, const std::string& section)
  : context_(context), section_(section)
{
    clock_gettime(CLOCK_REALTIME, &start_);
}

timed_section::~timed_section()
{
    log_debug(context_) << section_ << " " << std::fixed << elapsed();
}

double timed_section::elapsed() const
{
    timespec end;
    clock_gettime(CLOCK_REALTIME, &end);
    return 1e3 * (end.tv_sec - start_.tv_sec) +
        1e-6 * (end.tv_nsec - start_.tv_nsec);
}

} // namespace libbitcoin

#include <bitcoin/utility/timed_section.hpp>

#include <bitcoin/utility/logger.hpp>

#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#define CLOCK_REALTIME 0

void clock_gettime(int ign, struct timespec * ts)
{
    clock_serv_t cclock;
    mach_timespec_t mts;
    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
    clock_get_time(cclock, &mts);
    mach_port_deallocate(mach_task_self(), cclock);
    ts->tv_sec = mts.tv_sec;
    ts->tv_nsec = mts.tv_nsec;
}
#endif

namespace libbitcoin {

timed_section::timed_section(
    const std::string& context, const std::string& section)
  : context_(context), section_(section)
{
    clock_gettime(CLOCK_REALTIME, &start_);
}

timed_section::~timed_section()
{
    log_debug(context_) << section_ << " " << std::fixed << elapsed();
}

double timed_section::elapsed() const
{
    timespec end;
    clock_gettime(CLOCK_REALTIME, &end);
    return 1e3 * (end.tv_sec - start_.tv_sec) +
        1e-6 * (end.tv_nsec - start_.tv_nsec);
}

} // namespace libbitcoin

Fix Mac OS X compilation issue


// Copyright 2014-present Bill Fisher. All rights reserved.

#include "ofpx_jsonrpc.h"
#include "ofp/api/apiserver.h"

using namespace ofpx;
using ExitStatus = JsonRpc::ExitStatus;

const int STDIN = 0;
const int STDOUT = 1;

//-------//
// r u n //
//-------//

int JsonRpc::run(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv);
  setMaxOpenFiles();

  ofp::Driver driver;
  ofp::api::ApiServer server{&driver, STDIN, STDOUT};
  driver.run();

  return 0;
}

//-------------------------------//
// s e t M a x O p e n F i l e s //
//-------------------------------//

void JsonRpc::setMaxOpenFiles() {
  struct rlimit rlp{};

  if (::getrlimit(RLIMIT_NOFILE, &rlp) < 0) {
    ofp::log::error("getrlimit failed:", errno);
    return;
  }

  rlp.rlim_cur = 10000;

  if (::setrlimit(RLIMIT_NOFILE, &rlp) < 0) {
    ofp::log::error("setrlimit failed:", rlp.rlim_cur, errno);
    return;
  }

  ofp::log::info("Changed open file limit to", rlp.rlim_cur);
}

// Copyright 2014-present Bill Fisher. All rights reserved.

#include "ofpx_jsonrpc.h"
#include "ofp/api/apiserver.h"

using namespace ofpx;
using ExitStatus = JsonRpc::ExitStatus;

const int STDIN = 0;
const int STDOUT = 1;

//-------//
// r u n //
//-------//

int JsonRpc::run(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv);
  setMaxOpenFiles();

  ofp::Driver driver;
  ofp::api::ApiServer server{&driver, STDIN, STDOUT};
  driver.run();

  return 0;
}

//-------------------------------//
// s e t M a x O p e n F i l e s //
//-------------------------------//

void JsonRpc::setMaxOpenFiles() {
  struct rlimit rlp{};

  if (::getrlimit(RLIMIT_NOFILE, &rlp) < 0) {
    std::error_code err{errno, std::generic_category()};
    ofp::log::error("getrlimit failed for RLIMIT_NOFILE:", err);
    return;
  }

  rlp.rlim_cur = 1000;

  if (::setrlimit(RLIMIT_NOFILE, &rlp) < 0) {
    std::error_code err{errno, std::generic_category()};
    ofp::log::error("setrlimit failed for RLIMIT_NOFILE:", rlp.rlim_cur, err);
    return;
  }

  ofp::log::info("Changed open file limit to", rlp.rlim_cur);
}

Fix error logging for getrlimit and setrlimit.


#define CAT(X,Y)    CAT_(X,Y)
#define CAT_(X,Y)   X ## Y

#define COUNTSTRING(Stem,Val)                                                  \
    Stem:                                                                      \
    CAT(.L_,Stem):                                                             \
        .word (CAT(CAT(.L_,Stem),_end) - CAT(.L_,undefined_word) - 1) ;        \
        .utf32 Val                                                    ;        \
    .global Stem ;                                                             \
    CAT(CAT(.L_,Stem),_end):                                                   \
    //

COUNTSTRING(undefined_word, "undefined word")
COUNTSTRING(ok            , "ok"            )

.word 0

#define CAT(X,Y)    CAT_(X,Y)
#define CAT_(X,Y)   X ## Y

#define COUNTSTRING(Stem,Val)                                                  \
    Stem:                                                                      \
    CAT(.L_,Stem):                                                             \
        .word (CAT(CAT(.L_,Stem),_end) - CAT(.L_,Stem) - 1) ;                  \
        .utf32 Val                                          ;                  \
    .global Stem ;                                                             \
    CAT(CAT(.L_,Stem),_end):                                                   \
    //

COUNTSTRING(undefined_word, "undefined word")
COUNTSTRING(ok            , "ok"            )

.word 0

Mend bad macro in stringtable


#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <3ds.h>

#include "constants.h"
#include "patches.h"

#define log(...) fprintf(stderr, __VA_ARGS__)

int main(int argc, char** argv)
{
    gfxInitDefault();
    consoleInit(GFX_TOP, NULL);
    GetVersionConstants();
    PatchSrvAccess();

// ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper
    // svcBackdoor(PatchProcessWrapper);
    // log("[0x%08X] - Patched process\n", ret);

    // Main loop
    while (aptMainLoop())
    {
        hidScanInput();

        u32 kDown = hidKeysDown();
        if (kDown & KEY_START)
            break;
        gspWaitForVBlank();
    }

    gfxExit();
    return 0;
}

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <3ds.h>

#include "constants.h"
#include "patches.h"

#define log(...) fprintf(stderr, __VA_ARGS__)

int main(int argc, char** argv)
{
    gfxInitDefault();
    consoleInit(GFX_TOP, NULL);

    if (!GetVersionConstants()) {
        log("Warning, your platform is (either fully or partially) unsupported!\n");
    }

    PatchSrvAccess();

// ONLY UNCOMMENT AFTER CUSTOMIZING PatchProcessWrapper
    // svcBackdoor(PatchProcessWrapper);
    // log("[0x%08X] - Patched process\n", ret);

    // Main loop
    while (aptMainLoop())
    {
        hidScanInput();

        u32 kDown = hidKeysDown();
        if (kDown & KEY_START)
            break;
        gspWaitForVBlank();
    }

    gfxExit();
    return 0;
}

Add warning if not all platform-specific constants are known for a given platform.


// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-pch -o %t.1 %s
// RUN: %clang_cc1 -triple x86_64-linux-gnu -error-on-deserialized-decl S1_keyfunc -error-on-deserialized-decl S3 -include-pch %t.1 -emit-pch -o %t.2 %s
// RUN: %clang_cc1 -triple x86_64-linux-gnu -error-on-deserialized-decl S1_method -error-on-deserialized-decl S3 -include-pch %t.2 -emit-llvm-only %s

#ifndef HEADER1
#define HEADER1
// Header.

struct S1 {
  void S1_method();
  virtual void S1_keyfunc();
};

struct S3 {};

struct S2 {
  operator S3();
};

#elif !defined(HEADER2)
#define HEADER2

// Chained PCH.
S1 *s1;
S2 *s2;

#else

// Using the headers.

void test(S1*, S2*) {
}

#endif

// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-pch -o %t.1 %s
// RUN: %clang_cc1 -triple x86_64-linux-gnu -error-on-deserialized-decl S1_keyfunc -error-on-deserialized-decl S3 -include-pch %t.1 -emit-pch -o %t.2 %s
// RUN: %clang_cc1 -triple x86_64-linux-gnu -error-on-deserialized-decl S1_method -error-on-deserialized-decl S3 -include-pch %t.2 -emit-llvm-only %s

// FIXME: Why does this require an x86 target?
// REQUIRES: x86-registered-target

#ifndef HEADER1
#define HEADER1
// Header.

struct S1 {
  void S1_method();
  virtual void S1_keyfunc();
};

struct S3 {};

struct S2 {
  operator S3();
};

#elif !defined(HEADER2)
#define HEADER2

// Chained PCH.
S1 *s1;
S2 *s2;

#else

// Using the headers.

void test(S1*, S2*) {
}

#endif

Fix bots failing on an explicit triple


#include "library.h"

#include "libs/console.h" // console.log, console.error

namespace grok {
namespace libs {
using namespace grok::vm;
using namespace grok::obj;

int LoadLibraries(VMContext *ctx)
{
    // just console for now
    auto V = GetVStore(ctx);

    auto C = std::make_shared<Console>();
    auto Wrapped = Value(std::make_shared<Object>(C));
    V->StoreValue("console", Wrapped);

    return 0;
}

}
}

#include "library.h"

#include "libs/console.h" // console.log, console.error

namespace grok {
namespace libs {
using namespace grok::vm;
using namespace grok::obj;

int LoadLibraries(VMContext *ctx)
{
    // just console for now
    auto V = GetVStore(ctx);

    auto C = std::make_shared<Console>();
    DefineInternalObjectProperties(C.get());
    C->SetNonWritable();
    auto Wrapped = Value(std::make_shared<Object>(C));
    V->StoreValue("console", Wrapped);

    return 0;
}

}
}

Set Console object to non writable


#include "thread_cache.h"

#include "allocators/dq_sc_allocator.h"
#include "runtime_vars.h"

namespace {

cache_aligned SpinLock g_threadcache_lock(LINKER_INITIALIZED);
cache_aligned scalloc::PageHeapAllocator<scalloc::ThreadCache, 64> g_threadcache_alloc;
cache_aligned uint64_t g_thread_id;

}  // namespace

namespace scalloc {

void ThreadCache::InitModule() {
  SpinLockHolder holder(&g_threadcache_lock);
  CompilerBarrier();
  if(!module_init_) {
    RuntimeVars::InitModule();
    SlabScAllocator::InitModule();
    DQScAllocator::InitModule();

    g_threadcache_alloc.Init(RuntimeVars::SystemPageSize());

    module_init_  = true;
  }
}

ThreadCache* ThreadCache::NewCache() {
  ThreadCache* cache = NULL;
  {
    SpinLockHolder holder(&g_threadcache_lock);
    CompilerBarrier();
    cache = g_threadcache_alloc.New();
  }
  cache->allocator_.Init(__sync_fetch_and_add(&g_thread_id, 1));
  return cache;
}

}  // namespace scalloc

#include "thread_cache.h"

#include "allocators/dq_sc_allocator.h"
#include "runtime_vars.h"

namespace {

cache_aligned SpinLock g_threadcache_lock(LINKER_INITIALIZED);
cache_aligned scalloc::PageHeapAllocator<scalloc::ThreadCache, 64> g_threadcache_alloc;
cache_aligned uint64_t g_thread_id;

}  // namespace

namespace scalloc {

bool ThreadCache::module_init_;
__thread ThreadCache* ThreadCache::tl_cache_ TLS_MODE;

void ThreadCache::InitModule() {
  SpinLockHolder holder(&g_threadcache_lock);
  CompilerBarrier();
  if(!module_init_) {
    RuntimeVars::InitModule();
    SlabScAllocator::InitModule();
    DQScAllocator::InitModule();

    SizeMap::Instance().Init();

    g_threadcache_alloc.Init(RuntimeVars::SystemPageSize());

    module_init_  = true;
  }
}

ThreadCache* ThreadCache::NewCache() {
  ThreadCache* cache = NULL;
  {
    SpinLockHolder holder(&g_threadcache_lock);
    CompilerBarrier();
    cache = g_threadcache_alloc.New();
  }
  cache->allocator_.Init(__sync_fetch_and_add(&g_thread_id, 1));
  return cache;
}

}  // namespace scalloc

Fix missing symbols in thread cache.


#include "./test.h"
#include "../src/camera.h"

TEST(Test_Camera, ConstructorFromMatrices)
{
  Camera expected;

  Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(),
                expected.getOrigin());

  EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
  EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f);

  // just to recalculate the view matrix from the angles and test them
  camera.changeAzimuth(0);

  EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f);
}

#include "./test.h"
#include "../src/camera.h"

TEST(Test_Camera, ConstructorFromMatricesWithDefaultValues)
{
  Camera expected;

  Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(),
                expected.getOrigin());

  EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
  EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f);

  // just to recalculate the view matrix from the angles and test them
  camera.changeAzimuth(0);

  EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f);
  EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(),
                       camera.getProjectionMatrix(), 1e-5f);
  EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
}

TEST(Test_Camera, ConstructorFromMatricesAfterRotation)
{
  Camera expected;
  expected.changeAzimuth(M_PI * 0.25f);

  Camera camera(expected.getViewMatrix(), expected.getProjectionMatrix(),
                expected.getOrigin());

  EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
  EXPECT_NEAR(expected.getRadius(), camera.getRadius(), 1e-5f);

  // just to recalculate the view matrix from the angles and test them
  camera.changeAzimuth(0);

  EXPECT_Matrix4f_NEAR(expected.getViewMatrix(), camera.getViewMatrix(), 1e-5f);
  EXPECT_Matrix4f_NEAR(expected.getProjectionMatrix(),
                       camera.getProjectionMatrix(), 1e-5f);
  EXPECT_Vector3f_NEAR(expected.getPosition(), camera.getPosition(), 1e-5f);
}

Extend first camera test and add another one.


/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    if (0 == add) {
        return SkColorFilter::CreateModeFilter(mul | SK_ColorBLACK,
                                               SkXfermode::Mode::kModulate_Mode);
    }
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

Simplify LightingFilter in add-free case am: 0698300cc5


#include <QApplication>

#include "mainwindow.h"
#include "runguard.h"

int main(int argc, char **argv)
{
    RunGuard guard("UwNDcyZjc6MjE1tN2Ma3NGIf5OGx");

    if (!guard.tryToRun())
        return 0;

    QApplication a(argc, argv);
    MainWindow w;

    w.show();

    return a.exec();
}

#include <QApplication>

#include "mainwindow.h"
#include "runguard.h"

QString getUserName()
{
    QString name = qgetenv("USER");

    if (name.isEmpty())
        name = qgetenv("USERNAME");

    return name;
}

int main(int argc, char **argv)
{
    RunGuard guard(getUserName() + "-doer-UwNDcyZjc6MjE1tN2Ma3NGIf5OGx");

    if (!guard.tryToRun())
        return 0;

    QApplication a(argc, argv);
    MainWindow w;

    w.show();

    return a.exec();
}

Allow to run doer as a different user on the same machine


#include <iostream>
#include <cstdlib> // for RAND_MAX
#include <ctime>
using namespace std;

int main(int argc, char* argv[]) {
   const int LARGEST_POSSIBLE = 100;

   srand(time(0)); // seed the random number generator based on current time
   //srand(10);
   rand();
   // the rand() function generates a random integer from 0 to RAND_MAX
   int chosen = rand() % 101               ; // how to cut interval to [0, 100]?
   cout << "I choose the number " << chosen << "!" << endl;
   cout << "RAND_MAX is " << RAND_MAX << endl;
}

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

int main(int argc, char* argv[]) {
   const int LARGEST_POSSIBLE = 100;

   // Some of this will look funny for now; we will explain later.

   // A random_device helps to "seed" a number generator.
   random_device rd;
   // a compiler-chosen "good" random number generator.
   default_random_engine engine(rd());

   // Takes the output of the engine and maps it to a uniform distribution
   // between two parameters.
   uniform_int_distribution<int> distr(1, LARGEST_POSSIBLE);

   // Now "call" the distribution to get a number.
   int chosen = distr(engine);
   cout << "I choose the number " << chosen << "!" << endl;

   // Every time I call the distribution I get a new number.
   cout << "Next number: " << distr(engine) << endl;
   cout << "Next number: " << distr(engine) << endl;
}

Use C++11 <random> instead of C rand().


#include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(TestPage, StackAllocate) {
	Page p;
}

TEST(TestPage, mapOnePage) {
	Span<Page> pages{nullptr, 1};
	auto result = Page::map(pages);
	EXPECT_TRUE(result);
	EXPECT_NE(result(), nullptr);
	pages.value(result());
	EXPECT_EQ(Page::unmap(pages), 0);
}

TEST(TestPage, setPermissions) {
	Span<Page> pages{nullptr, 1};
}

TEST(TestPage, setPermissionsOnUnmappedPage) {
	Span<Page> pages{nullptr, 1};

	// Get a fresh page.
	{
		auto r = Page::map(pages);
		ASSERT_TRUE(r);
		pages.value(r());
	}

	// Explicitly unmap it.
	{
		auto e = Page::unmap(pages);
		ASSERT_EQ(e, 0);
	}

	// Fail to set permissions on unmapped page.
	{
		auto e = Page::setPermissions(pages, Page::Permissions::READ);
		ASSERT_NE(e, 0);
	}
}

#if 0
TEST(PageSpan, mapAndUnmap) {
	PageSpan pages{nullptr, 1};
	auto map = pages.map();
	map.unmap();
}
#endif  // 0

#include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(TestPage, stackAllocate) {
	[[maybe_unused]] Page p;
}

TEST(TestPage, mapOnePage) {
	Span<Page> pages{nullptr, 1};
	auto result = Page::map(pages);
	EXPECT_TRUE(result);
	EXPECT_NE(result(), nullptr);
	pages.value(result());
	EXPECT_EQ(Page::unmap(pages), 0);
}

TEST(TestPage, setPermissions) {
	Span<Page> pages{nullptr, 1};
}

TEST(TestPage, setPermissionsOnUnmappedPage) {
	Span<Page> pages{nullptr, 1};

	// Get a fresh page.
	{
		auto r = Page::map(pages);
		ASSERT_TRUE(r);
		pages.value(r());
	}

	// Explicitly unmap it.
	{
		auto e = Page::unmap(pages);
		ASSERT_EQ(e, 0);
	}

	// Fail to set permissions on unmapped page.
	{
		auto e = Page::setPermissions(pages, Page::Permissions::READ);
		ASSERT_NE(e, 0);
	}
}

#if 0
TEST(PageSpan, mapAndUnmap) {
	PageSpan pages{nullptr, 1};
	auto map = pages.map();
	map.unmap();
}
#endif  // 0

Mark stack allocated page as unused


//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_networking_sntp.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp =
{
    "nanoFramework.Networking.Sntp",
    0x733B4551,
    method_lookup,
    { 1, 0, 2, 49 }
};

//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_networking_sntp.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp =
{
    "nanoFramework.Networking.Sntp",
    0x733B4551,
    method_lookup,
    { 1, 0, 2, 2 }
};

Update nanoFramework.Networking.Sntp version to 1.0.2 ***NO_CI***


/**
 * Zillians MMO
 * Copyright (C) 2007-2010 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "language/logging/LoggerWrapper.h"
#include "language/ThorScriptVM.h"

int main(int argc, char** argv)
{
	zillians::language::ThorScriptVM vm;
	return vm.main(argc, argv);
}

/**
 * Zillians MMO
 * Copyright (C) 2007-2010 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "language/logging/LoggerWrapper.h"
#include "language/ThorScriptVM.h"

int main(int argc, const char** argv)
{
	zillians::language::ThorScriptVM vm;
	return vm.main(argc, argv);
}

Fix warning: convert from char** to const char**


#include "Halide.h"
#include <stdio.h>
#include <thread>

using namespace Halide;

int main(int argc, char **argv) {
    // Test if the compiler itself is thread-safe. This test is
    // intended to be run in a thread-sanitizer.
    std::vector<std::thread> threads;
    for (int i = 0; i < 1000; i++) {
        threads.emplace_back([]{
            Func f;
            Var x;
            f(x) = x;
            f.realize(100);
        });
    }

    for (auto &t : threads) {
        t.join();
    }

    printf("Success!\n");

    return 0;
}

#include "Halide.h"
#include <stdio.h>
#include <future>

using namespace Halide;

static std::atomic<int> foo;

int main(int argc, char **argv) {
    // Test if the compiler itself is thread-safe. This test is
    // intended to be run in a thread-sanitizer.
    std::vector<std::future<void>> futures;
    for (int i = 0; i < 1000; i++) {
        futures.emplace_back(std::async(std::launch::async, []{
            Func f;
            Var x;
            f(x) = x;
            f.realize(100);
        }));
    }

    for (auto &f : futures) {
        f.wait();
    }

    printf("Success!\n");

    return 0;
}

Use std::async() instead of std::thread()


/*
 * ty, a collection of GUI and command-line tools to manage Teensy devices
 *
 * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT)
 * Copyright (c) 2015 Niels Martignène <niels.martignene@gmail.com>
 */

#include <QSettings>

#include "database.hh"

using namespace std;

void SettingsDatabase::put(const QString &key, const QVariant &value)
{
    if (!settings_)
        return;

    settings_->setValue(key, value);
}

void SettingsDatabase::remove(const QString &key)
{
    if (!settings_)
        return;

    settings_->remove(key);
}

QVariant SettingsDatabase::get(const QString &key, const QVariant &default_value) const
{
    if (!settings_)
        return default_value;

    return settings_->value(key, default_value);
}

void SettingsDatabase::clear()
{
    if (!settings_)
        return;

    settings_->clear();
}

/*
 * ty, a collection of GUI and command-line tools to manage Teensy devices
 *
 * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT)
 * Copyright (c) 2015 Niels Martignène <niels.martignene@gmail.com>
 */

#include <QSettings>

#include "database.hh"

using namespace std;

void SettingsDatabase::put(const QString &key, const QVariant &value)
{
    settings_->setValue(key, value);
}

void SettingsDatabase::remove(const QString &key)
{
    settings_->remove(key);
}

QVariant SettingsDatabase::get(const QString &key, const QVariant &default_value) const
{
    return settings_->value(key, default_value);
}

void SettingsDatabase::clear()
{
    settings_->clear();
}

Remove 'useless' checks from SettingsDatabase


#include "MainWindow.h"

#include <Application.h>
#include <Menu.h>
#include <MenuItem.h>
#include <View.h>

#include "MainView.h"

MainWindow::MainWindow(void)
	:	BWindow(BRect(100,100,500,400),"Font Demo", B_TITLED_WINDOW,
					B_ASYNCHRONOUS_CONTROLS)
{
	BRect r(Bounds());
	r.bottom = 20;
	fMenuBar = new BMenuBar(r,"menubar");
	AddChild(fMenuBar);
	r = Bounds();
	r.top = 20;
	MainView *view = new MainView(r);
	AddChild(view);
}
void
MainWindow::MessageReceived(BMessage *msg)
{
	switch (msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool
MainWindow::QuitRequested(void)
{
	be_app->PostMessage(B_QUIT_REQUESTED);
	return true;
}

#include "MainWindow.h"

#include <Application.h>
#include <Menu.h>
#include <MenuItem.h>
#include <View.h>

#include "MainView.h"

MainWindow::MainWindow(void)
	:	BWindow(BRect(100, 100, 900, 550),"Font Demo", B_TITLED_WINDOW,
					B_ASYNCHRONOUS_CONTROLS)
{
	BRect r(Bounds());
	r.bottom = 20;
	fMenuBar = new BMenuBar(r,"menubar");
	AddChild(fMenuBar);
	r = Bounds();
	r.top = 20;
	MainView *view = new MainView(r);
	AddChild(view);
}
void
MainWindow::MessageReceived(BMessage *msg)
{
	switch (msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool
MainWindow::QuitRequested(void)
{
	be_app->PostMessage(B_QUIT_REQUESTED);
	return true;
}

Make the initial window size larger to see all text


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cc/blink/web_external_bitmap_impl.h"

#include "cc/resources/shared_bitmap.h"

namespace cc_blink {

namespace {

SharedBitmapAllocationFunction g_memory_allocator;

}  // namespace

void SetSharedBitmapAllocationFunction(
    SharedBitmapAllocationFunction allocator) {
  g_memory_allocator = allocator;
}

WebExternalBitmapImpl::WebExternalBitmapImpl() {
}

WebExternalBitmapImpl::~WebExternalBitmapImpl() {
}

void WebExternalBitmapImpl::setSize(blink::WebSize size) {
  if (size != size_) {
    shared_bitmap_ = g_memory_allocator(gfx::Size(size));
    size_ = size;
  }
}

blink::WebSize WebExternalBitmapImpl::size() {
  return size_;
}

uint8* WebExternalBitmapImpl::pixels() {
  return shared_bitmap_->pixels();
}

}  // namespace cc_blink

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cc/blink/web_external_bitmap_impl.h"

#include "cc/resources/shared_bitmap.h"

namespace cc_blink {

namespace {

SharedBitmapAllocationFunction g_memory_allocator;

}  // namespace

void SetSharedBitmapAllocationFunction(
    SharedBitmapAllocationFunction allocator) {
  g_memory_allocator = allocator;
}

WebExternalBitmapImpl::WebExternalBitmapImpl() {
}

WebExternalBitmapImpl::~WebExternalBitmapImpl() {
}

void WebExternalBitmapImpl::setSize(blink::WebSize size) {
  if (size != size_) {
    shared_bitmap_ = g_memory_allocator(gfx::Size(size));
    size_ = size;
  }
}

blink::WebSize WebExternalBitmapImpl::size() {
  return size_;
}

uint8* WebExternalBitmapImpl::pixels() {
  if (!shared_bitmap_) {
    // crbug.com/520417: not sure why a non-null WebExternalBitmap is
    // being passed to prepareMailbox when the shared_bitmap_ is null.
    // Best hypothesis is that the bitmap is zero-sized.
    DCHECK(size_.isEmpty());
    return nullptr;
  }
  return shared_bitmap_->pixels();
}

}  // namespace cc_blink

Add null check in WebExternalBitmapImpl::pixels.


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t s) {
  return HeapAlloc(win_heap, 0, s);
}

void* win_heap_realloc(void* p, size_t s) {
  if (!p)
    return win_heap_malloc(s);
  return HeapReAlloc(win_heap, 0, p, s);
}

void win_heap_free(void* s) {
  HeapFree(win_heap, 0, s);
}

size_t win_heap_msize(void* p) {
  return HeapSize(win_heap, 0, p);
}

}  // extern "C"

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t size) {
  return HeapAlloc(win_heap, 0, size);
}

void win_heap_free(void* size) {
  HeapFree(win_heap, 0, size);
}

void* win_heap_realloc(void* ptr, size_t size) {
  if (!ptr)
    return win_heap_malloc(size);
  if (!size) {
    win_heap_free(ptr);
    return NULL;
  }
  return HeapReAlloc(win_heap, 0, ptr, size);
}

size_t win_heap_msize(void* ptr) {
  return HeapSize(win_heap, 0, ptr);
}

}  // extern "C"


#include "yugong.hpp"

#include <cstdint>
#include <cstdlib>

namespace yg {

    void YGStack::alloc(YGStack &stack, uintptr_t size) {
        void *mem = std::malloc(size);
        uintptr_t start = (uintptr_t)mem;

        stack.start = start;
        stack.size = size;
        stack.sp = start + size;
    }

    void YGStack::free(YGStack &stack) {
        void *mem = (void*)stack.start;
        std::free(mem);
    }

    void ll::push_initial_frame(YGStack &stack, FuncPtr func) {
        uintptr_t *stack_bottom = (uintptr_t*)(stack.start + stack.size);
        stack_bottom[-1] = 0;
        stack_bottom[-2] = (uintptr_t)func;
        stack_bottom[-3] = (uintptr_t)_yg_func_begin_resume;
        stack.sp = (uintptr_t)(&stack_bottom[-3]);
    }

}

#include "yugong.hpp"

#include <cstdint>
#include <cstdlib>

namespace yg {

    void YGStack::alloc(YGStack &stack, uintptr_t size) {
        void *mem = std::malloc(size);
        uintptr_t start = reinterpret_cast<uintptr_t>(mem);

        stack.start = start;
        stack.size = size;
        stack.sp = start + size;
    }

    void YGStack::free(YGStack &stack) {
        void *mem = reinterpret_cast<void*>(stack.start);
        std::free(mem);
    }

    void ll::push_initial_frame(YGStack &stack, FuncPtr func) {
        uintptr_t *stack_bottom = reinterpret_cast<uintptr_t*>(stack.start + stack.size);
        stack_bottom[-1] = 0;
        stack_bottom[-2] = reinterpret_cast<uintptr_t>(func);
        stack_bottom[-3] = reinterpret_cast<uintptr_t>(_yg_func_begin_resume);
        stack.sp         = reinterpret_cast<uintptr_t>(&stack_bottom[-3]);
    }

}

Use C++-style reinterpret_cast when possible.


#define BOOST_TEST_MODULE rainback
#include "init.hpp"

#include <QApplication>

struct QApplicationFixture
{
    int argc;
    char name[100];
    char* argv[1];

    QApplication* app;
public:
    QApplicationFixture() :
        argc(1)
    {
        strcpy(name, "rainback");
        argv[0] = name;
        app = new QApplication(argc, argv);
    }

    ~QApplicationFixture()
    {
        delete app;
    }
};

BOOST_GLOBAL_FIXTURE(QApplicationFixture);

// vim: set ts=4 sw=4 :

#define BOOST_TEST_MODULE rainback
#include "init.hpp"

#include <QCoreApplication>

struct QApplicationFixture
{
    int argc;
    char name[100];
    char* argv[1];

    QCoreApplication* app;
public:
    QApplicationFixture() :
        argc(1)
    {
        strcpy(name, "rainback");
        argv[0] = name;
        app = new QCoreApplication(argc, argv);
    }

    ~QApplicationFixture()
    {
        delete app;
    }
};

BOOST_GLOBAL_FIXTURE(QApplicationFixture);

// vim: set ts=4 sw=4 :

Make the test fixture use QApplication


// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify -fshort-wchar %s

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

// RUN: %clang -fsyntax-only -verify %s
// RUN: %clang -fsyntax-only -verify -fshort-wchar %s

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

Fix test on MSVC: since the test includes a system header it cannot use clang_cc1.


#include <libclientserver.h>

Thread::Thread()
{
	m_IsRunning = false;
	m_IsDetached = false;
}

Thread::~Thread()
{
	if (IsRunning())
		Stop();

}

void Thread::Start()
{
	m_IsRunning = true;
	if (pthread_create(&m_thread, NULL, RunInternal, this) != 0)
		abort();
}

void Thread::Stop()
{
#ifdef DEBUG
	if (IsDetached() == true)
		abort();

	if (m_IsRunning == false)
	{
		abort();	//Attempted to stop an already stopped thread
	}
#endif
	if (pthread_join(m_thread, NULL) != 0)
		abort();
}

void Thread::Detach()
{
	if (pthread_detach(m_thread) != 0)
		abort();
	m_IsDetached = true;
}

bool Thread::IsRunning()
{
	return m_IsRunning;
}

bool Thread::IsDetached()
{
	return m_IsDetached;
}

void Thread::Run()
{
	abort();	//You should override this function
}

void *Thread::RunInternal(void *ptr)
{
	class Thread *self = (Thread *) ptr;
	self->Run();
	return NULL;
}

#include <libclientserver.h>

Thread::Thread()
{
	m_IsRunning = false;
	m_IsDetached = false;
}

Thread::~Thread()
{
	if (IsRunning())
		Stop();

}

void Thread::Start()
{
	m_IsRunning = true;
	if (pthread_create(&m_thread, NULL, RunInternal, this) != 0)
		abort();
}

void Thread::Stop()
{
#ifdef DEBUG
	if (IsDetached() == true)
		abort();

	if (m_IsRunning == false)
	{
		abort();	//Attempted to stop an already stopped thread
	}
#endif
	if (pthread_join(m_thread, NULL) != 0)
		abort();
	m_IsRunning = false;
}

void Thread::Detach()
{
	if (pthread_detach(m_thread) != 0)
		abort();
	m_IsDetached = true;
}

bool Thread::IsRunning()
{
	return m_IsRunning;
}

bool Thread::IsDetached()
{
	return m_IsDetached;
}

void Thread::Run()
{
	abort();	//You should override this function
}

void *Thread::RunInternal(void *ptr)
{
	class Thread *self = (Thread *) ptr;
	self->Run();
	return NULL;
}

Fix State Tracking when thread stops


#include "hotkey.h"
#include "ui_hotkey.h"

hotkey::hotkey(QWidget *parent) :
    s(s),
    QWidget(parent),
    ui(new Ui::hotkey)
{
    ui->setupUi(this);
}

hotkey::~hotkey()
{
    delete ui;
}

void hotkey::keyPressEvent(QKeyEvent *event)
{
    int uKey = event->key();
    Qt::Key key = static_cast<Qt::Key>(uKey);
    if(key == Qt::Key_unknown)
    {
       return;
    }
    if(key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Alt )
    {
        return ;
    }
    Qt::KeyboardModifiers modifiers = event->modifiers();
    if(modifiers & Qt::ShiftModifier)
        uKey += Qt::SHIFT;
    if(modifiers & Qt::ControlModifier)
        uKey += Qt::CTRL;
    if(modifiers & Qt::AltModifier)
        uKey += Qt::ALT;
    ui->label_2->setText(QKeySequence(uKey).toString());
    this->s->setText(QKeySequence(uKey).toString());
}

void hotkey::keyReleaseEvent(QKeyEvent *event)
{
    this->~hotkey();
}

#include "hotkey.h"
#include "ui_hotkey.h"

hotkey::hotkey(QWidget *parent) :
    s(s),
    QWidget(parent),
    ui(new Ui::hotkey)
{
    ui->setupUi(this);
}

hotkey::~hotkey()
{
    delete ui;
}

void hotkey::keyPressEvent(QKeyEvent *event)
{
    int uKey = event->key();
    Qt::Key key = static_cast<Qt::Key>(uKey);
    if(key == Qt::Key_unknown)
    {
       return;
    }
    if(key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Alt || key == Qt::Key_Meta)
    {
        return ;
    }
    Qt::KeyboardModifiers modifiers = event->modifiers();
    if(modifiers & Qt::ShiftModifier)
        uKey += Qt::SHIFT;
    if(modifiers & Qt::ControlModifier)
        uKey += Qt::CTRL;
    if(modifiers & Qt::AltModifier)
        uKey += Qt::ALT;
    if(modifiers & Qt::MetaModifier)
        uKey += Qt::META;
    ui->label_2->setText(QKeySequence(uKey).toString());
    this->s->setText(QKeySequence(uKey).toString());
}

void hotkey::keyReleaseEvent(QKeyEvent *event)
{
    this->~hotkey();
}

Allow meta key to be shortcut assigned


#include "box.hpp"

Box::Box(): // default constructor
        min_{0.0, 0.0, 0.0},
        max_{0.0, 0.0, 0.0}
        {}

Box::Box(Box const& b): // copy constructor
        min_{b.min_},
        max_{b.max_}
        {}

Box::Box(Box&& b): // move constructor
        Box()
        {
                swap(*this, b);
        }

Box::Box(glm::vec3 const& min, glm::vec3 const& max):
        min_{min},
        max_{max}
        {}

void Box::swap(Box & b1, Box & b2) {
        std::swap(b1.min_, b2.min_);
        std::swap(b1.max_, b2.max_);
}

glm::vec3 Box::getMin() const {
        return min_;
}

glm::vec3 Box::getMax() const {
        return max_;
}

/* virtual */ double area() const {
        return 0.0;
}

/* virtual */ double volume() const {
        return 0.0;
}

Add dummy area and volume methods.


/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2012 Sandro Santilli <strk@keybit.net>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/util/Interrupt.h>
#include <geos/util/GEOSException.h> // for inheritance

namespace geos {
namespace util { // geos::util

class GEOS_DLL InterruptedException: public GEOSException {
public:
	InterruptedException() :
		GEOSException("InterruptedException", "Interrupted!") {}
};

void
Interrupt::interrupt() { throw InterruptedException(); }

bool Interrupt::requested = false;
Interrupt::Callback *Interrupt::callback = 0;
void *Interrupt::callback_arg = 0;

} // namespace geos::util
} // namespace geos

/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2012 Sandro Santilli <strk@keybit.net>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/util/Interrupt.h>
#include <geos/util/GEOSException.h> // for inheritance

namespace geos {
namespace util { // geos::util

class GEOS_DLL InterruptedException: public GEOSException {
public:
	InterruptedException() :
		GEOSException("InterruptedException", "Interrupted!") {}
};

void
Interrupt::interrupt() {
  requested = false;
  throw InterruptedException();
}

bool Interrupt::requested = false;
Interrupt::Callback *Interrupt::callback = 0;
void *Interrupt::callback_arg = 0;

} // namespace geos::util
} // namespace geos

Clear interruption request flag just before interrupting


#include <X11/keysym.h>

#include "grid.hpp"
#include "thumbnail_manager.hpp"
#include "x_connection.hpp"
#include "x_client_chooser.hpp"
#include "x_client_thumbnail_gl.hpp"

int main(int argc, char ** argv)
{
  xcb_keysym_t east_key = XK_l;
  xcb_keysym_t west_key = XK_h;
  xcb_keysym_t north_key = XK_k;
  xcb_keysym_t south_key = XK_j;
  xcb_keysym_t quit_key = XK_Escape;
  xcb_keysym_t action_key = XK_Tab;
  xcb_mod_mask_t mod = XCB_MOD_MASK_1;

  x_connection c;

  grid_t grid;

  x_client_thumbnail::factory factory;

  thumbnail_manager tm(c, &grid, &factory);
  x_client_chooser cp(c, &tm,
                      east_key, west_key, north_key, south_key,
                      quit_key, action_key, mod);

  c.run_event_loop();

  return 0;
}

#include <signal.h>
#include <X11/keysym.h>

#include "grid.hpp"
#include "thumbnail_manager.hpp"
#include "x_connection.hpp"
#include "x_client_chooser.hpp"
#include "x_client_thumbnail_gl.hpp"

x_event_source_t * g_event_source = NULL;

void sig_handler(int signum)
{
  if (g_event_source) g_event_source->shutdown();
}

int main(int argc, char ** argv)
{
  xcb_keysym_t east_key = XK_l;
  xcb_keysym_t west_key = XK_h;
  xcb_keysym_t north_key = XK_k;
  xcb_keysym_t south_key = XK_j;
  xcb_keysym_t quit_key = XK_Escape;
  xcb_keysym_t action_key = XK_Tab;
  xcb_mod_mask_t mod = XCB_MOD_MASK_1;

  x_connection c;
  g_event_source = &c;

  signal(SIGINT,  sig_handler);
  signal(SIGTERM, sig_handler);

  grid_t grid;

  x_client_thumbnail::factory factory;

  thumbnail_manager tm(c, &grid, &factory);
  x_client_chooser cp(c, &tm,
                      east_key, west_key, north_key, south_key,
                      quit_key, action_key, mod);

  c.run_event_loop();

  return 0;
}

Implement a simple signal handler


// Solution to the TwoSum problem from LeetCode
#include "two_sum.h"

TwoSum::TwoSum() {

}

vector<int> TwoSum::solver(vector<int>& nums, int target) {
  for(int i=0; i<nums.size(); i++) {
    for(int j=0; j<nums.size(); j++) {
      int value = nums[i] + nums[j];

      if ((value == target) && (i != j)) { // Return if value equals target
        vector<int> return_vector = {i,j};
        return return_vector;
      }
    }
  }
  return {-1, -1};
}

// Run Basic test cases on solver
bool TwoSum::test_case() {
  vector<int> test_vector = {3,2,4};
  vector<int> result = solver(test_vector, 6);
  if (result[0] == 1 && result[1] == 2)
    return true;
  else
    return false;
}

// Solution to the TwoSum problem from LeetCode
#include "two_sum.h"

TwoSum::TwoSum() {

}

vector<int> TwoSum::solver(vector<int>& nums, int target) {
  for(int i=0; i<nums.size(); i++) {
    for(int j=0; j<nums.size(); j++) {
      int sum = nums[i] + nums[j];

      if ((sum == target) && (i != j)) { // Return if sum equals target
        vector<int> return_vector = {i,j};
        return return_vector;
      }
    }
  }
  return {-1, -1};
}

// Run Basic test cases on solver
bool TwoSum::test_case() {
  vector<int> test_vector = {3,2,4};
  vector<int> result = solver(test_vector, 6);
  if (result[0] == 1 && result[1] == 2)
    return true;
  else
    return false;
}

Rename variable value to sum


// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp $(which clang-check) %t/mock-libcxx/bin/
// RUN: cp "%s" "%t/test.cpp"
// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++

#include <mock_vector>
vector v;

// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp $(which clang-check) %t/mock-libcxx/bin/
// RUN: cp "%s" "%t/test.cpp"
// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin

#include <mock_vector>
vector v;

Set '-target' flag in the test checking the MacOS include dir