<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 <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "config.h"

#include "osd/OSDMap.h"
#include "mon/MonMap.h"

void usage(const char *me)
{
  cout << me << " usage: [--print] [--createsimple <monmapfile> <numosd> [--clobber] [--pgbits <bitsperosd>]] <mapfilename>" << std::endl;
  cout << me << "   --export-crush <file>   write osdmap's crush map to <file>" << std::endl;
  cout << me << "   --import-crush <file>   replace osdmap's crush map with <file>" << std::endl;
  exit(1);
}

void printmap(const char *me, OSDMap *m)
{
  cout << me << ": osdmap: epoch " << m->get_epoch() << std::endl
       << me << ": osdmap: fsid " << m->get_fsid() << std::endl;
  /*for (unsigned i=0; i<m->mon_inst.size(); i++)
    cout << me << ": osdmap:  " //<< "mon" << i << " "
	 << m->mon_inst[i] << std::endl;
  */
}

int main(int argc, const char **argv)
{
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  parse_config_options(args);

  const char *me = argv[0];

  const char *fn = 0;
  bool print = false;
  bool createsimple = false;
  const char *monmapfn = 0;
  int num_osd = 0;
  int pg_bits = g_conf.osd_pg_bits;
  bool clobber = false;
  bool modified = false;
  const char *export_crush = 0;
  const char *import_crush = 0;
  list<entity_addr_t> add, rm;

  for (unsigned i=0; i<args.size(); i++) {
    if (strcmp(args[i], "--print") == 0)
      print = true;
    else if (strcmp(args[i], "--createsimple") == 0) {
      createsimple = true;
      monmapfn = args[++i];
      num_osd = atoi(args[++i]);
    } else if (strcmp(args[i], "--clobber") == 0)
      clobber = true;
    else if (strcmp(args[i], "--pgbits") == 0)
      pg_bits = atoi(args[++i]);
    else if (strcmp(args[i], "--export-crush") == 0)
      export_crush = args[++i];
    else if (strcmp(args[i], "--import-crush") == 0)
      import_crush = args[++i];
    else if (!fn)
      fn = args[i];
    else
      usage(me);
  }
  if (!fn) {
    cerr << me << ": must specify osdmap filename" << std::endl;
    usage(me);
  }

  OSDMap osdmap;
  bufferlist bl;

  cout << me << ": osdmap file '" << fn << "'" << std::endl;

  int r = 0;
  if (!(createsimple && clobber)) {
    r = bl.read_file(fn);
    osdmap.decode(bl);
  }
  if (!createsimple && r < 0) {
    cerr << me << ": couldn't open " << fn << ": " << strerror(errno) << std::endl;
    return -1;
  }
  else if (createsimple && !clobber && r == 0) {
    cerr << me << ": " << fn << " exists, --clobber to overwrite" << std::endl;
    return -1;
  }

  if (createsimple) {
    MonMap monmap;
    int r = monmap.read(monmapfn);
    if (r < 0) {
      cerr << me << ": can't read monmap from " << monmapfn << ": " << strerror(r) << std::endl;
      exit(1);
    }
    osdmap.build_simple(0, monmap.fsid, num_osd, pg_bits, 0);
    modified = true;
  }

  if (import_crush) {
    bufferlist cbl;
    r = cbl.read_file(import_crush);
    if (r < 0) {
      cerr << me << ": error reading crush map from " << import_crush << std::endl;
      exit(1);
    }
    // validate
    CrushWrapper cw;
    //cw._decode(cbl,    FIXME
    bufferlist::iterator p = cbl.begin();
    osdmap.crush._decode(p);
    cout << me << ": imported crush map from " << import_crush << std::endl;
    modified = true;
  }

  if (export_crush) {
    bufferlist cbl;
    osdmap.crush._encode(cbl);
    r = cbl.write_file(export_crush);
    if (r < 0) {
      cerr << me << ": error writing crush map to " << import_crush << std::endl;
      exit(1);
    }
    cout << me << ": exported crush map to " << export_crush << std::endl;
  }

  if (!print && !modified) {
    cerr << me << ": no action specified?" << std::endl;
    usage(me);
  }
  if (modified)
    osdmap.inc_epoch();

  if (print)
    printmap(me, &osdmap);

  if (modified) {
    osdmap.encode(bl);

    // write it out
    cout << me << ": writing epoch " << osdmap.get_epoch()
	 << " to " << fn
	 << std::endl;
    int r = bl.write_file(fn);
    assert(r >= 0);
  }

  return 0;
}
<commit_msg>osdmaptool: small fix<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 <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "config.h"

#include "osd/OSDMap.h"
#include "mon/MonMap.h"

void usage(const char *me)
{
  cout << me << " usage: [--print] [--createsimple <monmapfile> <numosd> [--clobber] [--pgbits <bitsperosd>]] <mapfilename>" << std::endl;
  cout << me << "   --export-crush <file>   write osdmap's crush map to <file>" << std::endl;
  cout << me << "   --import-crush <file>   replace osdmap's crush map with <file>" << std::endl;
  exit(1);
}

void printmap(const char *me, OSDMap *m)
{
  cout << me << ": osdmap: epoch " << m->get_epoch() << std::endl
       << me << ": osdmap: fsid " << m->get_fsid() << std::endl;
  /*for (unsigned i=0; i<m->mon_inst.size(); i++)
    cout << me << ": osdmap:  " //<< "mon" << i << " "
	 << m->mon_inst[i] << std::endl;
  */
}

