text:
#include "native.hpp"
#include <fc/log/logger.hpp>
#include <boost/thread/thread.hpp>

#include <eosiolib/symbol.hpp>

extern "C" void vm_unload_account(uint64_t account);
//defined in python_contract.pyx
int system_upgrade(uint64_t version, const string& script);

using namespace eosiosystem;

bool remove_expired_boost_accounts() {
   std::vector<uint64_t> v;
   uint64_t _now = current_time();
   eosio::multi_index<N(boost), boost_account> _boost(N(eosio), N(eosio));

   for(auto itr=_boost.begin();itr!=_boost.end(); itr++) {
      if (itr->expiration < _now) {
         v.push_back(itr->account);
      }
   }

   for(uint64_t& a: v) {
      auto itr = _boost.find(a);
      if (itr != _boost.end()) {
         vm_unload_account(a);
         _boost.erase(itr);
      }
   }

   return true;
}

bool is_boost_account_expired(uint64_t account) {
   uint64_t _now = current_time();
   eosio::multi_index<N(boost), boost_account> _boost(N(eosio), N(eosio));
   auto itr = _boost.find(account);
   if (itr != _boost.end()) {
      if (itr->expiration < _now) {
//         _boost.erase(itr); //removed in eosiosystem::onblock
         return true;
      }
   }
   return false;
}

bool is_boost_account(uint64_t account, bool& expired) {
   uint64_t _now = current_time();
   eosio::multi_index<N(boost), boost_account> _boost(N(eosio), N(eosio));

   auto itr = _boost.find(account);
   expired = false;
   if (itr != _boost.end()) {
      if (itr->expiration < _now) {
         expired = true;
      }
      return true;
   }
   return false;
}

namespace eosiosystem {

system_contract::system_contract( account_name s )
:contract(s), _boost(_self, _self), _upgrade(_self, _self)
{
   if (!_upgrade.exists()) {
      struct upgrade up;
      up.version = 0;
      _upgrade.set(up, _self);
   }
}

system_contract::~system_contract() {

}

void system_contract::upgrade(uint64_t version, std::string script) {
   require_auth(_self);
   wlog("upgrade: version ${n1}", ("n1", version));
   auto up = _upgrade.get();
   if (up.version >= version) {
      return;
   }
   boost::thread t([version,script]{
//      system_upgrade(version, script);
   });
}

}

extern "C" {
   int native_apply( uint64_t receiver, uint64_t code, uint64_t action ) {
      auto self = receiver;
      if( code == self ) {
         eosiosystem::system_contract thiscontract( self );
         switch( action ) {
         case N(upgrade):
            eosio::execute_action( &thiscontract, &eosiosystem::system_contract::upgrade );
            break;
         /*
         case N(boost):
            eosio::execute_action( &thiscontract, &eosiosystem::system_contract::boost );
            break;
         case N(cancelboost):
            eosio::execute_action( &thiscontract, &eosiosystem::system_contract::cancelboost );
            break;
         */
         default:
               return 0;
         }
         return 1;
         /* does not allow destructor of thiscontract to run: eosio_exit(0); */
      }
      return 0;
   }
}
/*
EOSIO_NATIVE_ABI( eosiosystem::system_contract,
     (boost)(cancelboost)
)
*/

#include <eosio.token/eosio.token.hpp>

void db_store_i64_in_account( uint64_t code, uint64_t scope, uint64_t table_id, uint64_t payer, uint64_t key, const char* buffer, size_t buffer_size );
void db_update_i64_without_check_code( int iterator, uint64_t payer, const char* buffer, size_t buffer_size );
void db_remove_i64_without_check_code( int iterator );

struct currency_stats {
   asset          supply;
   asset          max_supply;
   account_name   issuer;

   uint64_t primary_key()const { return supply.symbol.name(); }
};

typedef eosio::multi_index<N(stat), currency_stats> stats;

static uint64_t eosio_token = N(eosio.token);
static uint64_t table_id = N(accounts);

void sub_balance( uint64_t owner, int64_t amount, uint64_t symbol ) {

   int it = db_find_i64(eosio_token, owner, table_id, symbol>>8);
   eosio_assert(it >=0, "no balance found");

   asset balance{0, symbol};
   db_get_i64(it, &balance, sizeof(balance));

   eosio_assert( balance.amount >= amount, "overdrawn balance" );

   if( balance.amount == amount ) {
      db_remove_i64_without_check_code(it);
   } else {
      balance.amount -= amount;
      db_update_i64_without_check_code(it, owner, (char*)&balance, sizeof(balance));
   }
}

void add_balance( uint64_t owner, int64_t amount, uint64_t symbol, uint64_t ram_payer )
{
   int it = db_find_i64(eosio_token, owner, table_id, symbol>>8);

   asset balance{0, symbol};
   if (it < 0) {
      balance.amount = amount;
      db_store_i64_in_account(eosio_token, owner, table_id, ram_payer, symbol>>8, (char*)&balance, sizeof(balance));
   } else {
      db_get_i64(it, &balance, sizeof(balance));
      balance.amount += amount;
      db_update_i64_without_check_code(it, ram_payer, (char*)&balance, sizeof(balance));
   }
}

