<commit_before>
#include <ctime>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <stack>
#include <queue>
#include <algorithm>

using namespace std;

const int Max = 501;

const char CH_EXTEND = '?';
const char CH_CLOSED = '.';
const char CH_PATH = '*';

const char CH_START = 's';
const char CH_END = 'e';
const char CH_WALL = 'o';

const int DIR_NUM = 8;
const int DIR_X[] = {-1, 1,  0, 0, -1, -1, 1, 1};
const int DIR_Y[] = { 0, 0, -1, 1,  1, -1, 1,-1};

int _maze_col;
int _maze_row;
char _maze_map[Max][Max];

bool _closed[Max][Max];
bool _extend[Max][Max];
// preceding direction
int _dir_pre[Max][Max];

struct Position {
	int x, y;
	int step; // g
	double h1, h2, h3; // h1 is important
	Position() {}
	Position(int a, int b):x(a), y(b), step(0), h1(0), h2(0),h3(0) {}
	Position(int a, int b, int c):x(a), y(b), step(c), h1(0), h2(0),h3(0) {}
	bool operator == (const Position &a) const {
		return (x == a.x && y == a.y);
	}
	void heuristic(const Position& p) {
		// Chebyshev
		h1 = max(abs(p.x - x), abs(p.y - y));
		// Euclid
		h2 = sqrt((p.x - x)*(p.x - x)*1.0 + (p.y - y)*(p.y - y));
		// Manhattan
		h3 = abs(p.x - x) + abs(p.y - y);
	}
	bool operator < (const Position &a) const {
		// evaluation function
		double f = step + h1;
		double fa = a.step + a.h1;
		if (f != fa)
			return f > fa;
		// extra guarantee
		if (h2 != a.h2)
			return h2 > a.h2;
		return h3 > a.h3;
	}
};
Position _pstart;
Position _pgoal;

void print_maze() {
	for (int i = 0; i < _maze_row; ++i) {
		for (int j = 0; j < _maze_col; ++j) {
			if (_closed[i][j] && _maze_map[i][j] == ' ') {
				printf("%c", CH_CLOSED);
			} else if (_extend[i][j] && _maze_map[i][j] == ' ') {
				printf("%c", CH_EXTEND);
			} else {
				printf("%c", _maze_map[i][j]);
			}
		}
		puts("");
	}
	printf("\t closed node: '%c' \n", CH_CLOSED);
	printf("\t extend node: '%c' \n", CH_EXTEND);
	printf("\t   path node: '%c' \n", CH_PATH);
	puts("");
}

void delay() {
	int M = 1, N = 10000;
	for (int i = 0; i < M; ++i)
		for (int j = 0; j < N; ++j);
}

void prepare() {
    memset(_closed, false, sizeof(_closed));
	memset(_extend, false, sizeof(_extend));
    for (int i = 0; i < _maze_row; ++i) {
		for (int j = 0; j < _maze_col; ++j) {
            if (_maze_map[i][j] == CH_PATH) {
                _maze_map[i][j] = ' ';
            }
        }
    }
}

inline bool valid_position(int row, int col) {
	if (_maze_map[row][col] == 'o') {
		return false;
	}
	if (_extend[row][col]) {
		return false;
	}
	if (_closed[row][col]) {
		return false;
	}
	return true;
}

int DFS(Position top) {
    if (top == _pgoal) {
		return top.step;
	}

    _closed[top.x][top.y] = true;
    print_maze();
    for (int i = 0; i < DIR_NUM; ++i) {
        int tx = top.x + DIR_X[i];
        int ty = top.y + DIR_Y[i];
        if (_maze_map[tx][ty] == 'o') {
			continue;
		}
        if (_closed[tx][ty]) {
			continue;
		}
        _dir_pre[tx][ty] = i;
        int ret = DFS(Position(tx, ty, top.step + 1));
        if (ret >= 0) {
			return ret;
		}
        // backtracking
        //_closed[tx][ty] = false;
    }

    return -1;
}

int DFS_stack() {
	stack<Position> open_set;
	_extend[_pstart.x][_pstart.y] = true;
	_pstart.step = 0;

	open_set.push(_pstart);
	while (!open_set.empty()) {
		Position top = open_set.top();
		if (top == _pgoal) {
			return top.step;
		}
		open_set.pop();
		_closed[top.x][top.y] = true;
		print_maze();
		for (int i = 0; i < DIR_NUM; ++i) {
			int tx = top.x + DIR_X[i];
			int ty = top.y + DIR_Y[i];
			if (_extend[tx][ty]) {
				continue;
			}
			if (_maze_map[tx][ty] == 'o') {
				continue;
			}
			_extend[tx][ty] = true;
			_dir_pre[tx][ty] = i;
			Position tmp(tx, ty, top.step + 1);
			open_set.push(tmp);
		}
	}

	return -1;
}

int BFS() {
	queue<Position> open_set;
	_extend[_pstart.x][_pstart.y] = true;
	_pstart.step = 0;

	open_set.push(_pstart);
	while (!open_set.empty()) {
		Position top = open_set.front();
		if (top == _pgoal) {
			return top.step;
		}
		open_set.pop();
		_closed[top.x][top.y] = true;
		print_maze();
		for (int i = 0; i < DIR_NUM; ++i) {
			int tx = top.x + DIR_X[i];
			int ty = top.y + DIR_Y[i];
			if (_extend[tx][ty]) {
				continue;
			}
			if (_maze_map[tx][ty] == 'o') {
				continue;
			}
			_extend[tx][ty] = true;
			_dir_pre[tx][ty] = i;
			Position tmp(tx, ty, top.step + 1);
			open_set.push(tmp);
		}
	}

	return -1;
}

int Astar() {
	priority_queue<Position> open_set;

	_extend[_pstart.x][_pstart.y] = true;
	_pstart.step = 0;
	_pstart.heuristic(_pgoal);

	open_set.push(_pstart);
	while (!open_set.empty()) {
		Position top = open_set.top();
		if (top == _pgoal) {
			return top.step;
		}
		open_set.pop();
		_closed[top.x][top.y] = true;
		print_maze();
		for (int i = 0; i < DIR_NUM; ++i) {
			int tx = top.x + DIR_X[i];
			int ty = top.y + DIR_Y[i];
			if (_extend[tx][ty]) {
				continue;
			}
			if (_maze_map[tx][ty] == 'o') {
				continue;
			}
			_extend[tx][ty] = true;
			_dir_pre[tx][ty] = i;
			Position tmp(tx, ty, top.step + 1);
			tmp.heuristic(_pgoal);
			open_set.push(tmp);
		}
	}

	return -1;
}

int IDSearch(Position top, int depth) {
    if (top == _pgoal) {
		return top.step;
	}

    _closed[top.x][top.y] = true;
	print_maze();
    for (int i = 0; i < DIR_NUM; ++i) {
        int tx = top.x + DIR_X[i];
        int ty = top.y + DIR_Y[i];
        if (_maze_map[tx][ty] == 'o') {
			continue;
		}
        if (_closed[tx][ty]) {
			continue;
		}
        Position tmp(tx, ty, top.step + 1);
        tmp.heuristic(_pgoal);
        if (tmp.h1 + tmp.step > depth) {
			continue;
		}
        _dir_pre[tx][ty] = i;
        int ret = IDSearch(tmp, depth);
        if (ret >= 0) {
			return ret;
		}
        // _closed[tx][ty] = false;
    }

    return -1;
}

int IDAstar() {
    _pstart.heuristic(_pgoal);
    for (int depth = _pstart.h1; depth < _maze_col * _maze_row; ++depth) {
        printf("depth:%d \n", depth);
        memset(_closed, false, sizeof(_closed));
        int ret = IDSearch(_pstart, depth);
        if (ret >= 0) return ret;
    }
    return -1;
}

void init_maze_map() {
	puts("Input your map or copy and paste from ./map.txt");

	scanf("%d,%d", &_maze_col, &_maze_row);
	memset(_maze_map, 0, sizeof(_maze_map));
	for (int i = 0; i < _maze_row; ++i) {
		getchar();
		for (int j = 0; j < _maze_col; ++j) {
			scanf("%c", &_maze_map[i][j]);
			if (_maze_map[i][j] == 's') {
				_pstart.x = i;
				_pstart.y = j;
			} else if (_maze_map[i][j] == 'e') {
				_pgoal.x = i;
				_pgoal.y = j;
			}
		}
	}
	getchar();
}

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

    do {
menu:
		puts("");
        puts("=========== Routing Algorithms ===========");
		puts("----------------- DFS --------------");
		puts("    1. Depth-first search, recursive");
    	puts("    2. Depth-first search, stack");
		puts("----------------- BFS ------------------");
		puts("    3. Breadth-first search");
		puts("    4. A* search algorithm");
		puts("    5. Iterative deepening A*");
		puts("-------------------COMMAND--------------------");
		puts("    8. reset maze map");
		puts("    9. exit");
		puts("==============================================");
		printf("    input index number: ");

        char input_str[64] = {0};
input:
		fgets(input_str, sizeof(input_str), stdin);
		int input_len = strlen(input_str) - 1;
		for (int i = 0; i < input_len; ++i) {
			if (input_str[i] < '0' || input_str[i] > '9') {
				puts("input error, please try again.");
				goto input;
			}
		}
        int index = 0;
		sscanf(input_str, "%d", &index);
		printf("\nyour choose index:%d\n", index);

        prepare();
        clock_t time_start = clock();
        int result = 0;
        switch (index) {
        case 1:
            result = DFS(_pstart);
            break;
        case 2:
            result = DFS_stack();
            break;
        case 3:
            result = BFS();
            break;
        case 4:
            result = Astar();
            break;
		case 5:
            result = IDAstar();
			break;
		case 8:
			init_maze_map();
			goto menu;
		case 9:
            puts("\nsee you :)\n");
			goto done;
		default:
            puts("input error, please try again.");
            goto input;
		}
        clock_t time_end = clock();

        double cost_time = (double)(time_end - time_start)/CLOCKS_PER_SEC;
		printf("search cost time: %lfs\n", cost_time);
		if (result == -1) {
			puts("This maze have no solution");
			continue;
		}

		printf("The path need %d steps \n", result);
		Position tmp = _pgoal;
		while (true) {
			int i = _dir_pre[tmp.x][tmp.y];
			tmp.x -= DIR_X[i];
			tmp.y -= DIR_Y[i];
			if (tmp == _pstart) break;
			_maze_map[tmp.x][tmp.y] = CH_PATH;
		}
		print_maze();
	} while (true);