int main(int argc, const char **argv)
{
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  parse_config_options(args);

  const char *me = argv[0];

  const char *fn = 0;
  bool print = false;
  bool createsimple = false;
  const char *monmapfn = 0;
  int num_osd = 0;
  int pg_bits = g_conf.osd_pg_bits;
  bool clobber = false;
  bool modified = false;
  const char *export_crush = 0;
  const char *import_crush = 0;
  list<entity_addr_t> add, rm;

  for (unsigned i=0; i<args.size(); i++) {
    if (strcmp(args[i], "--print") == 0)
      print = true;
    else if (strcmp(args[i], "--createsimple") == 0) {
      createsimple = true;
      monmapfn = args[++i];
      num_osd = atoi(args[++i]);
    } else if (strcmp(args[i], "--clobber") == 0)
      clobber = true;
    else if (strcmp(args[i], "--pgbits") == 0)
      pg_bits = atoi(args[++i]);
    else if (strcmp(args[i], "--export-crush") == 0)
      export_crush = args[++i];
    else if (strcmp(args[i], "--import-crush") == 0)
      import_crush = args[++i];
    else if (!fn)
      fn = args[i];
    else
      usage(me);
  }
  if (!fn) {
    cerr << me << ": must specify osdmap filename" << std::endl;
    usage(me);
  }

  OSDMap osdmap;
  bufferlist bl;

  cout << me << ": osdmap file '" << fn << "'" << std::endl;

  int r = 0;
  if (!(createsimple && clobber)) {
    r = bl.read_file(fn);
    osdmap.decode(bl);
  }
  if (!createsimple && r < 0) {
    cerr << me << ": couldn't open " << fn << ": " << strerror(errno) << std::endl;
    return -1;
  }
  else if (createsimple && !clobber && r == 0) {
    cerr << me << ": " << fn << " exists, --clobber to overwrite" << std::endl;
    return -1;
  }

  if (createsimple) {
    MonMap monmap;
    int r = monmap.read(monmapfn);
    if (r < 0) {
      cerr << me << ": can't read monmap from " << monmapfn << ": " << strerror(r) << std::endl;
      exit(1);
    }
    osdmap.build_simple(0, monmap.fsid, num_osd, pg_bits, 0);
    modified = true;
  }

  if (import_crush) {
    bufferlist cbl;
    r = cbl.read_file(import_crush);
    if (r < 0) {
      cerr << me << ": error reading crush map from " << import_crush << std::endl;
      exit(1);
    }
    // validate
    CrushWrapper cw;
    //cw._decode(cbl,    FIXME
    bufferlist::iterator p = cbl.begin();
    osdmap.crush._decode(p);
    cout << me << ": imported crush map from " << import_crush << std::endl;
    modified = true;
  }

  if (export_crush) {
    bufferlist cbl;
    osdmap.crush._encode(cbl);
    r = cbl.write_file(export_crush);
    if (r < 0) {
      cerr << me << ": error writing crush map to " << import_crush << std::endl;
      exit(1);
    }
    cout << me << ": exported crush map to " << export_crush << std::endl;
  }

  if (!print && !modified && !export_crush && !import_crush) {
    cerr << me << ": no action specified?" << std::endl;
    usage(me);
  }
  if (modified)
    osdmap.inc_epoch();

  if (print)
    printmap(me, &osdmap);

  if (modified) {
    osdmap.encode(bl);

    // write it out
    cout << me << ": writing epoch " << osdmap.get_epoch()
	 << " to " << fn
	 << std::endl;
    int r = bl.write_file(fn);
    assert(r >= 0);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include"all_defines.hpp"

#include"processes.hpp"
#include"mutexes.hpp"
#include"executors.hpp"

void MailBox::insert(ValueHolderRef & message) {
	AppLock l(mtx);
	messages.insert(message);
}

bool MailBox::recv(Object::ref & res) {
	AppLock l(mtx);
	ValueHolderRef ref;
        messages.remove(ref);
	if (ref.empty()) {
		return false;
	} else {
		/*Save the received message's Semispace into
		  the heap's other spaces
		*/
		parent.heap().other_spaces.insert(ref);
		res = ref.value();
		return true;
	}
}

bool MailBox::empty() {
	AppLock l(mtx);
	return messages.empty();
}

void MailBox::clear() {
	AppLock l(mtx);
	ValueHolderRef tmp;
	messages.swap(tmp);
}

/*
 * Process-level GC functions
 */
/*
Refer to doc/process-gc.txt and in particular src/workers.cpp
*/

bool Process::waiting_and_not_black(void) {
	AppLock l(mtx);
	return (stat == process_waiting) && !black;
}

bool Process::receive_message(ValueHolderRef& M, bool& is_waiting) {
	is_waiting = false;
	AppTryLock l(mtx);
	if(!l) return false; /*failed to lock, retry later*/
	if(stat == process_dead) return true; /*silently succeed*/
	mbox.insert(M);
	if(stat == process_waiting) {
		is_waiting = true;
		stat = process_running;
	}
	return true;
}

bool Process::anesthesize(void) {
	AppLock l(mtx);
	if(stat == process_waiting && !black) {
		stat = process_anesthesized;
		return true;
	} else {
		return false;
	}
}

bool Process::unanesthesize(void) {
	AppLock l(mtx);
	if (mbox.empty()) {
		stat = process_waiting;
		return false;
	} else {
		/*since the sender of the message can't send
		unless it gets the mutex (and we have the
		mutex), we expect mbox to be empty at this
		point
		*/
		stat = process_running;
		return true;
	}
}

void Process::kill(void) {
	stat = process_dead;
	mbox.clear();
	global_cache.clear();
	invalid_globals.clear();
	free_heap();
}
void Process::atomic_kill(void) {
	{AppLock l(mtx);
		stat = process_dead;
		mbox.clear();
	}
	/*used only when running anyway; since we're dead,
	no need to lock
	*/
	global_cache.clear();
	/*lock notification_mtx in case someone decides to
	notify us at this time
	*/
	{AppLock l(notification_mtx);
		invalid_globals.clear();
	}
	free_heap();
}

void Process::set_waiting() {
	AppLock l(mtx);
	stat = process_waiting;
}

Heap& Process::heap(void) {
	return *this;
}

MailBox& Process::mailbox(void) {
	return mbox;
}

/*
 * Global variables
 */
void Process::invalidate_changed_globals(void) {
	/*create-temp-and-swap*/
	std::vector<Symbol*> temp;
	{AppLock l(notification_mtx);
		temp.swap(invalid_globals);
	}
	typedef std::map<Symbol*, Object::ref> cache_map;
	/*work on temp*/
	for(size_t i = 0; i < temp.size(); ++i) {
		cache_map::iterator it = global_cache.find(temp[i]);
		if(it != global_cache.end()) {
			global_cache.erase(it);
		}
	}
}

void Process::notify_global_change(Symbol* S) {
	AppLock l(notification_mtx);
	invalid_globals.push_back(S);
}

Object::ref Process::global_read(Symbol* S) {
	typedef std::map<Symbol*, Object::ref> cache_map;
	cache_map::iterator it = global_cache.find(S);
	if(it != global_cache.end()) {
		return it->second;
	}
	/*not in cache: read it*/
	ValueHolderRef read;
	S->copy_value_to_and_add_notify(read, this);
	Object::ref rv = read.value();
	other_spaces.insert(read);
	/*now cache*/
	global_cache[S] = rv;
	return rv;
}

void Process::global_write(Symbol* S, Object::ref o) {
	typedef std::map<Symbol*, Object::ref> cache_map;
	cache_map::iterator it = global_cache.find(S);
	if(it != global_cache.end()) {
		global_cache.erase(it);
	}
	S->set_value(o);
}

void Process::global_acquire( void ) {
	global_cache.clear();
}

/*
 * Heap inheritance
 */

void Process::scan_root_object(GenericTraverser* gt) {
	for(size_t i = 0; i < stack.size(); ++i) {
		gt->traverse(stack[i]);
	}
	typedef std::map<Symbol*, Object::ref>::iterator cache_it;
	cache_it it;
	for(it = global_cache.begin(); it != global_cache.end(); ++it) {
		gt->traverse(it->second);
	}
        // scan extra roots
        for (std::vector<Object::ref*>::iterator it = extra_roots.begin();
             it != extra_roots.end(); ++it) {
                gt->traverse(*(*it));
        }

	/*insert code for traversing process-local vars here*/
}

/*
 * Execution
 */

ProcessStatus Process::execute(size_t& reductions, Process*& Q) {
	/*try*/ {
		/*only do this here, because we don't give
		very strict assurances about when a process
		"sends" a global to all the other processes
		anyway, and invalidate_changed_globals()
		involves a lock.
		*/
		invalidate_changed_globals();
		::execute(*this, reductions, Q, 0);
	} /*catch(HlError& h) ...*/
	/*In the future, when we catch an HlError,
	get the process's error handler and force it
	onto the stack for future execution. i.e.
	transform a C-side exception into an hl-side
	invocation of (err 'type "message")
	*/
}

<commit_msg>fixed MailBox::recv, simple-send-recv.test now works<commit_after>#include"all_defines.hpp"

#include"processes.hpp"
#include"mutexes.hpp"
#include"executors.hpp"

void MailBox::insert(ValueHolderRef & message) {
	AppLock l(mtx);
	messages.insert(message);
}

bool MailBox::recv(Object::ref & res) {
	AppLock l(mtx);
	ValueHolderRef ref;
        messages.remove(ref);
	if (ref.empty()) {
		return false;
	} else {
		/*Save the received message's Semispace into
		  the heap's other spaces
		*/
		parent.heap().other_spaces.insert(ref);
		res = parent.heap().other_spaces.value();
		return true;
	}
}

bool MailBox::empty() {
	AppLock l(mtx);
	return messages.empty();
}

void MailBox::clear() {
	AppLock l(mtx);
	ValueHolderRef tmp;
	messages.swap(tmp);
}

/*
 * Process-level GC functions
 */
/*
Refer to doc/process-gc.txt and in particular src/workers.cpp
*/

bool Process::waiting_and_not_black(void) {
	AppLock l(mtx);
	return (stat == process_waiting) && !black;
}

bool Process::receive_message(ValueHolderRef& M, bool& is_waiting) {
	is_waiting = false;
	AppTryLock l(mtx);
	if(!l) return false; /*failed to lock, retry later*/
	if(stat == process_dead) return true; /*silently succeed*/
	mbox.insert(M);
	if(stat == process_waiting) {
		is_waiting = true;
		stat = process_running;
	}
	return true;
}

bool Process::anesthesize(void) {
	AppLock l(mtx);
	if(stat == process_waiting && !black) {
		stat = process_anesthesized;
		return true;
	} else {
		return false;
	}
}

bool Process::unanesthesize(void) {
	AppLock l(mtx);
	if (mbox.empty()) {
		stat = process_waiting;
		return false;
	} else {
		/*since the sender of the message can't send
		unless it gets the mutex (and we have the
		mutex), we expect mbox to be empty at this
		point
		*/
		stat = process_running;
		return true;
	}
}

void Process::kill(void) {
	stat = process_dead;
	mbox.clear();
	global_cache.clear();
	invalid_globals.clear();
	free_heap();
}
void Process::atomic_kill(void) {
	{AppLock l(mtx);
		stat = process_dead;
		mbox.clear();
	}
	/*used only when running anyway; since we're dead,
	no need to lock
	*/
	global_cache.clear();
	/*lock notification_mtx in case someone decides to
	notify us at this time
	*/
	{AppLock l(notification_mtx);
		invalid_globals.clear();
	}
	free_heap();
}

void Process::set_waiting() {
	AppLock l(mtx);
	stat = process_waiting;
}

Heap& Process::heap(void) {
	return *this;
}

MailBox& Process::mailbox(void) {
	return mbox;
}

/*
 * Global variables
 */
void Process::invalidate_changed_globals(void) {
	/*create-temp-and-swap*/
	std::vector<Symbol*> temp;
	{AppLock l(notification_mtx);
		temp.swap(invalid_globals);
	}
	typedef std::map<Symbol*, Object::ref> cache_map;
	/*work on temp*/
	for(size_t i = 0; i < temp.size(); ++i) {
		cache_map::iterator it = global_cache.find(temp[i]);
		if(it != global_cache.end()) {
			global_cache.erase(it);
		}
	}
}

void Process::notify_global_change(Symbol* S) {
	AppLock l(notification_mtx);
	invalid_globals.push_back(S);
}

Object::ref Process::global_read(Symbol* S) {
	typedef std::map<Symbol*, Object::ref> cache_map;
	cache_map::iterator it = global_cache.find(S);
	if(it != global_cache.end()) {
		return it->second;
	}
	/*not in cache: read it*/
	ValueHolderRef read;
	S->copy_value_to_and_add_notify(read, this);
	Object::ref rv = read.value();
	other_spaces.insert(read);
	/*now cache*/
	global_cache[S] = rv;
	return rv;
}

void Process::global_write(Symbol* S, Object::ref o) {
	typedef std::map<Symbol*, Object::ref> cache_map;
	cache_map::iterator it = global_cache.find(S);
	if(it != global_cache.end()) {
		global_cache.erase(it);
	}
	S->set_value(o);
}

void Process::global_acquire( void ) {
	global_cache.clear();
}

/*
 * Heap inheritance
 */

void Process::scan_root_object(GenericTraverser* gt) {
	for(size_t i = 0; i < stack.size(); ++i) {
		gt->traverse(stack[i]);
	}
	typedef std::map<Symbol*, Object::ref>::iterator cache_it;
	cache_it it;
	for(it = global_cache.begin(); it != global_cache.end(); ++it) {
		gt->traverse(it->second);
	}
        // scan extra roots
        for (std::vector<Object::ref*>::iterator it = extra_roots.begin();
             it != extra_roots.end(); ++it) {
                gt->traverse(*(*it));
        }

	/*insert code for traversing process-local vars here*/
}

/*
 * Execution
 */

ProcessStatus Process::execute(size_t& reductions, Process*& Q) {
	/*try*/ {
		/*only do this here, because we don't give
		very strict assurances about when a process
		"sends" a global to all the other processes
		anyway, and invalidate_changed_globals()
		involves a lock.
		*/
		invalidate_changed_globals();
		::execute(*this, reductions, Q, 0);
	} /*catch(HlError& h) ...*/
	/*In the future, when we catch an HlError,
	get the process's error handler and force it
	onto the stack for future execution. i.e.
	transform a C-side exception into an hl-side
	invocation of (err 'type "message")
	*/
}

<|endoftext|>


<commit_before>#ifndef UNICODE
  #define UNICODE
#endif
#ifndef _UNICODE
  #define _UNICODE
#endif
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN

#pragma comment(lib, "Shlwapi.lib")

#include "unicodeText.h"
#include <windows.h>
#include <Shlwapi.h>
#include <stdio.h>

const wchar_t* PythonScriptSuffix = L"-script.py";

const int ErrorGetModuleFileName     = 10000;
const int ErrorCreateProcess         = 10001;
const int ErrorSetConsoleCtrlHandler = 10002;
const int ErrorGetExitCodeProcess    = 10003;

BOOL WINAPI interruptHandler(DWORD code)
{
  return TRUE;
}

void error(int errorCode, const wchar_t *msg)
{
  DWORD lastError = GetLastError();
  if (lastError != ERROR_SUCCESS)
  {
    const size_t MsgBufferMaxSize = 500;
    wchar_t errMsgBuffer[MsgBufferMaxSize];
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
      NULL, lastError, 0, (LPTSTR)&errMsgBuffer, MsgBufferMaxSize, NULL);
    wprintf(L"Error [%d] %s: %s", errorCode, msg, errMsgBuffer);
  }
  else
    wprintf(L"Error [%d] %s\n", errorCode, msg);
  ExitProcess(errorCode);
}

wchar_t *skipPastThis(wchar_t *commandLine)
{
  BOOL quoted;
  wchar_t c;
  wchar_t *result = commandLine;

  // Find the first whitespace or the 2nd quote if commandLine
  // starts with a quote.
  quoted = commandLine[0] == L'\"';
  if (!quoted)
    c = L' ';
  else {
    c = L'\"';
    ++result;
  }
  result = wcschr(result, c);
  if (result == NULL)
    return L"";
  else
  {
    // Skip past space or closing quote.
    ++result;
    // Skip past whitespace
    while (*result && iswspace(*result))
      ++result;
    return result;
  }
}

int wmain()
{
  // Determine full path to this executable without extension.
  wchar_t myPath[MAX_PATH];
  if (!GetModuleFileName(NULL, myPath, MAX_PATH))
    error(ErrorGetModuleFileName, L"GetModuleFileName failed");
  PathRemoveExtension(myPath);

  // Read the Python file and try get an interpreter path from the shebang.

  wchar_t *pythonExe = L"python.exe";

  size_t len = wcslen(myPath) + wcslen(PythonScriptSuffix) + 1;
  wchar_t *buff = new wchar_t[len];
  buff[0] = '\0';
  wcscat_s(buff, len, myPath);
  wcscat_s(buff, len, PythonScriptSuffix);

  FILE *fp;
  errno_t err = _wfopen_s(&fp, buff, L"rb");
  if (err)
    error(-1, L"Python script");

  const int BufferSize = 500;
  char buffer[BufferSize];
  size_t bytesRead = fread(buffer, 1, BufferSize, fp);
  fclose(fp);
  size_t textBytesOffset;
  Encoding::Value encoding = getEncoding(buffer, bytesRead, &textBytesOffset);

  wchar_t wbuffer[BufferSize];
  size_t wcharCount = decode(buffer + textBytesOffset, bytesRead - textBytesOffset,
    encoding, wbuffer, BufferSize);
  wchar_t *firstLineStart = wbuffer;
  if (wcharCount > 2)
  {
    if (firstLineStart[0] == L'#' && firstLineStart[1] == L'!')
    {
      firstLineStart += 2;

      // Look for line ending.
      wchar_t *firstLineEnd = wcschr(firstLineStart, L'\n');
      if (firstLineEnd)
      {
        if (firstLineEnd > firstLineStart && *(firstLineEnd - 1) == L'\r')
          --firstLineEnd;
        *firstLineEnd = L'\0';
      }
      else
        firstLineEnd = firstLineStart + wcharCount;

      // Got a shebang line. Interpret as path.
      errno_t err = _wfopen_s(&fp, firstLineStart, L"rb");
      fclose(fp);
      if (err == 0)
        pythonExe = firstLineStart;
    }
  }

  // Build a command line.

  // Remove ourselves from the command line.
  wchar_t *arguments = skipPastThis(GetCommandLine());
  size_t commandLineSize = wcslen(pythonExe) +
                           wcslen(myPath) +
                           wcslen(PythonScriptSuffix) +
                           wcslen(arguments) +
                           3; // 2 spaces and terminator.

  // No need to delete this because the process will end anyway.
  wchar_t *commandLine = new wchar_t[commandLineSize];
  commandLine[0] = '\0';

  wcscat_s(commandLine, commandLineSize, pythonExe);
  wcscat_s(commandLine, commandLineSize, L" ");
  wcscat_s(commandLine, commandLineSize, myPath);
  wcscat_s(commandLine, commandLineSize, PythonScriptSuffix);
  wcscat_s(commandLine, commandLineSize, L" ");
  wcscat_s(commandLine, commandLineSize, arguments);

  // For the purpose of transparency we disable Ctrl-c
  // keyboard interrupt for this wrapper process,
  // so keyboard interrrupts only occur in the called python.
  BOOL okay = SetConsoleCtrlHandler(interruptHandler, TRUE);
  if (!okay)
     error(ErrorSetConsoleCtrlHandler, L"SetConsoleCtrlHandler failed");

  // Run the command.
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  okay = CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
  if (!okay)
    error(ErrorCreateProcess, L"CreateProcess failed");

  CloseHandle(pi.hThread);
  WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);

  DWORD returnCode;
  okay = GetExitCodeProcess(pi.hProcess, &returnCode);
  if (!okay)
    error(ErrorGetExitCodeProcess, L"GetExitCodeProcess failed");

  ExitProcess(returnCode);
}
<commit_msg>Fixed: whitespace in script path would not work.<commit_after>#ifndef UNICODE
  #define UNICODE
