<commit_before>/**
 * Copyright (c) 2011-2014 sx developers (see AUTHORS)
 *
 * This file is part of sx.
 *
 * sx is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * 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 <sx/command/qrcode.hpp>

#include <iostream>
#include <sx/utility/utility.hpp>

using namespace sx;
using namespace sx::extension;

console_result qrcode::invoke(std::istream& input, std::ostream& output,
    std::ostream& cerr)
{
    // Bound parameters.
    const auto path = get_file_option();
    const auto address = get_address_argument();

    // TODO
    // Create qrcode as binary data.
    // If path is empty or stdio sentinel set write data to output,
    // otherwise write data to specified path.

    cerr << SX_QRCODE_NOT_IMPLEMENTED << std::endl;
    return console_result::failure;
}

//#!/bin/bash
//if [ $# -ne 2 ]; then
//    echo "Usage: qrcode ADDRESS FILENAME"
//    exit 1
//fi
//command -v qrencode >/dev/null 2>&1 || { echo >&2 "Please install 'qrencode'."; exit 1; }
//ADDR=$1
//FILE=$2
//qrencode bitcoin:$ADDR -o $FILE -s 10
//
<commit_msg>Comments<commit_after>/**
 * Copyright (c) 2011-2014 sx developers (see AUTHORS)
 *
 * This file is part of sx.
 *
 * sx is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * 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 <sx/command/qrcode.hpp>

#include <iostream>
#include <sx/utility/utility.hpp>

using namespace sx;
using namespace sx::extension;

console_result qrcode::invoke(std::istream& input, std::ostream& output,
    std::ostream& cerr)
{
    // Bound parameters.
    const auto path = get_file_option();
    const auto address = get_address_argument();

    // TODO
    // Create qrcode as binary data.
    // If path is empty or SX_STDIN_PATH_SENTINEL, write data to output;
    // Otherwise write data to specified path.

    cerr << SX_QRCODE_NOT_IMPLEMENTED << std::endl;
    return console_result::failure;
}

//#!/bin/bash
//if [ $# -ne 2 ]; then
//    echo "Usage: qrcode ADDRESS FILENAME"
//    exit 1
//fi
//command -v qrencode >/dev/null 2>&1 || { echo >&2 "Please install 'qrencode'."; exit 1; }
//ADDR=$1
//FILE=$2
//qrencode bitcoin:$ADDR -o $FILE -s 10
//
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include "Timer.h"
#include "Cond.h"

#include "config.h"
#include "include/Context.h"

#define dout(x)  if (x <= g_conf.debug_timer) *_dout << dbeginl << g_clock.now() << " TIMER "
#define derr(x)  if (x <= g_conf.debug_timer) *_derr << dbeginl << g_clock.now() << " TIMER "

#define DBL 10

#include <signal.h>
#include <sys/time.h>
#include <math.h>

// single global instance
Timer      g_timer;

/**** thread solution *****/

bool Timer::get_next_due(utime_t& when)
{
  if (scheduled.empty()) {
    dout(10) << "get_next_due - nothing scheduled" << dendl;
    return false;
  } else {
    map< utime_t, set<Context*> >::iterator it = scheduled.begin();
    when = it->first;
    dout(10) << "get_next_due - " << when << dendl;
    return true;
  }
}

void Timer::timer_entry()
{
  lock.Lock();

  while (!thread_stop) {

    // now
    utime_t now = g_clock.now();

    // any events due?
    utime_t next;
    bool next_due = get_next_due(next);

    if (next_due && now >= next) {
      // move to pending list
      list<Context*> pending;

      map< utime_t, set<Context*> >::iterator it = scheduled.begin();
      while (it != scheduled.end()) {
        if (it->first > now) break;

        utime_t t = it->first;
        dout(DBL) << "queueing event(s) scheduled at " << t << dendl;

        for (set<Context*>::iterator cit = it->second.begin();
             cit != it->second.end();
             cit++) {
          pending.push_back(*cit);
          event_times.erase(*cit);
          num_event--;
        }

        map< utime_t, set<Context*> >::iterator previt = it;
        it++;
        scheduled.erase(previt);
      }

      if (!pending.empty()) {
        sleeping = false;
        lock.Unlock();
        {
	  // make sure we're not holding any locks while we do callbacks
          // make the callbacks myself.
          for (list<Context*>::iterator cit = pending.begin();
               cit != pending.end();
               cit++) {
            dout(DBL) << "start callback " << *cit << dendl;
            (*cit)->finish(0);
            dout(DBL) << "finish callback " << *cit << dendl;
	    delete *cit;
          }
          pending.clear();
          assert(pending.empty());
        }
        lock.Lock();
      }

    }
    else {
      // sleep
      if (next_due) {
        dout(DBL) << "sleeping until " << next << dendl;
        timed_sleep = true;
        sleeping = true;
        timeout_cond.WaitUntil(lock, next);  // wait for waker or time
        utime_t now = g_clock.now();
        dout(DBL) << "kicked or timed out at " << now << dendl;
      } else {
        dout(DBL) << "sleeping" << dendl;
        timed_sleep = false;
        sleeping = true;
        sleep_cond.Wait(lock);         // wait for waker
        utime_t now = g_clock.now();
        dout(DBL) << "kicked at " << now << dendl;
      }
    }
  }

  lock.Unlock();
}

/**
 * Timer bits
 */

void Timer::register_timer()
{
  if (timer_thread.is_started()) {
    if (sleeping) {
      dout(DBL) << "register_timer kicking thread" << dendl;
      if (timed_sleep)
        timeout_cond.SignalAll();
      else
        sleep_cond.SignalAll();
    } else {
      dout(DBL) << "register_timer doing nothing; thread is awake" << dendl;
      // it's probably doing callbacks.
    }
  } else {
    dout(DBL) << "register_timer starting thread" << dendl;
    timer_thread.create();
  }
}

void Timer::cancel_timer()
{
  // clear my callback pointers
  if (timer_thread.is_started()) {
    dout(10) << "setting thread_stop flag" << dendl;
    lock.Lock();
    thread_stop = true;
    if (timed_sleep)
      timeout_cond.SignalAll();
    else
      sleep_cond.SignalAll();
    lock.Unlock();

    dout(10) << "waiting for thread to finish" << dendl;
    void *ptr;
    timer_thread.join(&ptr);

    dout(10) << "thread finished, exit code " << ptr << dendl;
  }
}

/*
 * schedule
 */

void Timer::add_event_after(double seconds,
                            Context *callback)
{
  utime_t when = g_clock.now();
  when += seconds;
  add_event_at(when, callback);
}

void Timer::add_event_at(utime_t when,
                         Context *callback)
{
  lock.Lock();

  dout(DBL) << "add_event " << callback << " at " << when << dendl;

  // insert
  scheduled[when].insert(callback);
  assert(event_times.count(callback) == 0);
  event_times[callback] = when;

  num_event++;

  // make sure i wake up on time
  register_timer();

  lock.Unlock();
}

bool Timer::cancel_event(Context *callback)
{
  lock.Lock();

  dout(DBL) << "cancel_event " << callback << dendl;

  if (!event_times.count(callback)) {
    dout(DBL) << "cancel_event " << callback << " isn't scheduled (probably executing)" << dendl;
    lock.Unlock();
    return false;     // wasn't scheduled.
  }

  utime_t tp = event_times[callback];
  event_times.erase(callback);

  assert(scheduled.count(tp));
  assert(scheduled[tp].count(callback));
  scheduled[tp].erase(callback);
  if (scheduled[tp].empty())
    scheduled.erase(tp);

  lock.Unlock();

  // delete the canceled event.
  delete callback;

  return true;
}

// -------------------------------

void SafeTimer::add_event_after(double seconds, Context *c)
{
  assert(lock.is_locked());
  Context *w = new EventWrapper(this, c);
  dout(DBL) << "SafeTimer.add_event_after wrapping " << c << " with " << w << dendl;
  scheduled[c] = w;
  g_timer.add_event_after(seconds, w);
}

void SafeTimer::add_event_at(utime_t when, Context *c)
{
  assert(lock.is_locked());
  Context *w = new EventWrapper(this, c);
  dout(DBL) << "SafeTimer.add_event_at wrapping " << c << " with " << w << dendl;
  scheduled[c] = w;
  g_timer.add_event_at(when, w);
}

void SafeTimer::EventWrapper::finish(int r)
{
  timer->lock.Lock();
  if (timer->scheduled.count(actual)) {
    // still scheduled.  execute.
    actual->finish(r);
    timer->scheduled.erase(actual);
  } else {
    // i was canceled.
    assert(timer->canceled.count(actual));
  }

  // did i get canceled?
  // (this can happen even if i just executed above. e.g., i may have canceled myself.)
  if (timer->canceled.count(actual)) {
    timer->canceled.erase(actual);
    timer->cond.Signal();
  }

  // delete the original event
  delete actual;

  timer->lock.Unlock();
}

void SafeTimer::cancel_event(Context *c)
{
  assert(lock.is_locked());
  assert(scheduled.count(c));

  if (g_timer.cancel_event(scheduled[c])) {
    // hosed wrapper.  hose original event too.
    delete c;
  } else {
    // clean up later.
    canceled[c] = scheduled[c];
  }
  scheduled.erase(c);
}

void SafeTimer::cancel_all()
{
  assert(lock.is_locked());

  while (!scheduled.empty())
    cancel_event(scheduled.begin()->first);
}

void SafeTimer::join()
{
  assert(lock.is_locked());
  assert(scheduled.empty());

  if (!canceled.empty()) {
    while (!canceled.empty()) {
      // wait
      dout(2) << "SafeTimer.join waiting for " << canceled.size() << " to join: " << canceled << dendl;
      cond.Wait(lock);
    }
    dout(2) << "SafeTimer.join done" << dendl;
  }
}

SafeTimer::~SafeTimer()
{
  if (!scheduled.empty() && !canceled.empty()) {
    derr(0) << "SafeTimer.~SafeTimer " << scheduled.size() << " events scheduled, "
	    << canceled.size() << " canceled but unflushed"
	    << dendl;
  }
}
<commit_msg>timer: cleanup<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include "Timer.h"
#include "Cond.h"

#include "config.h"
#include "include/Context.h"

#define dout(x)  if (x <= g_conf.debug_timer) *_dout << dbeginl << g_clock.now() << " TIMER "
#define derr(x)  if (x <= g_conf.debug_timer) *_derr << dbeginl << g_clock.now() << " TIMER "

#define DBL 10

#include <signal.h>
#include <sys/time.h>
#include <math.h>

// single global instance
Timer      g_timer;

/**** thread solution *****/

bool Timer::get_next_due(utime_t& when)
{
  if (scheduled.empty()) {
    return false;
  } else {
    map< utime_t, set<Context*> >::iterator it = scheduled.begin();
    when = it->first;
    return true;
  }
}