done:
	return 0;
}
<commit_msg>update.<commit_after>
#include <ctime>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <stack>
#include <queue>
#include <algorithm>

using namespace std;

const int Max = 501;

const char CH_EXTEND = '?';
const char CH_CLOSED = '.';
const char CH_PATH = '*';

const char CH_START = 's';
const char CH_END = 'e';
const char CH_WALL = 'o';

const int DIR_NUM = 8;
const int DIR_X[] = {-1, 1,  0, 0, -1, -1, 1, 1};
const int DIR_Y[] = { 0, 0, -1, 1,  1, -1, 1,-1};

int _maze_col;
int _maze_row;
char _maze_map[Max][Max];

bool _closed[Max][Max];
bool _extend[Max][Max];
// preceding direction
int _dir_pre[Max][Max];

struct Position {
	int x, y;
	int step; // g
	double h1, h2, h3; // h1 is important
	Position() {}
	Position(int a, int b):x(a), y(b), step(0), h1(0), h2(0),h3(0) {}
	Position(int a, int b, int c):x(a), y(b), step(c), h1(0), h2(0),h3(0) {}
	bool operator == (const Position &a) const {
		return (x == a.x && y == a.y);
	}
	void heuristic(const Position& p) {
		// Chebyshev
		h1 = max(abs(p.x - x), abs(p.y - y));
		// Euclid
		h2 = sqrt((p.x - x)*(p.x - x)*1.0 + (p.y - y)*(p.y - y));
		// Manhattan
		h3 = abs(p.x - x) + abs(p.y - y);
	}
	bool operator < (const Position &a) const {
		// evaluation function
		double f = step + h1;
		double fa = a.step + a.h1;
		if (f != fa)
			return f > fa;
		// extra guarantee
		if (h2 != a.h2)
			return h2 > a.h2;
		return h3 > a.h3;
	}
};
Position _pstart;
Position _pgoal;

void print_maze() {
	for (int i = 0; i < _maze_row; ++i) {
		for (int j = 0; j < _maze_col; ++j) {
			if (_closed[i][j] && _maze_map[i][j] == ' ') {
				printf("%c", CH_CLOSED);
			} else if (_extend[i][j] && _maze_map[i][j] == ' ') {
				printf("%c", CH_EXTEND);
			} else {
				printf("%c", _maze_map[i][j]);
			}
		}
		puts("");
	}
	printf("\t closed node: '%c' \n", CH_CLOSED);
	printf("\t extend node: '%c' \n", CH_EXTEND);
	printf("\t   path node: '%c' \n", CH_PATH);
	puts("");
}

void delay() {
	int M = 1, N = 10000;
	for (int i = 0; i < M; ++i)
		for (int j = 0; j < N; ++j);
}

void prepare() {
    memset(_closed, false, sizeof(_closed));
	memset(_extend, false, sizeof(_extend));
    for (int i = 0; i < _maze_row; ++i) {
		for (int j = 0; j < _maze_col; ++j) {
            if (_maze_map[i][j] == CH_PATH) {
                _maze_map[i][j] = ' ';
            }
        }
    }
}

inline bool valid_position(int row, int col) {
	if (_maze_map[row][col] == CH_WALL) {
		return false;
	}
	if (_closed[row][col]) {
		return false;
	}
	if (_extend[row][col]) {
		return false;
	}
	return true;
}

int DFS(Position top) {
    if (top == _pgoal) {
		return top.step;
	}

    _closed[top.x][top.y] = true;
    print_maze();
    for (int i = 0; i < DIR_NUM; ++i) {
        int tx = top.x + DIR_X[i];
        int ty = top.y + DIR_Y[i];
        if (!valid_position(tx, ty)) {
			continue;
		}
        _dir_pre[tx][ty] = i;
        int ret = DFS(Position(tx, ty, top.step + 1));
        if (ret >= 0) {
			return ret;
		}
        // backtracking
        _closed[tx][ty] = false;
    }

    return -1;
}

int DFS_stack() {
	stack<Position> open_set;
	_extend[_pstart.x][_pstart.y] = true;
	_pstart.step = 0;

	open_set.push(_pstart);
	while (!open_set.empty()) {
		Position top = open_set.top();
		if (top == _pgoal) {
			return top.step;
		}
		open_set.pop();
		_closed[top.x][top.y] = true;
		print_maze();
		for (int i = 0; i < DIR_NUM; ++i) {
			int tx = top.x + DIR_X[i];
			int ty = top.y + DIR_Y[i];
			if (!valid_position(tx, ty)) {
				continue;
			}
			_extend[tx][ty] = true;
			_dir_pre[tx][ty] = i;
			Position tmp(tx, ty, top.step + 1);
			open_set.push(tmp);
		}
	}

	return -1;
}

int BFS() {
	queue<Position> open_set;
	_extend[_pstart.x][_pstart.y] = true;
	_pstart.step = 0;

	open_set.push(_pstart);
	while (!open_set.empty()) {
		Position top = open_set.front();
		if (top == _pgoal) {
			return top.step;
		}
		open_set.pop();
		_closed[top.x][top.y] = true;
		print_maze();
		for (int i = 0; i < DIR_NUM; ++i) {
			int tx = top.x + DIR_X[i];
			int ty = top.y + DIR_Y[i];
			if (!valid_position(tx, ty)) {
				continue;
			}
			_extend[tx][ty] = true;
			_dir_pre[tx][ty] = i;
			Position tmp(tx, ty, top.step + 1);
			open_set.push(tmp);
		}
	}

	return -1;
}

int Astar() {
	priority_queue<Position> open_set;

	_extend[_pstart.x][_pstart.y] = true;
	_pstart.step = 0;
	_pstart.heuristic(_pgoal);

	open_set.push(_pstart);
	while (!open_set.empty()) {
		Position top = open_set.top();
		if (top == _pgoal) {
			return top.step;
		}
		open_set.pop();
		_closed[top.x][top.y] = true;
		print_maze();
		for (int i = 0; i < DIR_NUM; ++i) {
			int tx = top.x + DIR_X[i];
			int ty = top.y + DIR_Y[i];
			if (!valid_position(tx, ty)) {
				continue;
			}
			_extend[tx][ty] = true;
			_dir_pre[tx][ty] = i;
			Position tmp(tx, ty, top.step + 1);
			tmp.heuristic(_pgoal);
			open_set.push(tmp);
		}
	}

	return -1;
}

int IDSearch(Position top, int depth) {
    if (top == _pgoal) {
		return top.step;
	}

    _closed[top.x][top.y] = true;
	print_maze();
    for (int i = 0; i < DIR_NUM; ++i) {
        int tx = top.x + DIR_X[i];
        int ty = top.y + DIR_Y[i];
		if (!valid_position(tx, ty)) {
			continue;
		}
        Position tmp(tx, ty, top.step + 1);
        tmp.heuristic(_pgoal);
        if (tmp.h1 + tmp.step > depth) {
			continue;
		}
        _dir_pre[tx][ty] = i;
        int ret = IDSearch(tmp, depth);
        if (ret >= 0) {
			return ret;
		}
        // _closed[tx][ty] = false;
    }

    return -1;
}

int IDAstar() {
    _pstart.heuristic(_pgoal);
    for (int depth = _pstart.h1; depth < _maze_col * _maze_row; ++depth) {
        printf("depth:%d \n", depth);
        memset(_closed, false, sizeof(_closed));
        int ret = IDSearch(_pstart, depth);
        if (ret >= 0) return ret;
    }
    return -1;
}

void init_maze_map() {
	puts("Input your map or copy and paste from ./map.txt");

	scanf("%d,%d", &_maze_col, &_maze_row);
	memset(_maze_map, 0, sizeof(_maze_map));
	for (int i = 0; i < _maze_row; ++i) {
		getchar();
		for (int j = 0; j < _maze_col; ++j) {
			scanf("%c", &_maze_map[i][j]);
			if (_maze_map[i][j] == CH_START) {
				_pstart.x = i;
				_pstart.y = j;
			} else if (_maze_map[i][j] == CH_END) {
				_pgoal.x = i;
				_pgoal.y = j;
			}
		}
	}
	getchar();
}

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

    do {
menu:
		puts("");
        puts("=========== Routing Algorithms ===========");
		puts("----------------- DFS --------------");
		puts("    1. Depth-first search, recursive");
    	puts("    2. Depth-first search, stack");
		puts("----------------- BFS ------------------");
		puts("    3. Breadth-first search");
		puts("    4. A* search algorithm");
		puts("    5. Iterative deepening A*");
		puts("-------------------COMMAND--------------------");
		puts("    8. reset maze map");
		puts("    9. exit");
		puts("==============================================");
		printf("    input index number: ");

        char input_str[64] = {0};
input:
		fgets(input_str, sizeof(input_str), stdin);
		int input_len = strlen(input_str) - 1;
		for (int i = 0; i < input_len; ++i) {
			if (input_str[i] < '0' || input_str[i] > '9') {
				puts("input error, please try again.");
				goto input;
			}
		}
        int index = 0;
		sscanf(input_str, "%d", &index);
		printf("\nyour choose index:%d\n", index);

        prepare();
        clock_t time_start = clock();
        int result = 0;
        switch (index) {
        case 1:
            result = DFS(_pstart);
            break;
        case 2:
            result = DFS_stack();
            break;
        case 3:
            result = BFS();
            break;
        case 4:
            result = Astar();
            break;
		case 5:
            result = IDAstar();
			break;
		case 8:
			init_maze_map();
			goto menu;
		case 9:
            puts("\nsee you :)\n");
			goto done;
		default:
            puts("input error, please try again.");
            goto input;
		}
        clock_t time_end = clock();

        double cost_time = (double)(time_end - time_start)/CLOCKS_PER_SEC;
		printf("search cost time: %lfs\n", cost_time);
		if (result == -1) {
			puts("This maze have no solution");
			continue;
		}

		printf("The path need %d steps \n", result);
		Position tmp = _pgoal;
		while (true) {
			int i = _dir_pre[tmp.x][tmp.y];
			tmp.x -= DIR_X[i];
			tmp.y -= DIR_Y[i];
			if (tmp == _pstart) break;
			_maze_map[tmp.x][tmp.y] = CH_PATH;
		}
		print_maze();
	} while (true);