#endif
#ifndef _UNICODE
  #define _UNICODE
#endif
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN

#pragma comment(lib, "Shlwapi.lib")

#include "unicodeText.h"
#include <windows.h>
#include <Shlwapi.h>
#include <stdio.h>

const wchar_t* PythonScriptSuffix = L"-script.py";

const int ErrorGetModuleFileName     = 10000;
const int ErrorCreateProcess         = 10001;
const int ErrorSetConsoleCtrlHandler = 10002;
const int ErrorGetExitCodeProcess    = 10003;

BOOL WINAPI interruptHandler(DWORD code)
{
  return TRUE;
}

void error(int errorCode, const wchar_t *msg)
{
  DWORD lastError = GetLastError();
  if (lastError != ERROR_SUCCESS)
  {
    const size_t MsgBufferMaxSize = 500;
    wchar_t errMsgBuffer[MsgBufferMaxSize];
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
      NULL, lastError, 0, (LPTSTR)&errMsgBuffer, MsgBufferMaxSize, NULL);
    wprintf(L"Error [%d] %s: %s", errorCode, msg, errMsgBuffer);
  }
  else
    wprintf(L"Error [%d] %s\n", errorCode, msg);
  ExitProcess(errorCode);
}

wchar_t *skipPastThis(wchar_t *commandLine)
{
  BOOL quoted;
  wchar_t c;
  wchar_t *result = commandLine;

  // Find the first whitespace or the 2nd quote if commandLine
  // starts with a quote.
  quoted = commandLine[0] == L'\"';
  if (!quoted)
    c = L' ';
  else {
    c = L'\"';
    ++result;
  }
  result = wcschr(result, c);
  if (result == NULL)
    return L"";
  else
  {
    // Skip past space or closing quote.
    ++result;
    // Skip past whitespace
    while (*result && iswspace(*result))
      ++result;
    return result;
  }
}

int wmain()
{
  // Determine full path to this executable without extension.
  wchar_t myPath[MAX_PATH];
  if (!GetModuleFileName(NULL, myPath, MAX_PATH))
    error(ErrorGetModuleFileName, L"GetModuleFileName failed");
  PathRemoveExtension(myPath);

  // Read the Python file and try get an interpreter path from the shebang.

  wchar_t *pythonExe = L"python.exe";

  size_t len = wcslen(myPath) + wcslen(PythonScriptSuffix) + 1;
  wchar_t *buff = new wchar_t[len];
  buff[0] = '\0';
  wcscat_s(buff, len, myPath);
  wcscat_s(buff, len, PythonScriptSuffix);

  FILE *fp;
  errno_t err = _wfopen_s(&fp, buff, L"rb");
  if (err)
    error(-1, L"Python script");

  const int BufferSize = 500;
  char buffer[BufferSize];
  size_t bytesRead = fread(buffer, 1, BufferSize, fp);
  fclose(fp);
  size_t textBytesOffset;
  Encoding::Value encoding = getEncoding(buffer, bytesRead, &textBytesOffset);

  wchar_t wbuffer[BufferSize];
  size_t wcharCount = decode(buffer + textBytesOffset, bytesRead - textBytesOffset,
    encoding, wbuffer, BufferSize);
  wchar_t *firstLineStart = wbuffer;
  if (wcharCount > 2)
  {
    if (firstLineStart[0] == L'#' && firstLineStart[1] == L'!')
    {
      firstLineStart += 2;

      // Look for line ending.
      wchar_t *firstLineEnd = wcschr(firstLineStart, L'\n');
      if (firstLineEnd)
      {
        if (firstLineEnd > firstLineStart && *(firstLineEnd - 1) == L'\r')
          --firstLineEnd;
        *firstLineEnd = L'\0';
      }
      else
        firstLineEnd = firstLineStart + wcharCount;

      // Got a shebang line. Interpret as path.
      errno_t err = _wfopen_s(&fp, firstLineStart, L"rb");
      fclose(fp);
      if (err == 0)
        pythonExe = firstLineStart;
    }
  }

  // Build a command line.

  // Remove ourselves from the command line.
  wchar_t *arguments = skipPastThis(GetCommandLine());
  size_t commandLineSize = wcslen(pythonExe) +
                           wcslen(myPath) +
                           wcslen(PythonScriptSuffix) +
                           wcslen(arguments) +
                           5; // 2 spaces, 2 quotes, terminator.

  // No need to delete this because the process will end anyway.
  wchar_t *commandLine = new wchar_t[commandLineSize];
  commandLine[0] = '\0';

  wcscat_s(commandLine, commandLineSize, pythonExe);
  wcscat_s(commandLine, commandLineSize, L" ");
  wcscat_s(commandLine, commandLineSize, L"\"");
  wcscat_s(commandLine, commandLineSize, myPath);
  wcscat_s(commandLine, commandLineSize, PythonScriptSuffix);
  wcscat_s(commandLine, commandLineSize, L"\"");
  wcscat_s(commandLine, commandLineSize, L" ");
  wcscat_s(commandLine, commandLineSize, arguments);

  // For the purpose of transparency we disable Ctrl-c
  // keyboard interrupt for this wrapper process,
  // so keyboard interrrupts only occur in the called python.
  BOOL okay = SetConsoleCtrlHandler(interruptHandler, TRUE);
  if (!okay)
     error(ErrorSetConsoleCtrlHandler, L"SetConsoleCtrlHandler failed");

  // Run the command.
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  okay = CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
  if (!okay)
    error(ErrorCreateProcess, L"CreateProcess failed");

  CloseHandle(pi.hThread);
  WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);

  DWORD returnCode;
  okay = GetExitCodeProcess(pi.hProcess, &returnCode);
  if (!okay)
    error(ErrorGetExitCodeProcess, L"GetExitCodeProcess failed");

  ExitProcess(returnCode);
}
<|endoftext|>