void Timer::timer_entry()
{
  lock.Lock();

  utime_t now = g_clock.now();

  while (!thread_stop) {

    // any events due?
    utime_t next;
    bool next_due = get_next_due(next);
    if (next_due) {
      dout(10) << "get_next_due - " << next << dendl;
    } else {
      dout(10) << "get_next_due - nothing scheduled" << dendl;
    }

    if (next_due && now >= next) {
      // move to pending list
      list<Context*> pending;

      map< utime_t, set<Context*> >::iterator it = scheduled.begin();
      while (it != scheduled.end()) {
        if (it->first > now) break;

        utime_t t = it->first;
        dout(DBL) << "queueing event(s) scheduled at " << t << dendl;

        for (set<Context*>::iterator cit = it->second.begin();
             cit != it->second.end();
             cit++) {
          pending.push_back(*cit);
          event_times.erase(*cit);
          num_event--;
        }

        map< utime_t, set<Context*> >::iterator previt = it;
        it++;
        scheduled.erase(previt);
      }

      if (!pending.empty()) {
        sleeping = false;
        lock.Unlock();
        {
	  // make sure we're not holding any locks while we do callbacks
          // make the callbacks myself.
          for (list<Context*>::iterator cit = pending.begin();
               cit != pending.end();
               cit++) {
            dout(DBL) << "start callback " << *cit << dendl;
            (*cit)->finish(0);
            dout(DBL) << "finish callback " << *cit << dendl;
	    delete *cit;
          }
          pending.clear();
          assert(pending.empty());
        }
        lock.Lock();
      }

      now = g_clock.now();
      dout(DBL) << "looping at " << now << dendl;
    }
    else {
      // sleep
      if (next_due) {
        dout(DBL) << "sleeping until " << next << dendl;
        timed_sleep = true;
        sleeping = true;
        timeout_cond.WaitUntil(lock, next);  // wait for waker or time
        now = g_clock.now();
        dout(DBL) << "kicked or timed out at " << now << dendl;
      } else {
        dout(DBL) << "sleeping" << dendl;
        timed_sleep = false;
        sleeping = true;
        sleep_cond.Wait(lock);         // wait for waker
        now = g_clock.now();
        dout(DBL) << "kicked at " << now << dendl;
      }
    }
  }

  lock.Unlock();
}

/**
 * Timer bits
 */

void Timer::register_timer()
{
  if (timer_thread.is_started()) {
    if (sleeping) {
      dout(DBL) << "register_timer kicking thread" << dendl;
      if (timed_sleep)
        timeout_cond.SignalAll();
      else
        sleep_cond.SignalAll();
    } else {
      dout(DBL) << "register_timer doing nothing; thread is awake" << dendl;
      // it's probably doing callbacks.
    }
  } else {
    dout(DBL) << "register_timer starting thread" << dendl;
    timer_thread.create();
  }
}

void Timer::cancel_timer()
{
  // clear my callback pointers
  if (timer_thread.is_started()) {
    dout(10) << "setting thread_stop flag" << dendl;
    lock.Lock();
    thread_stop = true;
    if (timed_sleep)
      timeout_cond.SignalAll();
    else
      sleep_cond.SignalAll();
    lock.Unlock();

    dout(10) << "waiting for thread to finish" << dendl;
    void *ptr;
    timer_thread.join(&ptr);

    dout(10) << "thread finished, exit code " << ptr << dendl;
  }
}

/*
 * schedule
 */

void Timer::add_event_after(double seconds,
                            Context *callback)
{
  utime_t when = g_clock.now();
  when += seconds;
  add_event_at(when, callback);
}

void Timer::add_event_at(utime_t when,
                         Context *callback)
{
  lock.Lock();

  dout(DBL) << "add_event " << callback << " at " << when << dendl;

  // insert
  scheduled[when].insert(callback);
  assert(event_times.count(callback) == 0);
  event_times[callback] = when;

  num_event++;

  // make sure i wake up on time
  register_timer();

  lock.Unlock();
}

bool Timer::cancel_event(Context *callback)
{
  lock.Lock();

  dout(DBL) << "cancel_event " << callback << dendl;

  if (!event_times.count(callback)) {
    dout(DBL) << "cancel_event " << callback << " isn't scheduled (probably executing)" << dendl;
    lock.Unlock();
    return false;     // wasn't scheduled.
  }

  utime_t tp = event_times[callback];
  event_times.erase(callback);

  assert(scheduled.count(tp));
  assert(scheduled[tp].count(callback));
  scheduled[tp].erase(callback);
  if (scheduled[tp].empty())
    scheduled.erase(tp);

  lock.Unlock();

  // delete the canceled event.
  delete callback;

  return true;
}

// -------------------------------

void SafeTimer::add_event_after(double seconds, Context *c)
{
  assert(lock.is_locked());
  Context *w = new EventWrapper(this, c);
  dout(DBL) << "SafeTimer.add_event_after wrapping " << c << " with " << w << dendl;
  scheduled[c] = w;
  g_timer.add_event_after(seconds, w);
}

void SafeTimer::add_event_at(utime_t when, Context *c)
{
  assert(lock.is_locked());
  Context *w = new EventWrapper(this, c);
  dout(DBL) << "SafeTimer.add_event_at wrapping " << c << " with " << w << dendl;
  scheduled[c] = w;
  g_timer.add_event_at(when, w);
}

void SafeTimer::EventWrapper::finish(int r)
{
  timer->lock.Lock();
  if (timer->scheduled.count(actual)) {
    // still scheduled.  execute.
    actual->finish(r);
    timer->scheduled.erase(actual);
  } else {
    // i was canceled.
    assert(timer->canceled.count(actual));
  }

  // did i get canceled?
  // (this can happen even if i just executed above. e.g., i may have canceled myself.)
  if (timer->canceled.count(actual)) {
    timer->canceled.erase(actual);
    timer->cond.Signal();
  }

  // delete the original event
  delete actual;

  timer->lock.Unlock();
}

void SafeTimer::cancel_event(Context *c)
{
  assert(lock.is_locked());
  assert(scheduled.count(c));

  if (g_timer.cancel_event(scheduled[c])) {
    // hosed wrapper.  hose original event too.
    delete c;
  } else {
    // clean up later.
    canceled[c] = scheduled[c];
  }
  scheduled.erase(c);
}

void SafeTimer::cancel_all()
{
  assert(lock.is_locked());

  while (!scheduled.empty())
    cancel_event(scheduled.begin()->first);
}

void SafeTimer::join()
{
  assert(lock.is_locked());
  assert(scheduled.empty());

  if (!canceled.empty()) {
    while (!canceled.empty()) {
      // wait
      dout(2) << "SafeTimer.join waiting for " << canceled.size() << " to join: " << canceled << dendl;
      cond.Wait(lock);
    }
    dout(2) << "SafeTimer.join done" << dendl;
  }
}

SafeTimer::~SafeTimer()
{
  if (!scheduled.empty() && !canceled.empty()) {
    derr(0) << "SafeTimer.~SafeTimer " << scheduled.size() << " events scheduled, "
	    << canceled.size() << " canceled but unflushed"
	    << dendl;
  }
}
<|endoftext|>


<commit_before>/*
  main.cpp

  (C) Copyright 2015, Brad Parker
  All rights reserved.

  License: 3-clause BSD. See COPYING
*/

#include <QCoreApplication>
#include <QCommandLineParser>
#include <iostream>
#include "keyboard.h"

enum CommandLineParseResult
{
  CommandLineOk,
  CommandLineError,
  CommandLineVersionRequested,
  CommandLineHelpRequested
};

struct ColorOption {
  ColorOption() :
  region(REGION_LEFT)
  ,color(COLOR_RED)
  ,intensity(INTENSITY_HIGH)
  {}

  Region region;
  Color color;
  Intensity intensity;
};

struct KeyboardOptions {
  KeyboardOptions() :
  modeOption(MODE_NORMAL)
  ,colorOptions()
  ,modeSet(false)
  ,colorSet(false)
  {}

  Mode modeOption;
  QList<ColorOption*> colorOptions;
  bool modeSet;
  bool colorSet;

  void setMode(QString mode) {
    if(mode == "normal") { modeOption = MODE_NORMAL; }
    if(mode == "gaming") { modeOption = MODE_GAMING; }
    if(mode == "breathe") { modeOption = MODE_BREATHE; }
    if(mode == "demo") { modeOption = MODE_DEMO; }
    if(mode == "wave") { modeOption = MODE_WAVE; }

    modeSet = true;
  }

  void setColor(QString colorString) {
    QStringList fields = colorString.split(',');

    if(fields.count() != 3) {
      std::cerr << "invalid color selection" << std::endl;
      qApp->quit();
      return;
    }

    QString region = fields.at(0);
    QString color = fields.at(1);
    QString intensity = fields.at(2);

    ColorOption *colorOption = new ColorOption;

    if(region == "left") colorOption->region = REGION_LEFT;
    if(region == "middle") colorOption->region = REGION_MIDDLE;
    if(region == "right") colorOption->region = REGION_RIGHT;

    if(color == "off") colorOption->color = COLOR_OFF;
    if(color == "red") colorOption->color = COLOR_RED;
    if(color == "orange") colorOption->color = COLOR_ORANGE;
    if(color == "yellow") colorOption->color = COLOR_YELLOW;
    if(color == "green") colorOption->color = COLOR_GREEN;
    if(color == "sky") colorOption->color = COLOR_SKY;
    if(color == "blue") colorOption->color = COLOR_BLUE;
    if(color == "purple") colorOption->color = COLOR_PURPLE;
    if(color == "white") colorOption->color = COLOR_WHITE;

    if(intensity == "high") colorOption->intensity = INTENSITY_HIGH;
    if(intensity == "medium") colorOption->intensity = INTENSITY_MEDIUM;
    if(intensity == "low") colorOption->intensity = INTENSITY_LOW;
    if(intensity == "light") colorOption->intensity = INTENSITY_LIGHT;

    colorSet = true;

    colorOptions.append(colorOption);
  }
};

CommandLineParseResult parseCommandLine(QCommandLineParser &parser, KeyboardOptions *keyboardOptions, QString *errorMessage) {
  QCommandLineOption helpOption = parser.addHelpOption();
  QCommandLineOption versionOption = parser.addVersionOption();

  QCommandLineOption mode(QStringList() << "m" << "mode", "set color <mode>: normal, gaming, breathe, demo, wave", "mode");
  QCommandLineOption color(QStringList() << "c" << "color", "set a <color> using the format: region,color,intensity", "color");

  parser.addOption(mode);
  parser.addOption(color);

  if(!parser.parse(QCoreApplication::arguments())) {
    *errorMessage = parser.errorText();
    return CommandLineError;
  }

  if(parser.isSet(versionOption))
    return CommandLineVersionRequested;

  if(parser.isSet(helpOption))
    return CommandLineHelpRequested;

  if(parser.isSet(mode)) {
    keyboardOptions->setMode(parser.value(mode));
  }

  if(parser.isSet(color)) {
    foreach(const QString &colorValue, parser.values(color)) {
      keyboardOptions->setColor(colorValue);
    }
  }

  return CommandLineOk;
}