done:
	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Fix misuse of OmxCodec<commit_after><|endoftext|>


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

// This application is a test for AudioRendererAlgorithmOLA. It reads in a
// specified wav file (so far only 8, 16 and 32 bit are supported) and uses
// ARAO to scale the playback by a specified rate. Then it outputs the result
// to the specified location. Command line calls should be as follows:
//
//    wav_ola_test RATE INFILE OUTFILE

#include <iostream>
#include <string>

#include "base/callback.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "media/base/data_buffer.h"
#include "media/filters/audio_renderer_algorithm_ola.h"

using file_util::ScopedFILE;
using media::AudioRendererAlgorithmOLA;
using media::DataBuffer;

const double kDefaultWindowLength = 0.08;

struct WavHeader {
  int32 riff;
  int32 chunk_size;
  char unused0[8];
  int32 subchunk1_size;
  int16 audio_format;
  int16 channels;
  int32 sample_rate;
  char unused1[6];
  int16 bit_rate;
  char unused2[4];
  int32 subchunk2_size;
};

// Dummy class to feed data to OLA algorithm. Necessary to create callback.
class Dummy {
 public:
  Dummy(FILE* in, AudioRendererAlgorithmOLA* ola, size_t window_size)
      : input_(in),
        ola_(ola),
        window_size_(window_size) {
  }

  void ReadDataForAlg() {
    scoped_refptr<DataBuffer> buffer(new DataBuffer(window_size_));
    buffer->SetDataSize(window_size_);
    uint8* buf = buffer->GetWritableData();
    if (fread(buf, 1, window_size_, input_) > 0) {
      ola_->EnqueueBuffer(buffer.get());
    }
  }

 private:
  FILE* input_;
  AudioRendererAlgorithmOLA* ola_;
  size_t window_size_;

  DISALLOW_COPY_AND_ASSIGN(Dummy);
};

int main(int argc, const char** argv) {
  AudioRendererAlgorithmOLA ola;
  CommandLine::Init(argc, argv);
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();

  const std::vector<CommandLine::StringType>& filenames = cmd_line->args();
  if (filenames.empty()) {
    std::cerr << "Usage: " << argv[0] << " RATE INFILE OUTFILE\n"
              << std::endl;
    return 1;
  }

  // Retrieve command line options.
  FilePath in_path(filenames[1]);
  FilePath out_path(filenames[2]);
  double playback_rate = 0.0;

  // Determine speed of rerecord.
#if defined(OS_WIN)
  std::string filename_str = WideToASCII(filenames[0]);
#else
  const std::string& filename_str = filenames[0];
#endif
  if (!base::StringToDouble(filename_str, &playback_rate))
    playback_rate = 0.0;

  // Open input file.
  ScopedFILE input(file_util::OpenFile(in_path, "rb"));
  if (!(input.get())) {
    LOG(ERROR) << "could not open input";
    return 1;
  }

  // Open output file.
  ScopedFILE output(file_util::OpenFile(out_path, "wb"));
  if (!(output.get())) {
    LOG(ERROR) << "could not open output";
    return 1;
  }

  // Read in header.
  WavHeader wav;
  if (fread(&wav, sizeof(wav), 1, input.get()) < 1) {
    LOG(ERROR) << "could not read WAV header";
    return 1;
  }

  size_t window_size = static_cast<size_t>(wav.sample_rate
                                           * (wav.bit_rate / 8)
                                           * wav.channels
                                           * kDefaultWindowLength);

  // Instantiate dummy class and callback to feed data to |ola|.
  Dummy guy(input.get(), &ola, window_size);
  AudioRendererAlgorithmOLA::RequestReadCallback* cb =
      NewCallback(&guy, &Dummy::ReadDataForAlg);
  ola.Initialize(wav.channels,
                 wav.sample_rate,
                 wav.bit_rate,
                 static_cast<float>(playback_rate),
                 cb);
  ola.FlushBuffers();

  // Print out input format.
  std::cout << in_path.value() << "\n"
            << "Channels: " << wav.channels << "\n"
            << "Sample Rate: " << wav.sample_rate << "\n"
            << "Bit Rate: " << wav.bit_rate << "\n"
            << "\n"
            << "Scaling audio by " << playback_rate << "x..." << std::endl;

  // Write the header back out again.
  if (fwrite(&wav, sizeof(wav), 1, output.get()) < 1) {
    LOG(ERROR) << "could not write WAV header";
    return 1;
  }

  // Create buffer to be filled by |ola|.
  scoped_array<uint8> buf(new uint8[window_size]);

  CHECK(buf.get());

  // Keep track of bytes written to disk and bytes copied to |b|.
  size_t bytes_written = 0;
  size_t bytes;
  while ((bytes = ola.FillBuffer(buf.get(), window_size)) > 0) {
    if (fwrite(buf.get(), 1, bytes, output.get()) != bytes) {
      LOG(ERROR) << "could not write data after " << bytes_written;
    } else {
      bytes_written += bytes;
    }
  }

  // Seek back to the beginning of our output file and update the header.
  wav.chunk_size = 36 + bytes_written;
  wav.subchunk1_size = 16;
  wav.subchunk2_size = bytes_written;
  fseek(output.get(), 0, SEEK_SET);
  if (fwrite(&wav, sizeof(wav), 1, output.get()) < 1) {
    LOG(ERROR) << "could not write wav header.";
    return 1;
  }
  CommandLine::Reset();
  return 0;
}
<commit_msg>Fix compile on windows.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This application is a test for AudioRendererAlgorithmOLA. It reads in a
// specified wav file (so far only 8, 16 and 32 bit are supported) and uses
// ARAO to scale the playback by a specified rate. Then it outputs the result
// to the specified location. Command line calls should be as follows:
//
//    wav_ola_test RATE INFILE OUTFILE

#include <iostream>
#include <string>

#include "base/callback.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "media/base/data_buffer.h"
#include "media/filters/audio_renderer_algorithm_ola.h"

using file_util::ScopedFILE;
using media::AudioRendererAlgorithmOLA;
using media::DataBuffer;

const double kDefaultWindowLength = 0.08;

struct WavHeader {
  int32 riff;
  int32 chunk_size;
  char unused0[8];
  int32 subchunk1_size;
  int16 audio_format;
  int16 channels;
  int32 sample_rate;
  char unused1[6];
  int16 bit_rate;
  char unused2[4];
  int32 subchunk2_size;
};

// Dummy class to feed data to OLA algorithm. Necessary to create callback.
class Dummy {
 public:
  Dummy(FILE* in, AudioRendererAlgorithmOLA* ola, size_t window_size)
      : input_(in),
        ola_(ola),
        window_size_(window_size) {
  }

  void ReadDataForAlg() {
    scoped_refptr<DataBuffer> buffer(new DataBuffer(window_size_));
    buffer->SetDataSize(window_size_);
    uint8* buf = buffer->GetWritableData();
    if (fread(buf, 1, window_size_, input_) > 0) {
      ola_->EnqueueBuffer(buffer.get());
    }
  }

 private:
  FILE* input_;
  AudioRendererAlgorithmOLA* ola_;
  size_t window_size_;

  DISALLOW_COPY_AND_ASSIGN(Dummy);
};