<commit_before>/*
 *  This file is part of Poedit (https://poedit.net)
 *
 *  Copyright (C) 2017 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "qa_checks.h"

#include <unicode/uchar.h>

#include <wx/translation.h>

// -------------------------------------------------------------
// QACheck implementations
// -------------------------------------------------------------

namespace QA
{

class NotAllPlurals : public QACheck
{
public:
    bool CheckItem(CatalogItemPtr item) override
    {
        if (!item->HasPlural())
            return false;

        bool foundTranslated = false;
        bool foundEmpty = false;
        for (auto& s: item->GetTranslations())
        {
            if (s.empty())
                foundEmpty = true;
            else
                foundTranslated = true;
        }

        if (foundEmpty && foundTranslated)
        {
            item->SetIssue(CatalogItem::Issue::Warning, _("Not all plural forms are translated."));
            return true;
        }

        return false;
    }
};

class CaseMismatch : public QACheck
{
public:
    bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
    {
        if (u_isupper(source[0]) && u_islower(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start as a sentence."));
            return true;
        }

        if (u_islower(source[0]) && u_isupper(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start with a lowercase character."));
            return true;
        }

        return false;
    }
};

class WhitespaceMismatch : public QACheck
{
public:
    bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
    {
        if (u_isspace(source[0]) && !u_isspace(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation doesn’t start with a space."));
            return true;
        }

        if (!u_isspace(source[0]) && u_isspace(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation starts with a space, but the source text doesn’t."));
            return true;
        }

        if (source.Last() == '\n' && translation.Last() != '\n')
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a newline at the end."));
            return true;
        }

        if (source.Last() != '\n' && translation.Last() == '\n')
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a newline, but the source text doesn’t."));
            return true;
        }

        if (u_isspace(source.Last()) && !u_isspace(translation.Last()))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a space at the end."));
            return true;
        }

        if (!u_isspace(source.Last()) && u_isspace(translation.Last()))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a space, but the source text doesn’t."));
            return true;
        }

        return false;
    }
};

class PunctuationMismatch : public QACheck
{
public:
    bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
    {
        const UChar32 s_last = source.Last();
        const UChar32 t_last = translation.Last();
        const bool s_punct = u_ispunct(s_last);
        const bool t_punct = u_ispunct(t_last);

        if (s_punct && !t_punct)
        {
            item->SetIssue(CatalogItem::Issue::Warning,
                           wxString::Format(_(L"The translation should end with “%s”."), wxString(wxUniChar(s_last))));
            return true;
        }
        else if (!s_punct && t_punct)
        {
            item->SetIssue(CatalogItem::Issue::Warning,
                           wxString::Format(_(L"The translation should not end with “%s”."), wxString(wxUniChar(t_last))));
            return true;
        }
        else if (s_punct && t_punct && s_last != t_last)
        {
            if (t_last == L'…' && source.EndsWith("..."))
            {
                // as a special case, allow translating ... (3 dots) as … (ellipsis)
            }
            else
            {
                item->SetIssue(CatalogItem::Issue::Warning,
                               wxString::Format(_(L"The translation ends with “%s”, but the source text ends with “%s”."),
                                                wxString(wxUniChar(s_last)), wxString(wxUniChar(t_last))));
                return true;
            }
        }

        return false;
    }
};

} // namespace QA

// -------------------------------------------------------------
// QACheck support code
// -------------------------------------------------------------

bool QACheck::CheckItem(CatalogItemPtr item)
{
    if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))
        return true;

    if (item->HasPlural())
    {
        unsigned count = item->GetNumberOfTranslations();
        for (unsigned i = 1; i < count; i++)
        {
            auto t = item->GetTranslation(i);
            if (!t.empty() && CheckString(item, item->GetPluralString(), t))
                return true;
        }
    }

    return false;
}

bool QACheck::CheckString(CatalogItemPtr /*item*/, const wxString& /*source*/, const wxString& /*translation*/)
{
    wxFAIL_MSG("not implemented - must override CheckString OR CheckItem");
    return false;
}

// -------------------------------------------------------------
// QAChecker
// -------------------------------------------------------------

int QAChecker::Check(Catalog& catalog)
{
    // TODO: parallelize this (make async tasks for chunks of the catalog)
    //       doing it per-checker is MT-unsafe with API that calls SetIssue()!

    int issues = 0;

    for (auto& i: catalog.items())
        issues += Check(i);

    return issues;
}

int QAChecker::Check(CatalogItemPtr item)
{
    int issues = 0;

    for (auto& c: m_checks)
    {
        if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))
            continue;

        if (c->CheckItem(item))
            issues++;
    }

    return issues;
}

std::shared_ptr<QAChecker> QAChecker::GetFor(Catalog& /*catalog*/)
{
    auto c = std::make_shared<QAChecker>();
    c->AddCheck<QA::NotAllPlurals>();
    c->AddCheck<QA::CaseMismatch>();
    c->AddCheck<QA::WhitespaceMismatch>();
    c->AddCheck<QA::PunctuationMismatch>();
    return c;
}
<commit_msg>Fix swapped translation and source in warning text<commit_after>/*
 *  This file is part of Poedit (https://poedit.net)
 *
 *  Copyright (C) 2017 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "qa_checks.h"

#include <unicode/uchar.h>

#include <wx/translation.h>

// -------------------------------------------------------------
// QACheck implementations
// -------------------------------------------------------------

namespace QA
{

class NotAllPlurals : public QACheck
{
public:
    bool CheckItem(CatalogItemPtr item) override
    {
        if (!item->HasPlural())
            return false;

        bool foundTranslated = false;
        bool foundEmpty = false;
        for (auto& s: item->GetTranslations())
        {
            if (s.empty())
                foundEmpty = true;
            else
                foundTranslated = true;
        }

        if (foundEmpty && foundTranslated)
        {
            item->SetIssue(CatalogItem::Issue::Warning, _("Not all plural forms are translated."));
            return true;
        }

        return false;
    }
};

class CaseMismatch : public QACheck
{
public:
    bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
    {
        if (u_isupper(source[0]) && u_islower(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start as a sentence."));
            return true;
        }

        if (u_islower(source[0]) && u_isupper(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _("The translation should start with a lowercase character."));
            return true;
        }

        return false;
    }
};

class WhitespaceMismatch : public QACheck
{
public:
    bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
    {
        if (u_isspace(source[0]) && !u_isspace(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation doesn’t start with a space."));
            return true;
        }

        if (!u_isspace(source[0]) && u_isspace(translation[0]))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation starts with a space, but the source text doesn’t."));
            return true;
        }

        if (source.Last() == '\n' && translation.Last() != '\n')
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a newline at the end."));
            return true;
        }

        if (source.Last() != '\n' && translation.Last() == '\n')
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a newline, but the source text doesn’t."));
            return true;
        }

        if (u_isspace(source.Last()) && !u_isspace(translation.Last()))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation is missing a space at the end."));
            return true;
        }

        if (!u_isspace(source.Last()) && u_isspace(translation.Last()))
        {
            item->SetIssue(CatalogItem::Issue::Warning, _(L"The translation ends with a space, but the source text doesn’t."));
            return true;
        }

        return false;
    }
};

class PunctuationMismatch : public QACheck
{
public:
    bool CheckString(CatalogItemPtr item, const wxString& source, const wxString& translation) override
    {
        const UChar32 s_last = source.Last();
        const UChar32 t_last = translation.Last();
        const bool s_punct = u_ispunct(s_last);
        const bool t_punct = u_ispunct(t_last);

        if (s_punct && !t_punct)
        {
            item->SetIssue(CatalogItem::Issue::Warning,
                           wxString::Format(_(L"The translation should end with “%s”."), wxString(wxUniChar(s_last))));
            return true;
        }
        else if (!s_punct && t_punct)
        {
            item->SetIssue(CatalogItem::Issue::Warning,
                           wxString::Format(_(L"The translation should not end with “%s”."), wxString(wxUniChar(t_last))));
            return true;
        }
        else if (s_punct && t_punct && s_last != t_last)
        {
            if (t_last == L'…' && source.EndsWith("..."))
            {
                // as a special case, allow translating ... (3 dots) as … (ellipsis)
            }
            else
            {
                item->SetIssue(CatalogItem::Issue::Warning,
                               wxString::Format(_(L"The translation ends with “%s”, but the source text ends with “%s”."),
                                                wxString(wxUniChar(t_last)), wxString(wxUniChar(s_last))));
                return true;
            }
        }

        return false;
    }
};

} // namespace QA

// -------------------------------------------------------------
// QACheck support code
// -------------------------------------------------------------

bool QACheck::CheckItem(CatalogItemPtr item)
{
    if (!item->GetTranslation().empty() && CheckString(item, item->GetString(), item->GetTranslation()))
        return true;

    if (item->HasPlural())
    {
        unsigned count = item->GetNumberOfTranslations();
        for (unsigned i = 1; i < count; i++)
        {
            auto t = item->GetTranslation(i);
            if (!t.empty() && CheckString(item, item->GetPluralString(), t))
                return true;
        }
    }

    return false;
}

bool QACheck::CheckString(CatalogItemPtr /*item*/, const wxString& /*source*/, const wxString& /*translation*/)
{
    wxFAIL_MSG("not implemented - must override CheckString OR CheckItem");
    return false;
}

// -------------------------------------------------------------
// QAChecker
// -------------------------------------------------------------

int QAChecker::Check(Catalog& catalog)
{
    // TODO: parallelize this (make async tasks for chunks of the catalog)
    //       doing it per-checker is MT-unsafe with API that calls SetIssue()!

    int issues = 0;

    for (auto& i: catalog.items())
        issues += Check(i);

    return issues;
}

int QAChecker::Check(CatalogItemPtr item)
{
    int issues = 0;

    for (auto& c: m_checks)
    {
        if (item->GetString().empty() || (item->HasPlural() && item->GetPluralString().empty()))
            continue;

        if (c->CheckItem(item))
            issues++;
    }

    return issues;
}

std::shared_ptr<QAChecker> QAChecker::GetFor(Catalog& /*catalog*/)
{
    auto c = std::make_shared<QAChecker>();
    c->AddCheck<QA::NotAllPlurals>();
    c->AddCheck<QA::CaseMismatch>();
    c->AddCheck<QA::WhitespaceMismatch>();
    c->AddCheck<QA::PunctuationMismatch>();
    return c;
}
<|endoftext|>


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

#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"

#if !defined(OS_ANDROID)

namespace cc {
namespace {

class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green box is entirely behind a layer with background blur, so it
  // should appear blurred on its edges.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
  background->AddChild(green);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 436 pixels off by 1: crbug.com/259915
  float percentage_pixels_large_error = 1.09f;  // 436px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 1;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, DISABLED_BackgroundFilterBlurOutsets) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green border is outside the layer with background blur, but the
  // background blur should use pixels from outside its layer borders, up to the
  // radius of the blur effect. So the border should be blurred underneath the
  // top layer causing the green to bleed under the transparent layer, but not
  // in the 1px region between the transparent layer and the green border.
  scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
      gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
  background->AddChild(green_border);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(5.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 2250 pixels off by at most 2: crbug.com/259922
  float percentage_pixels_large_error = 5.625f;  // 2250px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_outsets.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // This verifies that the perspective of the clear layer (with black border)
  // does not influence the blending of the green box behind it. Also verifies
  // that the blur is correctly clipped inside the transformed clear layer.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
      gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
  background->AddChild(green);
  background->AddChild(blur);

  background->SetPreserves3d(true);
  gfx::Transform background_transform;
  background_transform.ApplyPerspectiveDepth(200.0);
  background->SetTransform(background_transform);

  blur->SetPreserves3d(true);
  gfx::Transform blur_transform;
  blur_transform.Translate(55.0, 65.0);
  blur_transform.RotateAboutXAxis(85.0);
  blur_transform.RotateAboutYAxis(180.0);
  blur_transform.RotateAboutZAxis(20.0);
  blur_transform.Translate(-60.0, -60.0);
  blur->SetTransform(blur_transform);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 151 pixels off by at most 2: crbug.com/225027
  float percentage_pixels_large_error = 0.3775f;  // 151px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_off_axis.png")));
}

}  // namespace
}  // namespace cc

#endif  // OS_ANDROID
<commit_msg>cc: Re-enable LayerTreeHostFiltersPixelTest.BackgroundFilterBlurOutsets<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/test/layer_tree_pixel_test.h"
#include "cc/test/pixel_comparator.h"

#if !defined(OS_ANDROID)

