// We need our declaration
#include "../../include/Utils/Dump.hpp"

namespace Utils
{
    // Produce a nice hexdump of the given byte array
    void hexDump(Strings::FastString & out, const uint8 * const array, const uint32 length, const uint32 colSize, const bool withAddress, const bool withCharVal)
    {
        uint32 i = 0;
        for (; i < length; i++)
        {
            if ((i % colSize) == 0)
            {
                // Output the charVal if any present
                if (withCharVal && i)
                {
                    out += " ";
                    for (uint32 j = i - colSize; j < i; j++)
                    {
                        out += Strings::FastString::Print("%c", array[j] < 32 ? '.' : array[j]);
                    }
                }

                out += "\n";
                if (withAddress)
                    out += Strings::FastString::Print("%08X ", i);

            }
            out += Strings::FastString::Print("%02X ", (unsigned int)array[i]);
        }
        // Output the charVal if any present
        if (withCharVal && i)
        {
            for (uint32 k = 0; k < colSize - (i % colSize); k++)
                out += "   ";

            out += " ";
            for (uint32 j = i - colSize; j < i; j++)
            {
                out += Strings::FastString::Print("%c", array[j] < 32 ? '.' : array[j]);
            }
        }
    }
}

Add missing file preventing compilation

Add missing file preventing compilation


/*
* Session Tickets
* (C) 2012 Jack Lloyd
*
* Released under the terms of the Botan license
*/

#include <botan/internal/tls_messages.h>
#include <botan/internal/tls_extensions.h>
#include <botan/internal/tls_reader.h>
#include <botan/tls_record.h>
#include <botan/loadstor.h>

namespace Botan {

namespace TLS {

New_Session_Ticket::New_Session_Ticket(const MemoryRegion<byte>& buf) :
   m_ticket_lifetime_hint(0)
   {
   if(buf.size() >= 4)
      {
      m_ticket_lifetime_hint = load_be<u32bit>(&buf[0], 0);
      m_ticket.resize(buf.size() - 4);
      copy_mem(&m_ticket[0], &buf[4], buf.size() - 4);
      }
   }

MemoryVector<byte> New_Session_Ticket::serialize() const
   {
   MemoryVector<byte> buf(4 + m_ticket.size());
   store_be(m_ticket_lifetime_hint, &buf[0]);
   copy_mem(&buf[4], &m_ticket[0], m_ticket.size());
   return buf;
   }

}

}

Add missing source file for New_Session_Ticket msg


/**
 * Convert Sorted Array to Binary Search Tree
 *
 * cpselvis(cpselvis@gmail.com)
 * September 25th, 2016
 */
#include<iostream>
#include<vector>

using namespace std;

struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
 public:
   TreeNode* sortedArrayToBST(vector<int>& nums) {
     return dfs(nums, 0, nums.size());
   }
   TreeNode* dfs(vector<int> &nums, int left, int right)
   {
     if (left > right)
     {
       return NULL;
     }
     int mid = (left + right) >> 1;

     TreeNode *node = new TreeNode(nums[mid]);

     node -> left = dfs(nums, left, mid - 1);
     node -> right = dfs(nums, mid + 1, right);
     return node;
   }
 };

int main(int argc, char **argv)
{
  Solution s;
  vector<int> vec({1, 2, 4, 5, 6 ,7 , 8});
  s.sortedArrayToBST(vec);
}

Convert Sorted Array to Binary Search Tree.


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

using namespace jogurt;

NUMERIC_TEST_CASE("2D vector addition", "[vec2]")
{
    vec2<T> v0 = {  1, 10 };
    vec2<T> v1 = { 20,  2 };
    vec2<T> v2 = {  4, 40 };

    SECTION("Zero is the neutral element")
    {
        REQUIRE(v0 + zero2<T>() == v0);
        REQUIRE(v1 + zero2<T>() == v1);
        REQUIRE(v0 - zero2<T>() == v0);
        REQUIRE(v1 - zero2<T>() == v1);
    }

    SECTION("Is comutative")
    {
        REQUIRE(v0 + v1 == v1 + v0);
        REQUIRE(v0 - v1 == -(v1 - v0));
    }

    SECTION("Is associative")
    {
        REQUIRE((v0 + v1) + v2 == v0 + (v1 + v2));
    }

    SECTION("Subtracting is adding the opposite")
    {
        REQUIRE(v0 - v1 == v0 + (-v1));
        REQUIRE(v1 - v0 == v1 + (-v0));
    }

    SECTION("Addition is distributive over multiplication")
    {
        REQUIRE(2 * (v0 + v1) == 2 * v0 + 2 * v1);
        REQUIRE(3 * (v1 - v2) == 3 * v1 - 3 * v2);
    }
}

Add simple vec2 addition test case

Add simple vec2 addition test case

Probably incomplete. Just there to get a foothold.


/*
 * https://leetcode.com/problems/find-the-difference/
 * Given two strings s and t which consist of only lowercase letters.
 * String t is generated by random shuffling string s and then add one more letter at a random position.
 * Find the letter that was added in t.
 Example:
 Input:
  s = "abcd"
  t = "abcde"
 Output:
  e
 Explanation:
  'e' is the letter that was added.
 */

class Solution {
public:
    char findTheDifference(string s, string t) {
        map<char, int> hash;
        for(int i = 0; i < t.size(); i++) {
            hash[t[i]] = (hash.count(t[i]) == 0) ? 1 : hash[t[i]] + 1;
        }

        for(int i = 0; i < s.size(); i++) {
            hash[s[i]] -= 1;
        }
        char res;
        for_each(begin(hash), end(hash), [&res](std::map<char, int>::reference element) {
            if(element.second == 1)
                res = element.first;
        });
        return res;
    }
};

Add solution 389. Find the Difference

Add solution 389. Find the Difference


/**
 * @file   main.cpp
 * @brief  Tester project entry-point.
 * @author zer0
 * @date   2016-11-01
 */

#include <gtest/gtest.h>

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

Create gtest entry-point in tester project.


class Solution {
public:
    vector<int> sortEvenOdd(vector<int>& nums) {
        if (nums.empty()) return nums;
        std::vector<int> odd, even;
        for (int i = 0; i < nums.size(); ++i) {
            if (i % 2 == 0) {
                even.emplace_back(nums[i]);
            } else {
                odd.emplace_back(nums[i]);
            }
        }
        std::sort(even.begin(), even.end());
        std::sort(odd.begin(), odd.end(), [](int i, int j){
            return i > j;
        });
        for (int i = 0; i < even.size(); ++i) {
            nums[i*2] = even[i];
            if ((i*2+1) < nums.size())
                nums[i*2+1] = odd[i];
        }
        return nums;
    }
};

Sort Even and Odd Indices Independently

Sort Even and Odd Indices Independently


#define FASTLED_INTERNAL
#include "FastLED.h"

/// Simplified form of bits rotating function.  Based on code found here - http://www.hackersdelight.org/hdcodetxt/transpose8.c.txt - rotating
/// data into LSB for a faster write (the code using this data can happily walk the array backwards)
void transpose8x1_noinline(unsigned char *A, unsigned char *B) {
  uint32_t x, y, t;

  // Load the array and pack it into x and y.
  y = *(unsigned int*)(A);
  x = *(unsigned int*)(A+4);

  // pre-transform x
  t = (x ^ (x >> 7)) & 0x00AA00AA;  x = x ^ t ^ (t << 7);
  t = (x ^ (x >>14)) & 0x0000CCCC;  x = x ^ t ^ (t <<14);

  // pre-transform y
  t = (y ^ (y >> 7)) & 0x00AA00AA;  y = y ^ t ^ (t << 7);
  t = (y ^ (y >>14)) & 0x0000CCCC;  y = y ^ t ^ (t <<14);

  // final transform
  t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
  y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
  x = t;

  *((uint32_t*)B) = y;
  *((uint32_t*)(B+4)) = x;
}

Tweak 4-way parallel output to work on pins 12-15 on esp8266 - keep blocked out for now, needs some more testing.