int main(int argc, const char** argv) {
  AudioRendererAlgorithmOLA ola;
  CommandLine::Init(argc, argv);
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();

  const std::vector<CommandLine::StringType>& filenames = cmd_line->args();
  if (filenames.empty()) {
    std::cerr << "Usage: " << argv[0] << " RATE INFILE OUTFILE\n"
              << std::endl;
    return 1;
  }

  // Retrieve command line options.
  FilePath in_path(filenames[1]);
  FilePath out_path(filenames[2]);
  double playback_rate = 0.0;

  // Determine speed of rerecord.
#if defined(OS_WIN)
  std::string filename_str = WideToASCII(filenames[0]);
#else
  const std::string& filename_str = filenames[0];
#endif
  if (!base::StringToDouble(filename_str, &playback_rate))
    playback_rate = 0.0;

  // Open input file.
  ScopedFILE input(file_util::OpenFile(in_path, "rb"));
  if (!(input.get())) {
    LOG(ERROR) << "could not open input";
    return 1;
  }

  // Open output file.
  ScopedFILE output(file_util::OpenFile(out_path, "wb"));
  if (!(output.get())) {
    LOG(ERROR) << "could not open output";
    return 1;
  }

  // Read in header.
  WavHeader wav;
  if (fread(&wav, sizeof(wav), 1, input.get()) < 1) {
    LOG(ERROR) << "could not read WAV header";
    return 1;
  }

  size_t window_size = static_cast<size_t>(wav.sample_rate
                                           * (wav.bit_rate / 8)
                                           * wav.channels
                                           * kDefaultWindowLength);

  // Instantiate dummy class and callback to feed data to |ola|.
  Dummy guy(input.get(), &ola, window_size);
  AudioRendererAlgorithmOLA::RequestReadCallback* cb =
      NewCallback(&guy, &Dummy::ReadDataForAlg);
  ola.Initialize(wav.channels,
                 wav.sample_rate,
                 wav.bit_rate,
                 static_cast<float>(playback_rate),
                 cb);
  ola.FlushBuffers();

  // Print out input format.
  std::cout << in_path.value() << "\n"
            << "Channels: " << wav.channels << "\n"
            << "Sample Rate: " << wav.sample_rate << "\n"
            << "Bit Rate: " << wav.bit_rate << "\n"
            << "\n"
            << "Scaling audio by " << playback_rate << "x..." << std::endl;

  // Write the header back out again.
  if (fwrite(&wav, sizeof(wav), 1, output.get()) < 1) {
    LOG(ERROR) << "could not write WAV header";
    return 1;
  }

  // Create buffer to be filled by |ola|.
  scoped_array<uint8> buf(new uint8[window_size]);

  CHECK(buf.get());

  // Keep track of bytes written to disk and bytes copied to |b|.
  size_t bytes_written = 0;
  size_t bytes;
  while ((bytes = ola.FillBuffer(buf.get(), window_size)) > 0) {
    if (fwrite(buf.get(), 1, bytes, output.get()) != bytes) {
      LOG(ERROR) << "could not write data after " << bytes_written;
    } else {
      bytes_written += bytes;
    }
  }

  // Seek back to the beginning of our output file and update the header.
  wav.chunk_size = 36 + bytes_written;
  wav.subchunk1_size = 16;
  wav.subchunk2_size = bytes_written;
  fseek(output.get(), 0, SEEK_SET);
  if (fwrite(&wav, sizeof(wav), 1, output.get()) < 1) {
    LOG(ERROR) << "could not write wav header.";
    return 1;
  }
  CommandLine::Reset();
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: urp_writer.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: jbu $ $Date: 2001-04-17 15:49:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library 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.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <assert.h>
#include <stdio.h>

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#include <osl/mutex.hxx>
#include <osl/conditn.h>

#include <typelib/typedescription.h>

#include <bridges/remote/connection.h>
#include <bridges/remote/remote.hxx>

#include <com/sun/star/uno/Sequence.hxx>

#include <bridges/remote/counter.hxx>

#include "urp_writer.hxx"
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"

#ifdef DEBUG
static MyCounter thisCounter( "DEBUG : WriterThread" );
#endif

using namespace ::osl;

namespace bridges_urp {

OWriterThread::OWriterThread( remote_Connection *pConnection, urp_BridgeImpl *pBridgeImpl,
                              uno_Environment *pEnvRemote) :
    m_pConnection( pConnection ),
    m_bAbort( sal_False ),
    m_pBridgeImpl( pBridgeImpl ),
    m_pEnvRemote( pEnvRemote ),
    m_bInBlockingWait( sal_False ),
    m_bEnterBlockingWait( sal_False )

{
    m_oslCondition = osl_createCondition();
    osl_resetCondition( m_oslCondition );
    m_pConnection->acquire( m_pConnection );

#ifdef DEBUG
    thisCounter.acquire();
#endif
}

OWriterThread::~OWriterThread()
{
    osl_destroyCondition( m_oslCondition );
    m_pConnection->release( m_pConnection );
#ifdef DEBUG
    thisCounter.release();
#endif
}

// touch is called with locked m_marshalingMutex
void OWriterThread::touch( sal_Bool bImmediately )
{
      if( bImmediately || m_pBridgeImpl->m_blockMarshaler.getPos() > m_pBridgeImpl->m_properties.nFlushBlockSize )
      {
        write();
      }
    else
    {
        // wake the writer thread up
        if( m_bInBlockingWait )
        {
            m_bInBlockingWait = sal_False;
            osl_setCondition( m_oslCondition );
        }
        else
        {
            // ensure, that the writing thread does not enter blocking mode
              m_bEnterBlockingWait = sal_False;
        }
    }
}

void OWriterThread::abort()
{
    MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );

    m_bAbort = sal_True;
    m_bEnterBlockingWait = sal_False;
    if( m_bInBlockingWait )
    {
        m_bInBlockingWait = sal_False;
        osl_setCondition( m_oslCondition );
    }
}

// must be called with locked marshaling mutex
void OWriterThread::write()
{
     if( ! m_pBridgeImpl->m_blockMarshaler.empty() && ! m_bAbort )
     {
        m_pBridgeImpl->m_blockMarshaler.finish( m_pBridgeImpl->m_nMarshaledMessages);
        m_pBridgeImpl->m_nMarshaledMessages = 0;

        sal_Int32 nLength = m_pBridgeImpl->m_blockMarshaler.getSize();
        sal_Int8 *pBuf = m_pBridgeImpl->m_blockMarshaler.getBuffer();

        if( nLength != m_pConnection->write( m_pConnection, pBuf, nLength ))
        {
            m_pBridgeImpl->m_blockMarshaler.restart();
            return;
        }
        m_pConnection->flush( m_pConnection );
        m_pBridgeImpl->m_blockMarshaler.restart();
    }
}

void OWriterThread::sendEmptyMessage()
{
    // must be called with locked marshaling mutex
    sal_Int32 a[2] = {0,0};
    if( m_pConnection )
    {
        m_pConnection->write( m_pConnection , (sal_Int8*) a , sizeof( sal_Int32) *2 );
    }
}

void OWriterThread::insertReleaseRemoteCall(
    rtl_uString *pOid,typelib_TypeDescriptionReference *pTypeRef)
{
    ::osl::MutexGuard guard( m_releaseCallMutex );

    struct RemoteReleaseCall call;
    call.sOid = pOid;
    call.typeInterface = pTypeRef;
    m_lstReleaseCalls.push_back( call );
}

/* The release calls for doubled interfaces
 *
 *
 ***/
void OWriterThread::executeReleaseRemoteCalls()
{
    sal_Bool bFound = sal_True;
    ::std::list< struct RemoteReleaseCall > lstReleaseCalls;
    {
        ::osl::MutexGuard guard( m_releaseCallMutex );
        lstReleaseCalls.swap( m_lstReleaseCalls );
    }

    for( ::std::list< struct RemoteReleaseCall >::iterator ii = lstReleaseCalls.begin();
         ii != lstReleaseCalls.end();
         ++ ii )
    {
        struct RemoteReleaseCall &call = (*ii) ;

        typelib_TypeDescription *pInterfaceTypeDesc = 0;
        typelib_TypeDescription *pReleaseMethod = 0;

        call.typeInterface.getDescription( &pInterfaceTypeDesc );
        if( ! pInterfaceTypeDesc->bComplete )
        {
            typelib_typedescription_complete( &pInterfaceTypeDesc );
        }

        uno_Any any;
        uno_Any *pAny = &any;

        typelib_typedescriptionreference_getDescription(
            &pReleaseMethod ,
            ((typelib_InterfaceTypeDescription*)pInterfaceTypeDesc)->ppAllMembers[REMOTE_RELEASE_METHOD_INDEX] );

        urp_sendRequest( m_pEnvRemote , pReleaseMethod, call.sOid.pData,
                         (typelib_InterfaceTypeDescription*) pInterfaceTypeDesc,
                         0, 0 , &pAny );

        typelib_typedescription_release( pReleaseMethod );
        typelib_typedescription_release( pInterfaceTypeDesc );
    }
}

void OWriterThread::run()
{
    while( ! m_bAbort )
    {
        sal_Bool bWait;
        {
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            bWait = m_bEnterBlockingWait;
            if( bWait )
            {
                osl_resetCondition( m_oslCondition );
                m_bInBlockingWait = sal_True;
            }
            m_bEnterBlockingWait = sal_True;
        }

        // wait for some notification
        if( bWait )
            osl_waitCondition( m_oslCondition , 0 );
        // (m_bInBlockingWait = sal_False was set by the activating thread)

          if( m_bAbort )
              break;

        // Wait for the timeout
        TimeValue value = { 0 , 1000 * m_pBridgeImpl->m_properties.nOnewayTimeoutMUSEC };
        osl_resetCondition( m_oslCondition );
        osl_waitCondition( m_oslCondition , &value );

        // check if there are some release calls to be sent ....
        executeReleaseRemoteCalls();

        {
            // write to the socket
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            if( ! m_pBridgeImpl->m_blockMarshaler.empty() )
            {
                write();
            }
        }
    }
}

}

<commit_msg>#85292# releases are now sent within 10 ms time range<commit_after>/*************************************************************************
 *
 *  $RCSfile: urp_writer.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: jbu $ $Date: 2001-04-18 07:31:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library 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.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <assert.h>
#include <stdio.h>

#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif

#include <osl/mutex.hxx>
#include <osl/conditn.h>

#include <typelib/typedescription.h>

#include <bridges/remote/connection.h>
#include <bridges/remote/remote.hxx>

#include <com/sun/star/uno/Sequence.hxx>

#include <bridges/remote/counter.hxx>

#include "urp_writer.hxx"
#include "urp_bridgeimpl.hxx"
#include "urp_marshal.hxx"
#include "urp_dispatch.hxx"

#ifdef DEBUG
static MyCounter thisCounter( "DEBUG : WriterThread" );
#endif

using namespace ::osl;

namespace bridges_urp {

OWriterThread::OWriterThread( remote_Connection *pConnection, urp_BridgeImpl *pBridgeImpl,
                              uno_Environment *pEnvRemote) :
    m_pConnection( pConnection ),
    m_bAbort( sal_False ),
    m_pBridgeImpl( pBridgeImpl ),
    m_pEnvRemote( pEnvRemote ),
    m_bInBlockingWait( sal_False ),
    m_bEnterBlockingWait( sal_False )

{
    m_oslCondition = osl_createCondition();
    osl_resetCondition( m_oslCondition );
    m_pConnection->acquire( m_pConnection );

#ifdef DEBUG
    thisCounter.acquire();
#endif
}

OWriterThread::~OWriterThread()
{
    osl_destroyCondition( m_oslCondition );
    m_pConnection->release( m_pConnection );
#ifdef DEBUG
    thisCounter.release();
#endif
}

// touch is called with locked m_marshalingMutex
void OWriterThread::touch( sal_Bool bImmediately )
{
      if( bImmediately || m_pBridgeImpl->m_blockMarshaler.getPos() > m_pBridgeImpl->m_properties.nFlushBlockSize )
      {
        write();
      }
    else
    {
        // wake the writer thread up
        if( m_bInBlockingWait )
        {
            m_bInBlockingWait = sal_False;
            osl_setCondition( m_oslCondition );
        }
        else
        {
            // ensure, that the writing thread does not enter blocking mode
              m_bEnterBlockingWait = sal_False;
        }
    }
}

void OWriterThread::abort()
{
    MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );

    m_bAbort = sal_True;
    m_bEnterBlockingWait = sal_False;
    if( m_bInBlockingWait )
    {
        m_bInBlockingWait = sal_False;
        osl_setCondition( m_oslCondition );
    }
}

// must be called with locked marshaling mutex
void OWriterThread::write()
{
     if( ! m_pBridgeImpl->m_blockMarshaler.empty() && ! m_bAbort )
     {
        m_pBridgeImpl->m_blockMarshaler.finish( m_pBridgeImpl->m_nMarshaledMessages);
        m_pBridgeImpl->m_nMarshaledMessages = 0;

        sal_Int32 nLength = m_pBridgeImpl->m_blockMarshaler.getSize();
        sal_Int8 *pBuf = m_pBridgeImpl->m_blockMarshaler.getBuffer();

        if( nLength != m_pConnection->write( m_pConnection, pBuf, nLength ))
        {
            m_pBridgeImpl->m_blockMarshaler.restart();
            return;
        }
        m_pConnection->flush( m_pConnection );
        m_pBridgeImpl->m_blockMarshaler.restart();
    }
}