namespace cc {
namespace {

class LayerTreeHostFiltersPixelTest : public LayerTreePixelTest {};

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlur) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green box is entirely behind a layer with background blur, so it
  // should appear blurred on its edges.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(30, 30, 140, 140), SK_ColorTRANSPARENT);
  background->AddChild(green);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 436 pixels off by 1: crbug.com/259915
  float percentage_pixels_large_error = 1.09f;  // 436px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 1;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL("background_filter_blur.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOutsets) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // The green border is outside the layer with background blur, but the
  // background blur should use pixels from outside its layer borders, up to the
  // radius of the blur effect. So the border should be blurred underneath the
  // top layer causing the green to bleed under the transparent layer, but not
  // in the 1px region between the transparent layer and the green border.
  scoped_refptr<SolidColorLayer> green_border = CreateSolidColorLayerWithBorder(
      gfx::Rect(1, 1, 198, 198), SK_ColorWHITE, 10, kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
      gfx::Rect(12, 12, 176, 176), SK_ColorTRANSPARENT);
  background->AddChild(green_border);
  background->AddChild(blur);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(5.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 2596 pixels off by at most 2: crbug.com/259922
  float percentage_pixels_large_error = 6.49f;  // 2596px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_outsets.png")));
}

TEST_F(LayerTreeHostFiltersPixelTest, BackgroundFilterBlurOffAxis) {
  scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
      gfx::Rect(200, 200), SK_ColorWHITE);

  // This verifies that the perspective of the clear layer (with black border)
  // does not influence the blending of the green box behind it. Also verifies
  // that the blur is correctly clipped inside the transformed clear layer.
  scoped_refptr<SolidColorLayer> green = CreateSolidColorLayer(
      gfx::Rect(50, 50, 100, 100), kCSSGreen);
  scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayerWithBorder(
      gfx::Rect(30, 30, 120, 120), SK_ColorTRANSPARENT, 1, SK_ColorBLACK);
  background->AddChild(green);
  background->AddChild(blur);

  background->SetPreserves3d(true);
  gfx::Transform background_transform;
  background_transform.ApplyPerspectiveDepth(200.0);
  background->SetTransform(background_transform);

  blur->SetPreserves3d(true);
  gfx::Transform blur_transform;
  blur_transform.Translate(55.0, 65.0);
  blur_transform.RotateAboutXAxis(85.0);
  blur_transform.RotateAboutYAxis(180.0);
  blur_transform.RotateAboutZAxis(20.0);
  blur_transform.Translate(-60.0, -60.0);
  blur->SetTransform(blur_transform);

  FilterOperations filters;
  filters.Append(FilterOperation::CreateBlurFilter(2.f));
  blur->SetBackgroundFilters(filters);

#if defined(OS_WIN)
  // Windows has 151 pixels off by at most 2: crbug.com/225027
  float percentage_pixels_large_error = 0.3775f;  // 151px / (200*200)
  float percentage_pixels_small_error = 0.0f;
  float average_error_allowed_in_bad_pixels = 1.f;
  int large_error_allowed = 2;
  int small_error_allowed = 0;
  pixel_comparator_.reset(new FuzzyPixelComparator(
      true,  // discard_alpha
      percentage_pixels_large_error,
      percentage_pixels_small_error,
      average_error_allowed_in_bad_pixels,
      large_error_allowed,
      small_error_allowed));
#endif

  RunPixelTest(GL_WITH_BITMAP,
               background,
               base::FilePath(FILE_PATH_LITERAL(
                   "background_filter_blur_off_axis.png")));
}

}  // namespace
}  // namespace cc

#endif  // OS_ANDROID
<|endoftext|>