int main(int argc, char *argv[]) {
  QCoreApplication app(argc, argv);
  app.setApplicationName("msi-keyboard");
  app.setApplicationVersion("1.0");

  QCommandLineParser parser;
  parser.setApplicationDescription("Keyboard color changer for MSI steelseries keyboards");

  QString errorMessage;
  KeyboardOptions keyboardOptions;

  switch(parseCommandLine(parser, &keyboardOptions, &errorMessage)) {
    case CommandLineOk:
      break;
    case CommandLineError:
      fputs(qPrintable(errorMessage), stderr);
      fputs("\n\n", stderr);
      fputs(qPrintable(parser.helpText()), stderr);
      return 1;
    case CommandLineVersionRequested:
      printf("%s %s\n", qPrintable(QCoreApplication::applicationName()),
             qPrintable(QCoreApplication::applicationVersion()));
      return 0;
    case CommandLineHelpRequested:
    {
      std::cout << qPrintable(parser.helpText()) << std::endl;

      QStringList regions = QStringList() << "left" << "middle" << "right";
      QStringList colors = QStringList() << "off" << "red" << "orange" << "yellow" << "green" << "sky" << "blue" << "purple" << "white";
      QStringList intensities = QStringList() << "high" << "medium" << "low" << "light";

      QString colorHelp = QString(R"(Available regions:

%1

Available colors:

%2

Available intensities:

%3

Example:

%4
)").arg(regions.join('\n')).arg(colors.join('\n')).arg(intensities.join('\n')).arg(QString(argv[0]) + " -m normal -c left,red,high -c middle,purple,high -c right,sky,high");

      std::cout << qPrintable(colorHelp) << std::endl;

      return 0;
    }
  }

  if(!keyboardOptions.modeSet && !keyboardOptions.colorSet) {
    std::cerr << "Please set an option to change, either the mode or color. Both can be specified, as well as multiple color options (one for each region)" << std::endl;
    return 1;
  }else{
    Keyboard k;

    if(keyboardOptions.modeSet) {
      k.setMode(keyboardOptions.modeOption);
    }

    if(keyboardOptions.colorSet) {
      for(int i = 0; i < keyboardOptions.colorOptions.count(); ++i) {
        ColorOption *colorOption = keyboardOptions.colorOptions.at(i);

        k.setColor(colorOption->region, colorOption->color, colorOption->intensity);
      }
    }
  }

  /*k.setMode(MODE_NORMAL);
  k.setColor(REGION_LEFT, COLOR_RED, INTENSITY_HIGH);
  k.setColor(REGION_MIDDLE, COLOR_PURPLE, INTENSITY_HIGH);
  k.setColor(REGION_RIGHT, COLOR_SKY, INTENSITY_HIGH);*/

  return 0;
}
<commit_msg>require mode to be set every time<commit_after>/*
  main.cpp

  (C) Copyright 2015, Brad Parker
  All rights reserved.

  License: 3-clause BSD. See COPYING
*/

#include <QCoreApplication>
#include <QCommandLineParser>
#include <iostream>
#include "keyboard.h"

enum CommandLineParseResult
{
  CommandLineOk,
  CommandLineError,
  CommandLineVersionRequested,
  CommandLineHelpRequested
};

struct ColorOption {
  ColorOption() :
  region(REGION_LEFT)
  ,color(COLOR_RED)
  ,intensity(INTENSITY_HIGH)
  {}

  Region region;
  Color color;
  Intensity intensity;
};

struct KeyboardOptions {
  KeyboardOptions() :
  modeOption(MODE_NORMAL)
  ,colorOptions()
  ,modeSet(false)
  ,colorSet(false)
  {}

  Mode modeOption;
  QList<ColorOption*> colorOptions;
  bool modeSet;
  bool colorSet;

  void setMode(QString mode) {
    if(mode == "normal") { modeOption = MODE_NORMAL; }
    if(mode == "gaming") { modeOption = MODE_GAMING; }
    if(mode == "breathe") { modeOption = MODE_BREATHE; }
    if(mode == "demo") { modeOption = MODE_DEMO; }
    if(mode == "wave") { modeOption = MODE_WAVE; }

    modeSet = true;
  }

  void setColor(QString colorString) {
    QStringList fields = colorString.split(',');

    if(fields.count() != 3) {
      std::cerr << "invalid color selection" << std::endl;
      qApp->quit();
      return;
    }

    QString region = fields.at(0);
    QString color = fields.at(1);
    QString intensity = fields.at(2);

    ColorOption *colorOption = new ColorOption;

    if(region == "left") colorOption->region = REGION_LEFT;
    if(region == "middle") colorOption->region = REGION_MIDDLE;
    if(region == "right") colorOption->region = REGION_RIGHT;

    if(color == "off") colorOption->color = COLOR_OFF;
    if(color == "red") colorOption->color = COLOR_RED;
    if(color == "orange") colorOption->color = COLOR_ORANGE;
    if(color == "yellow") colorOption->color = COLOR_YELLOW;
    if(color == "green") colorOption->color = COLOR_GREEN;
    if(color == "sky") colorOption->color = COLOR_SKY;
    if(color == "blue") colorOption->color = COLOR_BLUE;
    if(color == "purple") colorOption->color = COLOR_PURPLE;
    if(color == "white") colorOption->color = COLOR_WHITE;

    if(intensity == "high") colorOption->intensity = INTENSITY_HIGH;
    if(intensity == "medium") colorOption->intensity = INTENSITY_MEDIUM;
    if(intensity == "low") colorOption->intensity = INTENSITY_LOW;
    if(intensity == "light") colorOption->intensity = INTENSITY_LIGHT;

    colorSet = true;

    colorOptions.append(colorOption);
  }
};

CommandLineParseResult parseCommandLine(QCommandLineParser &parser, KeyboardOptions *keyboardOptions, QString *errorMessage) {
  QCommandLineOption helpOption = parser.addHelpOption();
  QCommandLineOption versionOption = parser.addVersionOption();

  QCommandLineOption mode(QStringList() << "m" << "mode", "set color <mode>: normal, gaming, breathe, demo, wave", "mode");
  QCommandLineOption color(QStringList() << "c" << "color", "set a <color> using the format: region,color,intensity", "color");

  parser.addOption(mode);
  parser.addOption(color);

  if(!parser.parse(QCoreApplication::arguments())) {
    *errorMessage = parser.errorText();
    return CommandLineError;
  }

  if(parser.isSet(versionOption))
    return CommandLineVersionRequested;

  if(parser.isSet(helpOption))
    return CommandLineHelpRequested;

  if(parser.isSet(mode)) {
    keyboardOptions->setMode(parser.value(mode));
  }

  if(parser.isSet(color)) {
    foreach(const QString &colorValue, parser.values(color)) {
      keyboardOptions->setColor(colorValue);
    }
  }

  return CommandLineOk;
}

int main(int argc, char *argv[]) {
  QCoreApplication app(argc, argv);
  app.setApplicationName("msi-keyboard");
  app.setApplicationVersion("1.0");

  QCommandLineParser parser;
  parser.setApplicationDescription("Keyboard color changer for MSI steelseries keyboards");

  QString errorMessage;
  KeyboardOptions keyboardOptions;

  switch(parseCommandLine(parser, &keyboardOptions, &errorMessage)) {
    case CommandLineOk:
      break;
    case CommandLineError:
      fputs(qPrintable(errorMessage), stderr);
      fputs("\n\n", stderr);
      fputs(qPrintable(parser.helpText()), stderr);
      return 1;
    case CommandLineVersionRequested:
      printf("%s %s\n", qPrintable(QCoreApplication::applicationName()),
             qPrintable(QCoreApplication::applicationVersion()));
      return 0;
    case CommandLineHelpRequested:
    {
      std::cout << qPrintable(parser.helpText()) << std::endl;

      QStringList regions = QStringList() << "left" << "middle" << "right";
      QStringList colors = QStringList() << "off" << "red" << "orange" << "yellow" << "green" << "sky" << "blue" << "purple" << "white";
      QStringList intensities = QStringList() << "high" << "medium" << "low" << "light";

      QString colorHelp = QString(R"(Available regions:

%1

Available colors:

%2

Available intensities:

%3

Example:

%4
)").arg(regions.join('\n')).arg(colors.join('\n')).arg(intensities.join('\n')).arg(QString(argv[0]) + " -m normal -c left,red,high -c middle,purple,high -c right,sky,high");

      std::cout << qPrintable(colorHelp) << std::endl;

      return 0;
    }
  }

  if(!keyboardOptions.modeSet || !keyboardOptions.colorSet) {
    std::cerr << "Please set a mode as well as at least one color region to change." << std::endl;
    return 1;
  }else{
    Keyboard k;

    if(keyboardOptions.modeSet) {
      k.setMode(keyboardOptions.modeOption);
    }

    if(keyboardOptions.colorSet) {
      for(int i = 0; i < keyboardOptions.colorOptions.count(); ++i) {
        ColorOption *colorOption = keyboardOptions.colorOptions.at(i);

        k.setColor(colorOption->region, colorOption->color, colorOption->intensity);
      }
    }
  }

  /*k.setMode(MODE_NORMAL);
  k.setColor(REGION_LEFT, COLOR_RED, INTENSITY_HIGH);
  k.setColor(REGION_MIDDLE, COLOR_PURPLE, INTENSITY_HIGH);
  k.setColor(REGION_RIGHT, COLOR_SKY, INTENSITY_HIGH);*/

  return 0;
}
<|endoftext|>


<commit_before>/*
 * libtins is a net packet wrapper library for crafting and
 * interpreting sniffed packets.
 *
 * Copyright (C) 2011 Nasel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <cassert>
#include "utils.h"
#include "pdu.h"
#include "rawpdu.h"

Tins::PDU::PDU(uint32_t flag, PDU *next_pdu) : _flag(flag), _inner_pdu(next_pdu) {

}

Tins::PDU::~PDU() {
    delete _inner_pdu;
}

uint32_t Tins::PDU::size() const {
    uint32_t sz = header_size() + trailer_size();
    const PDU *ptr(_inner_pdu);
    while(ptr) {
        sz += ptr->header_size() + trailer_size();
        ptr = ptr->inner_pdu();
    }
    return sz;
}

void Tins::PDU::flag(uint32_t new_flag) {
    _flag = new_flag;
}

void Tins::PDU::inner_pdu(PDU *next_pdu) {
    delete _inner_pdu;
    _inner_pdu = next_pdu;
}

uint8_t *Tins::PDU::serialize(uint32_t &sz) {
    sz = size();
    uint8_t *buffer = new uint8_t[sz];
    serialize(buffer, sz, 0);
    return buffer;
}

void Tins::PDU::serialize(uint8_t *buffer, uint32_t total_sz, const PDU *parent) {
    uint32_t sz = header_size() + trailer_size();
    /* Must not happen... */
    assert(total_sz >= sz);
    if(_inner_pdu)
        _inner_pdu->serialize(buffer + header_size(), total_sz - sz, this);
    write_serialization(buffer, total_sz, parent);
}

Tins::PDU *Tins::PDU::clone_inner_pdu(const uint8_t *ptr, uint32_t total_sz) {
    PDU *child = 0;
    if(inner_pdu()) {
        child = inner_pdu()->clone_packet(ptr, total_sz);
        if(!child)
            return 0;
    }
    else
        child = new RawPDU(ptr, total_sz);
    return child;
}

/* Static methods */
uint32_t Tins::PDU::do_checksum(uint8_t *start, uint8_t *end) {
    uint32_t checksum(0);
    uint16_t *ptr = (uint16_t*)start, *last = (uint16_t*)end, padding(0);
    if(((end - start) & 1) == 1) {
        last = (uint16_t*)end - 1;
        padding = *(end - 1) << 8;
    }
    while(ptr < last)
        checksum += Utils::net_to_host_s(*(ptr++));
    return checksum + padding;
}