void OWriterThread::sendEmptyMessage()
{
    // must be called with locked marshaling mutex
    sal_Int32 a[2] = {0,0};
    if( m_pConnection )
    {
        m_pConnection->write( m_pConnection , (sal_Int8*) a , sizeof( sal_Int32) *2 );
    }
}

void OWriterThread::insertReleaseRemoteCall(
    rtl_uString *pOid,typelib_TypeDescriptionReference *pTypeRef)
{
    {
        ::osl::MutexGuard guard( m_releaseCallMutex );

        struct RemoteReleaseCall call;
        call.sOid = pOid;
        call.typeInterface = pTypeRef;
        m_lstReleaseCalls.push_back( call );
    }
    {
        MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
        if( m_bInBlockingWait )
        {
            m_bInBlockingWait = sal_False;
            osl_setCondition( m_oslCondition );
        }
        else
        {
            // ensure, that the writing thread does not enter blocking mode
              m_bEnterBlockingWait = sal_False;
        }
    }
    fprintf( stderr , "%d\n" , m_lstReleaseCalls.size() );
}

/* The release calls for doubled interfaces
 *
 *
 ***/
void OWriterThread::executeReleaseRemoteCalls()
{
    sal_Bool bFound = sal_True;
    ::std::list< struct RemoteReleaseCall > lstReleaseCalls;
    {
        ::osl::MutexGuard guard( m_releaseCallMutex );
        lstReleaseCalls.swap( m_lstReleaseCalls );
    }

    for( ::std::list< struct RemoteReleaseCall >::iterator ii = lstReleaseCalls.begin();
         ii != lstReleaseCalls.end();
         ++ ii )
    {
        struct RemoteReleaseCall &call = (*ii) ;

        typelib_TypeDescription *pInterfaceTypeDesc = 0;
        typelib_TypeDescription *pReleaseMethod = 0;

        call.typeInterface.getDescription( &pInterfaceTypeDesc );
        if( ! pInterfaceTypeDesc->bComplete )
        {
            typelib_typedescription_complete( &pInterfaceTypeDesc );
        }

        uno_Any any;
        uno_Any *pAny = &any;

        typelib_typedescriptionreference_getDescription(
            &pReleaseMethod ,
            ((typelib_InterfaceTypeDescription*)pInterfaceTypeDesc)->ppAllMembers[REMOTE_RELEASE_METHOD_INDEX] );

        urp_sendRequest( m_pEnvRemote , pReleaseMethod, call.sOid.pData,
                         (typelib_InterfaceTypeDescription*) pInterfaceTypeDesc,
                         0, 0 , &pAny );

        typelib_typedescription_release( pReleaseMethod );
        typelib_typedescription_release( pInterfaceTypeDesc );
    }
}

void OWriterThread::run()
{
    while( ! m_bAbort )
    {
        sal_Bool bWait;
        {
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            bWait = m_bEnterBlockingWait;
            if( bWait )
            {
                osl_resetCondition( m_oslCondition );
                m_bInBlockingWait = sal_True;
            }
            m_bEnterBlockingWait = sal_True;
        }

        // wait for some notification
        if( bWait )
            osl_waitCondition( m_oslCondition , 0 );
        // (m_bInBlockingWait = sal_False was set by the activating thread)

          if( m_bAbort )
              break;

        // Wait for the timeout
        TimeValue value = { 0 , 1000 * m_pBridgeImpl->m_properties.nOnewayTimeoutMUSEC };
        osl_resetCondition( m_oslCondition );
        osl_waitCondition( m_oslCondition , &value );

        // check if there are some release calls to be sent ....
        executeReleaseRemoteCalls();

        {
            // write to the socket
            MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );
            if( ! m_pBridgeImpl->m_blockMarshaler.empty() )
            {
                write();
            }
        }
    }
}

}

<|endoftext|>


<commit_before>/**
 * @file evaluate_circuit.cpp
 * @see https://github.com/benjaminvillalonga/optimized_parallel_QC_with_TN
 *
 * @author Benjamin Villalonga (main contributor), Bron Nelson, Sergio Boixo and
 * Salvatore Mandra
 * @date Created: August 2018
 * @date Modified: August 2018
 *
 * @copyright: Copyright © 2019, United States Government, as represented
 * by the Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 * @licence: Apache License, Version 2.0
 */

#include "evaluate_circuit.h"

namespace qflex {

void QflexGrid::load(std::istream &istream) {
  I = J = 0;
  std::string line;
  while(std::getline(istream, line)) {

    // String unnecessary chars
    line.erase(std::remove_if(std::begin(line), std::end(line), [](auto &&x){ return not (x == '0' || x == '1'); }), std::end(line));

    // Get number of columns
    if(J != 0 and J != std::size(line)) throw std::string("Grid size is inconsistent");
    else J = std::size(line);

    // Get off qubits
    for(int q = 0; q < J; ++q)
      if(line[q] == '0')
        qubits_off.push_back({I, q});

    // Update number of rows
    ++I;
  }
};

void QflexGrid::load(const std::string &filename) {
  if(auto in = std::ifstream(filename); in.good()) this->load(in);
  else throw std::string("Cannot open grid file: ") + filename;
};

void get_output_states(const std::list<ContractionOperation>& ordering,
                       std::vector<std::vector<int>>* final_qubits,
                       std::vector<std::string>* output_states) {
  if (final_qubits == nullptr) {
    std::cout << "Final qubits must be non-null." << std::endl;
    assert(final_qubits != nullptr);
  }
  output_states->push_back("");
  std::vector<std::string> temp_output_states;
  for (const auto& op : ordering) {
    if (op.op_type != ContractionOperation::CUT) continue;
    // Any qubit with a terminal cut is in the final region.
    // TODO(martinop): update to use the new operation.
    if (op.cut.tensors.size() == 1) {
      final_qubits->push_back(op.cut.tensors[0]);
      for (const auto& state : *output_states) {
        std::vector<int> values = op.cut.values;
        if (values.empty()) values = {0, 1};
        for (const int value : values) {
          temp_output_states.push_back(state + std::to_string(value));
        }
      }
      *output_states = temp_output_states;
      temp_output_states.clear();
    }
  }
}

std::vector<std::pair<std::string, std::complex<double>>> EvaluateCircuit(
    QflexInput* input) {
  if (input == nullptr) {
    std::cout << "Input must be non-null." << std::endl;
    assert(input != nullptr);
  }
  // Set precision for the printed floats.
  std::cout.precision(12);

  // Timing variables.
  std::chrono::high_resolution_clock::time_point t_output_0, t_output_1;
  t_output_0 = std::chrono::high_resolution_clock::now();
  std::chrono::high_resolution_clock::time_point t0, t1;
  std::chrono::duration<double> time_span;

  // Reading input.
  const int super_dim = (int)pow(DIM, input->K);

  // Create the ordering for this tensor contraction from file.
  t0 = std::chrono::high_resolution_clock::now();
  std::list<ContractionOperation> ordering;
  ordering_data_to_contraction_ordering(input->ordering_data, input->grid.I,
                                        input->grid.J, input->grid.qubits_off, &ordering);
  t1 = std::chrono::high_resolution_clock::now();
  time_span =
      std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
  if (input->enable_timing_logs) {
    std::cout << "Time spent making contraction ordering: " << time_span.count()
              << "s" << std::endl;
  }

  // Get a list of qubits and output states for the final region.
  std::vector<std::vector<int>> final_qubits;
  std::vector<std::string> output_states;
  get_output_states(ordering, &final_qubits, &output_states);

  int init_length = input->grid.I * input->grid.J - input->grid.qubits_off.size();
  if (input->initial_state.empty()) {
    input->initial_state = std::string(init_length, '0');
  }
  if (input->final_state_A.empty()) {
    input->final_state_A = std::string(init_length - final_qubits.size(), '0');
  }

  // Scratch space to be reused for operations.
  t0 = std::chrono::high_resolution_clock::now();
  s_type* scratch = new s_type[(int)pow(super_dim, 7)];
  t1 = std::chrono::high_resolution_clock::now();
  time_span =
      std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
  if (input->enable_timing_logs) {
    std::cout << "Time spent reading allocating scratch space: "
              << time_span.count() << "s" << std::endl;
  }

  // Declaring and then filling 2D grid of tensors.
  std::vector<std::vector<Tensor>> tensor_grid(input->grid.I);
  for (int i = 0; i < input->grid.I; ++i) {
    tensor_grid[i] = std::vector<Tensor>(input->grid.J);
  }
  // Scope so that the 3D grid of tensors is destructed.
  {
    // Creating 3D grid of tensors from file.
    t0 = std::chrono::high_resolution_clock::now();
    std::vector<std::vector<std::vector<Tensor>>> tensor_grid_3D;
    circuit_data_to_grid_of_tensors(input->circuit_data, input->grid.I, input->grid.J,
                                    input->K, input->initial_state,
                                    input->final_state_A, final_qubits,
                                    input->grid.qubits_off, tensor_grid_3D, scratch);
    t1 = std::chrono::high_resolution_clock::now();
    time_span =
        std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
    if (input->enable_timing_logs) {
      std::cout << "Time spent creating 3D grid of tensors from file: "
                << time_span.count() << "s" << std::endl;
    }

    // Contract 3D grid onto 2D grid of tensors, as usual.
    t0 = std::chrono::high_resolution_clock::now();
    grid_of_tensors_3D_to_2D(tensor_grid_3D, tensor_grid, final_qubits,
                             input->grid.qubits_off, ordering, scratch);
    t1 = std::chrono::high_resolution_clock::now();
    time_span =
        std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
    if (input->enable_timing_logs) {
      std::cout << "Time spent creating 2D grid of tensors from 3D one: "
                << time_span.count() << "s" << std::endl;
    }

    // Freeing scratch data: delete and NULL.
    delete[] scratch;
    scratch = NULL;
  }

  // Perform tensor grid contraction.
  std::vector<std::complex<double>> amplitudes(output_states.size());
  std::vector<std::pair<std::string, std::complex<double>>> result;
  ContractGrid(ordering, &tensor_grid, &amplitudes);
  for (int c = 0; c < amplitudes.size(); ++c) {
    result.push_back(std::make_pair(
        input->final_state_A + " " + output_states[c], amplitudes[c]));
  }

  // Final time
  t_output_1 = std::chrono::high_resolution_clock::now();
  time_span = std::chrono::duration_cast<std::chrono::duration<double>>(
      t_output_1 - t_output_0);
  std::cout << "Total time: " << time_span.count() << "s" << std::endl;

  return result;
}

}  // namespace qflex
<commit_msg>Fix bug.<commit_after>/**
 * @file evaluate_circuit.cpp
 * @see https://github.com/benjaminvillalonga/optimized_parallel_QC_with_TN
 *
 * @author Benjamin Villalonga (main contributor), Bron Nelson, Sergio Boixo and
 * Salvatore Mandra
 * @date Created: August 2018
 * @date Modified: August 2018
 *
 * @copyright: Copyright © 2019, United States Government, as represented
 * by the Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 * @licence: Apache License, Version 2.0
 */