/** \file    xml_parser_test.cc
 *  \brief   Tests the FileUtil::GetFileName() function.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2015, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <stdexcept>
#include "FileUtil.h"
#include "util.h"

__attribute__((noreturn)) void Usage() {
    std::cerr << "usage: " << ::progname << " path\n";
    std::exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    ::progname = argv[0];
    if (argc != 2)
	Usage();

    try {
	FILE *file(std::fopen(argv[1], "r"));
	std::cout << "File pointer points to \"" << FileUtil::GetFileName(file) << "\".\n";
    } catch(const std::exception &x) {
	Error("caught exception: " + std::string(x.what()));
    }
}

Test for the new FileUtil::GetFileName() functions.


//===--- ProtocolConformance.cpp - AST Protocol Conformance -----*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the protocol conformance data structures.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/ProtocolConformance.h"
using namespace swift;

void *ProtocolConformance::operator new(size_t bytes, ASTContext &context,
                                        unsigned alignment) {
  return context.Allocate(bytes, alignment);

}

#define CONFORMANCE_SUBCLASS_DISPATCH(Method, Args)                        \
switch (getKind()) {                                                       \
  case ProtocolConformanceKind::Normal:                                    \
    static_assert(&ProtocolConformance::Method !=                          \
                    &NormalProtocolConformance::Method,                    \
                  "Must override NormalProtocolConformance::" #Method);    \
    return cast<NormalProtocolConformance>(this)->Method Args;             \
  case ProtocolConformanceKind::Specialized:                               \
    static_assert(&ProtocolConformance::Method !=                          \
                    &InheritedProtocolConformance::Method,                 \
                  "Must override InheritedProtocolConformance::" #Method); \
    return cast<SpecializedProtocolConformance>(this)->Method Args;        \
  case ProtocolConformanceKind::Inherited:                                 \
    static_assert(&ProtocolConformance::Method !=                          \
                    &InheritedProtocolConformance::Method,                 \
                  "Must override InheritedProtocolConformance::" #Method); \
    return cast<InheritedProtocolConformance>(this)->Method Args;          \
}

/// Get the protocol being conformed to.
ProtocolDecl *ProtocolConformance::getProtocol() const {
  CONFORMANCE_SUBCLASS_DISPATCH(getProtocol, ())
}

/// Get the module that contains the conforming extension or type declaration.
Module *ProtocolConformance::getContainingModule() const {
  CONFORMANCE_SUBCLASS_DISPATCH(getContainingModule, ())
}

/// Retrieve the complete set of type witnesses.
const TypeWitnessMap &ProtocolConformance::getTypeWitnesses() const {
  CONFORMANCE_SUBCLASS_DISPATCH(getTypeWitnesses, ())
}

const WitnessMap &ProtocolConformance::getWitnesses() const {
  CONFORMANCE_SUBCLASS_DISPATCH(getWitnesses, ())
}

const InheritedConformanceMap &
ProtocolConformance::getInheritedConformances() const {
  CONFORMANCE_SUBCLASS_DISPATCH(getInheritedConformances, ())
}

/// Determine whether the witness for the given requirement
/// is either the default definition or was otherwise deduced.
bool ProtocolConformance::usesDefaultDefinition(ValueDecl *requirement) const {
  CONFORMANCE_SUBCLASS_DISPATCH(usesDefaultDefinition, (requirement))
}

Add missing file from prior commit.

Add missing file from prior commit.

Swift SVN r6866


#include <iostream>

#include "node.h"
#include "car.h"

using namespace traffic;

int main(int argc, char* argv[])
{
    std::shared_ptr<Node> Rochester (new Node);
    std::shared_ptr<Node> Buffalo (new Node);

    Node::LinkNeighbors(Rochester, Buffalo, 60.0);

    std::cout << Rochester->GetDistanceFrom(Buffalo) << std::endl;

    return 0;
}

Add test file with main method

Add test file with main method


#include <atomic>
extern "C" {
#if 0
}
#endif

const std::memory_order mo_rlx = std::memory_order_relaxed;
const std::memory_order mo_rel = std::memory_order_release;
const std::memory_order mo_acq = std::memory_order_acquire;
const std::memory_order mo_acq_rel = std::memory_order_acq_rel;

int load_store(std::atomic<int> *x, std::atomic<int> *y) {
    int r = y->load(mo_acq);
	x->store(1, mo_rel);
    return r;
}
int load_cas(std::atomic<int> *x, std::atomic<int> *y) {
    int r = y->load(mo_acq);
	x->compare_exchange_weak(r, 20, mo_rel, mo_rlx);
    return r;
}

int main() { return 0; }
}

Add a simple experiment to test one particular optimization


//===----------------------------------------------------------------------===//
//
//                     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.
//
//===----------------------------------------------------------------------===//

// <vector>

// template <class... Args> iterator emplace(const_iterator pos, Args&&... args);

#include <vector>
#include <cassert>
int main()
{
#ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
    {
        std::vector<int> v;
        v.reserve(3);
        v = { 1, 2, 3 };
        v.emplace(v.begin(), v.back());
        assert(v[0] == 3);
    }
    {
        std::vector<int> v;
        v.reserve(4);
        v = { 1, 2, 3 };
        v.emplace(v.begin(), v.back());
        assert(v[0] == 3);
    }
#endif  // _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS
}

Add test for self-referencing emplace test.

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@159921 91177308-0d34-0410-b5e6-96231b3b80d8


#include "tests/gtest/gtest.h"
#include <cmath>
#include "pbrt.h"
#include "rng.h"
#include "shape.h"
#include "sampling.h"
#include "shapes/triangle.h"

static Float p(RNG &rng) {
    Float logu = Lerp(rng.UniformFloat(), -8., 8);
    return std::pow(10, logu);
}

TEST(Triangle, Reintersect) {
    for (int i = 0; i < 1000; ++i) {
        RNG rng(i);
        // Triangle vertices
        Point3f v[3];
        for (int j = 0; j < 3; ++j)
            for (int k = 0; k < 3; ++k) v[j][k] = p(rng);

        // Create the corresponding Triangle.
        Transform identity;
        int indices[3] = {0, 1, 2};
        std::vector<std::shared_ptr<Shape>> triVec =
            CreateTriangleMesh(&identity, &identity, false, 1, indices, 3, v,
                               nullptr, nullptr, nullptr, nullptr, nullptr);
        EXPECT_EQ(1, triVec.size());
        std::shared_ptr<Shape> tri = triVec[0];

        // Sample a point on the triangle surface to shoot the ray toward.
        Point2f u;
        u[0] = rng.UniformFloat();
        u[1] = rng.UniformFloat();
        Interaction pTri = tri->Sample(u);

        // Choose a ray origin.
        Point3f o;
        for (int j = 0; j < 3; ++j) o[j] = p(rng);

        // Intersect the ray with the triangle.
        Ray r(o, pTri.p - o);
        Float tHit;
        SurfaceInteraction isect;
        if (!tri->Intersect(r, &tHit, &isect, false))
            // We should almost always find an intersection, but rarely
            // miss, due to round-off error. Just do another go-around in
            // this case.
            continue;

        // Now trace a bunch of rays leaving the intersection point.
        for (int j = 0; j < 10000; ++j) {
            // Random direction leaving the intersection point.
            Point2f u;
            u[0] = rng.UniformFloat();
            u[1] = rng.UniformFloat();
            Vector3f w = UniformSampleSphere(u);
            Ray rOut = isect.SpawnRay(w);
            EXPECT_FALSE(tri->IntersectP(rOut));

            SurfaceInteraction spawnIsect;
            Float tHit;
            EXPECT_FALSE(tri->Intersect(rOut, &tHit, &isect, false));

            // Choose a random point to trace rays to.
            Point3f p2;
            for (int k = 0; k < 3; ++k) p2[k] = p(rng);
            rOut = isect.SpawnRayTo(p2);

            EXPECT_FALSE(tri->IntersectP(rOut));
            EXPECT_FALSE(tri->Intersect(rOut, &tHit, &isect, false));
        }
    }
}

Add test for incorrect self-intersections w/Triangles.


#include <bits/stdc++.h>
using namespace std;

typedef struct node node;

struct Node{
    int data;
    Node *left;
    Node *right;

    Node(const int & value, Node *lt = NULL, Node *rt = NULL):
        data(value), left(lt), right(rt) {}
};

class BST{
    public:
        BST(): root(NULL) {}
        ~BST(){
            destroy_tree();
        }
        void insert(int key);
        node* search(int key);
        void destroy_tree();

    private:
        Node *root;
};

Add noilerplate code for Binary Search Trees.


/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTypes.h"

static const size_t kBufferSize = 256;

#define LOG_TAG "skia"
#include <android/log.h>

void SkDebugf(const char format[], ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
    va_end(args);
}

/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTypes.h"

static const size_t kBufferSize = 256;

#define LOG_TAG "skia"
#include <android/log.h>

static bool gSkDebugToStdOut = false;

extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) {
    gSkDebugToStdOut = debugToStdOut;
}

void SkDebugf(const char format[], ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);

    // Print debug output to stdout as well.  This is useful for command
    // line applications (e.g. skia_launcher)
    if (gSkDebugToStdOut) {
        vprintf(format, args);
    }

    va_end(args);
}

Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs.

Review URL: https://codereview.appspot.com/6733065

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@6059 2bbb7eff-a529-9590-31e7-b0007b416f81


#include "capi/ruby.h"

extern "C" {
  unsigned long rb_fix2uint(VALUE obj) {
    unsigned long num = rb_num2ulong(obj);

    if((int)num < 0) {
      rb_raise(rb_eRangeError, "integer too small to convert into unsigned int");
    }

    if((unsigned int)num != num) {
      rb_raise(rb_eRangeError, "integer too big to convert into unsigned int");
    }

    return num;
  }

  long rb_fix2int(VALUE obj) {
    long num = rb_num2long(obj);

    if((int)num != num) {
      rb_raise(rb_eRangeError, "integer too big to convert into unsigned int");
    }

    return num;
  }
}

#include "capi/ruby.h"

extern "C" {
  unsigned long rb_fix2uint(VALUE obj) {
    unsigned long num = rb_num2ulong(obj);

    if((long)num < 0) {
      rb_raise(rb_eRangeError, "integer too small to convert into unsigned int");
    }

    if((unsigned int)num != num) {
      rb_raise(rb_eRangeError, "integer too big to convert into unsigned int");
    }

    return num;
  }

  long rb_fix2int(VALUE obj) {
    long num = rb_num2long(obj);

    if((int)num != num) {
      rb_raise(rb_eRangeError, "integer too big to convert into unsigned int");
    }

    return num;
  }
}

Fix range check for rb_fix2uint

Fix range check for rb_fix2uint

Fixes #2770


// Chapter 20, Exercise 11: Given a list<int> as a by-reference parameter, make
// a vector<double> and copy the elements of the list into it. Verify that the
// copy was complete and correct, then print the elements in order of increasing
// value.

#include "../lib_files/std_lib_facilities.h"

template<class Iter>
void print_ctr(Iter first, Iter last)
{
    cout << "{";
    while (first != last) {
        cout << " " << *first;
        ++first;
    }
    cout << " }\n";
}

void list_cpy(const list<int>& li)
{
    vector<double> vd;
    list<int>::const_iterator li_it = li.begin();
    while (li_it != li.end()) {
        vd.push_back(*li_it);
        ++li_it;
    }

    // verify copy
    cout << "Length of list:   " << li.size() << "\n";
    cout << "Length of vector: " << vd.size() << "\n";
    cout << "List:   ";
    print_ctr(li.begin(),li.end());
    cout << "Vector: ";
    print_ctr(vd.begin(),vd.end());
    vector<double> vd_sorted = vd;
    sort(vd_sorted.begin(),vd_sorted.end());
    cout << "Sorted: ";
    print_ctr(vd_sorted.begin(),vd_sorted.end());
}

int main()
try {
    list<int> li;
    for (int i = 0; i<10; ++i)
        li.push_back(randint(0,99));
    list_cpy(li);
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 11

Add Chapter 20, exercise 11


/**
 * Swap Nodes in Pairs
 * Dummy head.
 * cpselvis (cpselvis@gmail.com)
 * August 22th, 2016
 */
#include<iostream>

using namespace std;

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
  ListNode* swapPairs(ListNode* head) {
    ListNode *dummy = new ListNode(-1);
    dummy -> next = head;
    ListNode *prev = dummy;

    while (head && head -> next)
    {
      ListNode *next = head -> next -> next;
      prev -> next = head -> next;
      prev -> next -> next = head;
      head -> next = next;
      prev = head;
      head = next;
    }
    return dummy -> next;
  }
};

int main(int argc, char **argv)
{
  ListNode *l1 = new ListNode(1);
  l1 -> next = new ListNode(2);
  l1 -> next -> next = new ListNode(3);
  l1 -> next -> next -> next = new ListNode(4);

  Solution s;
  ListNode *l2 = s.swapPairs(l1);
  while (l2 != NULL)
  {
    cout << l2 -> val << endl;
    l2 = l2 -> next;
  }
}

Swap pairs in linked list.

Swap pairs in linked list.


/*
    Prime numbers using simple Sieve of Eratosthenes:
    Given a number N, find all prime numbers upto N (inclusive) using the simple
    Sieve of Eratosthenes method, which efficiently finds primes in the order of
    10^7. (The efficiency limit is due to poor cache utilisation.)

    Time complexity:
    O(N * log(log(N))), where N is the number upto which primes have to be found

    Space complexity:
    O(N), where N is the number upto which primes have to be found
*/

#include <cmath>
#include <iostream>
#include <vector>

using namespace std;

vector<bool> simpleSieve(const unsigned int &primeLimit) {
    vector<bool> isPrime(primeLimit + 1, true);   // "sieve" to mark numbers as prime

    isPrime[0] = isPrime[1] = false;

    unsigned int multiple;
    for (unsigned int num = 2; num <= sqrt(primeLimit); num++)
        if (isPrime[num])   // if the number is prime
            for (multiple = num * num; multiple <= primeLimit; multiple += num)
                isPrime[multiple] = false;  // mark its multiples as not prime

    return isPrime;
}

void printPrimes(const vector<bool> &markedPrimes) {
    for (unsigned int num = 2; num < markedPrimes.size(); num++)
        if (markedPrimes[num])  // if number is marked as prime
            cout << num << "\n";
}

void getPrimeLimit(unsigned int &primeLimit)
{
    cout << "Enter the number upto which primes are to be found : ";
    cin >> primeLimit;

    if ((int) primeLimit < 0) {
        cout << "Prime limit should be a positive integer! Try again.\n";
        getPrimeLimit(primeLimit);
    }
}

int main()
{
    ios_base::sync_with_stdio(false);   // don't sync C++ streams with C streams

    unsigned int primeLimit;
    getPrimeLimit(primeLimit);

    const vector<bool> markedPrimes = simpleSieve(primeLimit);

    cout << "\nAll prime numbers upto " << primeLimit << " (inclusive) are:\n";
    printPrimes(markedPrimes);

    return 0;
}

Add simple Sieve of Eratosthenes

Add simple Sieve of Eratosthenes


/*
  Summatories
*/
int main(){
  sum(i) from 1 to n = n(n+1)/2
  sum(i^2) from 1 to n = n(n+1)(2n+1)/6
  sum(i^3)  from 1 to n = (n^2(n+1)^2)/4
}

Add equations for some summatories.

Add equations for some summatories.