uint32_t Tins::PDU::pseudoheader_checksum(uint32_t source_ip, uint32_t dest_ip, uint32_t len, uint32_t flag) {
    uint32_t checksum(0);
    source_ip = Utils::net_to_host_l(source_ip);
    dest_ip = Utils::net_to_host_l(dest_ip);
    uint16_t *ptr = (uint16_t*)&source_ip;

    checksum += (uint32_t)(*ptr) + (uint32_t)(*(ptr+1));
    ptr = (uint16_t*)&dest_ip;
    checksum += (uint32_t)(*ptr) + (uint32_t)(*(ptr+1));
    checksum += flag + len;
    return checksum;
}

<commit_msg>Fixed a bug in PDU::size.<commit_after>/*
 * libtins is a net packet wrapper library for crafting and
 * interpreting sniffed packets.
 *
 * Copyright (C) 2011 Nasel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <cassert>
#include "utils.h"
#include "pdu.h"
#include "rawpdu.h"

Tins::PDU::PDU(uint32_t flag, PDU *next_pdu) : _flag(flag), _inner_pdu(next_pdu) {

}

Tins::PDU::~PDU() {
    delete _inner_pdu;
}

uint32_t Tins::PDU::size() const {
    uint32_t sz = header_size() + trailer_size();
    const PDU *ptr(_inner_pdu);
    while(ptr) {
        sz += ptr->header_size() + ptr->trailer_size();
        ptr = ptr->inner_pdu();
    }
    return sz;
}

void Tins::PDU::flag(uint32_t new_flag) {
    _flag = new_flag;
}

void Tins::PDU::inner_pdu(PDU *next_pdu) {
    delete _inner_pdu;
    _inner_pdu = next_pdu;
}

uint8_t *Tins::PDU::serialize(uint32_t &sz) {
    sz = size();
    uint8_t *buffer = new uint8_t[sz];
    serialize(buffer, sz, 0);
    return buffer;
}

void Tins::PDU::serialize(uint8_t *buffer, uint32_t total_sz, const PDU *parent) {
    uint32_t sz = header_size() + trailer_size();
    /* Must not happen... */
    assert(total_sz >= sz);
    if(_inner_pdu)
        _inner_pdu->serialize(buffer + header_size(), total_sz - sz, this);
    write_serialization(buffer, total_sz, parent);
}

Tins::PDU *Tins::PDU::clone_inner_pdu(const uint8_t *ptr, uint32_t total_sz) {
    PDU *child = 0;
    if(inner_pdu()) {
        child = inner_pdu()->clone_packet(ptr, total_sz);
        if(!child)
            return 0;
    }
    else
        child = new RawPDU(ptr, total_sz);
    return child;
}

/* Static methods */
uint32_t Tins::PDU::do_checksum(uint8_t *start, uint8_t *end) {
    uint32_t checksum(0);
    uint16_t *ptr = (uint16_t*)start, *last = (uint16_t*)end, padding(0);
    if(((end - start) & 1) == 1) {
        last = (uint16_t*)end - 1;
        padding = *(end - 1) << 8;
    }
    while(ptr < last)
        checksum += Utils::net_to_host_s(*(ptr++));
    return checksum + padding;
}