#include "evaluate_circuit.h"

namespace qflex {

void QflexGrid::load(std::istream &istream) {
  I = J = 0;
  std::string line;
  while(std::getline(istream, line)) if(std::size(line) and line[0] != '#') {

    // String unnecessary chars
    line.erase(std::remove_if(std::begin(line), std::end(line), [](auto &&x){ return not (x == '0' || x == '1'); }), std::end(line));

    // Continue if line is empty
    if(std::empty(line)) continue;

    // Get number of columns
    if(J != 0 and J != std::size(line)) throw std::string("Grid size is inconsistent");
    else J = std::size(line);

    // Get off qubits
    for(int q = 0; q < J; ++q)
      if(line[q] == '0')
        qubits_off.push_back({I, q});

    // Update number of rows
    ++I;
  }
};

void QflexGrid::load(const std::string &filename) {
  if(auto in = std::ifstream(filename); in.good()) this->load(in);
  else throw std::string("Cannot open grid file: ") + filename;
};

void get_output_states(const std::list<ContractionOperation>& ordering,
                       std::vector<std::vector<int>>* final_qubits,
                       std::vector<std::string>* output_states) {
  if (final_qubits == nullptr) {
    std::cout << "Final qubits must be non-null." << std::endl;
    assert(final_qubits != nullptr);
  }
  output_states->push_back("");
  std::vector<std::string> temp_output_states;
  for (const auto& op : ordering) {
    if (op.op_type != ContractionOperation::CUT) continue;
    // Any qubit with a terminal cut is in the final region.
    // TODO(martinop): update to use the new operation.
    if (op.cut.tensors.size() == 1) {
      final_qubits->push_back(op.cut.tensors[0]);
      for (const auto& state : *output_states) {
        std::vector<int> values = op.cut.values;
        if (values.empty()) values = {0, 1};
        for (const int value : values) {
          temp_output_states.push_back(state + std::to_string(value));
        }
      }
      *output_states = temp_output_states;
      temp_output_states.clear();
    }
  }
}

std::vector<std::pair<std::string, std::complex<double>>> EvaluateCircuit(
    QflexInput* input) {
  if (input == nullptr) {
    std::cout << "Input must be non-null." << std::endl;
    assert(input != nullptr);
  }
  // Set precision for the printed floats.
  std::cout.precision(12);

  // Timing variables.
  std::chrono::high_resolution_clock::time_point t_output_0, t_output_1;
  t_output_0 = std::chrono::high_resolution_clock::now();
  std::chrono::high_resolution_clock::time_point t0, t1;
  std::chrono::duration<double> time_span;

  // Reading input.
  const int super_dim = (int)pow(DIM, input->K);

  // Create the ordering for this tensor contraction from file.
  t0 = std::chrono::high_resolution_clock::now();
  std::list<ContractionOperation> ordering;
  ordering_data_to_contraction_ordering(input->ordering_data, input->grid.I,
                                        input->grid.J, input->grid.qubits_off, &ordering);
  t1 = std::chrono::high_resolution_clock::now();
  time_span =
      std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
  if (input->enable_timing_logs) {
    std::cout << "Time spent making contraction ordering: " << time_span.count()
              << "s" << std::endl;
  }

  // Get a list of qubits and output states for the final region.
  std::vector<std::vector<int>> final_qubits;
  std::vector<std::string> output_states;
  get_output_states(ordering, &final_qubits, &output_states);

  int init_length = input->grid.I * input->grid.J - input->grid.qubits_off.size();
  if (input->initial_state.empty()) {
    input->initial_state = std::string(init_length, '0');
  }
  if (input->final_state_A.empty()) {
    input->final_state_A = std::string(init_length - final_qubits.size(), '0');
  }

  // Scratch space to be reused for operations.
  t0 = std::chrono::high_resolution_clock::now();
  s_type* scratch = new s_type[(int)pow(super_dim, 7)];
  t1 = std::chrono::high_resolution_clock::now();
  time_span =
      std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
  if (input->enable_timing_logs) {
    std::cout << "Time spent reading allocating scratch space: "
              << time_span.count() << "s" << std::endl;
  }

  // Declaring and then filling 2D grid of tensors.
  std::vector<std::vector<Tensor>> tensor_grid(input->grid.I);
  for (int i = 0; i < input->grid.I; ++i) {
    tensor_grid[i] = std::vector<Tensor>(input->grid.J);
  }
  // Scope so that the 3D grid of tensors is destructed.
  {
    // Creating 3D grid of tensors from file.
    t0 = std::chrono::high_resolution_clock::now();
    std::vector<std::vector<std::vector<Tensor>>> tensor_grid_3D;
    circuit_data_to_grid_of_tensors(input->circuit_data, input->grid.I, input->grid.J,
                                    input->K, input->initial_state,
                                    input->final_state_A, final_qubits,
                                    input->grid.qubits_off, tensor_grid_3D, scratch);
    t1 = std::chrono::high_resolution_clock::now();
    time_span =
        std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
    if (input->enable_timing_logs) {
      std::cout << "Time spent creating 3D grid of tensors from file: "
                << time_span.count() << "s" << std::endl;
    }

    // Contract 3D grid onto 2D grid of tensors, as usual.
    t0 = std::chrono::high_resolution_clock::now();
    grid_of_tensors_3D_to_2D(tensor_grid_3D, tensor_grid, final_qubits,
                             input->grid.qubits_off, ordering, scratch);
    t1 = std::chrono::high_resolution_clock::now();
    time_span =
        std::chrono::duration_cast<std::chrono::duration<double>>(t1 - t0);
    if (input->enable_timing_logs) {
      std::cout << "Time spent creating 2D grid of tensors from 3D one: "
                << time_span.count() << "s" << std::endl;
    }

    // Freeing scratch data: delete and NULL.
    delete[] scratch;
    scratch = NULL;
  }

  // Perform tensor grid contraction.
  std::vector<std::complex<double>> amplitudes(output_states.size());
  std::vector<std::pair<std::string, std::complex<double>>> result;
  ContractGrid(ordering, &tensor_grid, &amplitudes);
  for (int c = 0; c < amplitudes.size(); ++c) {
    result.push_back(std::make_pair(
        input->final_state_A + " " + output_states[c], amplitudes[c]));
  }

  // Final time
  t_output_1 = std::chrono::high_resolution_clock::now();
  time_span = std::chrono::duration_cast<std::chrono::duration<double>>(
      t_output_1 - t_output_0);
  std::cout << "Total time: " << time_span.count() << "s" << std::endl;

  return result;
}

}  // namespace qflex
<|endoftext|>


<commit_before>#include "ContextTest.hpp"

CPPUNIT_TEST_SUITE_REGISTRATION(ContextTest);

#include "libdnf/dnf-context.hpp"
#include "libdnf/dnf-repo-loader.h"
#include "libdnf/sack/query.hpp"
#include "libdnf/nevra.hpp"
#include "libdnf/utils/File.hpp"
#include "libdnf/sack/packageset.hpp"
#include "libdnf/dnf-sack-private.hpp"

#include <memory>

void ContextTest::setUp()
{
    dnf_context_set_config_file_path("");
    context = dnf_context_new();
}

void ContextTest::tearDown()
{
    g_object_unref(context);
}

void ContextTest::testLoadModules()
{
    GError *error = nullptr;

    /* set up local context */
    // set releasever to avoid crashing on missing /etc/os-release in the test data
    dnf_context_set_release_ver(context, "26");
    dnf_context_set_arch(context, "x86_64");
    constexpr auto install_root = TESTDATADIR "/modules/";
    dnf_context_set_install_root(context, install_root);
    g_autoptr(DnfLock) lock = dnf_lock_new();
    dnf_lock_set_lock_dir(lock, "/tmp");
    constexpr auto repos_dir = TESTDATADIR "/modules/yum.repos.d/";
    dnf_context_set_repo_dir(context, repos_dir);
    dnf_context_set_solv_dir(context, "/tmp");
    auto ret = dnf_context_setup(context, nullptr, &error);
    g_assert_no_error(error);
    g_assert(ret);

    /* load local metadata repo */
    DnfRepo *repo = dnf_repo_loader_get_repo_by_id(dnf_context_get_repo_loader(context), "test", &error);
    g_assert_no_error(error);
    g_assert(repo != nullptr);
    g_assert_cmpint(dnf_repo_get_enabled(repo), ==, DNF_REPO_ENABLED_METADATA | DNF_REPO_ENABLED_PACKAGES);
    g_assert_cmpint(dnf_repo_get_kind(repo), ==, DNF_REPO_KIND_LOCAL);

    DnfState *state = dnf_state_new();
    dnf_repo_check(repo, G_MAXUINT, state, &error);
    g_object_unref(state);

    state = dnf_context_get_state(context);
    dnf_context_setup_sack(context, state, &error);
    g_assert_no_error(error);

    auto sack = dnf_context_get_sack(context);
    auto moduleExcludes = std::unique_ptr<libdnf::PackageSet>(dnf_sack_get_module_excludes(sack));
    CPPUNIT_ASSERT(moduleExcludes->size() != 0);

    libdnf::ModulePackageContainer * c = dnf_sack_get_module_container(sack);
    std::vector<libdnf::ModulePackage *> packages = c->getModulePackages();
    for(auto const& package: packages) {
        if (package->getName() == "httpd"){
            // disabled stream
            if (package->getStream() == "2.2")
                sackHasNot(sack, package);
            // default module:stream
            if (package->getStream() == "2.4")
                sackHas(sack, package);
        }
    }

    {
        libdnf::Query query{sack};
        // no match with modular RPM $name -> keep
        std::string nevra = "grub2-2.02-0.40.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) >= 1);
        auto package = dnf_package_new(sack, packageSet->operator[](0));
        CPPUNIT_ASSERT(dnf_package_get_nevra(package) == nevra);
        g_object_unref(package);
        query.clear();
    }

    {
        libdnf::Query query{sack};
        // $name matches with modular RPM $name -> exclude
        std::string nevra = "httpd-2.2.10-1.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);
        query.clear();
    }

    {
        libdnf::Query query{sack};
        // Provides: $name matches with modular RPM $name -> exclude
        std::string nevra = "httpd-provides-name-3.0-1.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);
        query.clear();
    }

    {
        libdnf::Query query{sack};
        // Provides: $name = ... matches with modular RPM $name -> exclude
        std::string nevra = "httpd-provides-name-version-release-3.0-1.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);
        query.clear();
    }
}