class Solution {
public:
    int minDistance(string word1, string word2) {
        int dp[word1.size()+1][word2.size()+1];
        for (int i = 0; i <= word1.size(); ++i) {
            for (int j = 0; j <= word2.size(); ++j) {
                dp[i][j] = 0;
            }
        }
        for (int i = 0; i <= word1.size(); ++i) {
            for (int j = 0; j <= word2.size(); ++j) {
                if (i == 0 || j == 0) {
                    dp[i][j] = 0;
                } else {
                    if (word1[i-1] == word2[j-1]) {
                        dp[i][j] = dp[i-1][j-1] + 1;
                    } else {
                        dp[i][j] = std::max(dp[i][j-1], dp[i-1][j]);
                    }
                }
            }
        }
        return word1.size() + word2.size() - 2 * dp[word1.size()][word2.size()];
    }
};

Delete Operation for Two Strings

Delete Operation for Two Strings


#include <bits/stdc++.h>

#define NO_OF_NODES 8

using namespace std;

struct node
{
    int fr, to, cost;
}p[6];

int c = 0, temp1 = 0, temp = 0;

void prims(int *a, int b[][NO_OF_NODES], int i, int j)
{
    a[i] = 1;
    while (c < 6)
    {
        int min = 999;
        for (int i = 0; i < NO_OF_NODES; i++)
        {
            if (a[i] == 1)
            {
                for (int j = 0; j < NO_OF_NODES; )
                {
                    if (b[i][j] >= min || b[i][j] == 0)
                    {
                        j++;
                    }
                    else if (b[i][j] < min)
                    {
                        min = b[i][j];
                        temp = i;
                        temp1 = j;
                    }
                }
            }
        }
        a[temp1] = 1;
        p[c].fr = temp;
        p[c].to = temp1;
        p[c].cost = min;
        c++;
        b[temp][temp1] = b[temp1][temp]=1000;
    }
    for (int k = 0; k < NO_OF_NODES-1; k++)
    {
        cout<<"Source node: "<<p[k].fr<<endl;
        cout<<"Destination node: "<<p[k].to<<endl;
        cout<<"Weight of node: "<<p[k].cost<<"\n\n";
    }
}

int main()
{   int a[NO_OF_NODES];
    for (int i = 0; i < NO_OF_NODES; i++)
    {
        a[i] = 0;
    }
    int b[NO_OF_NODES][NO_OF_NODES];
    for (int i = 0; i < NO_OF_NODES; i++)
    {
        cout<<"enter values for "<<(i+1)<<" row"<<endl;
        for (int j = 0; j < NO_OF_NODES; j++)
        {
            cin>>b[i][j];
        }
    }
    prims(a, b, 0, 0);

    return 0;
}

Add C++ solution for prims algorithm in graphs section


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

int anagram(string s)
{
	int len = s.size();
	if (len & 1) return -1;
	int flag[26] = {0};
	for (int i = len / 2; i < len; i++) {
		flag[s[i] - 'a']++;
	}
	int res = len / 2;
	for (int i = 0; i < len / 2; i++) {
		if (flag[s[i] - 'a']) {
			flag[s[i] - 'a']--;
			res--;
		}
	}
	return res;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		string s;
		cin >> s;
		cout << anagram(s) << endl;
	}
	return 0;
}

Add the solution to "Anagram".

Add the solution to "Anagram".


class Solution {
public:
    int cutOffTree(vector<vector<int>>& forest) {
        if(forest.empty()) return 0;
        if(forest[0].empty()) return 0;
        vector<vector<int>> t;
        for(int i=0;i<forest.size();i++){
            for(int j=0;j<forest[0].size();j++){
                if(forest[i][j]>1){
                    t.push_back({forest[i][j],i,j});
                }
            }
        }
        sort(t.begin(),t.end());
        int ans=0,x=0,y=0;
        for(int i=0;i<t.size();i++){
            int add=bfs(forest,x,y,t[i][1],t[i][2]);
            if(add==-1) return -1;
            ans+=add;
            x=t[i][1];
            y=t[i][2];
        }
        return ans;
    }
    int bfs(vector<vector<int>>& forest,int i,int j,int fi,int fj){
        if(i==fi && j==fj) return 0;
        queue<pair<int, int>> q;
        q.push(make_pair(i,j));
        vector<vector<bool>> visited(forest.size(),vector<bool>(forest[0].size(),false));
        visited[i][j]=true;
        int step=0;
        vector<vector<int>> dir={{1,0},{-1,0},{0,1},{0,-1}};
        while(q.size()){
            step++;
            int size=q.size();
            for(int i=0;i<size;i++){
                int row=q.front().first;
                int col=q.front().second;
                q.pop();
                for(int i=0;i<dir.size();i++){
                    int r=row+dir[i][0];
                    int c=col+dir[i][1];
                    if (r<0||r>=forest.size()||c<0||c>=forest[0].size()||visited[r][c]==1||forest[r][c]==0) continue;
                    if (r==fi&&c==fj) return step;
                    visited[r][c]=1;
                    q.push(make_pair(r,c));
                }
            }
        }
        return -1;
    }
};

Cut Off Trees for Golf Event

Cut Off Trees for Golf Event


// Chapter 25, exercise 6: write an infinite loop that is hard to recognize as
// an infinite loop

#include<iostream>
#include<exception>

using namespace std;

int main()
try
{
    for (char ch = 0; ch<250; ++ch)
        cout << int(ch) << '\n';
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
    return 2;
}

Add Chapter 25, exercise 6

Add Chapter 25, exercise 6


class Solution {
public:
    vector<int> rearrangeArray(vector<int>& nums) {
        std::vector<int> pos, neg, ret;
        for (const auto& i : nums) {
            if (i > 0) {
                pos.emplace_back(std::move(i));
            } else {
                neg.emplace_back(std::move(i));
            }
        }
        for (int i = 0; i < pos.size(); ++i) {
            nums[i*2] = std::move(pos[i]);
            nums[i*2+1] = std::move(neg[i]);
        }
        return nums;
    }
};

Rearrange Array Elements by Sign

Rearrange Array Elements by Sign


///
/// @file   has_openmp.cpp
/// @brief  Used to check if MSVC compiler supports OpenMP.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <omp.h>
#include <iostream>

int main()
{
  std::cout << "OpenMP version (yyyymm) : " << _OPENMP               << std::endl
            << "Number of CPU cores     : " << omp_get_max_threads() << std::endl;
  return 0;
}

Check if MSVC compiler supports OpenMP

Check if MSVC compiler supports OpenMP


/*
  Insert Node at the end of a linked list
  head pointer input could be NULL as well for empty list
  Node is defined as
  struct Node
  {
     int data;
     struct Node *next;
  }
*/

Node* Insert(Node *head,int data)
{
    Node* tmp = new Node();
    tmp->data = data;
    tmp->next = NULL;

    if (head == NULL) {
        return tmp;
    }
    else {
        if (head->next == NULL) {
            head->next = tmp;
            return head;
        }
        Insert(head->next, data);
        return head;
    }
}

Insert at tail of list

[task] Insert at tail of list


// Make sure __asan_gen_* strings have the correct prefixes on Darwin
// ("L" in __TEXT,__cstring, "l" in __TEXT,__const

// RUN: %clang_asan %s -S -o %t.s
// RUN: cat %t.s | FileCheck %s || exit 1

int x, y, z;
int main() { return 0; }
// CHECK: .section{{.*}}__TEXT,__const
// CHECK: l___asan_gen_
// CHECK: .section{{.*}}__TEXT,__cstring,cstring_literals
// CHECK: L___asan_gen_
// CHECK: L___asan_gen_
// CHECK: L___asan_gen_

[ASan] Add a test for __asan_gen_ globals labels on Darwin.

Per Nick Kledzik (http://llvm.org/bugs/show_bug.cgi?id=17976):
"""
For MacOSX, the labels in __cstring section should be 'L' labels, and the labels
in the __const section should be non-L or 'l' labels.  The later ('l') will cause
the linker to remove the label in the final executable.
"""

, so we need to ensure that the globals emitted by ASan have appropriate labels.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@198022 91177308-0d34-0410-b5e6-96231b3b80d8


// Created on November 19, 2013 by Lu, Wangshan.
#include <boost/asio.hpp>
#include <diffusion/factory.hpp>
namespace diffusion {
class NetReader : public Reader {
public:
    NetReader(std::string const & listening_ip_address, std::uint16_t listening_port);
    virtual bool has_next();
    virtual ByteBuffer get_next();
private:
};
} // namespace diffusion

// Created on November 19, 2013 by Lu, Wangshan.
#include <boost/asio.hpp>
#include <diffusion/factory.hpp>
namespace diffusion {
class NetReader : public Reader {
public:
    NetReader(std::string const & listening_ip_address, std::uint16_t listening_port);
    virtual bool can_read();
    virtual ByteBuffer read();
private:
};
} // namespace diffusion

Change names of the interface on net part.

Change has_next() to can_read().
Change read_next() to read().
So it reads more natural.


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

int main(int argc, char* argv[])
{
	//Hardest sudoku : http://www.mirror.co.uk/news/weird-news/worlds-hardest-sudoku-can-you-242294
	std::string chain = "005300000800000020070010500400005300010070006003200080060500009004000030000009700";

	Sudoku s;
	for(int i = 0; i < chain.size(); ++i)
		if(chain[i] != '0')
			s.setValue(i, chain[i]-'0');

	std::cout << s << std::endl;
	Sudoku::solve(s);
	std::cout << s << std::endl;
	return 0;
}

Test solver on the hardest sudoku

Test solver on the hardest sudoku


// Use RAII classes

#include <map>
#include <memory>
#include <string>
#include <vector>

int main()
{
	std::vector<int> vec = {1, 2, 3, 4, 5};
	std::map<std::string, int> map = {{"Foo", 10}, {"Bar", 20}};
	std::string str = "Some text";
	std::unique_ptr<int> ptr1 = std::make_unique<int>(8);
	std::shared_ptr<int> ptr2 = std::make_shared<int>(16);
}

// Avoid manual memory management by using classes that implement
// RAII.
//
// Every object created on [10-14] will internally manage some
// dynamically allocated memory (allocated with the `new` keyword).
// They are all, however, implemented such that they deallocate that
// memory when they are destroyed (that is, when they go out of
// scope). This practice is known as RAII.
//
// The user of these classes does not need to perform manual memory
// management, reducing the risk of memory leaks and other bugs. In
// fact, the use of `new` and `delete` can be avoided entirely by
// using these RAII types.
//
// Likewise, it is good practice to [ensure your own classes also
// implement the RAII idiom](/common-tasks/classes/encapsulate-memory-management.html).

Add "use RAII classes" sample

Add "use RAII classes" sample


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode * flipTree(TreeNode *root) {
        TreeNode* new_node = root;
        if (!root || !root->left)
            return root;

        new_node = flipTree(root->left);

        root->left->left = root->right;
        root->left->right = root;
        root->right = root->left = nullptr;

        return new_node;
    }

    TreeNode* upsideDownBinaryTree(TreeNode* root) {
        return flipTree(root);
    }
};

Use the DFS to solve the problem.

Use the DFS to solve the problem.

Signed-off-by: hwchiu <5d5bf96f0f7137bc5ec8b0b405b00e5a90f259c2@cs.nctu.edu.tw>


/*
 * Problem: Delete duplicate-value nodes from a sorted linked list
 * Author: Anirudha Bose <ani07nov@gmail.com>

   Remove all duplicate elements from a sorted linked list
   Node is defined as
   struct Node
   {
       int data;
       struct Node *next;
   }
 */

Node* RemoveDuplicates(Node *head)
{
    if(head == NULL || head->next == NULL)
        return head;

    Node *list = new Node;
    list = head;

    while(list->next != NULL)
    {
        if(list->data == list->next->data)
            list->next = list->next->next;
        else
            list = list->next;
    }
    return head;
}