uint32_t Tins::PDU::pseudoheader_checksum(uint32_t source_ip, uint32_t dest_ip, uint32_t len, uint32_t flag) {
    uint32_t checksum(0);
    source_ip = Utils::net_to_host_l(source_ip);
    dest_ip = Utils::net_to_host_l(dest_ip);
    uint16_t *ptr = (uint16_t*)&source_ip;

    checksum += (uint32_t)(*ptr) + (uint32_t)(*(ptr+1));
    ptr = (uint16_t*)&dest_ip;
    checksum += (uint32_t)(*ptr) + (uint32_t)(*(ptr+1));
    checksum += flag + len;
    return checksum;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <math.h>

using namespace std;

const int n = 9;

bool fun(bool *x)
{
	for (unsigned int j = 0; j < n-2; ++j)
		if ((x[j] != x[j+1]) && (x[j] != x[j+2]))
			return false;
	return true;
}

void overrun()
{
	for (unsigned int i = 0; i < pow(2, n); ++i)
	{
		bool x[n];
		unsigned k = i;
		for (unsigned int j = 0; j < n; ++j)
		{
			x[n-j-1] = 0x1 & k;
			k >>= 1;
		}
		if (fun(x))
		{
			for (unsigned int j = 0; j < n; ++j)
				cout << x[j];
			cout << endl;
		}
	}
}

int main(int argc, char* argv[])
{
	switch(argc)
	{
	case 1:
		cout << "запуск без параметров. выбран режим работы по умолчанию." << endl;
		overrun();
		return 0;
	case 2:
		if (!strcmp(argv[1],"-d"))
		{
			cout << "режим работы по умолчанию" << endl;
			overrun();
			return 0;
		}
		if (!strcmp(argv[1],"-i"))
		{
			cout << "интерактивный режим еще не поддерживается" << endl;
			return(10);
		}
		cout << "неизвестный параметр" << endl;
		return(1);
	default:
		cout << "слишком много параметров" << endl;
		return(2);
	}
}
<commit_msg>add caclculator expression (from C++ Bjarne Stroustrup)<commit_after>#include <iostream>
#include <map>
#include <math.h>

using namespace std;

const int n = 9;

bool fun(bool *x)
{
	for (unsigned int j = 0; j < n-2; ++j)
		if ((x[j] != x[j+1]) && (x[j] != x[j+2]))
			return false;
	return true;
}

enum Token_value
{
	NAME, NUMBER, END,
	PLUS = '+', MINUS = '-', MUL = '*', DIV = '/',
	PRINT = ';', ASSIGN = '=', LP = '(', RP = ')'
};

Token_value curr_tok = PRINT;
double number_value;
string string_value;
map<string, double> table;
int no_of_errors;

double expr(bool);

int error(const string& s)
{
	++no_of_errors;
	cerr << "ошибка: " << s << endl;
	return 1;
}

Token_value get_token()
{
	char ch = 0;
	cin >> ch;
	switch(ch)
	{
	case 0:
		return curr_tok = END;
	case ';':
	case '*':
	case '/':
	case '+':
	case '-':
	case '(':
	case ')':
	case '=':
		return curr_tok = Token_value(ch);
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
	case '.':
		cin.putback(ch);
		cin >> number_value;
		return curr_tok = NUMBER;
	default:
		if (isalpha(ch))
		{
			cin.putback(ch);
			cin >> string_value;
			return curr_tok = NAME;
		}
		error("неправильная лексема");
		return curr_tok = PRINT;
	}
}

double prim(bool get)
{
	if (get)
		get_token();

	switch(curr_tok)
	{
	case NUMBER:
	{
		double v = number_value;
		get_token();
		return v;
	}
	case NAME:
	{
		double& g = table[string_value];
		if (get_token() == ASSIGN)
			g = expr(true);
		return g;
	}
	case MINUS:
		return -prim(true);
	case LP:
	{
		double e = expr(true);
		if (curr_tok != RP)
			return error("ожидалась )");
		get_token();
		return e;
	}
	default:
		return error("ожидалось первичное выражение");
	}
}

double term(bool get)
{
	double left = prim(get);
	while (true)
	{
		switch(curr_tok)
		{
		case MUL:
			left *= prim(true);
			break;
		case DIV:
			if (double d = prim(true))
			{
				left /= d;
				break;
			}
			return error("деление на 0");
		default:
			return left;
		}
	}
}

double expr(bool get)
{
	double left = term(get);
	while(true)
	{
		switch(curr_tok)
		{
		case PLUS:
			left += term(true);
			break;
		case MINUS:
			left -= term(true);
			break;
		default:
			return left;
		}
	}
}

void calculate()
{
	while(cin)
	{
		get_token();
		if (curr_tok == END)
			break;
		if (curr_tok == PRINT)
			continue;
		cout << expr(false) << endl;
	}
}

void overrun()
{
	for (unsigned int i = 0; i < pow(2, n); ++i)
	{
		bool x[n];
		unsigned k = i;
		for (unsigned int j = 0; j < n; ++j)
		{
			x[n-j-1] = 0x1 & k;
			k >>= 1;
		}
		if (fun(x))
		{
			for (unsigned int j = 0; j < n; ++j)
				cout << x[j];
			cout << endl;
		}
	}
}

int main(int argc, char* argv[])
{
	switch(argc)
	{
	case 1:
		cout << "запуск без параметров. выбран режим работы по умолчанию." << endl;
		overrun();
		return 0;
	case 2:
		if (!strcmp(argv[1],"-d"))
		{
			cout << "режим работы по умолчанию" << endl;
			overrun();
			return 0;
		}
		if (!strcmp(argv[1],"-i"))
		{
			cout << "интерактивный режим еще не поддерживается, пока запускается просто калькулятор" << endl;
			calculate();
			return(10);
		}
		cout << "неизвестный параметр" << endl;
		return(1);
	default:
		cout << "слишком много параметров" << endl;
		return(2);
	}
}
<|endoftext|>


<commit_before>71beb2ca-4b02-11e5-b7e9-28cfe9171a43<commit_msg>Hey we can now do a thing<commit_after>71cb9df0-4b02-11e5-8e04-28cfe9171a43<|endoftext|>


<commit_before>fbbabf7d-2747-11e6-9068-e0f84713e7b8<commit_msg>GOD DAMNED IT!<commit_after>fbcbf1a3-2747-11e6-a882-e0f84713e7b8<|endoftext|>


<commit_before>#include <compression.hpp>
#ifdef ENVIRONMENT_WINDOWS
#define ZLIB_WINAPI
#endif
#include <zlib.h>
#include <stdexcept>
#include <type_traits>

namespace MCPP {

	static const char * zlib_error="ZLib error";
	static const Word inflate_buffer_default=256;

	void Inflate (const Byte * begin, const Byte * end, Vector<Byte> * buffer) {

		//	Null check
		if (buffer==nullptr) throw std::out_of_range(NullPointerError);

		//	Preserve initial count for atomicity
		Word initial_count=buffer->Count();

		//	In event of error we roll
		//	buffer back
		try {

			//	Create and initialize a stream
			z_stream stream;
			stream.zalloc=Z_NULL;
			stream.zfree=Z_NULL;
			stream.opaque=Z_NULL;

			if (inflateInit2(&stream,32+MAX_WBITS)!=Z_OK) throw std::runtime_error(zlib_error);

			try {

				//	Convert the number of bytes to
				//	decompress safely to the target
				//	integer type and store in stream
				stream.avail_in=static_cast<decltype(stream.avail_in)>(
					SafeInt<decltype(end-begin)>(end-begin)
				);
				//	The ZLib compression/decompression
				//	functions do not modify the in buffer,
				//	therefore it should technically be
				//	const, but it's not so we'll do an
				//	ugly const_cast here...
				stream.next_in=const_cast<decltype(stream.next_in)>(
					reinterpret_cast<const std::remove_pointer<decltype(stream.next_in)>::type *>(
						begin
					)
				);

				//	Loop and decompress
				for (;;) {

					//	Wire output buffer into stream
					stream.next_out=reinterpret_cast<decltype(stream.next_out)>(buffer->end());
					stream.avail_out=static_cast<decltype(stream.avail_out)>(
						SafeWord(
							buffer->Capacity()-buffer->Count()
						)
					);

					//	Inflate
					int result=inflate(&stream,Z_FINISH);

					//	Update buffer count
					buffer->SetCount(buffer->Capacity()-stream.avail_out);

					//	Did we decompress everything?
					//	If so we're done.
					if (result==Z_STREAM_END) break;

					//	Was more buffer space required?
					if (result==Z_BUF_ERROR) {

						buffer->SetCapacity();

						continue;

					}

					//	Something went wrong, throw
					throw std::runtime_error(zlib_error);

				}

			} catch (...) {

				//	Make sure stream is
				//	cleaned up
				inflateEnd(&stream);

				throw;

			}

			inflateEnd(&stream);

		} catch (...) {

			//	Roll buffer back
			buffer->SetCount(initial_count);

			//	Propagate
			throw;

		}

	}

	Vector<Byte> Inflate (const Byte * begin, const Byte * end) {

		//	Create buffer
		Vector<Byte> buffer(inflate_buffer_default);

		//	Inflate
		Inflate(begin,end,&buffer);

		//	Return
		return buffer;

	}

	void Deflate (const Byte * begin, const Byte * end, Vector<Byte> * buffer, bool gzip) {

		//	Null check
		if (buffer==nullptr) throw std::out_of_range(NullPointerError);

		//	Preserve initial count for atomicity
		Word initial_count=buffer->Count();

		//	In event of error we roll
		//	buffer back
		try {

			//	Create and initialize a stream
			z_stream stream;
			stream.zalloc=Z_NULL;
			stream.zfree=Z_NULL;
			stream.opaque=Z_NULL;

			if (deflateInit2(
				&stream,
				Z_DEFAULT_COMPRESSION,
				Z_DEFLATED,
				MAX_WBITS+(gzip ? 16 : 0),
				8,
				Z_DEFAULT_STRATEGY
			)!=Z_OK) throw std::runtime_error(zlib_error);

			try {

				//	Convert the number of bytes to
				//	compress safely to the target
				//	integer type and store them
				//	in stream
				stream.avail_in=static_cast<decltype(stream.avail_in)>(
					SafeInt<decltype(end-begin)>(end-begin)
				);
				//	The ZLib compression/decompression
				//	functions do not modify the in buffer,
				//	therefore it should technically be
				//	const, but it's not so we'll do an
				//	ugly const_cast here...
				stream.next_in=const_cast<decltype(stream.next_in)>(
					reinterpret_cast<const std::remove_pointer<decltype(stream.next_in)>::type *>(
						begin
					)
				);

				//	Loop and compress
				for (;;) {

					//	Wire output buffer into stream
					stream.next_out=reinterpret_cast<decltype(stream.next_out)>(buffer->end());
					stream.avail_out=static_cast<decltype(stream.avail_out)>(SafeWord(buffer->Capacity()-buffer->Count()));

					//	Deflate
					int result=deflate(&stream,Z_FINISH);

					//	Update buffer count
					buffer->SetCount(buffer->Capacity()-stream.avail_out);

					//	Did we compress everything?
					//	If so we're done
					if (result==Z_STREAM_END) break;

					//	Does the buffer need to be bigger?
					if (result==Z_BUF_ERROR) {

						buffer->SetCapacity();

						continue;

					}

					//	Error
					throw std::runtime_error(zlib_error);

				}

			} catch (...) {

				//	Make sure the stream is
				//	cleaned up
				deflateEnd(&stream);

				throw;

			}

			deflateEnd(&stream);

		} catch (...) {

			//	Roll buffer back
			buffer->SetCount(initial_count);

			//	Propagate
			throw;

		}

	}

	Vector<Byte> Deflate (const Byte * begin, const Byte * end, bool gzip) {

		//	We want to try and do this in
		//	one go, so get the bound and
		//	initialize the output buffer
		//	to that size
		Word num=Word(SafeInt<decltype(end-begin)>(end-begin));
		Vector<Byte> buffer(DeflateBound(num,gzip));

		//	Compress
		Deflate(begin,end,&buffer,gzip);

		//	Return
		return buffer;

	}

	Word DeflateBound (Word num, bool gzip) {

		//	Safely convert the input number to
		//	the type that deflateBound expects
		typedef FunctionInformation<decltype(deflateBound)>::ArgumentType<1>::Type LengthType;

		LengthType z_num=LengthType(SafeWord(num));

		//	Prepare a dummy stream
		z_stream stream;
		stream.zalloc=Z_NULL;
		stream.zfree=Z_NULL;
		stream.opaque=Z_NULL;

		if (deflateInit2(
			&stream,
			Z_DEFAULT_COMPRESSION,
			Z_DEFLATED,
			MAX_WBITS+(gzip ? 16 : 0),
			8,
			Z_DEFAULT_STRATEGY
		)!=Z_OK) throw std::runtime_error(zlib_error);

		Word bound;
		try {

			//	Obtain the bound
			bound=Word(
				SafeInt<decltype(deflateBound(&stream,z_num))>(
					deflateBound(&stream,z_num)
				)
			);

		} catch (...) {

			deflateEnd(&stream);

			throw;

		}

		//	Free the stream
		deflateEnd(&stream);

		//	Return
		return bound;

	}

}
<commit_msg>Compression Fix<commit_after>#include <compression.hpp>
#ifdef ENVIRONMENT_WINDOWS
#define ZLIB_WINAPI
#endif
#include <zlib.h>
#include <stdexcept>
#include <type_traits>

namespace MCPP {

	static const char * zlib_error="ZLib error";
	static const Word inflate_buffer_default=256;

	void Inflate (const Byte * begin, const Byte * end, Vector<Byte> * buffer) {

		//	Null check
		if (buffer==nullptr) throw std::out_of_range(NullPointerError);

		//	Preserve initial count for atomicity
		Word initial_count=buffer->Count();

		//	In event of error we roll
		//	buffer back
		try {

			//	Create and initialize a stream
			z_stream stream;
			stream.zalloc=Z_NULL;
			stream.zfree=Z_NULL;
			stream.opaque=Z_NULL;

			if (inflateInit2(&stream,32+MAX_WBITS)!=Z_OK) throw std::runtime_error(zlib_error);

			try {

				//	Wire input buffer into the stream
				auto avail=end-begin;
				stream.avail_in=static_cast<decltype(stream.avail_in)>(SafeInt<decltype(avail)>(avail));
				stream.next_in=const_cast<decltype(stream.next_in)>(
					reinterpret_cast<const std::remove_pointer<decltype(stream.next_in)>::type *>(
						begin
					)
				);

				//	Loop and decompress
				for (;;) {

					//	Wire output buffer into stream
					stream.next_out=reinterpret_cast<decltype(stream.next_out)>(buffer->end());
					stream.avail_out=static_cast<decltype(stream.avail_out)>(
						SafeWord(
							buffer->Capacity()-buffer->Count()
						)
					);

					//	Inflate
					int result=inflate(&stream,Z_FINISH);

					//	Update buffer count
					buffer->SetCount(buffer->Capacity()-stream.avail_out);

					//	Did we decompress everything?
					//	If so we're done.
					if (result==Z_STREAM_END) break;

					//	Was more buffer space required?
					if ((result==Z_BUF_ERROR) && (stream.avail_out==0)) {

						buffer->SetCapacity();

						continue;

					}

					//	Something went wrong, throw
					throw std::runtime_error(zlib_error);

				}

			} catch (...) {

				//	Make sure stream is
				//	cleaned up
				inflateEnd(&stream);

				throw;

			}

			inflateEnd(&stream);

		} catch (...) {

			//	Roll buffer back
			buffer->SetCount(initial_count);

			//	Propagate
			throw;

		}

	}

	Vector<Byte> Inflate (const Byte * begin, const Byte * end) {

		//	Create buffer
		Vector<Byte> buffer(inflate_buffer_default);

		//	Inflate
		Inflate(begin,end,&buffer);

		//	Return
		return buffer;

	}

	void Deflate (const Byte * begin, const Byte * end, Vector<Byte> * buffer, bool gzip) {

		//	Null check
		if (buffer==nullptr) throw std::out_of_range(NullPointerError);

		//	Preserve initial count for atomicity
		Word initial_count=buffer->Count();

		//	In event of error we roll
		//	buffer back
		try {

			//	Create and initialize a stream
			z_stream stream;
			stream.zalloc=Z_NULL;
			stream.zfree=Z_NULL;
			stream.opaque=Z_NULL;

			if (deflateInit2(
				&stream,
				Z_DEFAULT_COMPRESSION,
				Z_DEFLATED,
				MAX_WBITS+(gzip ? 16 : 0),
				8,
				Z_DEFAULT_STRATEGY
			)!=Z_OK) throw std::runtime_error(zlib_error);

			try {

				//	Convert the number of bytes to
				//	compress safely to the target
				//	integer type and store them
				//	in stream
				stream.avail_in=static_cast<decltype(stream.avail_in)>(
					SafeInt<decltype(end-begin)>(end-begin)
				);
				//	The ZLib compression/decompression
				//	functions do not modify the in buffer,
				//	therefore it should technically be
				//	const, but it's not so we'll do an
				//	ugly const_cast here...
				stream.next_in=const_cast<decltype(stream.next_in)>(
					reinterpret_cast<const std::remove_pointer<decltype(stream.next_in)>::type *>(
						begin
					)
				);

				//	Loop and compress
				for (;;) {

					//	Wire output buffer into stream
					stream.next_out=reinterpret_cast<decltype(stream.next_out)>(buffer->end());
					stream.avail_out=static_cast<decltype(stream.avail_out)>(SafeWord(buffer->Capacity()-buffer->Count()));

					//	Deflate
					int result=deflate(&stream,Z_FINISH);

					//	Update buffer count
					buffer->SetCount(buffer->Capacity()-stream.avail_out);

					//	Did we compress everything?
					//	If so we're done
					if (result==Z_STREAM_END) break;

					//	Does the buffer need to be bigger?
					if (result==Z_BUF_ERROR) {

						buffer->SetCapacity();

						continue;

					}

					//	Error
					throw std::runtime_error(zlib_error);

				}

			} catch (...) {

				//	Make sure the stream is
				//	cleaned up
				deflateEnd(&stream);

				throw;

			}

			deflateEnd(&stream);

		} catch (...) {

			//	Roll buffer back
			buffer->SetCount(initial_count);

			//	Propagate
			throw;

		}

	}

	Vector<Byte> Deflate (const Byte * begin, const Byte * end, bool gzip) {

		//	We want to try and do this in
		//	one go, so get the bound and
		//	initialize the output buffer
		//	to that size
		Word num=Word(SafeInt<decltype(end-begin)>(end-begin));
		Vector<Byte> buffer(DeflateBound(num,gzip));

		//	Compress
		Deflate(begin,end,&buffer,gzip);

		//	Return
		return buffer;

	}

	Word DeflateBound (Word num, bool gzip) {

		//	Safely convert the input number to
		//	the type that deflateBound expects
		typedef FunctionInformation<decltype(deflateBound)>::ArgumentType<1>::Type LengthType;

		LengthType z_num=LengthType(SafeWord(num));

		//	Prepare a dummy stream
		z_stream stream;
		stream.zalloc=Z_NULL;
		stream.zfree=Z_NULL;
		stream.opaque=Z_NULL;

		if (deflateInit2(
			&stream,
			Z_DEFAULT_COMPRESSION,
			Z_DEFLATED,
			MAX_WBITS+(gzip ? 16 : 0),
			8,
			Z_DEFAULT_STRATEGY
		)!=Z_OK) throw std::runtime_error(zlib_error);

		Word bound;
		try {

			//	Obtain the bound
			bound=Word(
				SafeInt<decltype(deflateBound(&stream,z_num))>(
					deflateBound(&stream,z_num)
				)
			);

		} catch (...) {

			deflateEnd(&stream);

			throw;

		}

		//	Free the stream
		deflateEnd(&stream);

		//	Return
		return bound;

	}

}
<|endoftext|>


<commit_before>#include <qgenericplugin_qpa.h>

#include <QDir>
#include <QGuiApplication>
#include <QImage>
#include <QOpenGLBuffer>
#include <QQuickView>

#include <QtConcurrentRun>
#include <QtDebug>

class Recorder : public QObject
{
    Q_OBJECT

public:
    Recorder(const QString &key, const QString &spec);
    ~Recorder();

protected:
    bool eventFilter(QObject *object, QEvent *event);

private slots:
    void grabFrame();

private:
    QString m_prefix;
    QQuickView *m_view;
    int m_frame;

    QSize m_size;

    QOpenGLBuffer *m_pbos[2];
};

Recorder::Recorder(const QString &, const QString &)
    : m_prefix("/tmp/" + qApp->applicationName() + "-" + QString::number(quint64(getpid())) + "/")
    , m_view(0)
    , m_frame(0)
{
    qApp->installEventFilter(this);
    qDebug() << "Recorder initialized:" << QDir().mkpath(m_prefix);

    m_pbos[0] = m_pbos[1] = 0;
}

Recorder::~Recorder()
{
    qDebug() << "Recorded" << m_frame << "frames to" << m_prefix;
}

bool Recorder::eventFilter(QObject *, QEvent *event)
{
    if (m_view)
        return false;

    if (event->type() == QEvent::ApplicationActivate) {
        QWindow *window = qApp->focusWindow();

        QQuickView *view = qobject_cast<QQuickView *>(window);

        if (!view)
            return false;

        connect(view, SIGNAL(afterRendering()), this, SLOT(grabFrame()), Qt::DirectConnection);

        m_view = view;
    }

    return false;
}

void storeFrame(QImage *image, int frame, const QString &prefix)
{
    QString num = QString::number(frame);
    num = QString(qMax(0, 8 - num.size()), QChar('0')) + num;

    image->save(prefix + num + ".ppm");

    delete image;
}

void Recorder::grabFrame()
{
    QImage *image = new QImage(m_size, QImage::Format_ARGB32_Premultiplied);

    if (m_view->size() != m_size) {
        for (int i = 0; i < 2; ++i) {
            delete m_pbos[i];
            m_pbos[i] = new QOpenGLBuffer(QOpenGLBuffer::PixelPackBuffer);
            m_pbos[i]->create();
            m_pbos[i]->bind();
            m_pbos[i]->setUsagePattern(QOpenGLBuffer::StreamRead);
            m_pbos[i]->allocate(m_view->width() * m_view->height() * 4);
        }
        m_size = m_view->size();
    }

    // read pixels into first pbo
    m_pbos[0]->bind();
    glReadPixels(0, 0, m_size.width(), m_size.height(), GL_BGRA, GL_UNSIGNED_BYTE, 0);

    // read second pbo
    if (image->size() == m_size) {
        m_pbos[1]->bind();
        const uchar *data = static_cast<uchar *>(m_pbos[1]->map(QOpenGLBuffer::ReadOnly)) + m_pbos[1]->size();
        int stride = m_size.width() * 4;
        for (int y = 0; y < m_size.height(); ++y)
            memcpy(image->scanLine(y), data -= stride, stride);
        QtConcurrent::run(storeFrame, image, m_frame - 1, m_prefix);
        m_pbos[1]->unmap();
        m_pbos[1]->release();
    } else {
        m_pbos[0]->release();
        delete image;
    }

    qSwap(m_pbos[0], m_pbos[1]);

    ++m_frame;
}

class RecorderPlugin : public QGenericPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QGenericPluginFactoryInterface" FILE "recorder.json")

public:
    RecorderPlugin();

    QStringList keys() const;
    QObject* create(const QString &key, const QString &specification);
};