<commit_before>/*
    qgpgmejob.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

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

    Libkleopatra 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "qgpgmejob.h"
#include "qgpgmeprogresstokenmapper.h"

#include <kleo/job.h>
#include <ui/passphrasedialog.h>

#include <qgpgme/eventloopinteractor.h>
#include <qgpgme/dataprovider.h>

#include <gpgmepp/context.h>
#include <gpgmepp/data.h>

#include <klocale.h>
#include <kstandarddirs.h>

#include <qstring.h>
#include <qstringlist.h>

#include <assert.h>
#include <string.h>

Kleo::QGpgMEJob::QGpgMEJob( Kleo::Job * _this, GpgME::Context * context )
  : GpgME::ProgressProvider(),
    GpgME::PassphraseProvider(),
    mThis( _this ),
    mCtx( context ),
    mPatterns( 0 ),
    mInData( 0 ),
    mInDataDataProvider( 0 ),
    mOutData( 0 ),
    mOutDataDataProvider( 0 )
{
  assert( context );
  QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(aboutToDestroy()),
		    _this, SLOT(slotCancel()) );
  context->setProgressProvider( this );
  // (mmutz) work around a gpgme bug in versions at least <= 0.9.0.
  //         These versions will return GPG_ERR_NOT_IMPLEMENTED from
  //         a CMS sign operation when a passphrase callback is set.
  if ( context->protocol() == GpgME::Context::OpenPGP )
    context->setPassphraseProvider( this );
}

Kleo::QGpgMEJob::~QGpgMEJob() {
  delete mCtx; mCtx = 0;
  if ( mPatterns )
    for ( const char* * it = mPatterns ; *it ; ++it )
      free( (void*)*it );
  delete[] mPatterns; mPatterns = 0;
  delete mInData; mInData = 0;
  delete mInDataDataProvider; mInDataDataProvider = 0;
  delete mOutData; mOutData = 0;
  delete mOutDataDataProvider; mOutDataDataProvider = 0;
}

void Kleo::QGpgMEJob::hookupContextToEventLoopInteractor() {
  mCtx->setManagedByEventLoopInteractor( true );
  QObject::connect( QGpgME::EventLoopInteractor::instance(),
		    SIGNAL(operationDoneEventSignal(GpgME::Context*,const GpgME::Error&)),
		    mThis, SLOT(slotOperationDoneEvent(GpgME::Context*,const GpgME::Error&)) );
}

void Kleo::QGpgMEJob::setPatterns( const QStringList & sl, bool allowEmpty ) {
  // create a new null-terminated C array of char* from patterns:
  mPatterns = new const char*[ sl.size() + 1 ];
  const char* * pat_it = mPatterns;
  for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it ) {
    if ( (*it).isNull() )
      continue;
    if ( (*it).isEmpty() && !allowEmpty )
      continue;
    *pat_it++ = strdup( (*it).utf8().data() );
  }
  *pat_it++ = 0;
}

GpgME::Error Kleo::QGpgMEJob::setSigningKeys( const std::vector<GpgME::Key> & signers ) {
  mCtx->clearSigningKeys();
  for ( std::vector<GpgME::Key>::const_iterator it = signers.begin() ; it != signers.end() ; ++it ) {
    if ( (*it).isNull() )
      continue;
    if ( const GpgME::Error err = mCtx->addSigningKey( *it ) )
      return err;
  }
  return 0;
}

void Kleo::QGpgMEJob::createInData( const QByteArray & in ) {
  mInDataDataProvider = new QGpgME::QByteArrayDataProvider( in );
  mInData = new GpgME::Data( mInDataDataProvider );
  assert( !mInData->isNull() );
}

void Kleo::QGpgMEJob::createOutData() {
  mOutDataDataProvider = new QGpgME::QByteArrayDataProvider();
  mOutData = new GpgME::Data( mOutDataDataProvider );
  assert( !mOutData->isNull() );
}

void Kleo::QGpgMEJob::doSlotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) {
  if ( context == mCtx ) {
    doEmitDoneSignal();
    doOperationDoneEvent( e );
    mThis->deleteLater();
  }
}

void Kleo::QGpgMEJob::doSlotCancel() {
  mCtx->cancelPendingOperation();
}

void Kleo::QGpgMEJob::showProgress( const char * what, int type, int current, int total ) {
  doEmitProgressSignal( QGpgMEProgressTokenMapper::instance()->map( what, type, current, total ), current, total );
}

char * Kleo::QGpgMEJob::getPassphrase( const char * useridHint, const char * /*description*/,
 				       bool previousWasBad, bool & canceled ) {
  // DF: here, description is the key fingerprint, twice, then "17 0". Not really descriptive.
  //     So I'm ignoring QString::fromLocal8Bit( description ) )
  QString msg = previousWasBad ?
                i18n( "You need a passphrase to unlock the secret key for user:
 %1 (retry)" ) :
                i18n( "You need a passphrase to unlock the secret key for user:
 %1" );
  msg = msg.arg( QString::fromUtf8( useridHint ) ) + "

";
  msg.prepend( "<qt>" );
  msg += i18n( "This dialog will reappear every time the passphrase is needed. For a more secure solution that also allows caching the passphrase, use gpg-agent." ) + "
";
  const QString gpgAgent = KStandardDirs::findExe( "gpg-agent" );
  if ( !gpgAgent.isEmpty() ) {
    msg += i18n( "gpg-agent was found in %1, but does not appear to be running." );
  } else {
    msg += i18n( "gpg-agent is part of gnupg-%1, which you can download from %2" )
           .arg( "1.9" )
           .arg( "http://www.gnupg.org/download" );  // add #gnupg2 if you can make this a real link
  }
  msg += "
";
  msg += i18n( "For information on how to set up gpg-agent, see %1" )
         .arg( "http://kmail.kde.org/kmail-pgpmime-howto.html" ) + "
";
  Kleo::PassphraseDialog dlg( msg, i18n("Passphrase Dialog") );
  if ( dlg.exec() != QDialog::Accepted ) {
    canceled = true;
    return 0;
  }
  canceled = false;
  // gpgme++ free()s it, and we need to copy as long as dlg isn't deleted :o
  return strdup( dlg.passphrase() );
}
<commit_msg>Substitute in gpgAgent string when found<commit_after>/*
    qgpgmejob.cpp

    This file is part of libkleopatra, the KDE keymanagement library
    Copyright (c) 2004 Klarlvdalens Datakonsult AB

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

    Libkleopatra 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "qgpgmejob.h"
#include "qgpgmeprogresstokenmapper.h"

#include <kleo/job.h>
#include <ui/passphrasedialog.h>

#include <qgpgme/eventloopinteractor.h>
#include <qgpgme/dataprovider.h>

#include <gpgmepp/context.h>
#include <gpgmepp/data.h>

#include <klocale.h>
#include <kstandarddirs.h>

#include <qstring.h>
#include <qstringlist.h>

#include <assert.h>
#include <string.h>

Kleo::QGpgMEJob::QGpgMEJob( Kleo::Job * _this, GpgME::Context * context )
  : GpgME::ProgressProvider(),
    GpgME::PassphraseProvider(),
    mThis( _this ),
    mCtx( context ),
    mPatterns( 0 ),
    mInData( 0 ),
    mInDataDataProvider( 0 ),
    mOutData( 0 ),
    mOutDataDataProvider( 0 )
{
  assert( context );
  QObject::connect( QGpgME::EventLoopInteractor::instance(), SIGNAL(aboutToDestroy()),
		    _this, SLOT(slotCancel()) );
  context->setProgressProvider( this );
  // (mmutz) work around a gpgme bug in versions at least <= 0.9.0.
  //         These versions will return GPG_ERR_NOT_IMPLEMENTED from
  //         a CMS sign operation when a passphrase callback is set.
  if ( context->protocol() == GpgME::Context::OpenPGP )
    context->setPassphraseProvider( this );
}

Kleo::QGpgMEJob::~QGpgMEJob() {
  delete mCtx; mCtx = 0;
  if ( mPatterns )
    for ( const char* * it = mPatterns ; *it ; ++it )
      free( (void*)*it );
  delete[] mPatterns; mPatterns = 0;
  delete mInData; mInData = 0;
  delete mInDataDataProvider; mInDataDataProvider = 0;
  delete mOutData; mOutData = 0;
  delete mOutDataDataProvider; mOutDataDataProvider = 0;
}

void Kleo::QGpgMEJob::hookupContextToEventLoopInteractor() {
  mCtx->setManagedByEventLoopInteractor( true );
  QObject::connect( QGpgME::EventLoopInteractor::instance(),
		    SIGNAL(operationDoneEventSignal(GpgME::Context*,const GpgME::Error&)),
		    mThis, SLOT(slotOperationDoneEvent(GpgME::Context*,const GpgME::Error&)) );
}

void Kleo::QGpgMEJob::setPatterns( const QStringList & sl, bool allowEmpty ) {
  // create a new null-terminated C array of char* from patterns:
  mPatterns = new const char*[ sl.size() + 1 ];
  const char* * pat_it = mPatterns;
  for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it ) {
    if ( (*it).isNull() )
      continue;
    if ( (*it).isEmpty() && !allowEmpty )
      continue;
    *pat_it++ = strdup( (*it).utf8().data() );
  }
  *pat_it++ = 0;
}

GpgME::Error Kleo::QGpgMEJob::setSigningKeys( const std::vector<GpgME::Key> & signers ) {
  mCtx->clearSigningKeys();
  for ( std::vector<GpgME::Key>::const_iterator it = signers.begin() ; it != signers.end() ; ++it ) {
    if ( (*it).isNull() )
      continue;
    if ( const GpgME::Error err = mCtx->addSigningKey( *it ) )
      return err;
  }
  return 0;
}

void Kleo::QGpgMEJob::createInData( const QByteArray & in ) {
  mInDataDataProvider = new QGpgME::QByteArrayDataProvider( in );
  mInData = new GpgME::Data( mInDataDataProvider );
  assert( !mInData->isNull() );
}

void Kleo::QGpgMEJob::createOutData() {
  mOutDataDataProvider = new QGpgME::QByteArrayDataProvider();
  mOutData = new GpgME::Data( mOutDataDataProvider );
  assert( !mOutData->isNull() );
}

void Kleo::QGpgMEJob::doSlotOperationDoneEvent( GpgME::Context * context, const GpgME::Error & e ) {
  if ( context == mCtx ) {
    doEmitDoneSignal();
    doOperationDoneEvent( e );
    mThis->deleteLater();
  }
}

void Kleo::QGpgMEJob::doSlotCancel() {
  mCtx->cancelPendingOperation();
}

void Kleo::QGpgMEJob::showProgress( const char * what, int type, int current, int total ) {
  doEmitProgressSignal( QGpgMEProgressTokenMapper::instance()->map( what, type, current, total ), current, total );
}

char * Kleo::QGpgMEJob::getPassphrase( const char * useridHint, const char * /*description*/,
 				       bool previousWasBad, bool & canceled ) {
  // DF: here, description is the key fingerprint, twice, then "17 0". Not really descriptive.
  //     So I'm ignoring QString::fromLocal8Bit( description ) )
  QString msg = previousWasBad ?
                i18n( "You need a passphrase to unlock the secret key for user:
 %1 (retry)" ) :
                i18n( "You need a passphrase to unlock the secret key for user:
 %1" );
  msg = msg.arg( QString::fromUtf8( useridHint ) ) + "

";
  msg.prepend( "<qt>" );
  msg += i18n( "This dialog will reappear every time the passphrase is needed. For a more secure solution that also allows caching the passphrase, use gpg-agent." ) + "
";
  const QString gpgAgent = KStandardDirs::findExe( "gpg-agent" );
  if ( !gpgAgent.isEmpty() ) {
    msg += i18n( "gpg-agent was found in %1, but does not appear to be running." )
           .arg( gpgAgent );
  } else {
    msg += i18n( "gpg-agent is part of gnupg-%1, which you can download from %2" )
           .arg( "1.9" )
           .arg( "http://www.gnupg.org/download" );  // add #gnupg2 if you can make this a real link
  }
  msg += "
";
  msg += i18n( "For information on how to set up gpg-agent, see %1" )
         .arg( "http://kmail.kde.org/kmail-pgpmime-howto.html" ) + "
";
  Kleo::PassphraseDialog dlg( msg, i18n("Passphrase Dialog") );
  if ( dlg.exec() != QDialog::Accepted ) {
    canceled = true;
    return 0;
  }
  canceled = false;
  // gpgme++ free()s it, and we need to copy as long as dlg isn't deleted :o
  return strdup( dlg.passphrase() );
}
<|endoftext|>


<commit_before>void padRefresh(TPad *pad,int flag=0);
void hksimple()
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-*  This script illustrates the advantages of a TH1K histogram
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  TH1 *hpx[3];
  int j;

// Create a new canvas.
  c1 = new TCanvas("c1","Dynamic Filling Example",200,10,700,500);
  c1->SetFillColor(42);
  c1->GetFrame()->SetFillColor(21);
  c1->GetFrame()->SetBorderSize(6);
  c1->GetFrame()->SetBorderMode(-1);

// Create a normal histogram and two TH1K histograms
  hpx[0]    = new TH1F("hp0","This is the px distribution",1000,-4,4);
  hpx[1]    = new TH1K("hk1","This is the px distribution",1000,-4,4);
  hpx[2]    = new TH1K("hk2","This is the px distribution",1000,-4,4,16);
  c1->Divide(1,3);
   for (j=0;j<3;j++) {c1->cd(j+1); hpx[j]->Draw();hpx[j]->SetFillColor(48);}

// Fill histograms randomly
  gRandom->SetSeed();
  Float_t px, py, pz;
  const Int_t kUPDATE = 10;
  for (Int_t i = 0; i <= 600; i++) {
     gRandom->Rannor(px,py);
     for (j=0;j<3;j++) {hpx[j]->Fill(px);}
     if (i && (i%kUPDATE) == 0) {
           padRefresh(c1);
     }
  }
}
void padRefresh(TPad *pad,int flag)
{
  if (!pad) return;
  pad->Modified();
  pad->Update();
  TList *tl = pad->GetListOfPrimitives();
  if (!tl) return;
  TListIter next(tl);
  TObject *to;
  while ((to=next())) {
    if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}
  if (flag) return;
  gSystem->ProcessEvents();
}
<commit_msg>Some changes in the graphics attributes. A Gaussian fit added to the 3 histograms to illustrate the advantage of TH1K.<commit_after>void padRefresh(TPad *pad,int flag=0);
void hksimple()
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-*  This script illustrates the advantages of a TH1K histogram
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

// Create a new canvas.
  c1 = new TCanvas("c1","Dynamic Filling Example",200,10,600,900);
  c1->SetFillColor(42);

// Create a normal histogram and two TH1K histograms
  TH1 *hpx[3];
  hpx[0]    = new TH1F("hp0","Normal histogram",1000,-4,4);
  hpx[1]    = new TH1K("hk1","Nearest Neighboor of order 3",1000,-4,4);
  hpx[2]    = new TH1K("hk2","Nearest Neighboor of order 16",1000,-4,4,16);
  c1->Divide(1,3);
  Int_t j;
  for (j=0;j<3;j++) {
     c1->cd(j+1);
     gPad->SetFrameFillColor(33);
     hpx[j]->SetFillColor(48);
     hpx[j]->Draw();
  }

// Fill histograms randomly
  gRandom->SetSeed();
  Float_t px, py, pz;
  const Int_t kUPDATE = 10;
  for (Int_t i = 0; i <= 300; i++) {
     gRandom->Rannor(px,py);
     for (j=0;j<3;j++) {hpx[j]->Fill(px);}
     if (i && (i%kUPDATE) == 0) {
           padRefresh(c1);
     }
  }

  for (j=0;j<3;j++) hpx[j]->Fit("gaus","","");
  padRefresh(c1);
}
void padRefresh(TPad *pad,int flag)
{
  if (!pad) return;
  pad->Modified();
  pad->Update();
  TList *tl = pad->GetListOfPrimitives();
  if (!tl) return;
  TListIter next(tl);
  TObject *to;
  while ((to=next())) {
    if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}
  if (flag) return;
  gSystem->ProcessEvents();
}
<|endoftext|>


<commit_before>/******************************
** Tsunagari Tile Engine     **
** resourcer.cpp             **
** Copyright 2011 OmegaSDG   **
******************************/

#include <errno.h>
#include <stdlib.h>

#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <Gosu/Audio.hpp>
#include <Gosu/Bitmap.hpp>
#include <Gosu/Image.hpp>
#include <Gosu/IO.hpp>

#include "common.h"
#include "config.h"
#include "log.h"
#include "resourcer.h"
#include "window.h"

static void xmlErrorCb(void* pstrFilename, const char* msg, ...)
{
	const std::string* filename = (const std::string*)pstrFilename;
	char buf[512];
	va_list ap;

	va_start(ap, msg);
	snprintf(buf, sizeof(buf)-1, msg, va_arg(ap, char*));
	Log::err(*filename, buf);
	va_end(ap);
}

Resourcer::Resourcer(GameWindow* window, const std::string& zip_filename)
	: window(window), z(NULL), zip_filename(zip_filename)
{
}

Resourcer::~Resourcer()
{
	if (z && zip_close(z))
		Log::err(zip_filename,
		         std::string("closing : ") + zip_strerror(z));
}

bool Resourcer::init()
{
	int err;
	z = zip_open(zip_filename.c_str(), 0x0, &err);
	if (!z) {
		char buf[512];
		zip_error_to_str(buf, sizeof(buf), err, errno);
		Log::err(zip_filename, buf);
	}

	return !err;
}

Gosu::Image* Resourcer::getImage(const std::string& name)
{
	boost::shared_ptr<Gosu::Buffer> buffer(read(name));
	if (!buffer)
		return NULL;
	Gosu::Bitmap bitmap;
	Gosu::loadImageFile(bitmap, buffer->frontReader());
	return new Gosu::Image(window->graphics(), bitmap, false);
}

void Resourcer::getBitmap(Gosu::Bitmap& bitmap, const std::string& name)
{
	boost::shared_ptr<Gosu::Buffer> buffer(read(name));
	if (!buffer)
		return;
	return Gosu::loadImageFile(bitmap, buffer->frontReader());
}

Gosu::Image* Resourcer::bitmapSection(const Gosu::Bitmap& src,
        unsigned x, unsigned y, unsigned w, unsigned h, bool tileable)
{
	return new Gosu::Image(window->graphics(), src, x, y, w, h, tileable);
}

xmlDoc* Resourcer::getXMLDoc(const std::string& name)
{
	const std::string docStr = getString(name);
	if (docStr.empty())
		return NULL;

	xmlParserCtxt* ctxt = xmlNewParserCtxt();
	const std::string pathname = path(name);
	ctxt->vctxt.userData = (void*)&pathname;
	ctxt->vctxt.error = xmlErrorCb;
	boost::shared_ptr<void> ctxtDeleter(ctxt, xmlFreeParserCtxt);

	xmlDoc* doc = xmlCtxtReadMemory(ctxt, docStr.c_str(),
			(int)docStr.size(), NULL, NULL,
			XML_PARSE_NOBLANKS |
			XML_PARSE_NONET |
			XML_PARSE_DTDVALID);
	if (!doc) {
		Log::err(pathname, "Could not parse file");
		return NULL;
	}
	else if (!ctxt->valid) {
		Log::err(pathname, "XML document does not follow DTD");
		return NULL;
	}

	return doc;
}

/* FIXME
 * We use Gosu::Sample for music because Gosu::Song's SDL implementation
 * doesn't support loading from a memory buffer at the moment.
 */
Gosu::Sample* Resourcer::getSample(const std::string& name)
{
	boost::shared_ptr<Gosu::Buffer> buffer(read(name));
	if (!buffer)
		return NULL;
	return new Gosu::Sample(buffer->frontReader());
}

std::string Resourcer::getString(const std::string& name)
{
	strMap::iterator entry = strings.find(name);
	if (entry != strings.end())
		return entry->second;

	std::string result = getStringFromZip(name);

	strings[name] = result;
	return result;
}

std::string Resourcer::getStringFromZip(const std::string& name)
{
	struct zip_stat stat;
	zip_file* zf;
	int size;
	char* buf;
	std::string str;

	if (zip_stat(z, name.c_str(), 0x0, &stat)) {
		Log::err(path(name), "file missing");
		return "";
	}

	size = (int)stat.size;
	buf = new char[size + 1];
	buf[size] = '\0';

	zf = zip_fopen(z, name.c_str(), 0x0);
	if (!zf) {
		Log::err(path(name),
		         std::string("opening : ") + zip_strerror(z));
		return "";
	}

	if (zip_fread(zf, buf, size) != size) {
		Log::err(path(name), "reading didn't complete");
		zip_fclose(zf);
		return "";
	}

	str = buf;
	delete[] buf;

	zip_fclose(zf);
	return str;
}

boost::shared_ptr<Gosu::Buffer> Resourcer::read(const std::string& name)
{
	return readFromZip(name);
}

boost::shared_ptr<Gosu::Buffer> Resourcer::readFromZip(const std::string& name)
{
	struct zip_stat stat;
	zip_file* zf;
	int size;

	if (zip_stat(z, name.c_str(), 0x0, &stat)) {
		Log::err(path(name), "file missing");
		return boost::shared_ptr<Gosu::Buffer>();
	}

	size = (int)stat.size;

	if (!(zf = zip_fopen(z, name.c_str(), 0x0))) {
		Log::err(path(name),
		         std::string("opening : ") + zip_strerror(z));
		return boost::shared_ptr<Gosu::Buffer>();
	}

	boost::shared_ptr<Gosu::Buffer> buffer(new Gosu::Buffer);
	buffer->resize(size);
	if (zip_fread(zf, buffer->data(), size) != size) {
		Log::err(path(name), "reading didn't complete");
		zip_fclose(zf);
		// buffer is automatically deallocated
		return boost::shared_ptr<Gosu::Buffer>();
	}

	zip_fclose(zf);
	return buffer;
}

std::string Resourcer::path(const std::string& entry_name) const
{
	return zip_filename + "/" + entry_name;
}

void Resourcer::cacheTally(const std::string& key, const int mod)
{
	cache[key].first += mod;
	if (cache[key].first < 0)
		Log::dev(key, "cache underrun of "+itostr(cache[key].first));
}

<commit_msg>Weird return in Resourcer::init. It was suddenly breaking things.<commit_after>/******************************
** Tsunagari Tile Engine     **
** resourcer.cpp             **
** Copyright 2011 OmegaSDG   **
******************************/

#include <errno.h>
#include <stdlib.h>

#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <Gosu/Audio.hpp>
#include <Gosu/Bitmap.hpp>
#include <Gosu/Image.hpp>
#include <Gosu/IO.hpp>

#include "common.h"
#include "config.h"
#include "log.h"
#include "resourcer.h"
#include "window.h"

static void xmlErrorCb(void* pstrFilename, const char* msg, ...)
{
	const std::string* filename = (const std::string*)pstrFilename;
	char buf[512];
	va_list ap;

	va_start(ap, msg);
	snprintf(buf, sizeof(buf)-1, msg, va_arg(ap, char*));
	Log::err(*filename, buf);
	va_end(ap);
}

Resourcer::Resourcer(GameWindow* window, const std::string& zip_filename)
	: window(window), z(NULL), zip_filename(zip_filename)
{
}

Resourcer::~Resourcer()
{
	if (z && zip_close(z))
		Log::err(zip_filename,
		         std::string("closing : ") + zip_strerror(z));
}

bool Resourcer::init()
{
	int err;
	z = zip_open(zip_filename.c_str(), 0x0, &err);
	if (!z) {
		char buf[512];
		zip_error_to_str(buf, sizeof(buf), err, errno);
		Log::err(zip_filename, buf);
		return false;
	}

	return true;
}

Gosu::Image* Resourcer::getImage(const std::string& name)
{
	boost::shared_ptr<Gosu::Buffer> buffer(read(name));
	if (!buffer)
		return NULL;
	Gosu::Bitmap bitmap;
	Gosu::loadImageFile(bitmap, buffer->frontReader());
	return new Gosu::Image(window->graphics(), bitmap, false);
}

void Resourcer::getBitmap(Gosu::Bitmap& bitmap, const std::string& name)
{
	boost::shared_ptr<Gosu::Buffer> buffer(read(name));
	if (!buffer)
		return;
	return Gosu::loadImageFile(bitmap, buffer->frontReader());
}

Gosu::Image* Resourcer::bitmapSection(const Gosu::Bitmap& src,
        unsigned x, unsigned y, unsigned w, unsigned h, bool tileable)
{
	return new Gosu::Image(window->graphics(), src, x, y, w, h, tileable);
}

xmlDoc* Resourcer::getXMLDoc(const std::string& name)
{
	const std::string docStr = getString(name);
	if (docStr.empty())
		return NULL;

	xmlParserCtxt* ctxt = xmlNewParserCtxt();
	const std::string pathname = path(name);
	ctxt->vctxt.userData = (void*)&pathname;
	ctxt->vctxt.error = xmlErrorCb;
	boost::shared_ptr<void> ctxtDeleter(ctxt, xmlFreeParserCtxt);

	xmlDoc* doc = xmlCtxtReadMemory(ctxt, docStr.c_str(),
			(int)docStr.size(), NULL, NULL,
			XML_PARSE_NOBLANKS |
			XML_PARSE_NONET |
			XML_PARSE_DTDVALID);
	if (!doc) {
		Log::err(pathname, "Could not parse file");
		return NULL;
	}
	else if (!ctxt->valid) {
		Log::err(pathname, "XML document does not follow DTD");
		return NULL;
	}

	return doc;
}

/* FIXME
 * We use Gosu::Sample for music because Gosu::Song's SDL implementation
 * doesn't support loading from a memory buffer at the moment.
 */
Gosu::Sample* Resourcer::getSample(const std::string& name)
{
	boost::shared_ptr<Gosu::Buffer> buffer(read(name));
	if (!buffer)
		return NULL;
	return new Gosu::Sample(buffer->frontReader());
}

std::string Resourcer::getString(const std::string& name)
{
	strMap::iterator entry = strings.find(name);
	if (entry != strings.end())
		return entry->second;

	std::string result = getStringFromZip(name);

	strings[name] = result;
	return result;
}

std::string Resourcer::getStringFromZip(const std::string& name)
{
	struct zip_stat stat;
	zip_file* zf;
	int size;
	char* buf;
	std::string str;

	if (zip_stat(z, name.c_str(), 0x0, &stat)) {
		Log::err(path(name), "file missing");
		return "";
	}

	size = (int)stat.size;
	buf = new char[size + 1];
	buf[size] = '\0';

	zf = zip_fopen(z, name.c_str(), 0x0);
	if (!zf) {
		Log::err(path(name),
		         std::string("opening : ") + zip_strerror(z));
		return "";
	}

	if (zip_fread(zf, buf, size) != size) {
		Log::err(path(name), "reading didn't complete");
		zip_fclose(zf);
		return "";
	}

	str = buf;
	delete[] buf;

	zip_fclose(zf);
	return str;
}

boost::shared_ptr<Gosu::Buffer> Resourcer::read(const std::string& name)
{
	return readFromZip(name);
}

boost::shared_ptr<Gosu::Buffer> Resourcer::readFromZip(const std::string& name)
{
	struct zip_stat stat;
	zip_file* zf;
	int size;

	if (zip_stat(z, name.c_str(), 0x0, &stat)) {
		Log::err(path(name), "file missing");
		return boost::shared_ptr<Gosu::Buffer>();
	}

	size = (int)stat.size;

	if (!(zf = zip_fopen(z, name.c_str(), 0x0))) {
		Log::err(path(name),
		         std::string("opening : ") + zip_strerror(z));
		return boost::shared_ptr<Gosu::Buffer>();
	}

	boost::shared_ptr<Gosu::Buffer> buffer(new Gosu::Buffer);
	buffer->resize(size);
	if (zip_fread(zf, buffer->data(), size) != size) {
		Log::err(path(name), "reading didn't complete");
		zip_fclose(zf);
		// buffer is automatically deallocated
		return boost::shared_ptr<Gosu::Buffer>();
	}

	zip_fclose(zf);
	return buffer;
}

std::string Resourcer::path(const std::string& entry_name) const
{
	return zip_filename + "/" + entry_name;
}

void Resourcer::cacheTally(const std::string& key, const int mod)
{
	cache[key].first += mod;
	if (cache[key].first < 0)
		Log::dev(key, "cache underrun of "+itostr(cache[key].first));
}

<|endoftext|>


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

#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
#include "global_objects_noui.hpp"
using namespace json_spirit;
using namespace std;

int64_t GetCoinYearReward(int64_t nTime);

//CCriticalSection cs_main;
//static boost::thread_group* postThreads = NULL;

double GRCMagnitudeUnit(int64_t locktime);
std::string qtGetNeuralHash(std::string data);
volatile bool bCPIDsLoaded;
volatile bool bProjectsInitialized;
std::string GetNeuralNetworkSupermajorityHash(double& out_popularity);

int64_t GetRSAWeightByCPID(std::string cpid);

Value getsubsidy(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "getsubsidy [nTarget]\n"
            "Returns proof-of-work subsidy value for the specified value of target.");

    return (uint64_t)GetProofOfWorkReward(0, GetAdjustedTime(),0);
}