int transfer_inline(uint64_t to, int64_t amount, uint64_t symbol) {
   try {
      uint64_t from = current_receiver();
      eosio_assert( from != to, "cannot transfer to self" );
//      require_auth( from );
      eosio_assert( is_account( to ), "to account does not exist");

      auto sym = symbol>>8;
      stats statstable( eosio_token, sym );
      const auto& st = statstable.get( sym );

//      require_recipient( from );
      require_recipient( to );

      asset quantity{(int64_t)amount, symbol};

      eosio_assert( quantity.is_valid(), "invalid quantity" );
      eosio_assert( quantity.amount > 0, "must transfer positive quantity" );
      eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );

      sub_balance( from, amount, symbol );
      add_balance( to, amount, symbol, to );
      return 1;
   } catch (...) {
       throw;
   }
   return 0;
}

static uint64_t EOS = S(4, EOS);

int transfer(uint64_t from, uint64_t to, int64_t amount, uint64_t symbol) {
   eosio_assert( from != to, "cannot transfer to self" );
   require_auth( from );
   eosio_assert( is_account( to ), "to account does not exist");

   auto sym = symbol>>8;
   stats statstable( eosio_token, sym );
   const auto& st = statstable.get( sym );

//      require_recipient( from );
   require_recipient( to );

   asset quantity{(int64_t)amount, EOS};

   eosio_assert( quantity.is_valid(), "invalid quantity" );
   eosio_assert( quantity.amount > 0, "must transfer positive quantity" );
   eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );

   sub_balance( from, amount, EOS );
   add_balance( to, amount, EOS, to );
   return 1;
}

max_stars_repo_name: learnforpractice/pyeos

max_issues_repo_name: openchatproject/safeos

max_forks_repo_name: learnforpractice/pyeos


text:
// Copyright 2016 Bogumił Chojnowski
// bogumil DOT chojnowski AT gmail DOT com
// This is extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2010 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed
// under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <iostream>
#include <memory>
// back-end
#include <boost/msm/back/state_machine.hpp>
//front-end
#include <boost/msm/front/state_machine_def.hpp>
#ifndef BOOST_MSM_NONSTANDALONE_TEST
#define BOOST_TEST_MODULE MyTest
#endif
#include <boost/test/unit_test.hpp>

namespace msm = boost::msm;
namespace mpl = boost::mpl;

namespace
{
    struct Lightbulp
    {
        Lightbulp(int c) : current(c) {}
        int current;
    };

    // events
    struct ev_toggle {};

    // front-end: define the FSM structure
    struct bistable_switch_ : public msm::front::state_machine_def<bistable_switch_>
    {
         bistable_switch_(std::unique_ptr<Lightbulp> bulp, int load)
            : bulp_(std::move(bulp))
        {
            BOOST_CHECK_MESSAGE(bulp_->current == 3, "Wrong current value");
            BOOST_CHECK_MESSAGE(load == 5, "Wrong load value");
            bulp_->current = 10;
        }

        std::unique_ptr<Lightbulp> bulp_;

        // The list of FSM states
        struct Off : public msm::front::state<>
        {
            template <typename Event, typename FSM>
            void on_entry(Event const&, FSM& ) { }
            template <typename Event, typename FSM>
            void on_exit(Event const&, FSM&) { }
        };

        struct On : public msm::front::state<>
        {
            template <typename Event, typename FSM>
            void on_entry(Event const&, FSM& ) { }
            template <typename Event, typename FSM>
            void on_exit(Event const&, FSM&) { }
        };

        // the initial state of the player SM. Must be defined
        typedef Off initial_state;

        void turn_on(ev_toggle const&) { bulp_->current = 11; }
        void turn_off(ev_toggle const&) { bulp_->current = 9; }

        typedef bistable_switch_ bs_; // makes transition table cleaner

        // Transition table for player
        struct transition_table : mpl::vector<
            //    Start     Event         Next      Action				 Guard
            //  +---------+-------------+---------+---------------------+----------------------+
          a_row < Off     , ev_toggle   , On      , &bs_::turn_on                              >,
          a_row < On      , ev_toggle   , Off     , &bs_::turn_off                             >
            //  +---------+-------------+---------+---------------------+----------------------+
        > {};
        // Replaces the default no-transition response.

        template <typename Event, typename FSM>
        void no_transition(Event const&, FSM&, int)
        {
            BOOST_FAIL("no_transition called!");
        }
    };

    // Pick a back-end
    typedef msm::back::state_machine<bistable_switch_> bistable_switch;

    BOOST_AUTO_TEST_CASE(my_test)
    {
        auto bulp = std::make_unique<Lightbulp>(3);

        bistable_switch bs(std::move(bulp), 5);
        BOOST_CHECK_MESSAGE(bs.bulp_->current == 10, "Wrong returned current value");

        bs.start();

        bs.process_event(ev_toggle());
        BOOST_CHECK_MESSAGE(bs.bulp_->current == 11, "Wrong returned current value");

        bs.process_event(ev_toggle());
        BOOST_CHECK_MESSAGE(bs.bulp_->current == 9, "Wrong returned current value");

        bs.stop();
    }
}

