Example #1
0
void
ViewerNode::resetWipe()
{
    ScopedChanges_RAII changes(this);
    _imp->wipeCenter.lock()->resetToDefaultValue(DimSpec::all(), ViewSetSpec::all());
    _imp->wipeAngle.lock()->resetToDefaultValue(DimSpec::all(), ViewSetSpec::all());
    _imp->wipeAmount.lock()->resetToDefaultValue(DimSpec::all(), ViewSetSpec::all());
}
Example #2
0
void
ViewerNode::setRefreshButtonDown(bool down)
{
    KnobButtonPtr knob = _imp->refreshButtonKnob.lock();
    // Ignore evaluation

    ScopedChanges_RAII changes(this, true);
    knob->setValue(down, ViewIdx(0), DimIdx(0), eValueChangedReasonTimeChanged);

}
Example #3
0
ConstantEditor::ConstantEditor(bool forceScalar, bool forceVector):QWidget()
{
    hChanges=false;
    isScalar=false;
    QGridLayout * layout = new QGridLayout();
    scalar_rb = new QRadioButton("Scalar", this);
    vector_rb = new QRadioButton("Vector", this);
    scalar_rb->setDown(true);
    QObject::connect(scalar_rb,SIGNAL(toggled(bool)),this,SLOT(radioButtonSelected(bool)));
    QObject::connect(scalar_rb,SIGNAL(toggled(bool)),this,SLOT(changes()));
    layout->addWidget(scalar_rb,0,0,1,2);
    layout->addWidget(vector_rb,2,0,1,2);
    QDoubleValidator * v=new QDoubleValidator(this);
    s_edit=new QLineEdit(this);
    QObject::connect(s_edit,SIGNAL(textEdited(QString)),this,SLOT(changes()));
    QObject::connect(s_edit,SIGNAL(returnPressed()),this,SIGNAL(saveChanges()));
    s_edit->setValidator(v);
    layout->addWidget(s_edit,1,1,1,3);
    v1_edit=new QLineEdit(this);
    QObject::connect(v1_edit,SIGNAL(textEdited(QString)),this,SLOT(changes()));
    QObject::connect(v1_edit,SIGNAL(returnPressed()),this,SIGNAL(saveChanges()));
    v1_edit->setValidator(v);
    layout->addWidget(v1_edit,3,1,1,1);
    v2_edit=new QLineEdit(this);
    QObject::connect(v2_edit,SIGNAL(textEdited(QString)),this,SLOT(changes()));
    QObject::connect(v2_edit,SIGNAL(returnPressed()),this,SIGNAL(saveChanges()));
    v2_edit->setValidator(v);
    layout->addWidget(v2_edit,3,2,1,1);
    v3_edit=new QLineEdit(this);
    QObject::connect(v3_edit,SIGNAL(textEdited(QString)),this,SLOT(changes()));
    QObject::connect(v3_edit,SIGNAL(returnPressed()),this,SIGNAL(saveChanges()));
    v3_edit->setValidator(v);
    layout->addWidget(v3_edit,3,3,1,1);
    s_edit->setText("0.0");
    v1_edit->setText("0.0");
    v2_edit->setText("0.0");
    v3_edit->setText("0.0");
    vector_rb->setEnabled(!forceScalar);
    scalar_rb->setEnabled(!forceVector);
    this->setLayout(layout);
    hChanges=false;
}
 std::vector<unsigned int> ArbitrarySeg::getSegments(const std::vector<float>& rateOfChange, const Parameters& params){
   // Divide by arbitrary number of segments
   unsigned int segments = params.getArbitrarySegments();
   std::vector<unsigned int> changes(1); // start vector with a 0 to enable first classification
   if(rateOfChange.size() <= segments){
     return changes;
   }
   float interval = rateOfChange.size() / segments;
   for (unsigned int i = 1; i < segments; i++){
     changes.push_back((unsigned int)(interval * i + 0.5));
   }
   return changes;
 }
Example #5
0
 std::vector<unsigned int> CosineHcdf::getSegments(const std::vector<float>& rateOfChange, const Parameters& params){
   // Pick peaks
   std::vector<unsigned int> changes(1); // start vector with a 0 to enable first classification
   unsigned int neighbours = params.getHcdfPeakPickingNeighbours();
   for (unsigned int hop = 0; hop < rateOfChange.size(); hop++){
     bool peak = true;
     for (int i = -neighbours; i <= (signed)neighbours; i++)
       if(i != 0 && hop+i < rateOfChange.size()) // only test valid neighbours
         if(rateOfChange[hop+i] >= rateOfChange[hop])
           peak = false; // there's a neighbour of higher or equal value; this isn't a peak
     if(peak)
       changes.push_back(hop);
   }
   return changes;
 }