Value getmininginfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getmininginfo\n"
            "Returns an object containing mining-related information.");

    uint64_t nWeight = 0;
    int64_t nTime= GetAdjustedTime();
    pwalletMain->GetStakeWeight(nWeight);
    Object obj, diff, weight;
    uint64_t nNetworkWeight = GetPoSKernelPS();
    obj.push_back(Pair("blocks",        (int)nBestHeight));
    diff.push_back(Pair("proof-of-work",        GetDifficulty()));
    diff.push_back(Pair("proof-of-research",    GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    diff.push_back(Pair("proof-of-stake",    GetDifficulty(GetLastBlockIndex(pindexBest, true))));

    { LOCK(MinerStatus.lock);
        // not using real weigh to not break calculation
        bool staking = MinerStatus.nLastCoinStakeSearchInterval && MinerStatus.WeightSum;
        uint64_t nExpectedTime = staking ? (GetTargetSpacing(nBestHeight) * nNetworkWeight / MinerStatus.ValueSum) : 0;
        diff.push_back(Pair("search-interval",      (int)nMinerSleep));
        diff.push_back(Pair("last-search-interval", (int)MinerStatus.nLastCoinStakeSearchInterval));
        weight.push_back(Pair("minimum",    MinerStatus.WeightMin));
        weight.push_back(Pair("maximum",    MinerStatus.WeightMax));
        weight.push_back(Pair("combined",   MinerStatus.WeightSum));
        weight.push_back(Pair("valuesum",   MinerStatus.ValueSum));
        weight.push_back(Pair("legacy",   nWeight/(double)COIN));
        obj.push_back(Pair("stakeweight", weight));
        obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
        obj.push_back(Pair("staking", staking));
        obj.push_back(Pair("mining-error", MinerStatus.ReasonNotStaking));
        obj.push_back(Pair("mining-message", MinerStatus.Message));
        obj.push_back(Pair("time-to-stake_days", nExpectedTime/86400.0));
        obj.push_back(Pair("expectedtime", nExpectedTime));
        obj.push_back(Pair("mining-version", MinerStatus.Version));
        obj.push_back(Pair("mining-created", MinerStatus.CreatedCnt));
        obj.push_back(Pair("mining-accepted", MinerStatus.AcceptedCnt));
        obj.push_back(Pair("mining-kernels-found", MinerStatus.KernelsFound));
        // Avoid calculating coinage of all coins just to get interest,
        // reuse value found by miner which has to load blocks anyway
        double dInterest = MinerStatus.CoinAgeSum * GetCoinYearReward(nTime) * 33 / (365 * 33 + 8);
        obj.push_back(Pair("InterestPending",dInterest/(double)COIN));
    }

    obj.push_back(Pair("difficulty",    diff));
    obj.push_back(Pair("blockvalue",    (uint64_t)GetProofOfWorkReward(0,  GetAdjustedTime(),1)));
    obj.push_back(Pair("errors",        GetWarnings("statusbar")));
    obj.push_back(Pair("pooledtx",      (uint64_t)mempool.size()));
    //double nCutoff =  GetAdjustedTime() - (60*60*24*14);
    obj.push_back(Pair("stakeinterest",    (uint64_t)GetCoinYearReward( GetAdjustedTime())));
    obj.push_back(Pair("testnet",       fTestNet));
    double neural_popularity = 0;
    std::string neural_hash = GetNeuralNetworkSupermajorityHash(neural_popularity);
    obj.push_back(Pair("PopularNeuralHash", neural_hash));
    //9-19-2015 - CM
    #if defined(WIN32) && defined(QT_GUI)
    obj.push_back(Pair("MyNeuralHash", qtGetNeuralHash("")));
    #endif

    obj.push_back(Pair("NeuralPopularity", neural_popularity));
    obj.push_back(Pair("CPID",msPrimaryCPID));
    obj.push_back(Pair("RSAWeight",(double)GetRSAWeightByCPID(msPrimaryCPID)));
    StructCPID network = GetInitializedStructCPID2("NETWORK",mvNetwork);

    {
        double dMagnitudeUnit = GRCMagnitudeUnit(nTime);
        double dAccrualAge,AvgMagnitude;
        int64_t nBoinc = ComputeResearchAccrual(nTime, msPrimaryCPID, "getmininginfo", pindexBest, false, 69, dAccrualAge, dMagnitudeUnit, AvgMagnitude);
        obj.push_back(Pair("Magnitude Unit",dMagnitudeUnit));
        obj.push_back(Pair("BoincRewardPending",nBoinc/(double)COIN));
    }

    obj.push_back(Pair("MiningProject",msMiningProject));
    obj.push_back(Pair("MiningInfo 1", msMiningErrors));
    obj.push_back(Pair("MiningInfo 2", msPoll));
    obj.push_back(Pair("MiningInfo 5", msMiningErrors5));
    obj.push_back(Pair("MiningInfo 6", msMiningErrors6));
    obj.push_back(Pair("MiningInfo 7", msMiningErrors7));
    obj.push_back(Pair("MiningInfo 8", msMiningErrors8));

    return obj;
}
<commit_msg>changes<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
#include "global_objects_noui.hpp"
using namespace json_spirit;
using namespace std;

int64_t GetCoinYearReward(int64_t nTime);

//CCriticalSection cs_main;
//static boost::thread_group* postThreads = NULL;

double GRCMagnitudeUnit(int64_t locktime);
std::string qtGetNeuralHash(std::string data);
volatile bool bCPIDsLoaded;
volatile bool bProjectsInitialized;
std::string GetNeuralNetworkSupermajorityHash(double& out_popularity);

int64_t GetRSAWeightByCPID(std::string cpid);

Value getsubsidy(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "getsubsidy [nTarget]\n"
            "Returns proof-of-work subsidy value for the specified value of target.");

    return (uint64_t)GetProofOfWorkReward(0, GetAdjustedTime(),0);
}