ext: cpp

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
#include <iostream>
#include <boost/chrono.hpp>
//#include <chrono>
#include <ctime>

long fibonacci(unsigned n)
{
    if (n < 2) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}

int main()
{
    boost::chrono::time_point<boost::chrono::system_clock> start, end;
    start = boost::chrono::system_clock::now();
    std::cout << "f(42) = " << fibonacci(42) << '\n';
    end = boost::chrono::system_clock::now();

    boost::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = boost::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

max_stars_repo_name: wvat/NTRTsim

max_issues_repo_name: wvat/NTRTsim

max_forks_repo_name: wvat/NTRTsim


text:
/*==============================================================================
  Copyright (c) 2017, 2018 Matt Calabrese

  Distributed under the Boost Software License, Version 1.0. (See accompanying
  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/

#ifndef ARGOT_UNION_DETAIL_CONFIG_HPP_
#define ARGOT_UNION_DETAIL_CONFIG_HPP_

#include <boost/preprocessor/config/limits.hpp>

// #define ARGOT_NO_PREPROCESSED_UNION 1

#ifdef ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES_IS_VALID
#error ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES_IS_VALID shall not be user-defined.
#else

// NOTE:
//   If ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES is defined by the user, make
//   certain that every translation unit in the build defines it the same.
#ifndef ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES
#define ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES 16
#endif  // ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES
#if ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES < 0
#error ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES must be greater than 0.
#elif ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES - 1 > BOOST_PP_LIMIT_ITERATION
#error ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES exceeds the Boost.PP iteration limit.
#else
#define ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES_IS_VALID 1
#endif  // The validity checks for ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES

#endif  // The check for ARGOT_MAX_PREPROCESSED_UNION_ALTERNATIVES_IS_VALID definition

#endif  // ARGOT_UNION_DETAIL_CONFIG_HPP_

ext: hpp

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
//
// Created by sean on 08/08/16.
//

#ifndef PCL_DETECT_HANDS_HAND_POSE_STORAGE_HPP
#define PCL_DETECT_HANDS_HAND_POSE_STORAGE_HPP

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/filesystem.hpp>
#include <Eigen/Dense>
#include <mutex>
#include <set>

namespace pt = boost::property_tree;
namespace fs = boost::filesystem;

namespace pcltools {

namespace fileio {

class ArmPoseStorage {

 private:
  constexpr static auto PCD_DIRECTORY_NAME = "basedir";
  constexpr static auto POSES_NAME = "poses";
  constexpr static auto FILENAME_NAME = "file";
  constexpr static auto POINT_1_NAME = "point1";
  constexpr static auto POINT_2_NAME = "point2";
  constexpr static auto RADIUS_NAME = "radius";

 public:
  ArmPoseStorage (fs::path const & pcd_directory);

  auto save (fs::path const & destination_path) -> bool;

  auto load (fs::path const & source_path) -> bool;

  auto getPcdDirectory () const noexcept -> fs::path;

  auto addPose (fs::path const & file_path,
                Eigen::Vector3f const & point_1,
                Eigen::Vector3f const & point_2,
                float radius) -> void;

  auto getPoses () const
  -> std::vector <std::tuple <fs::path, Eigen::Vector3f, Eigen::Vector3f, float>> const &;

 private:
  fs::path pcd_directory_;

  // TODO: Eigen aligned allocator
  std::vector <std::tuple <fs::path, Eigen::Vector3f, Eigen::Vector3f, float>> poses_;
  mutable std::mutex poses_mutex_;
};

}
}

#endif //PCL_DETECT_HANDS_HAND_POSE_STORAGE_HPP

max_stars_repo_name: leaveitout/pcltools

max_issues_repo_name: leaveitout/pcltools

max_forks_repo_name: leaveitout/pcltools


text:
//
// Created by alex on 5/28/19.
//

#include <types/Image.h>
#include <types/Color.h>
#include <boost/python.hpp>
#include <cmath>
#include <algorithm>
#include <random>
#include <numeric>

#include <iostream>
#include <fstream>

template<typename T>
T clamp(T x, T a, T b)
{
    if(x < a) return a;
    if(x > b) return b;
    return x;
}

struct Coord
{
    int x, y;
};

Color bilinear_interpolation(std::array<Color, 4> corners, std::array<Coord, 4> coords, double x, double y)
{
    double r = 0.0, g = 0.0, b = 0.0;
    double sum = 0.0;

    for(int i = 0; i < 4; i++)
    {
        double d = sqrt(
                (coords[i].x - x) * (coords[i].x - x) +
                (coords[i].y - y) * (coords[i].y - y));

        r += corners[i].r * d;
        g += corners[i].g * d;
        b += corners[i].b * d;

        sum += d;
    }

    r /= sum;
    g /= sum;
    b /= sum;

    return Color(
            static_cast<uint8_t>(r),
            static_cast<uint8_t>(g),
            static_cast<uint8_t>(b));
}

Image separate_blue_channel(const Image& image)
{
    Image new_image(image.width(), image.height());

    for(int row = 0; row < static_cast<int>(image.height()); row++)
        for(int column = 0; column < static_cast<int>(image.width()); column++)
        {
            auto color = image.pixelAt(row, column);
            new_image.setPixel(row, column, Color(0, 0, color.b));
        }

    return new_image;
}

Image separate_red_channel(const Image& image)
{
    Image new_image(image.width(), image.height());

    for(int row = 0; row < static_cast<int>(image.height()); row++)
        for(int column = 0; column < static_cast<int>(image.width()); column++)
        {
            auto color = image.pixelAt(row, column);
            new_image.setPixel(row, column, Color(color.r, 0, 0));
        }

    return new_image;
}

Image separate_green_channel(const Image& image)
{
    Image new_image(image.width(), image.height());

    for(int row = 0; row < static_cast<int>(image.height()); row++)
        for(int column = 0; column < static_cast<int>(image.width()); column++)
        {
            auto color = image.pixelAt(row, column);
            new_image.setPixel(row, column, Color(0, color.g, 0));
        }

    return new_image;
}

Image luminance_map(const Image& image)
{
    Image new_image(image.width(), image.height());

    for(int row = 0; row < static_cast<int>(image.height()); row++)
        for(int column = 0; column < static_cast<int>(image.width()); column++)
        {
            auto color = image.pixelAt(row, column);
            auto luminance = static_cast<long long int>(color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722);
            new_image.setPixel(row, column, Color(luminance, luminance, luminance));
        }

    return new_image;
}

Image pixel_sort(const Image& source, const Image& mask)
{
    struct Interval {int column, row_start, row_end; };

    std::vector<Interval> intervals;
    for(int column = 0; column < static_cast<int>(source.width()); column++)
    {
        int row = 0;
        while(row < static_cast<int>(source.height()))
        {
            int row_begin = row;
            while(row < static_cast<int>(source.height()) && mask.pixelAt(row, column).r == 255u)
                row ++;
            intervals.push_back({column, row_begin, row - 1});

            while(row < static_cast<int>(source.height()) && mask.pixelAt(row, column).r != 255u)
                row ++;
        }
    }

    Image result = source;

    std::vector<Color> pixels;
    for(const auto& [column, row_start, row_end]: intervals)
    {
        for(int row = row_start; row <= row_end; row++)
            pixels.push_back(result.pixelAt(row, column));

        std::sort(pixels.begin(), pixels.end(), [](const auto& lhs, const auto& rhs)
        {
            auto a = lhs.r * 0.2126 + lhs.g * 0.7152 + lhs.b * 0.0722;
            auto b = rhs.r * 0.2126 + rhs.g * 0.7152 + rhs.b * 0.0722;

            return a < b;
        });

        for(int row = row_start, i = 0; row <= row_end; row++, i++)
            result.setPixel(row, column, pixels[i]);

        pixels.clear();
    }

    return result;
}

Image pixel_distort_displace(const Image& source, const Image& map, double row_factor, double column_factor)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            double displacement = row_factor * (map.pixelAt(row, column).r / 255. * 2. - 1.);
            long long int column_displaced = static_cast<long long int>(displacement * column_factor) + column;
            long long int row_displaced= static_cast<long long int>(displacement * row_factor) + row;

            if((row_displaced >= 0 && row_displaced < static_cast<int>(source.height())) &&
               (column_displaced >= 0 && column_displaced < static_cast<int>(source.width()))
                    )
            {
                new_image.setPixel(row_displaced, column_displaced, source.pixelAt(row, column));
            }
        }

    for(int row = 0; row < static_cast<int>(source.height()); row++)
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            if(new_image.pixelAt(row, column).r == 0 &&
               new_image.pixelAt(row, column).g == 0 &&
               new_image.pixelAt(row, column).b == 0)
                new_image.setPixel(row, column, source.pixelAt(row, column));
        }

    return new_image;
}

Image displacement(const Image& source, const Image& map, double row_factor, double column_factor)
{
    Image new_image(source.width(), source.height());
    Image known_pixels(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            double displacement = (map.pixelAt(row, column).r / 255. * 2. - 1.);
            long long int column_displaced = static_cast<long long int>(displacement * column_factor) + column;
            long long int row_displaced= static_cast<long long int>(displacement * row_factor) + row;

            row_displaced = (row_displaced + static_cast<int>(source.height())) % static_cast<int>(source.height());
            column_displaced = (column_displaced + static_cast<int>(source.width())) % static_cast<int>(source.width());

            new_image.setPixel(row_displaced, column_displaced, source.pixelAt(row, column));
            known_pixels.setPixel(row_displaced, column_displaced, Color(1, 0, 0));
        }
    }

    int row_radius = std::max(1, static_cast<int>(row_factor)) * 3;
    int column_radius = std::max(1, static_cast<int>(column_factor)) * 3;

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            if(!known_pixels.pixelAt(row, column).r)
            {
                std::array<Color, 4> samples{};
                std::array<Coord, 4> coords{};
                char rowDir[] = {1, -1, 0, 0};
                char colDir[] = {0, 0, -1, 1};

                for(int i = 0; i < 4; i++)
                {
                    int row_ = row, column_ = column;
                    bool finished = false;

                    for(int l = 0; l < row_radius && !finished; l++)
                    {
                        row_ += rowDir[i];
                        column_ = column;
                        for(int k = 0; k < column_radius && !finished; k++)
                        {
                            column_ += colDir[i];

                            if(known_pixels.pixelAt(
                                    (row_ + static_cast<int>(source.height())) % static_cast<int>(source.height()),
                                    (column_ + static_cast<int>(source.width())) % static_cast<int>(source.width())).r)
                            {
                                coords[i] = {
                                        (column_ + static_cast<int>(source.width())) % static_cast<int>(source.width()),
                                        (row_ + static_cast<int>(source.height())) % static_cast<int>(source.height())};
                                samples[i] = new_image.pixelAt(
                                        (row_ + static_cast<int>(source.height())) % static_cast<int>(source.height()),
                                        (column_ + static_cast<int>(source.width())) % static_cast<int>(source.width()));
                                finished = true;
                            }
                        }
                    }
                }

                new_image.setPixel(row, column,
                        bilinear_interpolation(samples, coords, column, row));
                known_pixels.setPixel(row, column, Color(1, 0, 0));
            }
        }
    }

    return new_image;
}

Image lift_gain(const Image& source, double lift, double gain)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            auto color = source.pixelAt(static_cast<int>(row), static_cast<int>(column));
            auto r = color.r * (gain - lift) + lift;
            auto g = color.g * (gain - lift) + lift;
            auto b = color.b * (gain - lift) + lift;

            r = clamp(r, 0., 255.);
            g = clamp(g, 0., 255.);
            b = clamp(b, 0., 255.);

            new_image.setPixel(static_cast<int>(row), static_cast<int>(column), Color(static_cast<uint8_t>(r), static_cast<uint8_t>(g),
                                                                                static_cast<uint8_t>(b)));
        }

    return new_image;
}

Image gamma_(const Image& source, double gamma)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            auto color = source.pixelAt(static_cast<int>(row), static_cast<int>(column));
            auto r = pow(color.r, 1. / gamma);
            auto g = pow(color.g, 1. / gamma);
            auto b = pow(color.b, 1. / gamma);

            r = clamp(r, 0., 255.);
            g = clamp(g, 0., 255.);
            b = clamp(b, 0., 255.);

            new_image.setPixel(static_cast<int>(row), static_cast<int>(column), Color(static_cast<uint8_t>(r), static_cast<uint8_t>(g),
                                                                                static_cast<uint8_t>(b)));
        }

    return new_image;
}

Image contrast(const Image& source, double contrast)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            auto color = source.pixelAt(static_cast<int>(row), static_cast<int>(column));
            auto r = color.r * (1. + contrast) * (-1.) - contrast / 2.;
            auto g = color.g * (1. + contrast) * (-1.) - contrast / 2.;
            auto b = color.b * (1. + contrast) * (-1.) - contrast / 2.;

            r = clamp(r, 0., 255.);
            g = clamp(g, 0., 255.);
            b = clamp(b, 0., 255.);

            new_image.setPixel(static_cast<int>(row), static_cast<int>(column), Color(static_cast<uint8_t>(r), static_cast<uint8_t>(g),
                                                                                static_cast<uint8_t>(b)));
        }

    return new_image;
}

Image brightness(const Image& source, double brightness)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
        for(int column = 0; column < static_cast<int>(source.width()); column++)
        {
            auto color = source.pixelAt(static_cast<int>(row), static_cast<int>(column));
            auto r = color.r + brightness * 255;
            auto g = color.g + brightness * 255;
            auto b = color.b + brightness * 255;

            r = clamp(r, 0., 255.);
            g = clamp(g, 0., 255.);
            b = clamp(b, 0., 255.);

            new_image.setPixel(static_cast<int>(row), static_cast<int>(column), Color(static_cast<uint8_t>(r), static_cast<uint8_t>(g),
                                                                                static_cast<uint8_t>(b)));
        }

    return new_image;
}

Image box_blur(const Image& source, double row_factor, double column_factor)
{
    static auto get_pixel_or_black = [](const Image& image, int row, int column)
    {
        if(row < static_cast<int>(image.height()) && column < static_cast<int>(image.width()) && row >= 0 && column >= 0)
            return image.pixelAt(row, column);
        return Color();
    };

    Image tmp(source.width(), source.height());
    {
        double weight = 1.0f / column_factor;
        int half = static_cast<int>(column_factor / 2);
        for(int row = 0; row < static_cast<int>(source.height()); row++)
            for(int column = 0; column < static_cast<int>(source.width()); column++)
            {
                double r = 0., g = 0., b = 0.;
                for(int i = -half; i <= half; i++)
                {
                    r += get_pixel_or_black(source, row, column + i).r * weight;
                    g += get_pixel_or_black(source, row, column + i).g * weight;
                    b += get_pixel_or_black(source, row, column + i).b * weight;
                }

                r = clamp(r, 0., 255.);
                g = clamp(g, 0., 255.);
                b = clamp(b, 0., 255.);

                tmp.setPixel(static_cast<int>(row), static_cast<int>(column), Color(static_cast<uint8_t>(r), static_cast<uint8_t>(g),
                                                                                static_cast<uint8_t>(b)));
            }
    }

    Image new_image(source.width(), source.height());

    {
        double weight = 1.0f / row_factor;
        int half = static_cast<int>(column_factor / 2);
        for(int row = 0; row < static_cast<int>(source.height()); row++)
            for(int column = 0; column < static_cast<int>(source.width()); column++)
            {
                double r = 0., g = 0., b = 0.;
                for(int i = -half; i <= half; i++)
                {
                    r += get_pixel_or_black(tmp, row + i, column).r * weight;
                    g += get_pixel_or_black(tmp, row + i, column).g * weight;
                    b += get_pixel_or_black(tmp, row + i, column).b * weight;
                }

                r = clamp(r, 0., 255.);
                g = clamp(g, 0., 255.);
                b = clamp(b, 0., 255.);

                new_image.setPixel(static_cast<int>(row), static_cast<int>(column), Color(static_cast<uint8_t>(r), static_cast<uint8_t>(g),
                                                                                static_cast<uint8_t>(b)));
            }
    }

    return new_image;
}

Image mask(const Image& source, const Image& mask)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(source.width()); column++)
            if(mask.pixelAt(row, column).r == 255u)
                new_image.setPixel(row, column, source.pixelAt(row, column));
            else new_image.setPixel(row, column, Color(0, 0, 0));
    }

    return new_image;
}

Image add(const Image& a, const Image& b)
{
    Image new_image(a.width(), a.height());

    for(int row = 0; row < static_cast<int>(a.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(a.width()); column++)
        {
            uint8_t r_ = a.pixelAt(row, column).r + b.pixelAt(row, column).r;
            uint8_t g_ = a.pixelAt(row, column).g + b.pixelAt(row, column).g;
            uint8_t b_ = a.pixelAt(row, column).b + b.pixelAt(row, column).b;

            new_image.setPixel(row, column, Color(r_, g_, b_));
        }
    }

    return new_image;
}

Image strict_add(const Image& a, const Image& b)
{
    Image new_image(a.width(), a.height());

    for(int row = 0; row < static_cast<int>(a.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(a.width()); column++)
        {
            int r_ = static_cast<int>(a.pixelAt(row, column).r) + static_cast<int>(b.pixelAt(row, column).r);
            int g_ = static_cast<int>(a.pixelAt(row, column).g) + static_cast<int>(b.pixelAt(row, column).g);
            int b_ = static_cast<int>(a.pixelAt(row, column).b) + static_cast<int>(b.pixelAt(row, column).b);

            r_ = clamp(r_, 0, 255);
            g_ = clamp(g_, 0, 255);
            b_ = clamp(b_, 0, 255);

            new_image.setPixel(row, column, Color(r_, g_, b_));
        }
    }

    return new_image;
}

Image multiply(const Image& a, const Image& b)
{
    Image new_image(a.width(), a.height());

    for(int row = 0; row < static_cast<int>(a.height()); row++)
    {
        for (int column = 0; column < static_cast<int>(a.width()); column++)
        {
            int r_ = static_cast<int>(a.pixelAt(row, column).r) * static_cast<int>(b.pixelAt(row, column).r);
            int g_ = static_cast<int>(a.pixelAt(row, column).g) * static_cast<int>(b.pixelAt(row, column).g);
            int b_ = static_cast<int>(a.pixelAt(row, column).b) * static_cast<int>(b.pixelAt(row, column).b);

            r_ /= 255;
            g_ /= 255;
            b_ /= 255;

            new_image.setPixel(row, column, Color(r_, g_, b_));
        }
    }

    return new_image;
}

namespace PerlinNoise
{
    double lerp(double a, double b, double x)
    {
        return a + x * (b - a);
    }

    double fade(double t)
    {
        return t * t * t * (t * (t * 6 - 15) + 10);
    }

    int inc(int num)
    {
        return num + 1;
    }

    double grad(int hash, double x, double y, double z)
    {
        switch(hash & 0xF)
        {
            case 0x0: return  x + y;
            case 0x1: return -x + y;
            case 0x2: return  x - y;
            case 0x3: return -x - y;
            case 0x4: return  x + z;
            case 0x5: return -x + z;
            case 0x6: return  x - z;
            case 0x7: return -x - z;
            case 0x8: return  y + z;
            case 0x9: return -y + z;
            case 0xA: return  y - z;
            case 0xB: return -y - z;
            case 0xC: return  y + x;
            case 0xD: return -y + z;
            case 0xE: return  y - x;
            case 0xF: return -y - z;
            default: return 0;
        }
    }

    double perlin(const std::vector<int>& p, double x, double y, double z)
    {
        int xi = static_cast<int>(x) & 255;
        int yi = static_cast<int>(y) & 255;
        int zi = static_cast<int>(z) & 255;

        double xf = x - static_cast<int>(x);
        double yf = y - static_cast<int>(y);
        double zf = z - static_cast<int>(z);

        double u = fade(xf);
        double v = fade(yf);
        double w = fade(zf);

        int aaa, aba, aab, abb, baa, bba, bab, bbb;
        aaa = p[p[p[    xi ]+    yi ]+    zi ];
        aba = p[p[p[    xi ]+inc(yi)]+    zi ];
        aab = p[p[p[    xi ]+    yi ]+inc(zi)];
        abb = p[p[p[    xi ]+inc(yi)]+inc(zi)];
        baa = p[p[p[inc(xi)]+    yi ]+    zi ];
        bba = p[p[p[inc(xi)]+inc(yi)]+    zi ];
        bab = p[p[p[inc(xi)]+    yi ]+inc(zi)];
        bbb = p[p[p[inc(xi)]+inc(yi)]+inc(zi)];

        double x1, x2, y1, y2;
        x1 = lerp(grad (aaa, xf, yf, zf), grad(baa, xf - 1, yf, zf), u);
        x2 = lerp(grad (aba, xf, yf - 1, zf), grad(bba, xf - 1, yf - 1, zf), u);
        y1 = lerp(x1, x2, v);
        x1 = lerp(grad (aab, xf, yf, zf - 1), grad (bab, xf - 1, yf , zf - 1), u);
        x2 = lerp(grad (abb, xf, yf - 1, zf - 1), grad (bbb, xf - 1, yf - 1, zf - 1), u);
        y2 = lerp(x1, x2, v);

        return (lerp(y1, y2, w) + 1) / 2;
    }

    Image perlin_noise(const Image& source, long long int seed, double zoom, double z, long long int octaves, double persistence)
    {
        Image new_image(source.width(), source.height());

        std::mt19937 engine(seed);

        std::vector<int> permutation;
        permutation.resize(256);
        std::iota(std::begin(permutation), std::end(permutation), 0);
        std::shuffle(std::begin(permutation), std::end(permutation), engine);

        permutation.insert(permutation.end(), permutation.begin(), permutation.end());

        std::vector<double> noise_array;

        noise_array.reserve(source.width() * source.height());
        double min = 1000;
        double max = -1000;
        for(int row = 0; row < static_cast<int>(source.height()); row++)
        {
            for(int column = 0; column < static_cast<int>(source.width()); column++)
            {
                double frequency = 1;
                double amplitude = 1;
                double max_value = 0;
                double total = 0;

                const double x = static_cast<double>(row) / static_cast<int>(source.height()) * zoom;
                const double y = static_cast<double>(column) / static_cast<int>(source.width()) * zoom;

                for(int i = 0; i < octaves; i++)
                {
                    total += amplitude * perlin(permutation, x * frequency, y * frequency, z * frequency);

                    max_value += amplitude;
                    amplitude *= persistence;
                    frequency *= 2;
                }

                noise_array.push_back(total);
                min = std::min(min, total);
                max = std::max(max, total);
            }
        }

        int i = 0;
        for(int row = 0; row < static_cast<int>(source.height()); row++)
        {
            for (int column = 0; column < static_cast<int>(source.width()); column++)
            {
                double noise = noise_array[i++];
                noise = -1. + 2. * (noise - min) / (max - min);
                noise += 1.;
                noise /= 2.;

                uint8_t sample = static_cast<double>(noise * 255);

                new_image.setPixel(row, column, Color(sample, sample, sample));
            }
        }

        return new_image;
    }
}

Image noise(const Image& source, long long int seed)
{
    Image new_image(source.width(), source.height());

    std::mt19937 engine(seed);
    std::uniform_int_distribution<uint8_t> distribution;

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for (int column = 0; column < static_cast<int>(source.width()); column++)
        {
            uint8_t sample = distribution(engine);
            new_image.setPixel(row, column, Color(sample, sample, sample));
        }
    }

    return new_image;
}

Image discriminator_greater_than(const Image& source, long long int threshold)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(source.width()); column++)
            if(source.pixelAt(row, column).r >= threshold)
                new_image.setPixel(row, column, Color(255, 255, 255));
            else new_image.setPixel(row, column, Color(0, 0, 0));
    }

    return new_image;
}

Image discriminator_lesser_than(const Image& source, long long int threshold)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(source.width()); column++)
            if(source.pixelAt(row, column).r <= threshold)
                new_image.setPixel(row, column, Color(255, 255, 255));
            else new_image.setPixel(row, column, Color(0, 0, 0));
    }

    return new_image;
}

Image discriminator_range(const Image& source, long long int a, long long int b)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for(int column = 0; column < static_cast<int>(source.width()); column++)
            if(source.pixelAt(row, column).r >= a && source.pixelAt(row, column).r <= b)
                new_image.setPixel(row, column, Color(255, 255, 255));
            else new_image.setPixel(row, column, Color(0, 0, 0));
    }

    return new_image;
}

Image solid_color(const Image& source, Color color)
{
    Image new_image(source.width(), source.height());

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for (int column = 0; column < static_cast<int>(source.width()); column++)
            new_image.setPixel(row, column, color);
    }

    return new_image;
}

Image lens_distortion(const Image& source, double strength, double zoom)
{
    Image new_image(source.width(), source.height());

    int half_width = source.width() / 2;
    int half_height = source.height() / 2;

    strength = strength == 0 ? 0.0001 : strength;
    double correction_radius = sqrt(
            source.width() * source.width() +
            source.height() * source.height()) / strength;

    for(int row = 0; row < static_cast<int>(source.height()); row++)
    {
        for (int column = 0; column < static_cast<int>(source.width()); column++) {
            int new_row = row - half_height;
            int new_column = column - half_width;

            double distance = sqrt(new_row * new_row + new_column * new_column);
            double r = distance / correction_radius;
            double theta = r == 0 ? 1 : atan(r) / r;

            double source_row = half_height + theta * new_row * zoom;
            double source_column = half_width + theta * new_column * zoom;

            if (0 < source_row && source_row < source.height() &&
                0 < source_column && source_column < source.width())
            {
                double x = source_column - floor(source_column);
                double y = source_row - floor(source_row);

                new_image.setPixel(
                        row,
                        column,
                        bilinear_interpolation({
                            source.pixelAt(static_cast<unsigned int>(floor(source_row)), static_cast<unsigned int>(floor(source_column))), //0, 0
                            source.pixelAt(static_cast<unsigned int>(floor(source_row)), static_cast<unsigned int>(ceil(source_column))), //1, 0
                            source.pixelAt(static_cast<unsigned int>(ceil(source_row)), static_cast<unsigned int>(ceil(source_column))), //1, 1
                            source.pixelAt(static_cast<unsigned int>(ceil(source_row)), static_cast<unsigned int>(floor(source_column)))  //0, 1
                        },{
                            Coord{0, 0},
                            Coord{1, 0},
                            Coord{1, 1},
                            Coord{0, 1}
                        }, x, y));
            }
            else new_image.setPixel(row, column, Color(0, 0, 0));
        }
    }

    return new_image;
}

int hue(Color color)
{
    int max = std::max({color.r, color.g, color.b});
    int min = std::min({color.r, color.g, color.b});

    min = max == min ? min - 1 : min;

    int hue;
    if(max == color.r)
        hue = (static_cast<int>(color.g ) - color.b) / (max - min);
    else if(max == color.g)
        hue = 2 + (static_cast<int>(color.b) - color.r) / (max - min);
    else hue = 4 + (static_cast<int>(color.r) - color.g) / (max - min);

    hue *= 60;
    hue = hue < 0 ? hue + 360 : hue;

    return hue;
}

Image jpeg_artifacts(const Image& source, int radius)
{
    Image new_image = source;

    for(int row = 0; row < static_cast<int>(new_image.height()); row++)
    {
        for (int column = 0; column < static_cast<int>(new_image.width()); column++)
        {
            int row_swap = -1;
            int column_swap = -1;
            int max = hue(new_image.pixelAt(row, column));

            int row_ = row - radius;
            for(int i = -radius; i < radius; i++)
            {
                if(row_ < 0 || row_ >= static_cast<int>(new_image.height()))
                    continue;

                int column_ = column - radius;
                for(int j = -radius; j < radius; j++)
                {
                    if(column_ < 0 || column_ >= static_cast<int>(new_image.width()))
                        continue;

                    if(max < hue(new_image.pixelAt(row_, column_)))
                    {
                        max = hue(new_image.pixelAt(row_, column_));
                        row_swap = row_;
                        column_swap = column_;
                    }

                    column_++;
                }
            }

            if(row_swap != -1)
            {
                new_image.setPixel(row, column, new_image.pixelAt(row_swap, column_swap));
                new_image.setPixel(row_swap, column_swap, source.pixelAt(row, column));
            }
        }
    }

    return new_image;
}

BOOST_PYTHON_MODULE(images_internal)
{
    using namespace boost::python;

    def("luminance_map", luminance_map);
    def("separate_blue_channel", separate_blue_channel);
    def("separate_red_channel", separate_red_channel);
    def("separate_green_channel", separate_green_channel);
    def("pixel_sort", pixel_sort);
    def("pixel_distort_displace", pixel_distort_displace);
    def("displacement", displacement);
    def("lift_gain", lift_gain);
    def("gamma", gamma_);
    def("contrast", contrast);
    def("brightness", brightness);
    def("box_blur", box_blur);
    def("mask", mask);
    def("strict_add", strict_add);
    def("add", add);
    def("multiply", multiply);
    def("perlin_noise", PerlinNoise::perlin_noise);
    def("noise", noise);
    def("discriminator_greater_than", discriminator_greater_than);
    def("discriminator_lesser_than", discriminator_lesser_than);
    def("discriminator_range", discriminator_range);
    def("solid_color", solid_color);
    def("lens_distortion", lens_distortion);
    def("jpeg_artifacts", jpeg_artifacts);
}

max_stars_repo_name: Kerdek/gie

max_issues_repo_name: Kerdek/gie

max_forks_repo_name: Kerdek/gie