void ContextTest::sackHas(DnfSack * sack, libdnf::ModulePackage * pkg) const
{
    libdnf::Query query{sack};
    auto artifacts = pkg->getArtifacts();
    for(auto & artifact: artifacts) {
        artifact = artifact.replace(artifact.find("-0:"), 3, "-");
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, artifact.c_str());

        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) >= 1);
        auto package = dnf_package_new(sack, packageSet->operator[](0));
        CPPUNIT_ASSERT(dnf_package_get_nevra(package) == artifact);
        g_object_unref(package);

        query.clear();

    }
}

void ContextTest::sackHasNot(DnfSack * sack, libdnf::ModulePackage * pkg) const
{
    libdnf::Query query{sack};
    auto artifacts = pkg->getArtifacts();
    for(auto & artifact: artifacts) {
        artifact = artifact.replace(artifact.find("-0:"), 3, "-");
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, artifact.c_str());

        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);

        query.clear();
    }
}
<commit_msg>Setup platform to remove libdnf::critical messages with unit tests<commit_after>#include "ContextTest.hpp"

CPPUNIT_TEST_SUITE_REGISTRATION(ContextTest);

#include "libdnf/dnf-context.hpp"
#include "libdnf/dnf-repo-loader.h"
#include "libdnf/sack/query.hpp"
#include "libdnf/nevra.hpp"
#include "libdnf/utils/File.hpp"
#include "libdnf/sack/packageset.hpp"
#include "libdnf/dnf-sack-private.hpp"

#include <memory>

void ContextTest::setUp()
{
    dnf_context_set_config_file_path("");
    context = dnf_context_new();
}

void ContextTest::tearDown()
{
    g_object_unref(context);
}

void ContextTest::testLoadModules()
{
    GError *error = nullptr;

    /* set up local context */
    // set releasever to avoid crashing on missing /etc/os-release in the test data
    dnf_context_set_release_ver(context, "26");
    dnf_context_set_arch(context, "x86_64");
    constexpr auto install_root = TESTDATADIR "/modules/";
    dnf_context_set_install_root(context, install_root);
    g_autoptr(DnfLock) lock = dnf_lock_new();
    dnf_lock_set_lock_dir(lock, "/tmp");
    constexpr auto repos_dir = TESTDATADIR "/modules/yum.repos.d/";
    dnf_context_set_repo_dir(context, repos_dir);
    dnf_context_set_solv_dir(context, "/tmp");
    auto ret = dnf_context_setup(context, nullptr, &error);
    g_assert_no_error(error);
    g_assert(ret);

    /* load local metadata repo */
    DnfRepo *repo = dnf_repo_loader_get_repo_by_id(dnf_context_get_repo_loader(context), "test", &error);
    g_assert_no_error(error);
    g_assert(repo != nullptr);
    g_assert_cmpint(dnf_repo_get_enabled(repo), ==, DNF_REPO_ENABLED_METADATA | DNF_REPO_ENABLED_PACKAGES);
    g_assert_cmpint(dnf_repo_get_kind(repo), ==, DNF_REPO_KIND_LOCAL);

    DnfState *state = dnf_state_new();
    dnf_repo_check(repo, G_MAXUINT, state, &error);
    g_object_unref(state);

    // Setup platform to prevent logger critical message
    dnf_context_set_platform_module(context, "platform:26");

    state = dnf_context_get_state(context);
    dnf_context_setup_sack(context, state, &error);
    g_assert_no_error(error);

    auto sack = dnf_context_get_sack(context);
    auto moduleExcludes = std::unique_ptr<libdnf::PackageSet>(dnf_sack_get_module_excludes(sack));
    CPPUNIT_ASSERT(moduleExcludes->size() != 0);

    libdnf::ModulePackageContainer * c = dnf_sack_get_module_container(sack);
    std::vector<libdnf::ModulePackage *> packages = c->getModulePackages();
    for(auto const& package: packages) {
        if (package->getName() == "httpd"){
            // disabled stream
            if (package->getStream() == "2.2")
                sackHasNot(sack, package);
            // default module:stream
            if (package->getStream() == "2.4")
                sackHas(sack, package);
        }
    }

    {
        libdnf::Query query{sack};
        // no match with modular RPM $name -> keep
        std::string nevra = "grub2-2.02-0.40.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) >= 1);
        auto package = dnf_package_new(sack, packageSet->operator[](0));
        CPPUNIT_ASSERT(dnf_package_get_nevra(package) == nevra);
        g_object_unref(package);
        query.clear();
    }

    {
        libdnf::Query query{sack};
        // $name matches with modular RPM $name -> exclude
        std::string nevra = "httpd-2.2.10-1.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);
        query.clear();
    }

    {
        libdnf::Query query{sack};
        // Provides: $name matches with modular RPM $name -> exclude
        std::string nevra = "httpd-provides-name-3.0-1.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);
        query.clear();
    }

    {
        libdnf::Query query{sack};
        // Provides: $name = ... matches with modular RPM $name -> exclude
        std::string nevra = "httpd-provides-name-version-release-3.0-1.x86_64";
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, nevra.c_str());
        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);
        query.clear();
    }
}

void ContextTest::sackHas(DnfSack * sack, libdnf::ModulePackage * pkg) const
{
    libdnf::Query query{sack};
    auto artifacts = pkg->getArtifacts();
    for(auto & artifact: artifacts) {
        artifact = artifact.replace(artifact.find("-0:"), 3, "-");
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, artifact.c_str());

        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) >= 1);
        auto package = dnf_package_new(sack, packageSet->operator[](0));
        CPPUNIT_ASSERT(dnf_package_get_nevra(package) == artifact);
        g_object_unref(package);

        query.clear();

    }
}

void ContextTest::sackHasNot(DnfSack * sack, libdnf::ModulePackage * pkg) const
{
    libdnf::Query query{sack};
    auto artifacts = pkg->getArtifacts();
    for(auto & artifact: artifacts) {
        artifact = artifact.replace(artifact.find("-0:"), 3, "-");
        query.addFilter(HY_PKG_NEVRA_STRICT, HY_EQ, artifact.c_str());

        auto packageSet = const_cast<libdnf::PackageSet *>(query.runSet());
        CPPUNIT_ASSERT(dnf_packageset_count(packageSet) == 0);

        query.clear();
    }
}
<|endoftext|>


<commit_before>#include <smartref/smartref.h>

REFLECTABLE(foo);

namespace tests {

using smartref::using_;

//! These tests check for existence of the foo member-function.
namespace test_existence {

template<typename T>
constexpr auto has_foo(int) -> decltype(std::declval<T>().foo(), bool{}) {return true;}
template<typename T>
constexpr auto has_foo(...) {return false;}

struct Empty {};

struct NonConst
{
  void foo() {}
};

struct Const
{
  void foo() const {}
};

struct Mixed
{
  void foo() {}
  void foo() const {}
};

////////////////////////////////
// non-const member functions //
////////////////////////////////

static_assert(!has_foo<Empty>(0),
              "TEST FAILED: Empty seems to have a foo() member-function!");

static_assert(!has_foo<using_<Empty>>(0),
              "TEST FAILED: using_<Empty> seems to have a foo() member-function!");

static_assert(has_foo<NonConst>(0),
              "TEST FAILED: NonConst doesn't seem to have a foo() member-function!");

static_assert(has_foo<using_<NonConst>>(0),
              "TEST FAILED: using_<NonConst> doesn't seem to have a foo() member-function!");

static_assert(has_foo<Mixed>(0),
              "TEST FAILED: Mixed doesn't seem to have a foo() member-function!");

static_assert(has_foo<using_<Mixed>>(0),
              "TEST FAILED: using_<Mixed> doesn't seem to have a foo() member-function!");

////////////////////////////
// const member functions //
////////////////////////////

static_assert(!has_foo<const Empty>(0),
              "TEST FAILED: const Empty seems to have a foo() member-function!");

static_assert(!has_foo<const using_<Empty>>(0),
              "TEST FAILED: const using_<Empty> seems to have a foo() member-function!");

static_assert(!has_foo<const NonConst>(0),
              "TEST FAILED: const NonConst seems to have a foo() const member-function!");

static_assert(!has_foo<const using_<NonConst>>(0),
              "TEST FAILED: const using_<NonConst> seem to have a foo() const member-function!");

} // namespace test_existence
} // namespace tests
<commit_msg>Added two more test cases for the non-const member functions.<commit_after>#include <smartref/smartref.h>

REFLECTABLE(foo);

namespace tests {

using smartref::using_;

//! These tests check for existence of the foo member-function.
namespace test_existence {

template<typename T>
constexpr auto has_foo(int) -> decltype(std::declval<T>().foo(), bool{}) {return true;}
template<typename T>
constexpr auto has_foo(...) {return false;}

struct Empty {};

struct NonConst
{
  void foo() {}
};

struct Const
{
  void foo() const {}
};

struct Mixed
{
  void foo() {}
  void foo() const {}
};

////////////////////////////////
// non-const member functions //
////////////////////////////////

static_assert(!has_foo<Empty>(0),
              "TEST FAILED: Empty seems to have a foo() member-function!");

static_assert(!has_foo<using_<Empty>>(0),
              "TEST FAILED: using_<Empty> seems to have a foo() member-function!");

static_assert(has_foo<NonConst>(0),
              "TEST FAILED: NonConst doesn't seem to have a foo() member-function!");

static_assert(has_foo<using_<NonConst>>(0),
              "TEST FAILED: using_<NonConst> doesn't seem to have a foo() member-function!");

static_assert(has_foo<Const>(0),
              "TEST FAILED: Const doesn't seem to have a foo() member-function!");

// TODO: This should currently fail
static_assert(has_foo<using_<Const>>(0),
              "TEST FAILED: using_<Const> doesn't seem to have a foo() member-function!");

static_assert(has_foo<Mixed>(0),
              "TEST FAILED: Mixed doesn't seem to have a foo() member-function!");

static_assert(has_foo<using_<Mixed>>(0),
              "TEST FAILED: using_<Mixed> doesn't seem to have a foo() member-function!");

////////////////////////////
// const member functions //
////////////////////////////

static_assert(!has_foo<const Empty>(0),
              "TEST FAILED: const Empty seems to have a foo() member-function!");

static_assert(!has_foo<const using_<Empty>>(0),
              "TEST FAILED: const using_<Empty> seems to have a foo() member-function!");

static_assert(!has_foo<const NonConst>(0),
              "TEST FAILED: const NonConst seems to have a foo() const member-function!");

static_assert(!has_foo<const using_<NonConst>>(0),
              "TEST FAILED: const using_<NonConst> seem to have a foo() const member-function!");

} // namespace test_existence
} // namespace tests
<|endoftext|>