RecorderPlugin::RecorderPlugin()
    : QGenericPlugin()
{
}

QStringList RecorderPlugin::keys() const
{
    return (QStringList()
            << QLatin1String("recorder"));
}

QObject* RecorderPlugin::create(const QString &key,
                                const QString &specification)
{
    if (!key.compare(QLatin1String("recorder"), Qt::CaseInsensitive))
        return new Recorder(key, specification);
    return 0;
}

#include "main.moc"
<commit_msg>Handle stride.<commit_after>#include <qgenericplugin_qpa.h>

#include <QDir>
#include <QGuiApplication>
#include <QImage>
#include <QOpenGLBuffer>
#include <QQuickView>

#include <QtConcurrentRun>
#include <QtDebug>

class Recorder : public QObject
{
    Q_OBJECT

public:
    Recorder(const QString &key, const QString &spec);
    ~Recorder();

protected:
    bool eventFilter(QObject *object, QEvent *event);

private slots:
    void grabFrame();

private:
    QString m_prefix;
    QQuickView *m_view;
    int m_frame;

    QSize m_size;

    int m_stride;

    QOpenGLBuffer *m_pbos[2];
};

Recorder::Recorder(const QString &, const QString &specs)
    : m_prefix("/tmp/" + qApp->applicationName() + "-" + QString::number(quint64(getpid())) + "/")
    , m_view(0)
    , m_frame(0)
    , m_stride(1)
{
    qApp->installEventFilter(this);
    qDebug() << "Recorder initialized:" << QDir().mkpath(m_prefix);

    bool ok;
    int stride = specs.toInt(&ok);
    if (ok)
        m_stride = stride;
    m_pbos[0] = m_pbos[1] = 0;
}

Recorder::~Recorder()
{
    qDebug() << "Recorded" << m_frame << "frames to" << m_prefix;
}

bool Recorder::eventFilter(QObject *, QEvent *event)
{
    if (m_view)
        return false;

    if (event->type() == QEvent::ApplicationActivate) {
        QWindow *window = qApp->focusWindow();

        QQuickView *view = qobject_cast<QQuickView *>(window);

        if (!view)
            return false;

        connect(view, SIGNAL(afterRendering()), this, SLOT(grabFrame()), Qt::DirectConnection);

        m_view = view;
    }

    return false;
}

void storeFrame(QImage *image, int frame, const QString &prefix)
{
    QString num = QString::number(frame);
    num = QString(qMax(0, 8 - num.size()), QChar('0')) + num;

    image->save(prefix + num + ".ppm");

    delete image;
}

void Recorder::grabFrame()
{
    if (((m_frame - 1) % m_stride) != 0) {
        ++m_frame;
        return;
    }

    QImage *image = new QImage(m_size, QImage::Format_ARGB32_Premultiplied);

    if (m_view->size() != m_size) {
        for (int i = 0; i < 2; ++i) {
            delete m_pbos[i];
            m_pbos[i] = new QOpenGLBuffer(QOpenGLBuffer::PixelPackBuffer);
            m_pbos[i]->create();
            m_pbos[i]->bind();
            m_pbos[i]->setUsagePattern(QOpenGLBuffer::StreamRead);
            m_pbos[i]->allocate(m_view->width() * m_view->height() * 4);
        }
        m_size = m_view->size();
    }

    // read pixels into first pbo
    m_pbos[0]->bind();
    glReadPixels(0, 0, m_size.width(), m_size.height(), GL_BGRA, GL_UNSIGNED_BYTE, 0);

    // read second pbo
    if (image->size() == m_size) {
        m_pbos[1]->bind();
        const uchar *data = static_cast<uchar *>(m_pbos[1]->map(QOpenGLBuffer::ReadOnly)) + m_pbos[1]->size();
        int stride = m_size.width() * 4;
        for (int y = 0; y < m_size.height(); ++y)
            memcpy(image->scanLine(y), data -= stride, stride);
        QtConcurrent::run(storeFrame, image, m_frame - 1, m_prefix);
        m_pbos[1]->unmap();
        m_pbos[1]->release();
    } else {
        m_pbos[0]->release();
        delete image;
    }

    qSwap(m_pbos[0], m_pbos[1]);

    ++m_frame;
}

class RecorderPlugin : public QGenericPlugin
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QGenericPluginFactoryInterface" FILE "recorder.json")

public:
    RecorderPlugin();

    QStringList keys() const;
    QObject* create(const QString &key, const QString &specification);
};

RecorderPlugin::RecorderPlugin()
    : QGenericPlugin()
{
}

QStringList RecorderPlugin::keys() const
{
    return (QStringList()
            << QLatin1String("recorder"));
}

QObject* RecorderPlugin::create(const QString &key,
                                const QString &specification)
{
    if (!key.compare(QLatin1String("recorder"), Qt::CaseInsensitive))
        return new Recorder(key, specification);
    return 0;
}

#include "main.moc"
<|endoftext|>


<commit_before>f57dd61e-ad59-11e7-93b5-ac87a332f658<commit_msg>master branch<commit_after>f5fd03f0-ad59-11e7-bb0f-ac87a332f658<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The FacileCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"

#define CHECK_KNOWN_HASHES_FAST 1
#ifdef CHECK_KNOWN_HASHES_FAST
#include "pow_known_hashes.h"
#endif