Example #6
0
double kmeans::update_centers(const cluster_sequence & clusters, dataset & centers) {
    const dataset & data = *m_ptr_data;
    const size_t dimension = data[0].size();

    dataset calculated_clusters(clusters.size(), point(dimension, 0.0));
    std::vector<double> changes(clusters.size(), 0.0);

    parallel_for(std::size_t(0), clusters.size(), [this, &clusters, &centers, &calculated_clusters, &changes](const std::size_t p_index) {
        calculated_clusters[p_index] = centers[p_index];
        changes[p_index] = update_center(clusters[p_index], calculated_clusters[p_index]);
    });

    centers = std::move(calculated_clusters);

    return *(std::max_element(changes.begin(), changes.end()));
}
Example #7
0
void find_best_pair(message &M1, message &M2, const difference &D, const DifferentialPath &P){
	ofstream changes("good_changes.txt");
	vector<vector<int>> neutral_vectors;
	vector<vector<int>> tmp_neutral_vectors;
	vector<vector<int>> final_set;
	construct_neutral_set(M1, M2, D, P);
	read(neutral_vectors);

	set<int> clique;
	int max_clique_size = 15;
	vector<vector<int>> best_bits;

	for (auto i = neutral_vectors.begin(); i != neutral_vectors.end(); i++){
		cout << endl << (*i)[0] << " " << (*i)[1] << " " << (*i)[2] << " " << (*i)[3] << " " << (*i)[4] << endl;
		message tmp1(M1);
		message tmp2(M2);
		xor(tmp1.W, *i);
		xor(tmp2.W, *i);
		D.modify(tmp1, tmp2);
		construct_neutral_set(tmp1, tmp2, D, P);
		read(tmp_neutral_vectors);
		cout << endl << tmp_neutral_vectors.size() << endl;

		adj_matrix adj(tmp_neutral_vectors.size());
		adj.fill(tmp_neutral_vectors, tmp1, tmp2, D, P);
		kerbosh(adj.adj, adj.adj[1].size(), clique, tmp_neutral_vectors);
		cout << endl << "clique size " << clique.size() << endl;

		if (clique.size() >= max_clique_size){
			changes << "clique size " << clique.size() << endl;
			changes << (*i)[0] << " " << (*i)[1] << " " << (*i)[2] << " " << (*i)[3] << " " << (*i)[4] << endl << endl;
			max_clique_size = clique.size();

			show_clique(clique, tmp_neutral_vectors, final_set);
		}

		tmp_neutral_vectors.clear();
		clique.clear();
	}

	getchar();

	return;
}
Example #8
0
/*typedef enum {RED, BLACK} NodeColor;

struct RBTreeNode {
	int data;
	NodeColor color;
	RBTreeNode *parent;
	RBTreeNode *left, *right;
};

RBTreeNode *insert(RBTreeNode *root, RBTreeNode *data)
{
	RBTreeNode *y = nullptr;
	RBTreeNode *x = root;
	while(x) {
		y = x;
		if (data->data < x->data) {
			x = x->left;
		} else {
			x = x->right;
		}
	}
	data->parent = y;
	if (!y) {
		return data;
	} else if(data->data < y->data) {
		y->left = data;
	} else {
		y->right = data;
	}
	return root;
}

RBTreeNode *leftRotate(RBTreeNode *root, RBTreeNode *x)
{
	RBTreeNode *y = x->right;
	x->right = y->left;
	if (y->left) {
		y->left->parent = x;
	}
	y->parent = x->parent;
	if (!x->parent) {
		root = y;
	} else if(x == x->parent->left) {
		x->parent->left = y;
	} else {
		x->parent->right = y;
	}
	y->left = x;
	x->parent = y;
	return root;
}

RBTreeNode *rightRotate(RBTreeNode *root, RBTreeNode *x)
{
	RBTreeNode *y = x->left;
	x->left = y->right;
	if(y->right) {
		y->right->parent = x;
	}
	y->parent = x->parent;
	if(!y->parent) {
		root = y;
	} else if(x == x->parent->right) {
		x->parent->right = y;
	} else {
		x->parent->left = y;
	}
	y->right = x;
	x->parent = y;
	return root;
}

RBTreeNode *rbInsert(RBTreeNode *root, RBTreeNode *x)
{
	root = insert(root, x);
	x->color = RED;
	while (x != root && x->parent->color == RED) {
		if(x->parent == x->parent->parent->left) {
			RBTreeNode *y = x->parent->parent->right;
			if (y->color == RED) {
				x->parent->color = BLACK;
				y->color = BLACK;
				x->parent->parent->color = RED;
				x = x->parent->parent;
			} else if(x == x->parent->right) {
				x = x->parent;
				root = leftRotate(root, x);
				x->parent->color = BLACK;
				x->parent->parent->color = RED;
				root = rightRotate(root, x->parent->parent);
			}
		}
	}
	root->color = BLACK;
	return root;
}

std::string toRPN(const std::string &expr) {
    std::stack<char> expStack;
    std::string rpnStr;
    int nesting = 0;
    char prevChar;
    for(size_t i = 0; i < expr.size(); ++i) {
        char c = expr[i];
        switch (c) {
            case ')':
                expStack.pop();
				if(!expStack.empty()) {
					prevChar = expStack.top();
					if (prevChar == '+' || prevChar == '-' || prevChar == '*' || prevChar == '/' || prevChar == '^') {
						rpnStr += prevChar;
						expStack.pop();
					}
				}
                break;
            case '(':
            case '+':
            case '-':
            case '*':
            case '/':
            case '^':
                expStack.push(c);
                break;
            default:
                rpnStr += c; 
				if (!expStack.empty()) {
					prevChar = expStack.top();
					if (prevChar == '+' || prevChar == '-' || prevChar == '*' || prevChar == '/' || prevChar == '^') {
						rpnStr += prevChar;
						expStack.pop();
					}
				}
				break;
        }
    }
	return rpnStr;
}

void nextPALIN(std::string &num) {
	if(num.size() < 2UL) {
		return;
	}
	size_t size = num.size();
	size_t midPoint = (size)/2;
	bool modified = false;
	if(size%2 == 1 && num[midPoint] != '9') {
		num[midPoint] = num[midPoint] + 1;
		modified = true;
	}
	for(size_t i = midPoint-1; i >= 0; --i) {
		if(modified) {
			num[size-i-1] = num[i];
		} else {
			if(num[i] != '9') {
				num[i] = num[i] + 1;
				modified = true;
			}
			num[size-i-1] = num[i];
		}
		if(i == 0UL) {
			break;
		}
	}
}

std::string cellHeading(int N) {
	std::stack<char> heading;
	while(N > 0) {
		int rem = N%26;
		if(rem != 0) {
			N = N/26;
			heading.push('A' + rem - 1);
		} else {
			N = (N-26)/26;
			heading.push('Z');
		}
	}
	std::string ch;
	while(!heading.empty()) {
		ch += heading.top();
		heading.pop();
	}
	return ch;
}

void shiftArray(int ip[], size_t len) {
	if(len == 0UL) {
		return;
	}
	size_t leftIndex = 0UL, rightIndex = len -1UL;
	while(leftIndex < rightIndex) {
		//find zero item from right
		while(ip[leftIndex] != 0 && leftIndex < rightIndex) {
			++leftIndex;
		}
		//find non-zero item from left
		while(ip[rightIndex] == 0 && rightIndex > leftIndex) {
			--rightIndex;
		}
		//swap if indices are valid
		if(leftIndex < rightIndex) {
			ip[leftIndex] = ip[rightIndex];
			ip[rightIndex] = 0;
			leftIndex++;
			rightIndex--;
		}
	}
}

void minLengthUnsortedArray(int ip[], size_t len, size_t &left, size_t &right) {
	//if there is no or one element in the array
	if(len <= 1UL) {
		return;
	}
	size_t leftEdge = 0UL, rightEdge = len-1;
	for(size_t i = 1UL; i < len; ++i) {
		if(ip[leftEdge] <= ip[i]) {
			leftEdge = i;
		} else {
			break;
		}
	}
	//if the array is sorted already
	if(leftEdge == len-1) {
		left = leftEdge;
		right = leftEdge;
		return;
	}
	for(size_t i = 1UL; i < len; ++i) {
		if(ip[rightEdge] >= ip[len-1-i]) {
			rightEdge = len-1-i;
		} else {
			break;
		}
	}
	if(leftEdge < rightEdge) {
		int leftMax = ip[leftEdge-1], rightMin = ip[rightEdge+1];
		int midMin = ip[leftEdge], midMax = ip[leftEdge];
		for(size_t i = leftEdge+1; i <= rightEdge; ++i) {
			if(ip[i] < midMin) {
				midMin = ip[i];
			}
			if(ip[i] > midMax) {
				midMax = ip[i];
			}
		}
		for(size_t i = leftEdge-1; i > 0UL; --i) {
			if(ip[i] <= midMin) {
				left = i+1;
				break;
			}
		}
		for(size_t i = rightEdge+1; i < len; ++i) {
			if(ip[i] >= midMax) {
				right = i-1;
				break;
			}
		}
	}
}

int findSum(int a[], int len) {
	int sum = 0;
	for(int i = 0; i < len; ++i) {
		for(int j = 0; j < len - i; ++j) {
			int partialSum = 0;
			for(int k = j; k <= j+i; ++k) {
				partialSum += a[k];
			}
			sum += partialSum;
		}
	}
	return sum;
}


double getExpectation(int a, int b) {
	std::vector<double> numerator(a);
	double denom = 0.0;
	for(int i = 0; i < a; ++i) {
		numerator[i] = i*1.0/b;
		denom += numerator[i];
	}
	double expectedValue = 0.0;
	for(int i = 0; i < a; ++i) {
		expectedValue += (i+1)*numerator[i]/denom;
	}
	return expectedValue;
}

std::vector<int> makeExpression(int y) {
	for(int i = -1000; i <= 1000; ++i) {
		if(i == 0 || i == 1) continue;
		for(int j = -1000; j <= 1000; ++j) {
			if(j == 0 || j == 1) continue;
			for(int k = -1000; k <= 1000; ++k) {
				if(k == 0 || k == 1) continue;
				if((i*j+k) == y) {
					std::vector<int> result;
					result.push_back(i);
					result.push_back(j);
					result.push_back(k);
					return result;
				}
			}
		}
	}
	return std::vector<int>();
}

int stringlen(const char *str) {
    int len = 0;
    while(*str++)
        ++len;
    return len;
}

void reverse(char *str) {
    int len = stringlen(str);
    int halfLen = len >> 1;
	char *end = str+len-1;
    for(int i = 0; i < halfLen; ++i) {
        char c = *str;
        *str++ = *end;
        *end-- = c;
    }
}

void zeroOutRowsAndColumns(int m[5][4], int rows, int cols) {
	std::vector<bool> rowsWithZero(rows), colsWithZero(cols);
	for(int i = 0; i < rows; ++i) {
		for(int j = 0; j < cols; ++j) {
			if(m[i][j] == 0) {
				rowsWithZero[i] = true;
				colsWithZero[j] = true;
			}
		}
	}

	for(size_t r = 0UL; r < rows; ++r) {
		if(rowsWithZero[r]) {
			for(int i = 0; i < cols; ++i) {
				m[r][i] = 0;
			}
		}
	}
	for(size_t c = 0UL; c < cols; ++c) {
		if(colsWithZero[c]) {
			for(int i = 0; i < rows; ++i) {
				m[i][c] = 0;
			}
		}
	}
}

class KeyNotFound : public std::exception {
public:
	const char *what() {
		return "Key not found";
	}
};

class HashTable {
	struct HashNode;
	size_t m_size;
	std::vector<HashNode *> m_table;
	struct HashNode {
		std::string m_key;
		std::string m_value;
		HashNode *next;
	};

	HashNode *makeNode(const std::string &key, const std::string &value) {
		HashNode *node = new HashNode;
		node->m_key = key;
		node->m_value = value;
		node->next = 0;
		return node;
	}

	size_t hash(const std::string &key) const {
		return 0UL;
	}

	HashTable(const HashTable &);
	HashTable& operator=(HashTable&);
public:
	explicit HashTable(size_t size) : m_size(size), m_table(size, 0) {
	}

	void insertKey(const std::string &key, const std::string &value) {
		HashNode *node = makeNode(key, value);
		size_t index = hash(key);
		//Insert at the head
		if(m_table[index]) {
			node->next = m_table[index];
		}
		m_table[index] = node;
	}

	void deleteKey(const std::string &key) {
		size_t index = hash(key);
		if(m_table[index] == 0) {
			return;
		}
		HashNode *node = m_table[index];
		if(node->m_key == key) {
			m_table[index] = node->next;
			delete(node);
			return;
		}
		while(node->next) {
			if(node->next->m_key == key) {
				HashNode *temp = node->next;
				node->next = node->next->next;
				delete(temp);
				return;
			}
			node = node->next;
		}
	}

	const std::string &searchKey(const std::string &key) {
		size_t index = hash(key);
		HashNode *node = m_table[index];
		while(node) {
			if(node->m_key == key) {
				return node->m_value;
			}
			node = node->next;
		}
		throw KeyNotFound();
	}
};

class Tree {
	struct TreeNode {
		int value;
		TreeNode *left, *right;
	};
	TreeNode *m_root;
	bool _isBST(TreeNode *root) {
		if(root == 0) {
			return true;
		} else {
			bool bst = true;
			if(root->left) {
				bst = bst && (root->value >= root->left->value);
			}
			if(root->right) {
				bst = bst && (root->value < root->right->value);
			}
			if(bst) {
				return _isBST(root->left) && _isBST(root->right);
			}
			return bst;
		}
	}

	TreeNode *makeNode(int value) {
		TreeNode *node = new TreeNode;
		node->value = value;
		node->left = 0;
		node->right = 0;
		return node;
	}

	TreeNode *_insertNode(TreeNode *root, TreeNode *node) {
		if(!root) {
			root = node;
		} else if(root->value >= node->value) {
			root->left = _insertNode(root->left, node);
		} else {
			root->right = _insertNode(root->right, node);
		}
		return root;
	}
public:
	explicit Tree() : m_root(0) {}
	bool isBST() {
		if (!m_root) {
			return true;
		}
		if(m_root->left && m_root->right) {
			if (m_root->value >
		return _isBST(m_root);
	}
	void insertValue(int value) {
		TreeNode *node = makeNode(value);
		m_root = _insertNode(m_root, node);
	}
};

std::vector<int> COMPUTE_PREFIX_FUNCTION(const std::string &p) {
	int m = p.size();
	std::vector<int> prefixFunction(m);
	prefixFunction[0] = -1;
	int k = -1;
	for(int q = 1; q < m; ++q) {
		while(k > -1 && p[k+1] != p[q]) {
			k = prefixFunction[k];
		}
		if(p[k+1] == p[q]) {
			k = k + 1;
		}
		prefixFunction[q] = k;
	}
	return prefixFunction;
}

void KMP_MATCHER(const std::string &t, const std::string &p) {
	int n = t.size();
	int m = p.size();
	std::vector<int> prefix = COMPUTE_PREFIX_FUNCTION(p);
	int q = -1;
	for(int i = 0; i < n; ++i) {
		while(q > -1 && p[q+1] != t[i]) {
			q = prefix[q];
		}
		if(p[q+1] == t[i]) {
			q = q+1;
		}
		if(q == m-1) {
			std::cout << "Pattern occurs with shift " << i-m+1 << std::endl;
			q = prefix[q];
		}
	}
}

double myPow(double x, int n) {
	if(n == 0) {
		return 1.0;
	} else if(n == 1) {
		return x;
	} else {
		double temp = myPow(x, n/2);
		if(n%2 == 0) 
			return temp*temp;
		else 
			return temp*temp*x;
	}
}
//number is represented as vector of digits
std::vector<int> add(std::vector<int> a, std::vector<int> b) {
	std::vector<int> result;
	//assume a and b contain same number of elements, this will be relaxed
	//later
	if(a.size() != b.size()) {
		return result;
	}
	size_t idx = 0UL, n = a.size();
	int carry = 0;
	result.resize(a.size() + 1);
	for(size_t idx = 0UL; idx < n; ++idx) {
		result[idx] = (a[idx] + b[idx] + carry)%10;
		carry = (a[idx]+b[idx]+carry)/10;
	}
	result[n] = carry;
	return result;
}

struct Node {
	int sum;
	Node *left, *right;
};
Node * BST2GST(Node *root, int sum, int &tempSum) {
	if(root == 0) {
		tempSum = sum;
		return root;
	} else {
		Node *nextNode = BST2GST(root->right, sum, tempSum);
		if(nextNode) {
			root->sum = tempSum;
		} else {
			root->sum = tempSum + nextNode->sum;
		}
		return BST2GST(root->left, root->sum, tempSum);
	}
}

class Trie {
	struct TrieNode {
		bool isLeaf;
		char c;
		TrieNode *nodes[26];
		TrieNode(char _c) : isLeaf(false), c(_c) {
			for(size_t i = 0UL; i < 26UL; ++i) {
				nodes[i] = 0;
			}
		}
	};
	TrieNode *root;
public:
	Trie() : root(0) {}
};

void partition(int c, const std::vector<int>& s, std::vector<int>& p, size_t idx) {
	if(c == 0) {
		std::cout << "Pattern: ";
		for(size_t j = 0UL; j < p.size(); ++j) {
			std::cout << p[j] << " ";
		}
		std::cout << std::endl;
		return;
	}
	for(size_t i = idx; i < s.size(); ++i) {
		int dividend = c/s[i];
		if(dividend > 0) {
			for(int j = 1; j <= dividend; ++j) {
				p[i] += j;
				partition(c%s[i] + (dividend-j)*s[i], s, p, i+1);
				p[i] -= j;
			}
		}
	}
}

int division(int dividend, int divisor) {
	int quotient = 0;
	int numShifts = 0;
	int tempDivisor = divisor;
	while(dividend > tempDivisor) {
		++numShifts;
		tempDivisor <<= 1;
	}
	tempDivisor >>= 1;
	--numShifts;

	do {
		int t = dividend - tempDivisor;
		if(t >= 0) {
			quotient |= 1;
			dividend = t;
		} else {
			dividend <<= 1;
			quotient <<= 1;
			--numShifts;
		}
	} while(dividend >= divisor);
	if(numShifts > 0) {
		quotient <<= numShifts;
	}
	return quotient;
}

void merge(std::vector<int> &a, size_t startIndex, size_t midPoint, size_t endIndex) {
	std::vector<int> result(endIndex-startIndex+1);
	size_t idx = 0UL;
	size_t i = startIndex, j = midPoint+1;
	while(true) {
		if(a[i] <= a[j]) {
			result[idx++] = a[i];
			i++;
			if(i > midPoint) {
				break;
			}
		} else {
			result[idx++] = a[j];
			j++;
			if(j > endIndex) {
				break;
			}
		}
	}
	if(i > midPoint) {
		while(j <= endIndex)
			result[idx++] = a[j++];
	} else if(j > endIndex) {
		while(i <= midPoint)
			result[idx++] = a[i++];
	}
	for(i = startIndex, j = 0UL; i <= endIndex; ++i, ++j) {
		a[i] = result[j];
	}
}

void mergeSort(std::vector<int> &a, size_t startIndex, size_t endIndex) {
	if(startIndex != endIndex) {
		size_t midPoint = (startIndex+endIndex)/2;
		mergeSort(a, startIndex, midPoint);
		mergeSort(a, midPoint+1, endIndex);
		merge(a, startIndex, midPoint, endIndex);
	}
}

class HeapFull : public std::exception {
	const std::string m_exceptionMessage;
public:
	HeapFull() : m_exceptionMessage("Heap is full") {}
	const char *what() {
		return m_exceptionMessage.c_str();
	}
};

class HeapEmpty : public std::exception {
	const std::string m_exceptionMessage;
public:
	HeapEmpty() : m_exceptionMessage("Heap is empty"){}
	const char *what() {

	}
};

class Heap {
#define MAX_HEAP_SIZE 511
	int _a[MAX_HEAP_SIZE];
	int m_heapSize;
	void _swap(int &a, int &b) {
		int temp = a;
		a = b;
		b = temp;
	}

	void _heapify() {
		int index = 0;
		while(index < m_heapSize) {
			int leftChild = 2*index + 1;
			int rightChild = 2*index+2;
			if(leftChild >= m_heapSize) return;
			if(rightChild >= m_heapSize) {
				if(_a[index] > _a[leftChild]) {
					_swap(_a[leftChild], _a[index]);
				}
				return;
			} else {
				if(_a[index] > _a[leftChild] || _a[index] > _a[rightChild]) {
					if (_a[leftChild] < _a[rightChild]) {
						_swap(_a[leftChild], _a[index]);
						index = leftChild;
					} else {
						_swap(_a[rightChild], _a[index]);
						index = rightChild;
					}
				} else {
					return;
				}
			}
		}
	}

	void _bubbleUp() {
		int childIndex = m_heapSize-1;
		while(childIndex > 0) {
			int parentIndex = (childIndex-1) >> 1;
			if(_a[childIndex] < _a[parentIndex]) {
				_swap(_a[childIndex], _a[parentIndex]);
				childIndex = parentIndex;
			} else {
				return;
			}
		}
	}
public:
	Heap() : m_heapSize(0) {}
	void insert(int data) {
		if (m_heapSize >= MAX_HEAP_SIZE) {
			throw HeapFull();
		}
		_a[m_heapSize++] = data;
		_bubbleUp();
	}

	int extractMin() {
		if (isEmpty()) {
			throw HeapEmpty();
		}
		int minItem = _a[0];
		m_heapSize -= 1;
		if(m_heapSize > 0) {
			_a[0] = _a[m_heapSize];
			_heapify();
		}
		return minItem;
	}

	bool isEmpty() {
		return m_heapSize == 0;
	}
};

void swap(int &a, int &b) {
	int temp = a;
	a = b;
	b = temp;
}

int partition(std::vector<int> &a, int startIndex, int endIndex) {
	int highIndex = startIndex;
	int pivot = endIndex;
	for(int i = startIndex; i < endIndex; ++i) {
		if(a[i] < a[pivot]) {
			swap(a[i], a[highIndex]);
			highIndex++;
		}
	}
	swap(a[pivot], a[highIndex]);
	return highIndex;
}

void quickSort(std::vector<int> &a, int startIndex, int endIndex) {
	if(startIndex < endIndex) {
		int pivot = partition(a, startIndex, endIndex);
		quickSort(a, startIndex, pivot-1);
		quickSort(a, pivot+1, endIndex);
	}
}

int findMaxConsecutiveSum(std::vector<int> &a) {
	int s0 = a[0];
	int s = s0;
	for(size_t i = 1; i < a.size(); ++i) {
		if(a[i] < 0) {
			if(s0 < a[i]) {
				s0 = a[i];
			} else {
				s0 += a[i];
			}
		} else {
			if(s0 < 0) {
				s0 = a[i];
			} else {
				s0 += a[i];
			}
		}
		if(s < s0) {
			s = s0;
		}
	}
	return s;
}

void randomSelection(std::vector<int> &a, std::vector<int> &selected, int m) {
	int n = a.size();
	selected.resize(m);
	int t = 0, selectedSoFar = 0;
	srand(time(NULL));

	while(selectedSoFar < m) {
		int randomIndex = rand()%(n-t);
		if(randomIndex < (m-selectedSoFar)) {
			selected[selectedSoFar] = a[t];
			++selectedSoFar;
		}
		++t;
	}
}

int addIntegers(int x, int y) {
	int sum, carry;
	do {
		sum = x^y;
		carry = (x&y)<<1;
		x = sum;
		y = carry;
	} while(carry);
	return sum;
}

void findPrime(int n) {
	std::vector<bool> isComposite(n);
	int sqrtN = (int)sqrt(n);
	std::vector<int> primeList;
	for(int i = 2; i <= sqrtN; ++i) {
		if (!isComposite[i-2]) {
			primeList.push_back(i);
			for(int j = 2*i; j <= n; j += i) {
				isComposite[j-2] = true;
			}
		}
	}
	for(int i = sqrtN; i <= n; ++i) {
		if(!isComposite[i-2]) {
			primeList.push_back(i);
		}
	}
	std::cout << "Number of Primes: " << primeList.size() << std::endl;
	for(size_t idx = 0UL; idx < primeList.size(); ++idx) {
		std::cout << primeList[idx] << ", ";
	}
	std::cout << std::endl;
}

int my_strlen(const char *s) {
	char *t = (char *)s;
	int len = 0;
	while(*t) {
		++len;
		++t;
	}
	return len;
}

#include <algorithm>

struct ArrayNode {
	int index;
	char *s;
};

struct Compare {
	bool operator()(ArrayNode &left, ArrayNode &right) {
		int c = strcmp(left.s, right.s);
		if (c < 0) {
			return true;
		}
		return false;
	}
};

void creatSuffixArray(char *s) {
	int length = my_strlen(s);
	ArrayNode *a = new ArrayNode[length];
	for(int i = 0; i < length; ++i) {
		a[i].index = i;
		a[i].s = s+i;
	}
	Compare comp;
	std::sort(a, a+length, comp);
	std::cout << "Sorted Array: " << std::endl;
	for(int i = 0; i < length; ++i) {
		std::cout << a[i].index << ", ";
	}
	std::cout << std::endl;
}
*/
int minNumCoins(const int value, const std::vector<int> &coins)
{
  std::vector<int> changes(value+1, 10000);

  changes[0] = 0;
  for(int i = 1; i <= value; ++i) 
  {
    for(int j = 0; j <= i - 1; ++j)
    {
      for(int k = 0; k < coins.size(); ++k)
      {
        if ((j + coins[k]) == i && changes[i] > changes[j] + 1)
        {
          changes[i] = changes[j] + 1;
        }
      }
    }
  }
  return changes[value];
}
Example #9
0
void
TagDialog::storeTags( const KURL &kurl )
{
    int result = changes();
    QString url = kurl.path();
    if( result & TagDialog::TAGSCHANGED ) {
        MetaBundle mb( m_bundle );

        mb.setTitle( kLineEdit_title->text() );
        mb.setComposer( kComboBox_composer->currentText() );
        mb.setArtist( kComboBox_artist->currentText() );
        mb.setAlbum( kComboBox_album->currentText() );
        mb.setComment( kTextEdit_comment->text() );
        mb.setGenre( kComboBox_genre->currentText() );
        mb.setTrack( kIntSpinBox_track->value() );
        mb.setYear( kIntSpinBox_year->value() );
        mb.setDiscNumber( kIntSpinBox_discNumber->value() );
        mb.setLength( m_bundle.length() );
        mb.setBitrate( m_bundle.bitrate() );
        mb.setSampleRate( m_bundle.sampleRate() );
        storedTags.replace( url, mb );
    }
    if( result & TagDialog::SCORECHANGED )
        storedScores.replace( url, kIntSpinBox_score->value() );
    if( result & TagDialog::RATINGCHANGED )
        storedRatings.replace( url, kComboBox_rating->currentItem() ? kComboBox_rating->currentItem() + 1 : 0 );
    if( result & TagDialog::LYRICSCHANGED ) {
        if ( kTextEdit_lyrics->text().isEmpty() )
            storedLyrics.replace( url, QString::null );
        else {
            QDomDocument doc;
            QDomElement e = doc.createElement( "lyrics" );
            e.setAttribute( "artist", kComboBox_artist->currentText() );
            e.setAttribute( "title", kLineEdit_title->text() );
            QDomText t = doc.createTextNode( kTextEdit_lyrics->text() );
            e.appendChild( t );
            doc.appendChild( e );
            storedLyrics.replace( url, doc.toString() );
        }
    }
}
Example #10
0
void CCSVWriter::Write ( const CCachedLogInfo& cache
                       , const TFileName& fileName)
{
	std::ofstream authors ((fileName + _T(".authors.csv")).c_str());
	WriteStringList (authors, cache.GetLogInfo().GetAuthors());
	std::ofstream userRevPropNames ((fileName + _T(".revpropnames.csv")).c_str());
	WriteStringList (userRevPropNames, cache.GetLogInfo().GetUserRevProps());
	std::ofstream paths ((fileName + _T(".paths.csv")).c_str());
	WritePathList (paths, cache.GetLogInfo().GetPaths());

	std::ofstream changes ((fileName + _T(".changes.csv")).c_str());
	WriteChanges (changes, cache);
	std::ofstream merges ((fileName + _T(".merges.csv")).c_str());
	WriteMerges (merges, cache);
	std::ofstream userRevProps ((fileName + _T(".userrevprops.csv")).c_str());
	WriteRevProps (userRevProps, cache);

	std::ofstream revisions ((fileName + _T(".revisions.csv")).c_str());
	WriteRevisions (revisions, cache);
	std::ofstream skipranges ((fileName + _T(".skipranges.csv")).c_str());
    WriteSkipRanges (skipranges, cache);
}
Example #11
0
    /// true if messages are equal
    bool make_message_diff( gpb::Message const &templ,
                            gpb::Message const &src,
                            gpb::Message &result  )
    {
        boost::scoped_ptr<gpb::Message> new_result(src.New());
        new_result->CopyFrom( src );

        typedef gpb::FieldDescriptor field_desc;
        typedef std::vector<const field_desc *> field_list;
        field_list fields;

        new_result->GetReflection( )->ListFields(*new_result, &fields);

        size_t changes(0);

        for( field_list::const_iterator b(fields.begin()), e(fields.end());
                                                                b!=e; ++b )
        {
            field_desc const *next(*b);
            if( !next->is_repeated() &&
                !templ.GetReflection( )->HasField( templ, next ) )
            {
                ++changes;
                continue;
            }

            if( next->cpp_type( ) == field_desc::CPPTYPE_MESSAGE ) {
                changes += (!messages_diff( templ, *new_result, next ));
            } else {
                changes += (!field_diff( templ, *new_result, next ));
            }
        }

        result.GetReflection()->Swap( new_result.get(), &result );
        return changes == 0;
    }