Value getmininginfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getmininginfo\n"
            "Returns an object containing mining-related information.");

    uint64_t nWeight = 0;
    int64_t nTime= GetAdjustedTime();
    pwalletMain->GetStakeWeight(nWeight);
    Object obj, diff, weight;
    double nNetworkWeight = GetPoSKernelPS();
    obj.push_back(Pair("blocks",        (int)nBestHeight));
    diff.push_back(Pair("proof-of-work",        GetDifficulty()));
    diff.push_back(Pair("proof-of-research",    GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    diff.push_back(Pair("proof-of-stake",    GetDifficulty(GetLastBlockIndex(pindexBest, true))));

    { LOCK(MinerStatus.lock);
        // not using real weigh to not break calculation
        bool staking = MinerStatus.nLastCoinStakeSearchInterval && MinerStatus.WeightSum;
        uint64_t nExpectedTime = staking ? (GetTargetSpacing(nBestHeight) * nNetworkWeight / MinerStatus.ValueSum) : 0;
        diff.push_back(Pair("search-interval",      (int)nMinerSleep));
        diff.push_back(Pair("last-search-interval", (int)MinerStatus.nLastCoinStakeSearchInterval));
        weight.push_back(Pair("minimum",    MinerStatus.WeightMin));
        weight.push_back(Pair("maximum",    MinerStatus.WeightMax));
        weight.push_back(Pair("combined",   MinerStatus.WeightSum));
        weight.push_back(Pair("valuesum",   MinerStatus.ValueSum));
        weight.push_back(Pair("legacy",   nWeight/(double)COIN));
        obj.push_back(Pair("stakeweight", weight));
        obj.push_back(Pair("netstakeweight", nNetworkWeight));
        obj.push_back(Pair("staking", staking));
        obj.push_back(Pair("mining-error", MinerStatus.ReasonNotStaking));
        obj.push_back(Pair("mining-message", MinerStatus.Message));
        obj.push_back(Pair("time-to-stake_days", nExpectedTime/86400.0));
        obj.push_back(Pair("expectedtime", nExpectedTime));
        obj.push_back(Pair("mining-version", MinerStatus.Version));
        obj.push_back(Pair("mining-created", MinerStatus.CreatedCnt));
        obj.push_back(Pair("mining-accepted", MinerStatus.AcceptedCnt));
        obj.push_back(Pair("mining-kernels-found", MinerStatus.KernelsFound));
        // Avoid calculating coinage of all coins just to get interest,
        // reuse value found by miner which has to load blocks anyway
        double dInterest = MinerStatus.CoinAgeSum * GetCoinYearReward(nTime) * 33 / (365 * 33 + 8);
        obj.push_back(Pair("InterestPending",dInterest/(double)COIN));
    }

    obj.push_back(Pair("difficulty",    diff));
    obj.push_back(Pair("blockvalue",    (uint64_t)GetProofOfWorkReward(0,  GetAdjustedTime(),1)));
    obj.push_back(Pair("errors",        GetWarnings("statusbar")));
    obj.push_back(Pair("pooledtx",      (uint64_t)mempool.size()));
    //double nCutoff =  GetAdjustedTime() - (60*60*24*14);
    obj.push_back(Pair("stakeinterest",    (uint64_t)GetCoinYearReward( GetAdjustedTime())));
    obj.push_back(Pair("testnet",       fTestNet));
    double neural_popularity = 0;
    std::string neural_hash = GetNeuralNetworkSupermajorityHash(neural_popularity);
    obj.push_back(Pair("PopularNeuralHash", neural_hash));
    //9-19-2015 - CM
    #if defined(WIN32) && defined(QT_GUI)
    obj.push_back(Pair("MyNeuralHash", qtGetNeuralHash("")));
    #endif

    obj.push_back(Pair("NeuralPopularity", neural_popularity));
    obj.push_back(Pair("CPID",msPrimaryCPID));
    obj.push_back(Pair("RSAWeight",(double)GetRSAWeightByCPID(msPrimaryCPID)));
    StructCPID network = GetInitializedStructCPID2("NETWORK",mvNetwork);

    {
        double dMagnitudeUnit = GRCMagnitudeUnit(nTime);
        double dAccrualAge,AvgMagnitude;
        int64_t nBoinc = ComputeResearchAccrual(nTime, msPrimaryCPID, "getmininginfo", pindexBest, false, 69, dAccrualAge, dMagnitudeUnit, AvgMagnitude);
        obj.push_back(Pair("Magnitude Unit",dMagnitudeUnit));
        obj.push_back(Pair("BoincRewardPending",nBoinc/(double)COIN));
    }

    obj.push_back(Pair("MiningProject",msMiningProject));
    obj.push_back(Pair("MiningInfo 1", msMiningErrors));
    obj.push_back(Pair("MiningInfo 2", msPoll));
    obj.push_back(Pair("MiningInfo 5", msMiningErrors5));
    obj.push_back(Pair("MiningInfo 6", msMiningErrors6));
    obj.push_back(Pair("MiningInfo 7", msMiningErrors7));
    obj.push_back(Pair("MiningInfo 8", msMiningErrors8));

    return obj;
}
<|endoftext|>