Delete duplicate nodes from sorted list

Delete duplicate nodes from sorted list


//-----------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//-----------------------------------------------------------------------

// when linking with the object file generated from this file, calling
// aborts() will not abort the program, but simply resume
// operation. while usually useless, this is used in the test to
// generate the output of a triggered assertion without aborting the
// program. we do this, since we sometimes want to test that some code
// actually generates an assertion, which would otherwise be
// impossible

#include <base/logstream.h>

namespace  deal_II_exceptions
{
  namespace internals
  {
    unsigned int n_treated_exceptions;
  }
}

extern "C"
void abort()
#ifdef DEAL_II_ABORT_NOTHROW_EXCEPTION
  throw ()
#endif
{
  deallog << "Abort!!!" << std::endl;
  deal_II_exceptions::internals::n_treated_exceptions = 0;
}

//-----------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//-----------------------------------------------------------------------

// when linking with the object file generated from this file, calling
// aborts() will not abort the program, but simply resume
// operation. while usually useless, this is used in the test to
// generate the output of a triggered assertion without aborting the
// program. we do this, since we sometimes want to test that some code
// actually generates an assertion, which would otherwise be
// impossible

#include <base/logstream.h>

namespace  deal_II_exceptions
{
  namespace internals
  {
    extern unsigned int n_treated_exceptions;
  }
}

extern "C"
void abort()
#ifdef DEAL_II_ABORT_NOTHROW_EXCEPTION
  throw ()
#endif
{
  deallog << "Abort!!!" << std::endl;
  deal_II_exceptions::internals::n_treated_exceptions = 0;
}

Mark an external variable external.

Mark an external variable external.

git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@8841 0785d39b-7218-0410-832d-ea1e28bc413d


#define BOOST_TEST_MODULE test_types

#include <type_traits>

#include <boost/test/included/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>

#include "variable.hxx"
#include "boolean.hxx"
#include "function.hxx"

typedef boost::mpl::list<variable,boolean,function> types;

BOOST_AUTO_TEST_SUITE(test_types)