Example #12
0
bool
TagDialog::hasChanged()
{
    return changes();
}
Example #13
0
    void Document::decrypt(const uint8_t* key,
            int key_size,
            const std::string& key_name)
    {
        // Only accept 256bit keys.
        if (k_key_size != key_size)
        {
            throw LJ__Exception("Decrypt key must be 256bits.");
        }

        // Get the document to decrypt.
        const lj::bson::Node& source_node =
                doc_->nav(k_crypt_data).nav(key_name);
        lj::bson::Binary_type bt;
        uint32_t source_size;
        const uint8_t* source = lj::bson::as_binary(source_node,
                &bt,
                &source_size);

        // Get the initialization vector for the encrypted data.
        const lj::bson::Node& ivector_node =
                doc_->nav(k_crypt_vector).nav(key_name);
        uint32_t iv_size;
        const uint8_t* iv = lj::bson::as_binary(ivector_node,
                &bt,
                &iv_size);

        // Check to make sure the initialization vector is the correct length.
        if (GCM_IV_SIZE != iv_size)
        {
            throw LJ__Exception("Initialization vector for this encrypted data is incorrect.");
        }

        // Prepare all the data structures for the AES crypto in GCM mode.
        struct aes_ctx cipher_ctx;
        aes_set_encrypt_key(&cipher_ctx, key_size, key);
        struct gcm_key auth_key;
        gcm_set_key(&auth_key, &cipher_ctx, (nettle_crypt_func*) & aes_encrypt);
        struct gcm_ctx auth_ctx;
        gcm_set_iv(&auth_ctx, &auth_key, GCM_IV_SIZE, iv);

        // Perform the actual encryption.
        std::unique_ptr < uint8_t[] > destination(new uint8_t[source_size]);
        gcm_decrypt(&auth_ctx,
                &auth_key,
                &cipher_ctx,
                (nettle_crypt_func*) & aes_encrypt,
                source_size,
                destination.get(),
                source);

        // Extract the authentication information.
        uint8_t auth_tag[GCM_BLOCK_SIZE];
        gcm_digest(&auth_ctx, &auth_key, &cipher_ctx, (nettle_crypt_func*) & aes_encrypt, GCM_BLOCK_SIZE, auth_tag);

        // Get the  authentication vector from the encryption.
        const lj::bson::Node& authentication_node =
                doc_->nav(k_crypt_auth).nav(key_name);
        uint32_t authentication_size;
        const uint8_t* original_auth_tag = lj::bson::as_binary(authentication_node,
                &bt,
                &authentication_size);

        // Check to make sure the authentication tag is the correct size.
        if (GCM_BLOCK_SIZE != authentication_size)
        {
            throw LJ__Exception("Authentication tag for this encrypted data is incorrect.");
        }

        // Compare the authentication tag from decryption to the authentication tag from encryption.
        if (memcmp(auth_tag, original_auth_tag, GCM_BLOCK_SIZE) != 0)
        {
            throw LJ__Exception("Authentication tags did not match. Data may be corrupted.");
        }

        // The destination should now contain whatever was originally encrypted.
        // Turn the data back into a bson document
        lj::bson::Node changes(lj::bson::Type::k_document,
                destination.get());

        // Clean up anything sensitive from memory.
        lj::Wiper < uint8_t[]>::wipe(destination, source_size);
        lj::Wiper < uint8_t[]>::wipe(auth_tag, GCM_BLOCK_SIZE);

        // try to combine the documents.  This may throw an exception if things are
        // messed up.
        lj::bson::combine(doc_->nav("."), changes.nav("."));

        // Remove the encrypted data from the document.
        doc_->nav(k_crypt_vector).set_child(key_name, nullptr);
        doc_->nav(k_crypt_auth).set_child(key_name, nullptr);
        doc_->nav(k_crypt_data).set_child(key_name, nullptr);
    }