#define SIZEOF_ARRAY( a ) (sizeof( a ) / sizeof( a[ 0 ] ))

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{

	int minor_diff_lut[] = { 30, 40, 60, 136, 325, 889, 3161,  3161 * 4};
	//// whites per lut 1, 2, 4, 5, 6, 7, 8, 9
	int64_t minor_diff_lut_steps = SIZEOF_ARRAY(minor_diff_lut);

	unsigned int target_major, target_minor;

    unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact_dummy();

    // Genesis block
    if (pindexLast == NULL)
        return nProofOfWorkLimit;
		//return 4 + 0;

	if(pindexLast->nHeight == (Params().RC2SoftForkHeight() - 1))
		return nProofOfWorkLimit;

	//debgug
	//if(pindexLast->nHeight == 1 )
	//	return pindexLast->nBits;

    // Only change once per interval
    if ((pindexLast->nHeight+1) % Params().Interval() != 0)
    {
        if (Params().AllowMinDifficultyBlocks())
        {
            // Special difficulty rule for testnet:
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }
        return pindexLast->nBits;
    }

    // Go back by what we want to be 14 days worth of blocks
    const CBlockIndex* pindexFirst = pindexLast;
    for (int i = 0; pindexFirst && i < Params().Interval()-1; i++)
        pindexFirst = pindexFirst->pprev;
    assert(pindexFirst);

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
    LogPrintf("  nActualTimespan = %d  before bounds\n", nActualTimespan);

    // Retarget
    uint256 bnNew;
    uint256 bnOld;
    bnNew.SetCompact_dummy(pindexLast->nBits);
    bnOld = bnNew;

	if(pindexLast->nHeight < (Params().RC2SoftForkHeight() - 1)){

		if (bnNew == uint256(0x400)){
			if(nActualTimespan < Params().TargetTimespan()/120)
				bnNew = uint256(0x401);
			//return bnNew.GetCompact_dummy();
		}else{

			// revert target increase/decrease direction compared with bitecoin
			// bnNew *= nActualTimespan;
			// bnNew /= Params().TargetTimespan();

			// bnNew *= Params().TargetTimespan();
			// if(nActualTimespan > 0)
				// bnNew /= nActualTimespan;

			if(bnNew < nProofOfWorkLimit)
				bnNew = nProofOfWorkLimit;

			if (bnNew > 0x4000)
				bnNew = 0x4000; // 64 x 64

			int64_t raw_target = bnNew.GetLow64();

			target_major = ((raw_target >> 8) & 0xff);
			target_minor = (raw_target & 0xff);

			if(target_minor >= minor_diff_lut_steps) target_minor = minor_diff_lut_steps - 1;

			//increase or decrease?
			if (nActualTimespan < Params().TargetTimespan() * (minor_diff_lut_steps - 1) / minor_diff_lut_steps){
				//increase
				bool found_next = false;
				int64_t how_many_times = Params().TargetTimespan() / (nActualTimespan + 1);
				int64_t current_minor_diff = minor_diff_lut[target_minor];
				for(int i = target_minor; i < minor_diff_lut_steps - 1; i++)
					if(minor_diff_lut[i] > current_minor_diff * how_many_times){
						found_next = true;
						target_minor = i;
						break;
					}
				if(!found_next){
					target_major ++;
					target_minor = 0;
				}
				LogPrintf("GetNextWorkRequired increase diff. found_next: %d, how_many_times: %lu, current_minor_diff: %lu, target_major: %d, target_minor: %d\n", found_next, how_many_times, current_minor_diff, target_major, target_minor);
			}

			if (nActualTimespan > Params().TargetTimespan() * minor_diff_lut_steps / (minor_diff_lut_steps - 1)  ){ //warning divide by zero if minor_diff_lut empty
				//decrease
				bool found_next = false;
				int64_t how_many_times = nActualTimespan / Params().TargetTimespan();
				int64_t current_minor_diff = minor_diff_lut[target_minor];
				for(int i = target_minor; i >= 0; i--)
					if(minor_diff_lut[i] < current_minor_diff / ( how_many_times + 1)){
						found_next = true;
						target_minor = i;
						break;
					}
				if(!found_next){
					target_major --;
					target_minor = minor_diff_lut_steps - 1;
				}
				LogPrintf("GetNextWorkRequired decrease diff. found_next: %d, how_many_times: %lu, current_minor_diff: %lu, target_major: %d, target_minor: %d\n", found_next, how_many_times, current_minor_diff, target_major, target_minor);

			}

			bnNew = target_major & 0xff;
			bnNew <<= 8;
			bnNew += (target_minor & 0xff);
		}
	}
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//RC2 soft fork
	//Board solving difficulty grows almost geometrically
	//RC1 attempts to calculate best new diff
	//RC2 - increase / decrease diff by one when treshold is passed (sort of delta modulation)
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	else
	{
		int64_t how_many_times = Params().TargetTimespan() / (nActualTimespan + 1) / 6;

		if(bnNew < nProofOfWorkLimit)
			bnNew = nProofOfWorkLimit;

		if (bnNew > 0x4000)
			bnNew = 0x4000; // 64 x 64

		int64_t raw_target = bnNew.GetLow64();

		target_major = ((raw_target >> 8) & 0xff);
		target_minor = (raw_target & 0xff);

		if(target_minor >= minor_diff_lut_steps) target_minor = minor_diff_lut_steps - 1;

		//increase or decrease?
		//Params().TargetTimespan() - 1 day before fork, 1/6 day after fork (2h -> 20 min)
		if (nActualTimespan < Params().TargetTimespan() / 100 / 6 ){

			if(	target_minor < minor_diff_lut_steps -1){
				target_minor++;
			}
			else
			{
				target_major ++;
				target_minor = 0;
			}
			LogPrintf("GetNextWorkRequired increase diff. how_many_times: %lu, target_major: %d, target_minor: %d\n", how_many_times, target_major, target_minor);
		}

		if (nActualTimespan > Params().TargetTimespan() / 6  ){
			//decrease
			if(	target_minor > 0){
				target_minor--;
			}
			else
			{
				target_major --;
				target_minor = minor_diff_lut_steps - 1;
			}
			LogPrintf("GetNextWorkRequired decrease diff. how_many_times: %lu, target_major: %d, target_minor: %d\n", how_many_times, target_major, target_minor);

		}

		bnNew = target_major & 0xff;
		bnNew <<= 8;
		bnNew += (target_minor & 0xff);

	}

	/*
    if (nActualTimespan < Params().TargetTimespan()/100){
        //nActualTimespan = Params().TargetTimespan()/2;
		bnNew++;
		// if (nActualTimespan < Params().TargetTimespan()/4)
			// bnNew++;
	}
    if (bnNew != 0 && nActualTimespan > Params().TargetTimespan()*100){
        //nActualTimespan = Params().TargetTimespan()*2;
		bnNew--;
		// if (bnNew != 0 && nActualTimespan > Params().TargetTimespan()*4)
			// bnNew--;
	}
	*/

	if(bnNew < nProofOfWorkLimit)
		bnNew = nProofOfWorkLimit;

    if (bnNew > 0x4000)
        bnNew = 0x4000; // 64 x 64

    /// debug print
    LogPrintf("GetNextWorkRequired RETARGET\n");
    //LogPrintf("Params().TargetTimespan() = %d    nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan);
	LogPrintf("nActualTimespan = %d\n", nActualTimespan);
    LogPrintf("Before: %08x  %s\n", pindexLast->nBits, bnOld.ToString());
    LogPrintf("After:  %08x  %s\n", bnNew.GetCompact_dummy(), bnNew.ToString());

    return bnNew.GetCompact_dummy();
}