BOOST_AUTO_TEST_CASE_TEMPLATE(default_constructor, T, types)
{
  BOOST_CHECK(std::is_default_constructible<T>::value);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(destructible, T, types)
{
  BOOST_CHECK(std::is_destructible<T>::value);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(assignable, T, types)
{
  // copy assignable: operator=(const Type& other)
  BOOST_CHECK(std::is_copy_assignable<T>::value);
  // above implies move assignable (don't understand exactly)
  BOOST_CHECK(std::is_move_assignable<T>::value);
}

BOOST_AUTO_TEST_SUITE_END()

#define BOOST_TEST_MODULE test_types

#include <type_traits>

#include <boost/test/included/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>

#include "variable.hxx"
#include "boolean.hxx"
#include "function.hxx"

typedef boost::mpl::list<variable,boolean,function> types;

BOOST_AUTO_TEST_SUITE(test_types)

BOOST_AUTO_TEST_CASE_TEMPLATE(default_constructible, T, types)
{
  BOOST_CHECK(std::is_default_constructible<T>::value);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(copy_constructible, T, types)
{
  BOOST_CHECK(std::is_copy_constructible<T>::value);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(move_constructible, T, types)
{
  BOOST_CHECK(std::is_move_constructible<T>::value);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(destructible, T, types)
{
  BOOST_CHECK(std::is_destructible<T>::value);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(has_virtual_destructor, T, types)
{
  BOOST_CHECK(std::has_virtual_destructor<T>::value);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(assignable, T, types)
{
  // copy assignable: operator=(const Type& other)
  BOOST_CHECK(std::is_copy_assignable<T>::value);
  // above implies move assignable (don't understand exactly)
  BOOST_CHECK(std::is_move_assignable<T>::value);
}

BOOST_AUTO_TEST_SUITE_END()

Add tests (copy constructor, virtual destructor)


/*
  Insert Node at the end of a linked list
  head pointer input could be NULL as well for empty list
  Node is defined as
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* Insert(Node *head,int data)
{
  // Complete this method
  Node *newNode = (Node *)malloc(sizeof(Node));
  newNode->data = data;

  if (!head) {
      return newNode;
  }

  Node *lastNode = NULL;
  Node *node = head;
  while (node) {
      lastNode = node;
      node = node->next;
  }

  lastNode->next = newNode;
  return head;
}

Insert node at tail (cpp)

Insert node at tail (cpp)


#include <test/unit/math/test_ad.hpp>
#include <limits>

TEST(mathMixScalFun, lccdf_derivatives) {
  auto f = [](const double mu, const double sigma) {
    return
        [=](const auto& y) { return stan::math::normal_lccdf(y, mu, sigma); };
  };
  stan::test::expect_ad(f(0.0, 1.0), -50.0);
  stan::test::expect_ad(f(0.0, 1.0), -20.0 * stan::math::SQRT_TWO);
  stan::test::expect_ad(f(0.0, 1.0), -5.5);
  stan::test::expect_ad(f(0.0, 1.0), 0.0);
  stan::test::expect_ad(f(0.0, 1.0), 0.15);
  stan::test::expect_ad(f(0.0, 1.0), 1.14);
  stan::test::expect_ad(f(0.0, 1.0), 3.00);
  stan::test::expect_ad(f(0.0, 1.0), 10.00);
  stan::test::expect_ad(f(-1.0, 2.0), 1.50);
  stan::test::expect_ad(f(2.0, 1.0), 0.50);

  // thid order autodiff tests can fail at borders of piecewise function
  stan::test::ad_tolerances tols;
  tols.grad_hessian_grad_hessian_ = 1e1;
  stan::test::expect_ad(tols, f(0.0, 1.0), 0.1 * stan::math::SQRT_TWO);
}

Add mix test for normal_lccdf

Add mix test for normal_lccdf


/*
MIT License

Copyright (c) 2017 Blockchain-VCS

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.
*/

bool __nosha256 = false;

Add Command Line Argument Tracker

Add Command Line Argument Tracker


#include <bts/blockchain/address.hpp>
#include <bts/blockchain/pts_address.hpp>
#include <bts/blockchain/types.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>
#include <fc/variant_object.hpp>
#include <fc/exception/exception.hpp>

#include <iostream>

using namespace bts::blockchain;

int main( int argc, char** argv )
{

    if( argc == 2 )
    {
        fc::ecc::private_key k;
        try{
            auto key = bts::blockchain::public_key_type(std::string(argv[1]));
            auto obj = fc::mutable_variant_object();

            obj["public_key"] = public_key_type(key);
            obj["native_address"] = bts::blockchain::address(key);
            obj["pts_address"] = bts::blockchain::pts_address(key);

            std::cout << fc::json::to_pretty_string(obj);
            return 0;

        } catch (fc::exception e) {
            std::cout << e.to_detail_string();
        }
    }
    return -1;
}

#include <bts/blockchain/address.hpp>
#include <bts/blockchain/pts_address.hpp>
#include <bts/blockchain/types.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>
#include <fc/variant_object.hpp>
#include <fc/exception/exception.hpp>

#include <iostream>

using namespace bts::blockchain;

int main( int argc, char** argv )
{
    if( argc == 2 )
    {
        try
        {
            bts::blockchain::public_key_type key(argv[1]);
            fc::mutable_variant_object obj;

            obj["public_key"] = key;
            obj["native_address"] = bts::blockchain::address((fc::ecc::public_key_data)key);
            obj["pts_address"] = bts::blockchain::pts_address((fc::ecc::public_key)key);

            std::cout << fc::json::to_pretty_string(obj);
            return 0;

        }
        catch (fc::exception e)
        {
            std::cout << e.to_detail_string();
        }
    }
    return -1;
}

Fix compile errors on win32, update Qt submodule to fix compile errors there


/////////////////////////////////////////
//
//             OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////

// Floating options window file
// Created 24/9/08
// Karel Petranek

#include "Options.h"
#include "CClient.h"

void UpdateGameInputs()
{
	// Setup the controls
	cClient->getWorm(0)->SetupInputs( tLXOptions->sPlayerControls[0] );
	// TODO: setup also more viewports
	if(cClient->getNumWorms() >= 2)
		cClient->getWorm(1)->SetupInputs( tLXOptions->sPlayerControls[1] );

    cClient->getViewports()[0].setupInputs( tLXOptions->sPlayerControls[0] );
    cClient->getViewports()[1].setupInputs( tLXOptions->sPlayerControls[1] );

}

Hackontest: Update input keys in game, for Floating Options

git-svn-id: 0634bf30b6d7a21f2003d4a9f34c102a3ffa6fda@2375 34602234-ff1f-0410-a465-ea8f3b77ab7f


#include <iostream>
#include <vector>

template <template <typename>class Impl, class Param_list>
class APIExector{
	private:
		Impl<Param_list> m_impl;
	public:
		APIExector(Param_list p)
			:m_impl(p)
		{}
		void Execute()
		{ m_impl.Run(); }
		void Reload(const Param_list& p)
		{ m_impl.Configure(p); }

};

template <class Param_list>
class Variant1{
	private:
		Param_list m_param_list;
	public:
		Variant1(Param_list pl)
			:m_param_list(pl)
		{std::cout << "Variant1 : c'tor." << std::endl; }
		/* No Run() is required here unlike the virtual inheritance case */
		void Configure(const std::vector<std::string>){std::cout << "Variant1 : vector<string> configurator." << std::endl;}
};

template <class Param_list>
class Variant2{
	private:
		Param_list m_param_list;
	public:
		Variant2(Param_list pl)
			:m_param_list(pl)
		{std::cout << "Variant2 : Vector<int> c'tor" << std::endl; }
		void Run(){std::cout << "Variant2 : Run ()" << std::endl; }
};

int main(){
	APIExector<Variant1,std::string> var1("Variant1");
	APIExector<Variant1,std::vector<std::string> > var1_1(std::vector<std::string>(0));
	var1_1.Reload(std::vector<std::string>(0));

	APIExector<Variant2,std::vector<int> > var2(std::vector<int>(0));
	var2.Execute();
}

Test class for API conformance using templates instead of virtual functions.


/* mbed Microcontroller Library
 * Copyright (c) 2017 ARM Limited
 *
 * 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 "utest/utest.h"
#include "unity/unity.h"
#include "greentea-client/test_env.h"

#include "mbed.h"

using namespace utest::v1;

/**
 * This test is intended to gate devices that do not have enough RAM to run
 * Mbed os. Devices passing this test should have enough RAM to run all
 * other Mbed OS tests.
 *
 * If your device does not pass this test, then you should determine the
 * cause of high memory usage and fix it. If you cannot free enough memory,
 * then you should turn off Mbed OS support for this device.
 */

#define MIN_HEAP_SIZE   2048
#define MIN_DATA_SIZE   2048

volatile uint8_t test_buffer[MIN_DATA_SIZE];

static void minimum_heap_test()
{
    void *mem = malloc(MIN_HEAP_SIZE);
    TEST_ASSERT_NOT_EQUAL(NULL, mem);
    free(mem);
}

static void minimum_data_test()
{
    // Use test buffer so it is not optimized away
    for (int i = 0; i < MIN_DATA_SIZE; i++) {
        test_buffer[i] = i & 0xFF;
    }
}

utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(30, "default_auto");
    return greentea_test_setup_handler(number_of_cases);
}

Case cases[] = {
    Case("Minimum heap test", minimum_heap_test),
    Case("Minimum data test", minimum_data_test),
};

Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);

int main() {
    Harness::run(specification);
}

Add a minimum requirements HAL test

Add a minimum requirements HAL test

Add a test to ensure that devices have at least 2K free ram
and 2K free heap. This test should be the first test that fails
due to running out of ram or heap.


/*
	Program to test Depth First Search
*/

#include<iostream>
#include<vector>
#include "dfs.h"		// My implementation of Depth First Search

// tests Dfs (acyclic)

void testDfsA(){

	int n = 10;
	int m = 10;

	std::vector<std::vector<int>> edges = {
												{1,2},
												{2,3},
												{2,4},
												{3,5},
												{4,5},
												{5,6},
												{1,6},
												{4,7},
												{7,8},
												{9,10}

										};

	// Initialize dfs object
	Dfs dfs(n,m,edges);

	// Traverse
	std::cout<<"Traversal: ";

	dfs.traverse();

	// Test if graph is cyclic
	std::cout<<"\nGraph is cyclic: "<<dfs.isCyclic();

	// Print toplogical sort order
	std::cout<<"\nTopological Sort: ";
	dfs.topologicalSort();

}

//tests Dfs (cyclic)

void testDfsB(){

	int n = 10;
	int m = 11;

	std::vector<std::vector<int>> edges = {
												{1,2},
												{2,3},
												{2,4},
												{3,5},
												{4,5},
												{5,6},
												{1,6},
												{4,7},
												{7,8},
												{9,10},
												{6,1}

										};

	// Initialize dfs object
	Dfs dfs(n,m,edges);

	// Traverse
	std::cout<<"\nTraversal: ";

	dfs.traverse();

	// Test if graph is cyclic
	std::cout<<"\nGraph is cyclic: "<<dfs.isCyclic();

	// Print toplogical sort order
	std::cout<<"\nTopological Sort: ";
	dfs.topologicalSort();

}

int main(){

	// Call testDfsB()
	testDfsA();

	// Call testDfsB()
	testDfsB();

	return 0;
}

Add test program for depth first search

Add test program for depth first search


// RUN: clang -E -frtti %s -o - | FileCheck --check-prefix=CHECK-RTTI %s
// RUN: clang -E -fno-rtti %s -o - | FileCheck --check-prefix=CHECK-NO-RTTI %s

#if __has_feature(rtti)
int foo();
#else
int bar();
#endif

// CHECK-RTTI: foo
// CHECK-NO-RTTI: bar

Add FileCheck test for '__has_feature(rtti)'.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@90373 91177308-0d34-0410-b5e6-96231b3b80d8


// Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.

#include <boost/hana.hpp>

#include <iostream>
#include <string>
using namespace boost::hana;

struct concat_strings {
  template <char ...s1, char ...s2>
  constexpr auto operator()(_string<s1...>, _string<s2...>) const
  { return string<s1..., s2...>; }
};

template <typename S>
constexpr auto concat_all(S s) {
  return fold.left(s, string<>, concat_strings{});
}

constexpr auto formats = make_map(
  make_pair(type<int>, string<'%', 'd'>),
  make_pair(type<double>, string<'%', 'f'>),
  make_pair(type<char const*>, string<'%', 's'>)
);

constexpr struct _done { } done{};

template <typename F, typename ...Tokens>
struct unstream_t {
  F f;
  _tuple<Tokens...> tokens;

  template <typename Token>
  friend constexpr
  unstream_t<F, Tokens..., std::decay_t<Token>>
  operator<<(unstream_t&& self, Token&& token) {
    return {
      std::move(self.f),
      append(std::move(self.tokens), std::forward<Token>(token))
    };
  }

  friend auto operator<<(unstream_t&& self, _done) {
    auto fmt = concat_all(
      adjust_if(self.tokens,
        compose(not_, is_a<String>),
        [](auto&& token) {
          return formats[decltype_(token)];
        }
      )
    );

    auto args = remove_if(std::move(self.tokens), is_a<String>);

    return unpack(std::move(args), [&](auto&& ...args) {
      return std::move(self.f)(
        to<char const*>(fmt),
        std::forward<decltype(args)&&>(args)...
      );
    });
  }
};

template <typename F>
constexpr unstream_t<std::decay_t<F>> unstream(F&& f) {
    return {std::forward<F>(f), {}};
}

int main() {
  unstream(std::printf)
    << BOOST_HANA_STRING("C++Now ")
    << 2015
    << " is"
    << BOOST_HANA_STRING(" awesome!")
    << done;

  // equivalent to

  std::printf("C++Now %i%s awesome!", 2015, " is");
}

Add an example of compile-time printf formatting


class Solution {
public:
    int minDistance(string word1, string word2) {
        int l1=word1.length(),l2=word2.length();
        vector<vector<int>> dp(l1+1,vector<int>(l2+1));
        for(int i=0;i<=l1;i++){
            for(int j=0;j<=l2;j++){
                if(i==0 || j==0){
                    dp[i][j]=0;
                    continue;
                }
                if(word1[i-1]==word2[j-1]){
                    dp[i][j]=dp[i-1][j-1]+1;
                }else{
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        return l1+l2-dp[l1][l2]*2;
    }
};

Delete Operation for Two Strings

Delete Operation for Two Strings


/* Copyright 2019 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 <vector>

#include <gtest/gtest.h>
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/testing/util.h"
#include "tensorflow/lite/tools/command_line_flags.h"

namespace {

void InitKernelTest(int* argc, char** argv) {
  bool use_nnapi = false;
  std::vector<tflite::Flag> flags = {
      tflite::Flag::CreateFlag("--use_nnapi", &use_nnapi, "Use NNAPI"),
  };
  tflite::Flags::Parse(argc, const_cast<const char**>(argv), flags);

  if (use_nnapi) {
    tflite::SingleOpModel::SetForceUseNnapi(true);
  }
}

}  // namespace

int main(int argc, char** argv) {
  ::tflite::LogToStderr();
  ::testing::InitGoogleTest(&argc, argv);
  InitKernelTest(&argc, argv);
  return RUN_ALL_TESTS();
}

/* Copyright 2019 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 <vector>

#include <gtest/gtest.h>
#include "tensorflow/lite/kernels/test_util.h"
#include "tensorflow/lite/testing/util.h"
#include "tensorflow/lite/tools/command_line_flags.h"

namespace {

void InitKernelTest(int* argc, char** argv) {
  bool use_nnapi = false;
  std::vector<tflite::Flag> flags = {
      tflite::Flag::CreateFlag("use_nnapi", &use_nnapi, "Use NNAPI"),
  };
  tflite::Flags::Parse(argc, const_cast<const char**>(argv), flags);

  if (use_nnapi) {
    tflite::SingleOpModel::SetForceUseNnapi(true);
  }
}

}  // namespace

int main(int argc, char** argv) {
  ::tflite::LogToStderr();
  ::testing::InitGoogleTest(&argc, argv);
  InitKernelTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Fix command-line parsing for --use_nnapi

PiperOrigin-RevId: 249506404


// https://leetcode.com/problems/invert-binary-tree/
// We could do a depth first traversal. Reverse left subtree and right subtree first,
// then reverse left and right link of root.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr) {
            return nullptr;
        }
        TreeNode* tmp = root->left;
        root->left = invertTree(root->right);
        root->right = invertTree(tmp);
    }
};

Add a solution to problem 226: Invert Binary Tree.


// RUN: %clangxx_asan %s -o %t && %run %t | FileCheck %s

#include <stdio.h>

static void foo() {
  printf("foo\n");
}

int main() {
  return 0;
}

__attribute__((section(".preinit_array")))
void (*call_foo)(void) = &foo;

__attribute__((section(".init_array")))
void (*call_foo_2)(void) = &foo;

__attribute__((section(".fini_array")))
void (*call_foo_3)(void) = &foo;

// CHECK: foo
// CHECK: foo
// CHECK: foo

[ASan] Add test for .preinit_array/.init_array/.fini_array sections.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@247737 91177308-0d34-0410-b5e6-96231b3b80d8


#include <cstdio>
#include <fcntl.h>
#include <iostream>
#include <vector>
#include <string>
#include <termios.h>

class Display {
    public:
        Display(std::string devName, speed_t baud = B115200) {
            _devName = devName;
            _baud = baud;
            std::cout << "Init device: " << _devName.c_str() << std::endl;

            _fd = open(_devName.c_str(), O_NOCTTY | O_NONBLOCK | O_RDWR );
            if (_fd == -1) {
                std::perror("Display():open");
            }

            struct termios term;
            tcgetattr(_fd, &term);

            term.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL
                    |IXON|IXOFF);
            term.c_iflag |= IGNPAR;

            //output modes
            term.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONOCR|ONLRET|OFILL
                    |OFDEL|NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);

            //control modes
            term.c_cflag &= ~(CSIZE|PARENB|PARODD|HUPCL|CRTSCTS);
            term.c_cflag |= CREAD|CS8|CSTOPB|CLOCAL;

            //local modes
            term.c_lflag &= ~(ISIG|ICANON|IEXTEN|ECHO);
            term.c_lflag |= NOFLSH;

            cfsetospeed(&term, baud);
            cfsetispeed(&term, baud);

            //set new device settings
            if(tcsetattr(_fd, TCSANOW, &term) == -1) {
                std::perror("Display():tcsetattr");
            }
        }

    private:
        int _fd;
        std::string _devName;
        speed_t _baud;

};

int main (int argc, char *argv[]) {

    Display d("/s/blah/whatever");
}

Add simple display class and constructor


//
//  Remove_Duplicates_from_Sorted_Array.cpp
//  leetcode
//
//  Created by 邵建勇 on 15/5/10.
//  Copyright (c) 2015年 John Shaw. All rights reserved.
//

#include <stdio.h>
#include <vector>

using namespace std;

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        int index = 0;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[index] != nums[i]) {
                nums[++index] = nums[i];
            }
        }
        return index+1;
    }
};

Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array


#include <bits/stdc++.h>
using namespace std;
#define V 6
bool bfs(int rGraph[V][V], int s, int t, int parent[]){
	bool visited[V];
	memset(visited, 0, sizeof(visited));
	queue <int> q;
	q.push(s);
	visited[s] = true;
	parent[s] = -1;
	while (!q.empty()){
		int u = q.front();
		q.pop();
		for (int v=0; v<V; v++){
			if (visited[v]==false && rGraph[u][v] > 0){
				q.push(v);
				parent[v] = u;
				visited[v] = true;
			}
		}
	}
	return (visited[t] == true);
}

int fordFulkerson(int graph[V][V], int s, int t){
	int u, v;
	int rGraph[V][V]; // Residual graph where rGraph[i][j] indicates
					// residual capacity of edge from i to j (if there
					// is an edge. If rGraph[i][j] is 0, then there is not)
	for (u = 0; u < V; u++)
		for (v = 0; v < V; v++)
			rGraph[u][v] = graph[u][v];
	int parent[V];
	int max_flow = 0; // There is no flow initially
	while (bfs(rGraph, s, t, parent)){
		int path_flow = INT_MAX;
		for (v=t; v!=s; v=parent[v]){
			u = parent[v];
			path_flow = min(path_flow, rGraph[u][v]);
		}
		for (v=t; v != s; v=parent[v]){
			u = parent[v];
			rGraph[u][v] -= path_flow;
			rGraph[v][u] += path_flow;
		}
		max_flow += path_flow;
	}
	return max_flow;
}

int main(){
	int graph[V][V] = { {0, 16, 13, 0, 0, 0},
						{0, 0, 10, 12, 0, 0},
						{0, 4, 0, 0, 14, 0},
						{0, 0, 9, 0, 0, 20},
						{0, 0, 0, 7, 0, 4},
						{0, 0, 0, 0, 0, 0}
					};
  int origen = 0;
  int dest = 5;
	cout << "The maximum possible flow is "
       << fordFulkerson(graph, origen, dest);

	return 0;
}

Add Ford Fulkerson algorithm to find the max flow.


// RUN: %clang_cc1 -std=c++98 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
// RUN: %clang_cc1 -std=c++14 -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors
// RUN: %clang_cc1 -std=c++1z -triple x86_64-unknown-unknown %s -verify -fexceptions -fcxx-exceptions -pedantic-errors

#if __cplusplus < 201103L
// expected-no-diagnostics
#endif

namespace dr1684 { // dr1684: 3.6
#if __cplusplus >= 201103L
  struct NonLiteral { // expected-note {{because}}
    NonLiteral();
    constexpr int f() { return 0; } // expected-warning 0-1{{will not be implicitly 'const'}}
  };
  constexpr int f(NonLiteral &) { return 0; }
  constexpr int f(NonLiteral) { return 0; } // expected-error {{not a literal type}}
#endif
}

Add missing testcase from r224388.

Add missing testcase from r224388.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@224401 91177308-0d34-0410-b5e6-96231b3b80d8


// 67. Add Binary
/**
 * Given two binary strings, return their sum (also a binary string).
 *
 * For example,
 * a = "11"
 * b = "1"
 * Return "100".
 *
 * Tags: Math, String
 *
 * Similar Problems: (M) Add Two Numbers, (M) Multiply Strings, (E) Plus One
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    string addBinary(string a, string b) {
        string res("");

        int carry = 0, i = a.size() - 1, j = b.size() - 1;
        while (i >= 0 || j >= 0 || carry == 1) {
            if (i >= 0)
                carry += a[i--] - '0';

            if (j >= 0)
                carry += b[j--] - '0';

            res += carry % 2 + '0';
            carry = carry / 2;
        }

        reverse(res.begin(), res.end());
        return res;
    }
};

int main() {
    string a = "11", b = "1";
    Solution sol;
    string res = sol.addBinary(a, b);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution for 067 Add Binary

Add Solution for 067 Add Binary


#include <iostream>
#include <cmath>

#include <Carbon/Carbon.h>

using namespace std;

// This code was written to test the performance of an algorithm I suggested on StackOverflow.
// http://stackoverflow.com/a/8991238/63225

int main (void) {
  UnsignedWide startTime, endTime;

  double result;

  Microseconds(&startTime);

  for (int i = 0; i < 1000000; ++i) {
    result = floor(log2(i)) + 1;
  }

  Microseconds(&endTime);

  printf("%d\n", endTime.lo - startTime.lo);

  uint32_t v; // find the log base 2 of 32-bit v
  int r;      // result goes here

  static const int MultiplyDeBruijnBitPosition[32] =
  {
    0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
    8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
  };

  Microseconds(&startTime);

  for (int i = 0; i < 1000000; ++i) {
    v = i;
    v |= v >> 1; // first round down to one less than a power of 2
    v |= v >> 2;
    v |= v >> 4;
    v |= v >> 8;
    v |= v >> 16;

    result = MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];
  }

  Microseconds(&endTime);
  printf("%d\n", endTime.lo - startTime.lo);
  return 0;
}

Test code for an algorithm on StackOverflow.


#include "mbed.h"

Serial pc(USBTX, USBRX);
DigitalOut gpo(D0);
DigitalOut led(LED_RED);
DigitalOut power(D2);
AnalogIn sensor(A0);

int main()
{
    power = 1;
    pc.baud(9600);
    while (true) {
        if(sensor.read() > 0){
            led = 1;
        }else{
            led = 0;
        }
        wait(0.2f);
        pc.printf("%u\n\r", sensor.read());

        /*
        pc.printf("%u\n", sensor.read());
        wait(0.2f);
        */
    }
}

Create LIFI receiver and output analog values


#include <botan/botan.h>
#include <botan/pbkdf2.h>
#include <botan/hmac.h>
#include <botan/sha160.h>

#include <fstream>

using namespace Botan;

int main()
   {
   LibraryInitializer init;

   AutoSeeded_RNG rng;

   std::string passphrase = "secret";

   std::ifstream infile("readme.txt");
   std::ofstream outfile("readme.txt.enc");

   PKCS5_PBKDF2 pbkdf2(new HMAC(new SHA_160));

   pbkdf2.set_iterations(4096);
   pbkdf2.new_random_salt(rng, 8);
   SecureVector<byte> the_salt = pbkdf2.current_salt();

   SecureVector<byte> master_key = pbkdf2.derive_key(48, passphrase).bits_of();

   KDF* kdf = get_kdf("KDF2(SHA-1)");

   SymmetricKey key = kdf->derive_key(20, master_key, "cipher key");
   SymmetricKey mac_key = kdf->derive_key(20, master_key, "hmac key");
   InitializationVector iv = kdf->derive_key(8, master_key, "cipher iv");

   Pipe pipe(new Fork(
                new Chain(
                   get_cipher("Blowfish/CBC/PKCS7", key, iv, ENCRYPTION),
                   new Base64_Encoder,
                   new DataSink_Stream(outfile)
                   ),
                new Chain(
                   new MAC_Filter("HMAC(SHA-1)", mac_key),
                   new Hex_Encoder)
                )
      );

   outfile.write((const char*)the_salt.begin(), the_salt.size());

   pipe.start_msg();
   infile >> pipe;
   pipe.end_msg();

   SecureVector<byte> hmac = pipe.read_all(1);
   outfile.write((const char*)hmac.begin(), hmac.size());
   }

Add an example taken from the tutorial

Add an example taken from the tutorial


#include<iostream>
#include<vector>
#include<ctime>
#include<map>
#include"node.h"
using namespace std;

const int MaxElements = 100;

map<int, int> countingSort(vector<int> list) {
	map<int, int>  result;
	for (int i = 0; i < MaxElements; i++) {
		auto it = result.find(list[i]);
		if (it != result.end()) {
			result[list[i]] += 1;
		}
		else {
			result[list[i]] = 1;
		}
	}
	return result;

}

map<int, int> merge(map<int, int> fst, map<int, int> snd) {
	map<int, int> result;
	for (auto it = fst.begin(); it != fst.end(); it++) {
		result[(*it).first] = (*it).second;
	}
	for (auto it = snd.begin(); it != snd.end(); it++) {
		int keyToFind = (*it).first;
		auto rit = result.find(keyToFind);
		if (it != result.end()) {
			(*it).second += (*it).second;
		} else
			result[keyToFind] = (*it).second;
	}
	return result;
}

void zad2() {
	srand(time(NULL));
	vector<int> list;
	for (int i = 0; i < MaxElements; i++) {
		list.push_back(rand() % 10000 + 1);
	}
	//a
	map<int, int> result = countingSort(list);

	//б
	map<int, int> firstSorted;
	map<int, int> secondSorted;
	int i = 0;
	for (auto it = result.begin(); it != result.end(); it++, i++) {
		if (i % 2 == 0) {
			firstSorted[(*it).first] = (*it).second;
		}
		else secondSorted[(*it).first] = (*it).second;
	}
	map<int, int> merged = merge(firstSorted, secondSorted);

}

int main() {
	cout << 5;
	zad2();
	cin.get();
	return 0;
}

Add main file - remove main.cpp from .gitignore please


//147. Insertion Sort List
/*
Sort a linked list using insertion sort.

Author: Xinyu Liu
*/

#include <iostream>
using namespace std;

//Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution{
public:
    ListNode* insertionSortList(ListNode* head){
        ListNode* L = new ListNode(INT_MIN);
        while (head){
            ListNode* i = L;
            while (i ->next && i ->next ->val < head ->val){
                i = i->next;
            }
            ListNode* insert = new ListNode(head -> val);
            insert ->next = i ->next;
            i ->next = insert;
            head = head ->next;
        }
        return L->next;

    }
};

void main(){

    ListNode* n1 = new ListNode(6);
    n1 ->next = new ListNode(5);
    n1 ->next ->next = new ListNode(3);
    Solution sol;
    ListNode* n_sort = sol.insertionSortList(n1);
}

Add 147 Insertion Sort List

Add 147 Insertion Sort List


class Solution {
public:
    bool halvesAreAlike(string s) {
        int count = 0;
        std::unordered_set vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
        for (int i = 0; i < s.size()/2; ++i) {
            auto iter = vowels.find(s[i]);
            if (iter != vowels.end())
                ++count;
        }
        for (int i = s.size()/2; i < s.size(); ++i) {
            auto iter = vowels.find(s[i]);
            if (iter != vowels.end())
                --count;
        }
        return count == 0;
    }
};

Determine if String Halves Are Alike

Determine if String Halves Are Alike


#include <gtest/gtest.h>
#include <mlfe/operators_v2/squared_difference.h>
#include <mlfe/utils/gradient_checker.h>
#include <random>

using namespace mlfe;
using namespace mlfe::operators_v2;
namespace fn = mlfe::functional;

TEST(operator_v2, squared_difference_fwd){
    using T = float;
    auto a = Tensor::from_vector<T>({1, 2, 3, -4}, {2, 2});
    auto b = Tensor::from_vector<T>({5, 4, 3, 2}, {2, 2});
    auto y = squared_difference(a, b);
    EXPECT_EQ(y.data<T>()[0], 16);
    EXPECT_EQ(y.data<T>()[1], 4);
    EXPECT_EQ(y.data<T>()[2], 0);
    EXPECT_EQ(y.data<T>()[3], 36);
}

TEST(operator_v2, squared_difference_bwd){
    using T = float;
    constexpr T grad_eps = 1e-4;
    constexpr T pass_eps = 1e-3;
    auto a = fn::create_variable({2, 2});
    auto b = fn::create_variable({2, 2});
    auto analytical_a = fn::create_variable(a.shape());
    auto analytical_b = fn::create_variable(b.shape());
    std::mt19937 rng;
    std::uniform_real_distribution<T> dist(-1, 1);

    std::generate(a.begin<T>(), a.end<T>(), [&rng, &dist](){
        return dist(rng);
    });
    std::generate(b.begin<T>(), b.end<T>(), [&rng, &dist](){
        return dist(rng);
    });
    auto y = squared_difference(a, b);
    y.backprop_v2();
    std::copy(a.grad_v2().begin<T>(), a.grad_v2().end<T>(), analytical_a.begin<T>());
    std::copy(b.grad_v2().begin<T>(), b.grad_v2().end<T>(), analytical_b.begin<T>());
    auto func_a = [b](Tensor& a){
        return squared_difference(a, b);
    };
    auto func_b = [a](Tensor& b){
        return squared_difference(a, b);
    };
    auto numerical_a = numerical_gradient_v2(func_a, a, grad_eps);
    auto numerical_b = numerical_gradient_v2(func_b, b, grad_eps);
    auto diff_a = calculate_gradient_diff<T>(numerical_a, analytical_a);
    auto diff_b = calculate_gradient_diff<T>(numerical_b, analytical_b);
    EXPECT_NEAR(diff_a, T(0), pass_eps);
    EXPECT_NEAR(diff_b, T(0), pass_eps);
}

Add unit test for squared difference op

Add unit test for squared difference op


#include <string>
#include <"runDiff.h">

int main(int argc, const char * argv[])
{
	if (argc != 2)
	{
		std::cerr << "Usage: " << argv[0] << " input file name"<<std::endl;
		return 1;
	}
	runFiles(string(argv[1]));
	return 0;
}

Add symposium server main file.

Add symposium server main file.


#include <stdio.h>
#include <math.h>

int main(void)
{
    int num;

    printf("Enter num= ");
    scanf("%d", &num);

    printf("Result: %d\n", (int)sqrt(num) * (int)sqrt(num));

    return 0;
}

Add a solution of prob 2

Add a solution of prob 2


#include <iostream>

int main(int argc, char **argv)
{
	int number = 2520;

	// naive solution
	while (true) {
		for (int i = 2; i <= 20; i++) {
			if (number % i != 0) {
				break;
			}
			else if (i == 20 && number % i == 0) {
				std::cout << number << std::endl;
				return 0;
			}
		}
		number++;
	}

	return 0;
}

Add C++ solution to problem 005

Add C++ solution to problem 005

Signed-off-by: Rafael Campos Nunes <42f0a9af43f2538fd3153aecc7c3ff958e89d724@engineer.com>


#include <catch.hpp>

#include <mockturtle/utils/truth_table_cache.hpp>
#include <kitty/constructors.hpp>
#include <kitty/dynamic_truth_table.hpp>

using namespace mockturtle;

TEST_CASE( "working with a truth table cache", "[truth_table_cache]" )
{
  truth_table_cache<kitty::dynamic_truth_table> cache;

  kitty::dynamic_truth_table zero( 0u ), x1( 1u ), f_and( 2u ), f_or( 2u ), f_maj( 3u );

  kitty::create_from_hex_string( x1, "2" );
  kitty::create_from_hex_string( f_and, "8" );
  kitty::create_from_hex_string( f_or, "e" );
  kitty::create_from_hex_string( f_maj, "e8" );

  CHECK( cache.size() == 0 );
  CHECK( cache.insert( zero ) == 0 );
  CHECK( cache.insert( x1 ) == 2 );
  CHECK( cache.insert( f_and ) == 4 );
  CHECK( cache.insert( f_or ) == 6 );
  CHECK( cache.insert( f_maj ) == 8 );

  CHECK( cache.size() == 5 );

  CHECK( cache.insert( ~zero ) == 1 );
  CHECK( cache.insert( ~x1 ) == 3 );
  CHECK( cache.insert( ~f_and ) == 5 );
  CHECK( cache.insert( ~f_or ) == 7 );
  CHECK( cache.insert( ~f_maj ) == 9 );

  CHECK( cache.size() == 5 );

  CHECK( cache[0] == zero );
  CHECK( cache[1] == ~zero );
  CHECK( cache[2] == x1 );
  CHECK( cache[3] == ~x1 );
  CHECK( cache[4] == f_and );
  CHECK( cache[5] == ~f_and );
  CHECK( cache[6] == f_or );
  CHECK( cache[7] == ~f_or );
  CHECK( cache[8] == f_maj );
  CHECK( cache[9] == ~f_maj );
}

Add test case for truth table cache.

Add test case for truth table cache.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(NULL == head || NULL == head->next) return head;
        ListNode *prev = head, *current = head->next;
        while(current){
            if(current->val == prev->val){
                prev->next = current->next;
            }else{
                prev = prev->next;
            }
            current = current->next;
        }
        return head;
    }
};

Remove Duplicates from Sorted List

Remove Duplicates from Sorted List


#include <iostream>
#define show(x) cout << #x << " = " << x << endl;

using namespace std;

int main(){
    int e =32;
    show(e);
}

Implement useful macro for debug.

Implement useful macro for debug.


#include <Kokkos_Core.hpp>

#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

#if defined( DTK_SEARCH_MPI_UNIT_TEST )
#include <mpi.h>
#endif

struct ExecutionEnvironmentScopeGuard
{
    ExecutionEnvironmentScopeGuard( int argc, char *argv[] )
    {
#if defined( DTK_SEARCH_MPI_UNIT_TEST )
        MPI_Init( &argc, &argv );
#endif
        Kokkos::initialize( argc, argv );
    }
    ~ExecutionEnvironmentScopeGuard()
    {
        Kokkos::finalize();
#if defined( DTK_SEARCH_MPI_UNIT_TEST )
        MPI_Finalize();
#endif
    }
};

bool init_function() { return true; }

int main( int argc, char *argv[] )
{
    ExecutionEnvironmentScopeGuard scope_guard( argc, argv );
    return boost::unit_test::unit_test_main( &init_function, argc, argv );
}

Add main for unit tests using Boost UTF

Add main for unit tests using Boost UTF


#include <iostream>
#include <vector>
#include <thread>
#include <algorithm>
#include <cstdlib>

int main() {
    unsigned long long acm1 = 0;
    unsigned long long acm2 = 0;

    std::vector<int> v(1024);
    srand(time(nullptr));
    std::generate(v.begin(), v.end(), [&v]() { return rand() % v.size(); } );

    for_each(begin(v), end(v), [](int i) { std::cout << i << ' '; } );

    std::thread t1([&acm1, &v] {
        for (unsigned int i = 0; i < v.size() / 2; ++i) {
            acm1 += v[i];
        }
    });
    std::thread t2([&acm2, &v] {
        for (unsigned int i = v.size() / 2; i < v.size(); ++i) {
            acm2 += v[i];
        }
    });

    t1.join();
    t2.join();

    std::cout << "acm1: " << acm1 << std::endl;
    std::cout << "acm2: " << acm2 << std::endl;
    std::cout << "acm1 + acm2: " << acm1 + acm2 << std::endl;

    return 0;
}

Add c++11 thread creation with lambda function. It generates random
vector of 1024 integers and creates two threads to summarize bottom and
top half respectfully.

Compile with:

g++ -std=c++11 thread_lambda.cpp -o thread_lambda -lpthread


#include <stdio.h>

#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quick.hpp"

int main(void)
{
    int k;
    printf("Enter k= ");
    scanf("%d", &k);

    {
    }

    return 0;
}

Add solution of prob 3

Add solution of prob 3


/*
 *   compiling:
 *   	qmake -project
 *   	qmake
 *   	make
 *
 *   usage:
 *   	ini-diff first.ini second.ini output.ini
 *
 *   Outputs an INI diff that will be usable as a diff file in a WZ diff mod.
 *   Doesn't look at fields that were present in first.ini but are not present
 *   in second.ini, as diff mods can't remove fields.
 */

#include <QSettings>
#include <QStringList>

int main(int argc, char **argv) {
	if (argc != 4)
		return 1;
	QSettings first(argv[1], QSettings::IniFormat);
	QSettings second(argv[2], QSettings::IniFormat);
	QSettings result(argv[3], QSettings::IniFormat);
	QStringList firstKeys = first.allKeys();
	QStringList secondKeys = second.allKeys();
	for (int i = 0; i < secondKeys.length(); ++i) {
		if (!firstKeys.contains(secondKeys[i])
				||
			second.value(secondKeys[i]) != first.value(secondKeys[i])
		) {
			result.setValue(secondKeys[i], second.value(secondKeys[i]));
		}
	}
	return 0;
}

Rename the repository, add an ini diff tool


#include "Halide.h"

using namespace Halide;

int main() {

    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL)) {
        fprintf(stderr, "ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Func f;
    Var x, y, c;
    RDom r(0, 10);
    f(x, y, c) = sum(r);
    f.bound(c, 0, 3).glsl(x, y, c);

    f.realize(100, 100, 3);

    printf("Success!\n");

    return 0;
}

Add failing opengl test using an inline reduction


#include <iostream>
using namespace std;

int chocolates(int n, int c, int m)
{
    int sum = n / c;
    int wrapper = sum;
    while(wrapper / m) {
        int added = wrapper / m;
        wrapper = wrapper % m + added;
        sum += added;
    }
    return sum;
}

int main()
{
    int T;
    cin >> T;
    while (T--) {
        int n, c, m;
        cin >> n >> c >> m;
        cout << chocolates(n, c, m) << endl;
    }
    return 0;
}

Add the solution to "Chocolate feast".

Add the solution to "Chocolate feast".


#include <windows.h>
#include <assert.h>
#include <vector>

#include "TestUtil.cc"
#include "../shared/DebugClient.cc"

int main(int argc, char *argv[]) {
    if (argc == 1) {
        startChildProcess(L"CHILD");
        return 0;
    }

    const HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
    const long long kWidth = 20000;
    const long long kHeight = 20000;

    setWindowPos(0, 0, 1, 1);
    setBufferSize(kWidth, kHeight);
    setWindowPos(0, 0, std::min(80LL, kWidth), std::min(50LL, kHeight));

    setCursorPos(0, 0);
    printf("A");
    fflush(stdout);
    setCursorPos(kWidth - 2, kHeight - 1);
    printf("B");
    fflush(stdout);

    trace("sizeof(CHAR_INFO) = %d", (int)sizeof(CHAR_INFO));

    std::vector<CHAR_INFO> buffer(kWidth * kHeight);
    COORD bufSize = { kWidth, kHeight };
    COORD bufCoord = { 0, 0 };
    SMALL_RECT readRegion = { 0, 0, kWidth - 1, kHeight - 1 };
    BOOL success = ReadConsoleOutputW(conout, buffer.data(), bufSize, bufCoord, &readRegion);
    trace("ReadConsoleOutputW: success=%d", success);

    assert(buffer[0].Char.UnicodeChar == L'A');
    assert(buffer[kWidth * kHeight - 2].Char.UnicodeChar == L'B');
    trace("Top-left and bottom-right characters read successfully!");

    Sleep(30000);
    return 0;
}

Add a test case that performs a very large read.


// 7. Reverse Integer
/**
 * Reverse digits of an integer.
 *
 * Example1: x = 123, return 321
 * Example2: x = -123, return -321
 *
 * Have you thought about this?
 * Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
 *
 * If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
 *
 * Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
 *
 * For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
 *
 * Update (2014-11-10):
 * Test cases had been added to test the overflow behavior.
 *
 * Tags: Math
 *
 * Similar Problems: (E) String to Integer (atoi)
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

class Solution {
public:
    int reverse(int x) {
        int res = 0;

        while (x != 0)
        {
            int digit = x % 10;
            int temp = res * 10 + digit;
            if ((temp - digit) / 10 != res) // overflow
                return 0;

            res = temp;
            x = x / 10;
        }

        return res;
    }
};

int main()
{
    int x = 1000000003;
    Solution sol;
    int res = sol.reverse(x);
    cout << x << " -> " << res << endl;
    cin.get();

    return 0;
}

Add Solution for 7 Reverse Integer

Add Solution for 7 Reverse Integer


// Roll a die

#include <random>

int main()
{
	std::random_device random_device;
	std::mt19937 random_engine{random_device()};
	std::uniform_int_distribution<int> die_distribution{1, 6};

	int die_roll = die_distribution(random_engine);
}

// Generate a random integer according to a uniform distribution.
//
// The [`std::random_device`](cpp/numeric/random/random_device) on [7]
// provides a source of uniform non-deterministic random numbers
// (where such a source is available). We use this to seed the
// Mersenne Twister random number engine,
// [`std::mt19937`](cpp/numeric/random/mersenne_twister_engine), on
// [8]. Consider [other random number
// engines](http://en.cppreference.com/w/cpp/numeric/random#Predefined_random_number_generators)
// for different properties.
//
// On [9], we create a
// [`std::uniform_int_distribution`](cpp/numeric/random/uniform_int_distribution)
// representing a uniform random distribution of integers from 1 to 6
// inclusive. That is, each value from 1 to 6 has an equal chance of
// occurring.
//
// Finally, we generate a random number from the random engine,
// distributed according to the uniform integer distribution ([11]).
// This gives us a random integer from 1 to 6, as though we had rolled
// a 6-sided die.
//
// To generate further random numbers, simply call
// `die_distribution(random_engine)` again.

Add "roll a die" sample

Add "roll a die" sample


#include <conio.h>
#include <ctype.h>
#include <stdio.h>

int main() {
    printf("\nPress any keys -- Ctrl-D exits\n\n");

    while (true) {
        const int ch = getch();
        printf("0x%x", ch);
        if (isgraph(ch)) {
            printf(" '%c'", ch);
        }
        printf("\n");
        if (ch == 0x4) { // Ctrl-D
            break;
        }
    }
    return 0;
}

Add a test program that dumps console input via _getch.


#include <algorithm>
#include <iostream>
#include <list>
#include <vector>

#include "gtest/gtest.h"

template <typename InputIterator, typename OutputIterator>
auto addCarry(InputIterator begin, InputIterator end, OutputIterator obegin, const bool carryBit) {
    auto oit = obegin;
    bool carryFlag = carryBit;
    for (auto it = begin; it != end; ++it, ++oit) {
        *it += carryFlag;
        if (*it > 9) {
            carryFlag = true;
            *oit = (*it) % 10;
        } else {
            *oit = (*it);
        }
    }
    return oit;
}

template <typename FirstIterator, typename SecondIterator, typename OutputIterator>
auto sum(FirstIterator xbegin, FirstIterator xend, SecondIterator ybegin, SecondIterator yend,
         OutputIterator obegin, const bool carryBit) {

    auto firstIt = xbegin;
    auto secondIt = ybegin;
    auto outIt = obegin;
    bool carryFlag = carryBit;

    for (; (firstIt != xend) && (secondIt != yend); ++firstIt, ++secondIt, ++outIt) {
        auto sum = (*firstIt) + (*secondIt) + carryFlag;
        if (sum > 9) {
            carryFlag = true;
            *outIt = sum % 10;
        } else {
            *outIt = sum;
        }
    }

    if (firstIt == xend) {
        outIt = addCarry(secondIt, yend, outIt, carryBit);
    }

    if (secondIt == yend) {
        outIt = addCarry(firstIt, xend, outIt, carryBit);
    }

    return outIt;
}

template <typename Container> auto mysum(Container &x, Container &y) {
    Container results(std::max(x.size(), y.size()) + 1, 0);
    auto outIt = sum(x.begin(), x.end(), y.begin(), y.end(), results.begin(), 0);
    results.resize(std::distance(results.begin(), outIt));
    return results;
}

template <typename Container> void print(Container &data) {
    std::for_each(data.begin(), data.end(), [](auto item) { std::cout << item << " "; });
    std::cout << "\n";
}

TEST(BasicTests, Positive) {
    {
        std::vector<int> x{3, 1, 5}, y{5, 9, 2}, z{8, 0, 8};
        auto results = mysum(x, y);
        print(x);
        print(y);
        print(results);
        EXPECT_EQ(results, z);
    }

    {
        std::list<int> x{3, 1, 5, 1}, y{5, 9, 2}, z{8, 0, 8, 1};
        auto results = mysum(x, y);
        print(x);
        print(y);
        print(results);
        EXPECT_EQ(results, z);
    }
}

Add a template function which can calculate the sum of two numbers.


/**
 * link: https://leetcode.com/problems/rotate-array/
 */
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if(k <= 0)
            return;

        if(k >= nums.size())
            k = k % nums.size();

        vector<int> tmp(nums);
        tmp.insert(tmp.end(), nums.begin(), nums.end());

        for(int i = 0; i < nums.size(); i++)
        {
            nums[i] = tmp[nums.size()-k+i];
        }
    }
};

Add solution for 189. Rotate Array.

Add solution for 189. Rotate Array.


// Validate multiple reads

#include <sstream>
#include <string>

int main()
{
	std::istringstream stream{"John Smith 32"};

	std::string first_name;
	std::string family_name;
	int age;

	if (stream >> first_name &&
	    stream >> family_name &&
	    stream >> age) {
		// Use values
	}
}

// Validate reading multiple values from an input stream.
//
// We create a [`std::istringstream`](cpp/io/basic_istringstream) as
// the example input stream, which contains some values that we wish
// to read ([8]). This stream could be replaced by any other
// input stream, such as [`std::cin`](cpp/io/cin) or a file stream.
// We then create some objects on [10-11] into which we will read
// values from the stream.
//
// In the condition of the `if` statement on [14-16], we perform the
// extractions. The `&&` operators ensure that the condition
// is `true` only when all extractions succeed. Short-circuiting
// also ensures that an extraction is only evaluated if the previous
// extractions were successful.
//
// If you are reading values on multiple lines, consider [reading
// from the stream line-by-line](/common-tasks/input-streams/read-lines-from-stream.html)
// and then parsing each line.

Add "validate multiple reads" sample

Add "validate multiple reads" sample


# include <cstdlib> // std :: rand ()
# include <vector> // std :: vector <>
# include <list> // std :: list <>
# include <iostream> // std :: cout
# include <iterator> // std :: ostream_iterator <>
# include <algorithm> // std :: reverse , std :: generate

int main ()
{

	std::list <unsigned int> l1(100);
	for (auto& l : l1){
		l = std::rand() % 101;
	}
	std::copy(std::begin(l1), std::end(l1),
		std::ostream_iterator<int>(std::cout, "\n"));

	std::vector<unsigned int> v1(l1.size());
	std::copy(std::begin(l1), std::end(l1), std::begin(v1));
	std::copy(std::begin(v1), std::end(v1),
		std::ostream_iterator<int>(std::cout, "\n"));

	return 0;
}

Add 3.2 Vector and List

Add 3.2 Vector and List


//   Copyright 2018 otris software AG
//
//   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 <ews/ews.hpp>
#include <ews/ews_test_support.hpp>

#include <stdlib.h>

#include <exception>
#include <iostream>
#include <ostream>
#include <string>

int main()
{
    int res = EXIT_SUCCESS;
    ews::set_up();

    try
    {
        const auto env = ews::test::environment();
        auto service = ews::service(env.server_uri, env.domain, env.username,
                                    env.password);

        ews::distinguished_folder_id folder = ews::standard_folder::contacts;

        // Initial synchronization call
        auto result = service.sync_folder_items(folder);

        // Store sync_state for further synchronization calls
        auto sync_state = result.get_sync_state();

        // Output all existing items
        for (const auto& item : result.get_created_items())
        {
            std::cout << item.id() << "\n";
        }

        // Create test contact
        auto contact = ews::contact();
        contact.set_given_name("Darkwing");
        contact.set_surname("Duck");
        contact.set_email_address(
            ews::email_address(ews::email_address::key::email_address_1,
                "superhero@ducktales.com"));
        contact.set_job_title("Average Citizen");
        auto item_id = service.create_item(contact);

        // Follow-up synchronization call
        result = service.sync_folder_items(folder, sync_state);

        // Output all newly created items
        for (const auto& item : result.get_created_items())
        {
            std::cout << item.id() << "\n";
        }

        //TODO: Show that updated items are synched
        // But service.update_item(...) creates a new item

        // Delete test item
        service.delete_item(item_id);

        // Follow-up synchronization call
        result = service.sync_folder_items(folder, sync_state);

        // Output all deleted items
        for (const auto& item : result.get_deleted_items())
        {
            std::cout << item.id() << "\n";
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

// vim:et ts=4 sw=4

Add example for SyncFolderItems operation


// Copyright 2015 David Gasquez

#include <cstdio>

struct Node {
  int data;
  Node *left;
  Node *right;
  Node(int data): data(data), left(nullptr), right(nullptr) {}
};

void print_tree_post_order(Node *tree) {
  if (tree->left != nullptr) {
    print_tree_post_order(tree->left);
  }
  if (tree->right != nullptr) {
    print_tree_post_order(tree->right);
  }
  printf("%i ", tree->data);
  printf("\n");
}

int main(int argc, char const *argv[]) {
  Node *node = new Node(3);

  Node *node_left = new Node(2);
  node->left = node_left;
  Node *node_right = new Node(9);
  node->right = node_right;

  print_tree_post_order(node);

  return 0;
}

Add a simple binary tree code

Add a simple binary tree code


#include <iostream>
#include <string>

using namespace std;

template <typename T, typename... Args>
void foo(const T &t, const Args& ... rest) {
    cout << sizeof...(Args) << endl;
    cout << sizeof...(rest) << endl;
}

int main() {
    int i = 0;
    double d = 3.14;
    string s = "how now brown cow";
    foo(i, s, 42, d);
    foo(s, 42, "hi");
    foo(d, s);
    foo("hi");

    return 0;
}

Add solution for chapter 16 test 51

Add solution for chapter 16 test 51


#include "testHooks.h"

#include "filter/OrientationEngine.h"
#include "util/PIDcontroller.h"
#include "util/PIDparameters.h"
#include "filter/RCFilter.h"
#include "output/Horizon.h"
//TESTING "math/Vec3.cpp"
//TESTING "math/Quaternion.cpp"
//TESTING "math/GreatCircle.cpp"
//TESTING "math/SpatialMath.cpp"

PIDparameters pitchI(0.1, 0.0, 0.1);
PIDparameters rollI(0.1, 0.0, 0.1);
PIDparameters yawI(0.1, 0.0, 0.1);
PIDparameters pitchO(0.1, 0.0, 0.1);
PIDparameters rollO(0.1, 0.0, 0.1);
PIDparameters yawO(0.1, 0.0, 0.1);
Horizon horizon(&pitchI, &rollI, &yawI, &pitchO, &rollO, &yawO);
RCFilter engine(1.0, 1.0);

bool noOutputInStandby(){
	float torques[4] = {1.0, 1.0, 1.0, 1.0};

	horizon.standby();
	horizon.update(engine, torques);
	for(int i=0; i<4; i++){
		FPASSERT(torques[i], 0.0);
	}
	return true;
}

bool regularOutput(){
	float torques[4];
	horizon.activate();
	horizon.set(0.5, 0, 0, 0.5);
	horizon.update(engine, torques);
	return true;
}

int main(){
	TEST(noOutputInStandby);

	float torques[4];
	horizon.activate();
	horizon.set(0.5, 0, 0, 0.5);
	beginTest("Horizon calculation");
	horizon.update(engine, torques);
	benchFinish();
}

Test and benchmark Horizon attitude controller


#include <mlpack/core.hpp>
#include <mlpack/methods/ann/ffnn.hpp>

using namespace mlpack;
using namespace arma;
using namespace std;

PARAM_STRING_REQ("input_file", "Corpus of text to learn on.", "i");
PARAM_INT("history", "Length of history to cache.", "H", 3);

int main(int argc, char** argv)
{
  CLI::ParseCommandLine(argc, argv);

  const string inputFile = CLI::GetParam<string>("input_file");
  const size_t history = (size_t) CLI::GetParam<int>("history");

  // Now, we need to load the input dataset, convert it to character IDs, and
  // put it in an Armadillo matrix.
  vector<string> inputCorpus;
  fstream f(inputFile);
  while (!f.eof())
  {
    char buffer[1024];
    f.getline(buffer, 1024);
    inputCorpus.push_back(buffer);
  }
  f.close();

  // Okay; figure out how many data points we have.
  size_t numCharacters = 0;
  for (size_t i = 0; i < inputCorpus.size(); ++i)
    numCharacters += inputCorpus[i].size() + 1;

  // Start building our dataset.
  arma::mat dataset(history + 1, numCharacters);
  dataset.zeros();
  size_t currentCol = 0;
  for (size_t i = 0; i < inputCorpus.size(); ++i)
  {
    const string& str = inputCorpus[i];
    for (size_t j = 0; j <= str.size(); ++j)
    {
      const char c = (j == str.size()) ? '\0' : str[j];

      // Fill character.
      dataset(0, currentCol) = double(c);
      // Fill previous characters, if we can.  Careful not to underflow k.
      for (size_t k = std::min(j, history); k > 0; --k)
      {
        dataset(k, currentCol) = double(str[j - k]);
      }
      ++currentCol;
    }
  }

  // Now, we want to build a simple neural network.  Let's not start too hard.
  // How about three layers?  The first layer has 'history + 1' neurons; the
  // second can have '2 * history'; the third can have '512' (since there are
  // 256 possible outputs); the fourth can have '256', since that'll be the
  // output layer.

  // I wonder what will happen?
}

Load a corpus and get it into a nicer format.