Example #14
0
void KRegExpEditorPrivate::emitUndoRedoSignals()
{
  emit canUndo( _undoStack.count() > 1 );
  emit changes( _undoStack.count() > 1 );
  emit canRedo( _redoStack.count() > 0 );
}
tabuleiro *aleatorio(tabuleiro *tab,int before){
	int lin,col,i,l,com=0,barexist,barconess, posicoes;
	int linhas[100],comb[100];
	char tmp[100][100],local[100][100];
	tabuleiro *f, *w, *z, *x;

	


	for(lin=0;lin!=tab->tamanho[0];lin++){
		barexist=0;
		posicoes=0;
		for(col=0;col!=tab->tamanho[1];col++){
			if(caniboat(tab,lin,col)) posicoes++;
			else if(tab->quadro[lin][col]!='~' && tab->quadro[lin][col]!='.') barexist++;
		}
		barconess=tab->linhas[lin]-barexist;
		comb[lin]=combinacoes(posicoes,barconess);
	}


	for(i=0;i!=tab->tamanho[0];i++)
		linhas[i]=i;



	ordena(comb,linhas,0,tab->tamanho[0]);



	for(i=0;comb[i]==0;i++);

	l=linhas[i];
	com=0;








	for(lin=0;lin!=tab->tamanho[0];lin++)
	   	for(col=0;col!=tab->tamanho[1];col++)
	   		tmp[lin][col]=tab->quadro[lin][col];


		do{
			if(verifica(tab)==2) ;
			else if(verifica(tab)==0){

				for(lin=0;lin!=tab->tamanho[0];lin++)
	   				for(col=0;col!=tab->tamanho[1];col++)
	   					tab->quadro[lin][col]=tmp[lin][col];

	   				++com;

					if(com>=comb[i]) {com=0; l=linhas[++i];}

	   				tab=aleoaux(tab,l,com);
	   			}

	  	    else if(verifica(tab)==1){

	  	    	++com;

				if(com>=comb[i]) {com=0; l=linhas[++i];}



	  	    	tab=aleoaux(tab,l,com);
	  	    } 			

			do{
				for(lin=0;lin!=tab->tamanho[0];lin++)
	   				for(col=0;col!=tab->tamanho[1];col++)
	   					local[lin][col]=tab->quadro[lin][col];
	   	

        	f=aloca(tab);
        	w=verigual(tab,estra1(f));


        	f=aloca(w);
        	z=verigual(w,estra2(f));


        	f=aloca(z);
        	x=verigual(z,estra3(f));

        	f=aloca(x);
        	tab=verigual(x,estra4(f));



		}while(changes(local,tab) && verifica(tab)!=2);


		if(verifica(tab)==0){
			for(lin=0;lin!=tab->tamanho[0];lin++)
	   				for(col=0;col!=tab->tamanho[1];col++)
	   					tmp[lin][col]=tab->quadro[lin][col];

		}




		if(before==1){
			for(lin=0;lin!=tab->tamanho[0];lin++)
	   				for(col=0;col!=tab->tamanho[1];col++)
	   					tmp[lin][col]=tab->quadro[lin][col];

	   	return tab;

		}
		else if(verifica(tab)!=2 && i+1==tab->tamanho[0]) tab=aleatorio(tab,1);

		if(dots(tab) || verifica(tab)!=2) {
			for(lin=0;lin!=tab->tamanho[0];lin++)
	   				for(col=0;col!=tab->tamanho[1];col++)
	   					tmp[lin][col]=tab->quadro[lin][col];

	   	return tab;

		}

	}while(verifica(tab)!=2);


   return tab;
}
Example #16
0
int QDeclarativeState::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 1)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 1;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< QString*>(_v) = name(); break;
        case 1: *reinterpret_cast< QDeclarativeBinding**>(_v) = when(); break;
        case 2: *reinterpret_cast< QString*>(_v) = extends(); break;
        case 3: *reinterpret_cast< QDeclarativeListProperty<QDeclarativeStateOperation>*>(_v) = changes(); break;
        }
        _id -= 4;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setName(*reinterpret_cast< QString*>(_v)); break;
        case 1: setWhen(*reinterpret_cast< QDeclarativeBinding**>(_v)); break;
        case 2: setExtends(*reinterpret_cast< QString*>(_v)); break;
        }
        _id -= 4;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 4;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}