<commit_before>#ifndef MJOLNIR_READ_SPATIAL_PARTITION
#define MJOLNIR_READ_SPATIAL_PARTITION
#include <mjolnir/core/UnlimitedGridCellList.hpp>
#include <mjolnir/core/PeriodicGridCellList.hpp>
#include <mjolnir/core/NaivePairCalculation.hpp>
#include <mjolnir/core/VerletList.hpp>
#include <mjolnir/core/ImplicitMembraneList.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/input/get_toml_value.hpp>

namespace mjolnir
{

template<typename boundaryT, typename traitsT>
struct celllist_dispatcher;

template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<UnlimitedBoundary<realT, coordT>, traitsT>
{
    typedef UnlimitedGridCellList<traitsT> type;
    typedef realT real_type;
    static UnlimitedGridCellList<traitsT>
    invoke(const real_type cutoff, const real_type mergin)
    {
        return UnlimitedGridCellList<traitsT>{cutoff, mergin};
    }
};

template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<CubicPeriodicBoundary<realT, coordT>, traitsT>
{
    typedef PeriodicGridCellList<traitsT> type;
    typedef realT real_type;
    static PeriodicGridCellList<traitsT>
    invoke(const real_type cutoff, const real_type mergin)
    {
        return PeriodicGridCellList<traitsT>{cutoff, mergin};
    }
};

template<typename partitionT>
partitionT
read_exception_information(const toml::Table& global, partitionT&& sp)
{
    const auto& params = toml_value_at(global, "parameters", "[forcefield.global]"
            ).cast<toml::value_t::Array>();
    for(const auto& tab : params)
    {
        const auto& info = tab.cast<toml::value_t::Table>();
        const auto  idx = toml::get<std::size_t>(toml_value_at(
                    info, "index", "<anonymous> in parameters"));
        sp.chain_index(idx) = toml::get<std::size_t>(toml_value_at(
                    info, "chain", "<anonymous> in parameters"));

        for(auto exc : toml::get<std::vector<std::size_t>>(
                    toml_value_at(info, "except_chains",
                        "<anonymous> in parameters")))
        {
            sp.except_chains(idx).push_back(exc);
        }
        for(auto exb : toml::get<std::vector<std::size_t>>(
                    toml_value_at(info, "except_beads",
                        "<anonymous> in parameters")))
        {
            sp.except_indices(idx).push_back(exb);
        }
    }
    return sp;
}

template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_spatial_partition_for_distance(const toml::Table& global, potentialT&& pot)
{
    typedef typename traitsT::real_type real_type;

    const auto& sp = toml_value_at(
            global, "spatial_partition", "[forcefield.global]"
            ).cast<toml::value_t::Table>();
    const auto  type = toml::get<std::string>(
            toml_value_at(sp, "type", "[forcefield.global]"));
    if(type == "CellList")
    {
        typedef typename traitsT::boundary_type boundary_type;
        typedef typename celllist_dispatcher<boundary_type, traitsT>::type
                celllist_type;

        const auto co = pot.max_cutoff_length();
        const auto mg = toml::get<real_type>(toml_value_at(
                    sp, "mergin", "[forcefield.global]"));
        return make_unique<GlobalDistanceInteraction<
            traitsT, potentialT, celllist_type>>(std::move(pot),
                read_exception_information(global,
                    celllist_dispatcher<boundary_type, traitsT>::invoke(co, mg)));
    }
    else if(type == "VerletList")
    {
        const auto cutoff = pot.max_cutoff_length();
        const auto mergin = toml::get<real_type>(toml_value_at(
                    sp, "mergin", "[forcefield.global]"));
        return make_unique<GlobalDistanceInteraction<
            traitsT, potentialT, VerletList<traitsT>>>(std::move(pot),
                read_exception_information(
                    global, VerletList<traitsT>{cutoff, mergin}));
    }
    else if(type == "Naive")
    {
        return make_unique<GlobalDistanceInteraction<
            traitsT, potentialT, NaivePairCalculation<traitsT>>
            >(std::move(pot), read_exception_information(
                    global, NaivePairCalculation<traitsT>{}));
    }
    else
    {
        throw std::runtime_error("invalid spatial partition type: " + type);
    }
}

template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_spatial_partition_for_implicit_membrane(const toml::Table& global, potentialT&& pot)
{
    const auto cutoff = pot.max_cutoff_length();
    return make_unique<ZaxisExternalForceInteraction<
      traitsT, potentialT, ImplicitMembraneList<traitsT>>
		       >(std::move(pot), ImplicitMembraneList<traitsT>{cutoff});
}
}
#endif// MJOLNIR_READ_SPATIAL_PARTITION
<commit_msg>just pass by value<commit_after>#ifndef MJOLNIR_READ_SPATIAL_PARTITION
#define MJOLNIR_READ_SPATIAL_PARTITION
#include <mjolnir/core/UnlimitedGridCellList.hpp>
#include <mjolnir/core/PeriodicGridCellList.hpp>
#include <mjolnir/core/NaivePairCalculation.hpp>
#include <mjolnir/core/VerletList.hpp>
#include <mjolnir/core/ImplicitMembraneList.hpp>
#include <mjolnir/util/make_unique.hpp>
#include <mjolnir/input/get_toml_value.hpp>

namespace mjolnir
{

template<typename boundaryT, typename traitsT>
struct celllist_dispatcher;

template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<UnlimitedBoundary<realT, coordT>, traitsT>
{
    typedef UnlimitedGridCellList<traitsT> type;
    typedef realT real_type;
    static UnlimitedGridCellList<traitsT>
    invoke(const real_type cutoff, const real_type mergin)
    {
        return UnlimitedGridCellList<traitsT>{cutoff, mergin};
    }
};

template<typename realT, typename coordT, typename traitsT>
struct celllist_dispatcher<CubicPeriodicBoundary<realT, coordT>, traitsT>
{
    typedef PeriodicGridCellList<traitsT> type;
    typedef realT real_type;
    static PeriodicGridCellList<traitsT>
    invoke(const real_type cutoff, const real_type mergin)
    {
        return PeriodicGridCellList<traitsT>{cutoff, mergin};
    }
};

template<typename partitionT>
partitionT
read_exception_information(const toml::Table& global, partitionT sp)
{
    const auto& params = toml_value_at(global, "parameters", "[forcefield.global]"
            ).cast<toml::value_t::Array>();
    for(const auto& tab : params)
    {
        const auto& info = tab.cast<toml::value_t::Table>();
        const auto  idx = toml::get<std::size_t>(toml_value_at(
                    info, "index", "<anonymous> in parameters"));
        sp.chain_index(idx) = toml::get<std::size_t>(toml_value_at(
                    info, "chain", "<anonymous> in parameters"));

        for(auto exc : toml::get<std::vector<std::size_t>>(
                    toml_value_at(info, "except_chains",
                        "<anonymous> in parameters")))
        {
            sp.except_chains(idx).push_back(exc);
        }
        for(auto exb : toml::get<std::vector<std::size_t>>(
                    toml_value_at(info, "except_beads",
                        "<anonymous> in parameters")))
        {
            sp.except_indices(idx).push_back(exb);
        }
    }
    return sp;
}

template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_spatial_partition_for_distance(const toml::Table& global, potentialT pot)
{
    typedef typename traitsT::real_type real_type;

    const auto& sp = toml_value_at(
            global, "spatial_partition", "[forcefield.global]"
            ).cast<toml::value_t::Table>();
    const auto  type = toml::get<std::string>(
            toml_value_at(sp, "type", "[forcefield.global]"));
    if(type == "CellList")
    {
        typedef typename traitsT::boundary_type boundary_type;
        typedef typename celllist_dispatcher<boundary_type, traitsT>::type
                celllist_type;

        const auto co = pot.max_cutoff_length();
        const auto mg = toml::get<real_type>(toml_value_at(
                    sp, "mergin", "[forcefield.global]"));
        return make_unique<GlobalDistanceInteraction<
            traitsT, potentialT, celllist_type>>(std::move(pot),
                read_exception_information(global,
                    celllist_dispatcher<boundary_type, traitsT>::invoke(co, mg)));
    }
    else if(type == "VerletList")
    {
        const auto cutoff = pot.max_cutoff_length();
        const auto mergin = toml::get<real_type>(toml_value_at(
                    sp, "mergin", "[forcefield.global]"));
        return make_unique<GlobalDistanceInteraction<
            traitsT, potentialT, VerletList<traitsT>>>(std::move(pot),
                read_exception_information(
                    global, VerletList<traitsT>{cutoff, mergin}));
    }
    else if(type == "Naive")
    {
        return make_unique<GlobalDistanceInteraction<
            traitsT, potentialT, NaivePairCalculation<traitsT>>
            >(std::move(pot), read_exception_information(
                    global, NaivePairCalculation<traitsT>{}));
    }
    else
    {
        throw std::runtime_error("invalid spatial partition type: " + type);
    }
}

template<typename traitsT, typename potentialT>
std::unique_ptr<GlobalInteractionBase<traitsT>>
read_spatial_partition_for_implicit_membrane(const toml::Table& global, potentialT pot)
{
    const auto cutoff = pot.max_cutoff_length();
    return make_unique<ZaxisExternalForceInteraction<
      traitsT, potentialT, ImplicitMembraneList<traitsT>>
		       >(std::move(pot), ImplicitMembraneList<traitsT>{cutoff});
}
}
#endif// MJOLNIR_READ_SPATIAL_PARTITION
<|endoftext|>