bool check_pow_fast(uint256 hash, unsigned int nBits, GSol sol){
        uint256 t = hash;
        unsigned char vals[32 + 4];
        for(int i = 0; i < 32; i++){
                vals[31 - i] = (t.GetLow64() & 0xff);
                t = t / 256;
        }

        for(int i = 0; i < 20000; i++){
                int off = i * 32;
                if(vals[0] == known_hashes[off] && vals[1] == known_hashes[off + 1]
                //&& vals[2] == known_hashes[off + 2]
                ){
                        bool found = true;
                        for(int j = 2; j < 32; j++)
                                if(vals[j] != known_hashes[off + j]){
                                        found = false;
                                        break;
                                }
                        if(found){
                                //std::cout << "Check block OK " << hash.ToString() << "\n";
                                return true;
                        }
                }
        }
        return false;
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, GSol sol)
{
    bool fNegative;
    bool fOverflow;
    uint256 bnTarget;

	/*
	//not used
    if (Params().SkipProofOfWorkCheck())
       return true;
	*/

    #ifdef CHECK_KNOWN_HASHES_FAST
    if(check_pow_fast(hash, nBits, sol)) return true;
    #endif

    return game_check_sol(hash, nBits, sol);

    bnTarget.SetCompact_dummy(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())
        return error("CheckProofOfWork() : nBits below minimum work");

    // Check proof of work matches claimed amount
    if (hash > bnTarget)
        return error("CheckProofOfWork() : hash doesn't match nBits");

    return true;
}
//// chainwork
uint256 GetBlockProof(const CBlockIndex& block)
{
    uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact_dummy(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
	if (bnTarget >= 0xfffffff0)
		return 0xfffffff0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    //return (~bnTarget / (bnTarget + 1)) + 1;
	//return (uint256(0xfffffff0) / (bnTarget + 1)) + 1;
	return bnTarget + 1;
}
<commit_msg>Update pow.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The FacileCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"

//#define CHECK_KNOWN_HASHES_FAST 1
//#ifdef CHECK_KNOWN_HASHES_FAST
#include "pow_known_hashes.h"
//#endif

#define SIZEOF_ARRAY( a ) (sizeof( a ) / sizeof( a[ 0 ] ))

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{

	int minor_diff_lut[] = { 30, 40, 60, 136, 325, 889, 3161,  3161 * 4};
	//// whites per lut 1, 2, 4, 5, 6, 7, 8, 9
	int64_t minor_diff_lut_steps = SIZEOF_ARRAY(minor_diff_lut);

	unsigned int target_major, target_minor;

    unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact_dummy();

    // Genesis block
    if (pindexLast == NULL)
        return nProofOfWorkLimit;
		//return 4 + 0;

	if(pindexLast->nHeight == (Params().RC2SoftForkHeight() - 1))
		return nProofOfWorkLimit;

	//debgug
	//if(pindexLast->nHeight == 1 )
	//	return pindexLast->nBits;

    // Only change once per interval
    if ((pindexLast->nHeight+1) % Params().Interval() != 0)
    {
        if (Params().AllowMinDifficultyBlocks())
        {
            // Special difficulty rule for testnet:
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }
        return pindexLast->nBits;
    }

    // Go back by what we want to be 14 days worth of blocks
    const CBlockIndex* pindexFirst = pindexLast;
    for (int i = 0; pindexFirst && i < Params().Interval()-1; i++)
        pindexFirst = pindexFirst->pprev;
    assert(pindexFirst);

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
    LogPrintf("  nActualTimespan = %d  before bounds\n", nActualTimespan);

    // Retarget
    uint256 bnNew;
    uint256 bnOld;
    bnNew.SetCompact_dummy(pindexLast->nBits);
    bnOld = bnNew;

	if(pindexLast->nHeight < (Params().RC2SoftForkHeight() - 1)){

		if (bnNew == uint256(0x400)){
			if(nActualTimespan < Params().TargetTimespan()/120)
				bnNew = uint256(0x401);
			//return bnNew.GetCompact_dummy();
		}else{

			// revert target increase/decrease direction compared with bitecoin
			// bnNew *= nActualTimespan;
			// bnNew /= Params().TargetTimespan();

			// bnNew *= Params().TargetTimespan();
			// if(nActualTimespan > 0)
				// bnNew /= nActualTimespan;

			if(bnNew < nProofOfWorkLimit)
				bnNew = nProofOfWorkLimit;

			if (bnNew > 0x4000)
				bnNew = 0x4000; // 64 x 64

			int64_t raw_target = bnNew.GetLow64();

			target_major = ((raw_target >> 8) & 0xff);
			target_minor = (raw_target & 0xff);

			if(target_minor >= minor_diff_lut_steps) target_minor = minor_diff_lut_steps - 1;

			//increase or decrease?
			if (nActualTimespan < Params().TargetTimespan() * (minor_diff_lut_steps - 1) / minor_diff_lut_steps){
				//increase
				bool found_next = false;
				int64_t how_many_times = Params().TargetTimespan() / (nActualTimespan + 1);
				int64_t current_minor_diff = minor_diff_lut[target_minor];
				for(int i = target_minor; i < minor_diff_lut_steps - 1; i++)
					if(minor_diff_lut[i] > current_minor_diff * how_many_times){
						found_next = true;
						target_minor = i;
						break;
					}
				if(!found_next){
					target_major ++;
					target_minor = 0;
				}
				LogPrintf("GetNextWorkRequired increase diff. found_next: %d, how_many_times: %lu, current_minor_diff: %lu, target_major: %d, target_minor: %d\n", found_next, how_many_times, current_minor_diff, target_major, target_minor);
			}

			if (nActualTimespan > Params().TargetTimespan() * minor_diff_lut_steps / (minor_diff_lut_steps - 1)  ){ //warning divide by zero if minor_diff_lut empty
				//decrease
				bool found_next = false;
				int64_t how_many_times = nActualTimespan / Params().TargetTimespan();
				int64_t current_minor_diff = minor_diff_lut[target_minor];
				for(int i = target_minor; i >= 0; i--)
					if(minor_diff_lut[i] < current_minor_diff / ( how_many_times + 1)){
						found_next = true;
						target_minor = i;
						break;
					}
				if(!found_next){
					target_major --;
					target_minor = minor_diff_lut_steps - 1;
				}
				LogPrintf("GetNextWorkRequired decrease diff. found_next: %d, how_many_times: %lu, current_minor_diff: %lu, target_major: %d, target_minor: %d\n", found_next, how_many_times, current_minor_diff, target_major, target_minor);

			}

			bnNew = target_major & 0xff;
			bnNew <<= 8;
			bnNew += (target_minor & 0xff);
		}
	}
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//RC2 soft fork
	//Board solving difficulty grows almost geometrically
	//RC1 attempts to calculate best new diff
	//RC2 - increase / decrease diff by one when treshold is passed (sort of delta modulation)
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	else
	{
		int64_t how_many_times = Params().TargetTimespan() / (nActualTimespan + 1) / 6;

		if(bnNew < nProofOfWorkLimit)
			bnNew = nProofOfWorkLimit;

		if (bnNew > 0x4000)
			bnNew = 0x4000; // 64 x 64

		int64_t raw_target = bnNew.GetLow64();

		target_major = ((raw_target >> 8) & 0xff);
		target_minor = (raw_target & 0xff);

		if(target_minor >= minor_diff_lut_steps) target_minor = minor_diff_lut_steps - 1;

		//increase or decrease?
		//Params().TargetTimespan() - 1 day before fork, 1/6 day after fork (2h -> 20 min)
		if (nActualTimespan < Params().TargetTimespan() / 100 / 6 ){

			if(	target_minor < minor_diff_lut_steps -1){
				target_minor++;
			}
			else
			{
				target_major ++;
				target_minor = 0;
			}
			LogPrintf("GetNextWorkRequired increase diff. how_many_times: %lu, target_major: %d, target_minor: %d\n", how_many_times, target_major, target_minor);
		}

		if (nActualTimespan > Params().TargetTimespan() / 6  ){
			//decrease
			if(	target_minor > 0){
				target_minor--;
			}
			else
			{
				target_major --;
				target_minor = minor_diff_lut_steps - 1;
			}
			LogPrintf("GetNextWorkRequired decrease diff. how_many_times: %lu, target_major: %d, target_minor: %d\n", how_many_times, target_major, target_minor);

		}

		bnNew = target_major & 0xff;
		bnNew <<= 8;
		bnNew += (target_minor & 0xff);

	}

	/*
    if (nActualTimespan < Params().TargetTimespan()/100){
        //nActualTimespan = Params().TargetTimespan()/2;
		bnNew++;
		// if (nActualTimespan < Params().TargetTimespan()/4)
			// bnNew++;
	}
    if (bnNew != 0 && nActualTimespan > Params().TargetTimespan()*100){
        //nActualTimespan = Params().TargetTimespan()*2;
		bnNew--;
		// if (bnNew != 0 && nActualTimespan > Params().TargetTimespan()*4)
			// bnNew--;
	}
	*/

	if(bnNew < nProofOfWorkLimit)
		bnNew = nProofOfWorkLimit;

    if (bnNew > 0x4000)
        bnNew = 0x4000; // 64 x 64

    /// debug print
    LogPrintf("GetNextWorkRequired RETARGET\n");
    //LogPrintf("Params().TargetTimespan() = %d    nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan);
	LogPrintf("nActualTimespan = %d\n", nActualTimespan);
    LogPrintf("Before: %08x  %s\n", pindexLast->nBits, bnOld.ToString());
    LogPrintf("After:  %08x  %s\n", bnNew.GetCompact_dummy(), bnNew.ToString());

    return bnNew.GetCompact_dummy();
}

bool check_pow_fast(uint256 hash, unsigned int nBits, GSol sol){
        uint256 t = hash;
        unsigned char vals[32 + 4];
        for(int i = 0; i < 32; i++){
                vals[31 - i] = (t.GetLow64() & 0xff);
                t = t / 256;
        }

        for(int i = 0; i < 20000; i++){
                int off = i * 32;
                if(vals[0] == known_hashes[off] && vals[1] == known_hashes[off + 1]
                //&& vals[2] == known_hashes[off + 2]
                ){
                        bool found = true;
                        for(int j = 2; j < 32; j++)
                                if(vals[j] != known_hashes[off + j]){
                                        found = false;
                                        break;
                                }
                        if(found){
                                //std::cout << "Check block OK " << hash.ToString() << "\n";
                                return true;
                        }
                }
        }
        return false;
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, GSol sol)
{
    bool fNegative;
    bool fOverflow;
    uint256 bnTarget;

	/*
	//not used
    if (Params().SkipProofOfWorkCheck())
       return true;
	*/

    //#ifdef CHECK_KNOWN_HASHES_FAST
    int use_fast_pow = GetArg("-usefastpow", 1);
    if(use_fast_pow == 1 && check_pow_fast(hash, nBits, sol)) return true;
    //#endif

    return game_check_sol(hash, nBits, sol);

    bnTarget.SetCompact_dummy(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())
        return error("CheckProofOfWork() : nBits below minimum work");

    // Check proof of work matches claimed amount
    if (hash > bnTarget)
        return error("CheckProofOfWork() : hash doesn't match nBits");

    return true;
}
//// chainwork
uint256 GetBlockProof(const CBlockIndex& block)
{
    uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact_dummy(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
	if (bnTarget >= 0xfffffff0)
		return 0xfffffff0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    //return (~bnTarget / (bnTarget + 1)) + 1;
	//return (uint256(0xfffffff0) / (bnTarget + 1)) + 1;
	return bnTarget + 1;
}
<|endoftext|>


<commit_before>706c6354-4b02-11e5-8b3a-28cfe9171a43<commit_msg>Does anyone even read these anymore???<commit_after>707840dc-4b02-11e5-af7c-28cfe9171a43<|endoftext|>


<commit_before>#include "rbindv.hpp"	//#include "rbind.hpp"
#include <iostream>
#include <string>
#include <type_traits>

struct Func	{
	int operator ()(int a, int& b, int c = 1) const
		{ return a * 10000 + (b *= 100) + c; }
	int memFun(int a, int b, int c = 1) const
		{ return a * 10000 + b * 100 + c; }
};

int main()
{
	using namespace std::placeholders;
	using namespace mymd::placeholders;
	Func f;
	int a = 2014, b = 2, c = 3, result = 0;
	//----------------------------------------------------------------------------------
	//basic   基本
	auto b1 = mymd::rbind(f, _1, _2, _3);
	result = b1(a, b, c);
	std::cout << "---- basic use" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	auto b1_1 = mymd::rbind(f, until(_3rd));
	result = b1_1(a, b, c);
	std::cout << "---- basic use(placeholders range)" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 10;
	//preset default value     デフォルト値の設定
	auto b2 = mymd::rbind(f, a, _1, _2nd = 11);
	result = b2(b, c);
	std::cout << "---- do not use default value" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	a = 2014, b = 2, c = 10;
	result = b2(b);
	std::cout << "---- use default value for c(=11)" <<std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 4, c = 30;
	//optional argument     引数省略
	auto b3 = mymd::rbind(_1st, 2014, _2nd, _3rd);
	result = b3(Func(), b);
	std::cout << "---- use default value of original functor for c(=1)" << std::endl;
	std::cout << "b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 1;
	std::string str("abcdefg");
	//convert argument by yield method     yieldメソッドによる引数変換
	auto b4 = mymd::rbind(&Func::memFun	,
			    &f			,
			    2014		,
			    _1			,
			    _2nd.yield([](const std::string& s){ return s.length(); })
			    );
	result = b4(b, str);
	std::cout << "---- convert augument by yield for the last argument" << std::endl;
	std::cout << "b = " << b << ", s = " << str << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	//parameter type assert   引数の型の制約
	auto b5 = mymd::rbind(f, _1, _2, _3rd.assert<std::is_integral>());
	result = b5(a, b=8, c=23);
	std::cout << "---- parameter type assert" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	return 0;
}
<commit_msg>Update main.cpp<commit_after>#include "rbindv.hpp"	//#include "rbind.hpp"
#include <iostream>
#include <string>
#include <type_traits>

struct Func	{
	int operator ()(int a, int& b, int c = 1) const
		{ return a * 10000 + (b *= 100) + c; }
	int memFun(int a, int b, int c = 1) const
		{ return a * 10000 + b * 100 + c; }
};

template <template <typename> class Tr>
struct noref {
    template <typename V>
        struct apply    {
        static constexpr bool value = Tr<typename std::remove_reference<V>::type>::value;
    };
};

int main()
{
	using namespace std::placeholders;
	using namespace mymd::placeholders;
	Func f;
	int a = 2014, b = 2, c = 3, result = 0;
	//----------------------------------------------------------------------------------
	//basic   基本
	auto b1 = mymd::rbind(f, _1, _2, _3);
	result = b1(a, b, c);
	std::cout << "---- basic use" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	auto b1_1 = mymd::rbind(f, until(_3rd));
	result = b1_1(a, b, c);
	std::cout << "---- basic use(placeholders range)" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 10;
	//preset default value     デフォルト値の設定
	auto b2 = mymd::rbind(f, a, _1, _2nd = 11);
	result = b2(b, c);
	std::cout << "---- do not use default value" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	a = 2014, b = 2, c = 10;
	result = b2(b);
	std::cout << "---- use default value for c(=11)" <<std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 4, c = 30;
	//optional argument     引数省略
	auto b3 = mymd::rbind(_1st, 2014, _2nd, _3rd);
	result = b3(Func(), b);
	std::cout << "---- use default value of original functor for c(=1)" << std::endl;
	std::cout << "b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 1;
	std::string str("abcdefg");
	//convert argument by yield method     yieldメソッドによる引数変換
	auto b4 = mymd::rbind(&Func::memFun	,
			    &f			,
			    2014		,
			    _1			,
			    _2nd.yield([](const std::string& s){ return s.length(); })
			    );
	result = b4(b, str);
	std::cout << "---- convert augument by yield for the last argument" << std::endl;
	std::cout << "b = " << b << ", s = " << str << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	//parameter type assert   引数の型の制約
	auto b5 = mymd::rbind(f, _1, _2, _3rd.assert<noref<std::is_integral>>());
	result = b5(a, b=8, c=23);
	std::cout << "---- parameter type assert" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	return 0;
}
<|endoftext|>