UI Automation CreatePropertyCondition 0xc0000005 - ui-automation

I tried to re-use code (http://msdn.microsoft.com/en-us/library/windows/desktop/ff625913(v=vs.85).aspx#FindByName), but I want to wrap it in a simple class. When I'm run this code it falls on:
hr = g_pAutomation->CreatePropertyCondition(UIA_ClassNamePropertyId, varProp, &pCondition);
with 0xc0000005.
I know, it because of empty or broken pointer. But when I run this code without any classes (from main()), it works perfect.
What should I read and from where to understand why it happens?
#pragma once
#include <UIAutomation.h>
class Automator
{
protected:
IUIAutomation* g_pAutomation;
IUIAutomationElement* pRoot;
IUIAutomationElementArray* pArrFound;
IUIAutomationElement* pFound;
public:
Automator(void);
~Automator(void);
void ClearResources(void);
void FindAllWindows(void);
};
#include "Automator.h"
Automator::Automator(void)
{
pRoot = NULL;
pArrFound = NULL;
pFound = NULL;
g_pAutomation = NULL;
CoInitialize(NULL);
HRESULT hr;
hr = CoCreateInstance(__uuidof(CUIAutomation), NULL, CLSCTX_INPROC_SERVER,
__uuidof(IUIAutomation), (void**)&g_pAutomation);
if(FAILED(hr))
ClearResources();
else
{
hr = g_pAutomation->GetRootElement(&pRoot);
if (FAILED(hr) || pRoot == NULL)
ClearResources();
}
}
Automator::~Automator(void)
{
ClearResources();
}
//
//Doesn't work
//
void Automator::FindAllWindows(void)
{
VARIANT varProp;
varProp.vt = VT_BSTR;
varProp.bstrVal = L"";
IUIAutomationCondition* pCondition;
HRESULT hr = NULL;
if (g_pAutomation != NULL)
{
hr = g_pAutomation->CreatePropertyCondition(UIA_ClassNamePropertyId, varProp, &pCondition);
if(FAILED(hr))
{
if (pCondition != NULL)
pCondition->Release();
ClearResources();
}
else
{
pRoot->FindAll(TreeScope_Subtree, pCondition, &pArrFound);
}
}
if(pCondition != NULL)
pCondition->Release();
}
void Automator::ClearResources(void)
{
if (pRoot != NULL)
pRoot->Release();
if (pArrFound != NULL)
pArrFound->Release();
if (pFound != NULL)
pFound->Release();
if (g_pAutomation != NULL)
g_pAutomation->Release();
CoUninitialize();
}

I see a couple of issues:
Don't call CoInitialize/CoUninitialize from class constructors/destructors; do it inside your main (or thread entry point). A fair amount of code runs before main() gets called (static class initializers, for one) and having that run outside main() can result in problems.
You haven't shown your main() - where are you creating your Automator object? I suspect you haven't actually created an Automator, which is why it's crashing.
If I were going to write your main, it would look like this:
_wmain(int argc, wchar_t **argv)
{
CoInitialize();
{
Automator automator;
automator.FindAllWindows();
}
CoUninitialize();
}
The extra scope bracket is there to insure that the Automator destructor runs before CoUninitialize().

Related

How to Create an Input Name Script in Unity [duplicate]

This question already has answers here:
How to pass data (and references) between scenes in Unity
(6 answers)
Closed 2 years ago.
I have a name input script in the first scene, the plan is I want to call this input in the second scene, when I enter the name in the first scene, then the name will appear in the second scene too, how do you do that?
public class NamaUser : MonoBehaviour {
public InputField nama;
public Text teks;
public void NamaTeks () {
if (nama.text == "") {
teks.text = "Harap Isi Nama";
} else {
teks.text = "Namaku " + nama.text;
}
}
}
You can save the input's value PlayerPrefs.
Set the PlayerPrefs:
//Name of Pref in first parameter
//Value in second parameter
PlayerPrefs.SetString("value", teks.value);
Get the PlayerPref in second scene:
//Name of Pref in first parameter
//Returns value of PlayerPrefs
String a = PlayerPrefs.SetString("value");
Cons:
You can pass data not only between scenes but also between instances (game sessions).
Easy to manage since Unity handles all background process.
Can be used to store data to track highscores.
Pros:
Uses file system.
Data can easily be changed from prefs file.
Or, another way -- use Singelton and DontDestroyOnLoad()
Allows easy access to fields and saves an object between scenes.
For example use this template, to create your class.
using UnityEngine;
public class Singelton<T> : MonoBehaviour where T : Singelton<T>
{
private static T instance = null;
private bool alive = true;
public static T Instance
{
get
{
if (instance != null)
{
return instance;
}
else
{
//Find T
T[] managers = GameObject.FindObjectsOfType<T>();
if (managers != null)
{
if (managers.Length == 1)
{
instance = managers[0];
DontDestroyOnLoad(instance);
return instance;
}
else
{
if (managers.Length > 1)
{
Debug.LogError($"Have more that one {typeof(T).Name} in scene. " +
"But this is Singelton! Check project.");
for (int i = 0; i < managers.Length; ++i)
{
T manager = managers[i];
Destroy(manager.gameObject);
}
}
}
}
//create
GameObject go = new GameObject(typeof(T).Name, typeof(T));
instance = go.GetComponent<T>();
DontDestroyOnLoad(instance.gameObject);
return instance;
}
}
//Can be initialized externally
set
{
instance = value as T;
}
}
/// <summary>
/// Check flag if need work from OnDestroy or OnApplicationExit
/// </summary>
public static bool IsAlive
{
get
{
if (instance == null)
return false;
return instance.alive;
}
}
protected virtual void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = this as T;
}
else
{
Debug.LogError($"Have more that one {typeof(T).Name} in scene. " +
"But this is Singelton! Check project.");
Destroy(gameObject);
}
}
protected virtual void OnDestroy() { alive = false; }
protected virtual void OnApplicationQuit() { alive = false; }
}
Example of using:
class MyClass Settings : Singelton<Settings>
{
string param;
}

Unity multiple Coroutines null reference exception

I have seen the same question with an answer, but unfortunately I haven't fully understood how to address the issue, as I get a null reference exception.
I try to have 2 coroutines run simultaneously. Each is from a different base class. They both are identical, apart from the class's name and activation key (one is Up Arrow and the other Down Arrow).
public IEnumerator DetectArrow()
{
if (Input.GetKey(KeyCode.UpArrow))
{
if (PrintMessage == null)
{
PrintMessage += SendMessage;
}
}
return null;
}
public void SendMessage()
{
print("I am B.");
PrintMessage = null;
}
I try to run something such as this for the entire run (from a parent class):
void Update ()
{
if (b.PrintMessage != null)
{
b.PrintMessage();
}
if (a.PrintMessage != null)
{
a.PrintMessage();
}
}
So I'm not quite sure how to solve this. Thanks for the help.

Plugin dev: How to search only for interfaces in DLTK/PDT plugin?

I develop extension of PDT plugin. I need dialog with interfaces only (not classes). Basic code looks like it:
OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2(
DLTKUIPlugin.getActiveWorkbenchShell(),
multi,
PlatformUI.getWorkbench().getProgressService(),
null,
type,
PHPUILanguageToolkit.getInstance());
It's works fine but I get classes and interfaces together (type variables). Is any method to filter it? I can't find this kind of mechanism in PDT but classes and interfaces are recognize correctly (icons next to names).
I don't know if its the best solution but it works.
int falseFlags = 0;
int trueFlags = 0;
IDLTKSearchScope scope = SearchEngine.createSearchScope(getScriptFolder().getScriptProject());
trueFlags = PHPFlags.AccInterface;
OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2(
DLTKUIPlugin.getActiveWorkbenchShell(),
multi,
PlatformUI.getWorkbench().getProgressService(),
scope,
IDLTKSearchConstants.TYPE,
new PHPTypeSelectionExtension(trueFlags, falseFlags),
PHPUILanguageToolkit.getInstance());
And PHPTypeSelectionExtension looks like this:
public class PHPTypeSelectionExtension extends TypeSelectionExtension {
/**
* #see PHPFlags
*/
private int trueFlags = 0;
private int falseFlags = 0;
public PHPTypeSelectionExtension() {
}
public PHPTypeSelectionExtension(int trueFlags, int falseFlags) {
super();
this.trueFlags = trueFlags;
this.falseFlags = falseFlags;
}
#Override
public ITypeInfoFilterExtension getFilterExtension() {
return new ITypeInfoFilterExtension() {
#Override
public boolean select(ITypeInfoRequestor typeInfoRequestor) {
if (falseFlags != 0 && (falseFlags & typeInfoRequestor.getModifiers()) != 0) {
// Try to filter by black list.
return false;
} else if (trueFlags == 0 || (trueFlags & typeInfoRequestor.getModifiers()) != 0) {
// Try to filter by white list, if trueFlags == 0 this is fine 'couse we pass black list.
return true;
} else {
// Rest is filter out.
return false;
}
}
};
}
#SuppressWarnings("restriction")
#Override
public ISelectionStatusValidator getSelectionValidator() {
return new TypedElementSelectionValidator(new Class[] {IType.class, INamespace.class}, false);
}
}

how to access the text entry in GtkFileChooser

In GTK+, is it possible to access the GtkWidget -- text entry for file name in GtkFileChooser? I want to disable the editable attribute of the text entry using gtk_entry_set_editable.
As far as I know, no.
What do you ultimately want to achieve? Perhaps there is another approach.
If one had a legitimate reason to get a pointer to the GtkEntry, then derive from GtkFileChooserDialog, which will probably mutate into a GtkFileChooserDefault. GObject will complain about an illegal cast when checking type instance even though it works and the data of derived object can be accessed without errors, use GTK_FILE_CHOOSER instead of MY_FILE_CHOOSER to avoid the warning messages and a local static for the entry pointer. The entry widget is NOT accessible during construction. Here is the pertinent code:
static GtkEntry *chooser_entry;
static void my_file_chooser_finalize (GObject *object)
{
chooser_entry = NULL;
(G_OBJECT_CLASS (my_file_chooser_parent_class))->finalize (object);
}
static void my_file_chooser_init (MyFileChooser *self)
{
chooser_entry = NULL;
}
static void look_for_entry(GtkWidget *widget, void *self)
{
if (GTK_IS_ENTRY(widget)) {
chooser_entry = (GtkEntry*)widget;
}
else if (GTK_IS_CONTAINER(widget)) {
gtk_container_forall ( GTK_CONTAINER (widget), look_for_entry, self);
}
}
static void file_chooser_find_entry (GtkWidget *chooser)
{
GList *children, *iter;
/* Get all objects inside the dialog */
children = gtk_container_get_children (GTK_CONTAINER (chooser));
for (iter = children; iter; iter = iter->next) {
if (GTK_IS_CONTAINER(iter->data)) {
gtk_container_forall ( GTK_CONTAINER (iter->data), look_for_entry, chooser);
if (chooser_entry != NULL) {
break;
}
}
}
g_list_free (children);
}
GtkEntry *my_file_chooser_get_entry (GtkWidget *widget)
{
if (chooser_entry == NULL) {
file_chooser_find_entry (widget);
}
return chooser_entry;
}
char *my_file_chooser_get_entry_text(GtkWidget *widget)
{
char *text;
GtkEntry *entry;
text = NULL;
if (GTK_IS_FILE_CHOOSER(widget)) {
entry = my_file_chooser_get_entry(widget);
if (GTK_IS_ENTRY(entry)) {
if (gtk_entry_get_text_length (entry)) {
text = g_strdup (gtk_entry_get_text(entry));
}
}
}
return text;
}
Maybe not ideal, but works.

Balancing String based Binary Search Tree (For Spellchecking)

Update: I can't get "Balancing" to work, because I cannot get "doAVLBalance" to recognize the member functions "isBalanced()", "isRightHeavy()", "isLeftHeavy". And I don't know why! I tried Sash's example(3rd answer) exactly but I get "deceleration is incompatible" and I couldn't fix that...so I tried doing it my way...and it tells me those member functions don't exist, when they clearly do.
"Error: class "IntBinaryTree:TreeNode" has no member "isRightHeavy".
I'm stuck after trying for the last 4 hours :(. Updated code below, help would be much appreciated!!
I'm creating a String based Binary Search Tree and need to make it a "Balanced" tree. How do I do this?* Help please!! Thanks in advance!
BinarySearchTree.cpp:
bool IntBinaryTree::leftRotation(TreeNode *root)
{
//TreeNode *nodePtr = root; // Can use nodePtr instead of root, better?
// root, nodePtr, this->?
if(NULL == root)
{return NULL;}
TreeNode *rightOfTheRoot = root->right;
root->right = rightOfTheRoot->left;
rightOfTheRoot->left = root;
return rightOfTheRoot;
}
bool IntBinaryTree::rightRotation(TreeNode *root)
{
if(NULL == root)
{return NULL;}
TreeNode *leftOfTheRoot = root->left;
root->left = leftOfTheRoot->right;
leftOfTheRoot->right = root;
return leftOfTheRoot;
}
bool IntBinaryTree::doAVLBalance(TreeNode *root)
{
if(NULL==root)
{return NULL;}
else if(root->isBalanced()) // Don't have "isBalanced"
{return root;}
root->left = doAVLBalance(root->left);
root->right = doAVLBalance(root->right);
getDepth(root); //Don't have this function yet
if(root->isRightHeavy()) // Don't have "isRightHeavey"
{
if(root->right->isLeftheavey())
{
root->right = rightRotation(root->right);
}
root = leftRotation(root);
}
else if(root->isLeftheavey()) // Don't have "isLeftHeavey"
{
if(root->left->isRightHeavey())
{
root->left = leftRotation(root->left);
}
root = rightRotation(root);
}
return root;
}
void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
if(nodePtr == NULL)
nodePtr = newNode; //Insert node
else if(newNode->value < nodePtr->value)
insert(nodePtr->left, newNode); //Search left branch
else
insert(nodePtr->right, newNode); //search right branch
}
//
// Displays the number of nodes in the Tree
int IntBinaryTree::numberNodes(TreeNode *root)
{
TreeNode *nodePtr = root;
if(root == NULL)
return 0;
int count = 1; // our actual node
if(nodePtr->left !=NULL)
{ count += numberNodes(nodePtr->left);
}
if(nodePtr->right != NULL)
{
count += numberNodes(nodePtr->right);
}
return count;
}
// Insert member function
void IntBinaryTree::insertNode(string num)
{
TreeNode *newNode; // Poitner to a new node.
// Create a new node and store num in it.
newNode = new TreeNode;
newNode->value = num;
newNode->left = newNode->right = NULL;
//Insert the node.
insert(root, newNode);
}
// More member functions, etc.
BinarySearchTree.h:
class IntBinaryTree
{
private:
struct TreeNode
{
string value; // Value in the node
TreeNode *left; // Pointer to left child node
TreeNode *right; // Pointer to right child node
};
//Private Members Functions
// Removed for shortness
void displayInOrder(TreeNode *) const;
public:
TreeNode *root;
//Constructor
IntBinaryTree()
{ root = NULL; }
//Destructor
~IntBinaryTree()
{ destroySubTree(root); }
// Binary tree Operations
void insertNode(string);
// Removed for shortness
int numberNodes(TreeNode *root);
//int balancedTree(string, int, int); // TreeBalanced
bool leftRotation(TreeNode *root);
bool rightRotation(TreeNode *root);
bool doAVLBalance(TreeNode *root); // void doAVLBalance();
bool isAVLBalanced();
int calculateAndGetAVLBalanceFactor(TreeNode *root);
int getAVLBalanceFactor()
{
TreeNode *nodePtr = root; // Okay to do this? instead of just
// left->mDepth
// right->mDepth
int leftTreeDepth = (left !=NULL) ? nodePtr->left->Depth : -1;
int rightTreeDepth = (right != NULL) ? nodePtr->right->Depth : -1;
return(leftTreeDepth - rightTreeDepth);
}
bool isRightheavey() { return (getAVLBalanceFactor() <= -2); }
bool isLeftheavey() { return (getAVLBalanceFactor() >= 2); }
bool isBalanced()
{
int balanceFactor = getAVLBalanceFactor();
return (balanceFactor >= -1 && balanceFactor <= 1);
}
int getDepth(TreeNode *root); // getDepth
void displayInOrder() const
{ displayInOrder(root); }
// Removed for shortness
};
Programmers use AVL Tree concepts to balance binary trees. It is quite simple. More information can be found online. Quick wiki link
Below is the sample code which does tree balance using AVL algorithm.
Node *BinarySearchTree::leftRotation(Node *root)
{
if(NULL == root)
{
return NULL;
}
Node *rightOfTheRoot = root->mRight;
root->mRight = rightOfTheRoot->mLeft;
rightOfTheRoot->mLeft = root;
return rightOfTheRoot;
}
Node *BinarySearchTree::rightRotation(Node *root)
{
if(NULL == root)
{
return NULL;
}
Node *leftOfTheRoot = root->mLeft;
root->mLeft = leftOfTheRoot->mRight;
leftOfTheRoot->mRight = root;
return leftOfTheRoot;
}
Node *BinarySearchTree::doAVLBalance(Node *root)
{
if(NULL == root)
{
return NULL;
}
else if(root->isBalanced())
{
return root;
}
root->mLeft = doAVLBalance(root->mLeft);
root->mRight = doAVLBalance(root->mRight);
getDepth(root);
if(root->isRightHeavy())
{
if(root->mRight->isLeftHeavy())
{
root->mRight = rightRotation(root->mRight);
}
root = leftRotation(root);
}
else if(root->isLeftHeavy())
{
if(root->mLeft->isRightHeavy())
{
root->mLeft = leftRotation(root->mLeft);
}
root = rightRotation(root);
}
return root;
}
Class Definition
class BinarySearchTree
{
public:
// .. lots of methods
Node *getRoot();
int getDepth(Node *root);
bool isAVLBalanced();
int calculateAndGetAVLBalanceFactor(Node *root);
void doAVLBalance();
private:
Node *mRoot;
};
class Node
{
public:
int mData;
Node *mLeft;
Node *mRight;
bool mHasVisited;
int mDepth;
public:
Node(int data)
: mData(data),
mLeft(NULL),
mRight(NULL),
mHasVisited(false),
mDepth(0)
{
}
int getData() { return mData; }
void setData(int data) { mData = data; }
void setRight(Node *right) { mRight = right;}
void setLeft(Node *left) { mLeft = left; }
Node * getRight() { return mRight; }
Node * getLeft() { return mLeft; }
bool hasLeft() { return (mLeft != NULL); }
bool hasRight() { return (mRight != NULL); }
bool isVisited() { return (mHasVisited == true); }
int getAVLBalanceFactor()
{
int leftTreeDepth = (mLeft != NULL) ? mLeft->mDepth : -1;
int rightTreeDepth = (mRight != NULL) ? mRight->mDepth : -1;
return(leftTreeDepth - rightTreeDepth);
}
bool isRightHeavy() { return (getAVLBalanceFactor() <= -2); }
bool isLeftHeavy() { return (getAVLBalanceFactor() >= 2); }
bool isBalanced()
{
int balanceFactor = getAVLBalanceFactor();
return (balanceFactor >= -1 && balanceFactor <= 1);
}
};
There are many ways to do this, but I'd suggest that you actually not do this as all. If you want to store a BST of strings, there are much better options:
Use a prewritten binary search tree class. The C++ std::set class offers the same time guarantees as a balanced binary search tree and is often implemented as such. It's substantially easier to use than rolling you own BST.
Use a trie instead. The trie data structure is simpler and more efficient than a BST of strings, requires no balancing at all, and is faster than a BST.
If you really must write your own balanced BST, you have many options. Most BST implementations that use balancing are extremely complex and are not for the faint of heart. I'd suggest implementing either a treap or a splay tree, which are two balanced BST structures that are rather simple to implement. They're both more complex than the code you have above and I can't in this short space provide an implementation, but a Wikipedia search for these structures should give you plenty of advice on how to proceed.
Hope this helps!
Unfortunately, we programmers are literal beasts.
make it a "Balanced" tree.
"Balanced" is context dependent. The introductory data structures classes typically refer to a tree being "balanced" when the difference between the node of greatest depth and the node of least depth is minimized. However, as mentioned by Sir Templatetypedef, a splay tree is considered a balancing tree. This is because it can balance trees rather well in cases that few nodes accessed together at one time frequently. This is because it takes less node traversals to get at the data in a splay tree than a conventional binary tree in these cases. On the other hand, its worst-case performance on an access-by-access basis can be as bad as a linked list.
Speaking of linked lists...
Because otherwise without the "Balancing" it's the same as a linked-list I read and defeats the purpose.
It can be as bad, but for randomized inserts it isn't. If you insert already-sorted data, most binary search tree implementations will store data like an bloated and ordered linked list. However, that's only because you're building one side of the tree continually. (Imagine inserting 1, 2, 3, 4, 5, 6, 7, etc... into a binary tree. Try it on paper and see what happens.)
If you have to balance in a theoretical worst-case-must-guaranteed sense, I recommend looking up red-black trees. (Google it, second link is pretty good.)
If you have to balance it in a reasonable way for this particular scenario, I'd go with integer indices and a decent hash function -- that way the balancing will happen probabilistically without any extra code. That is to say, make your comparison function look like hash(strA) < hash(strB) instead of what you've got now. (For a quick but effective hash for this case, look up FNV hashing. First hit on Google. Go down until you see useful code.) You can worry about the details of implementation efficiency if you want to. (For example, you don't have to perform both hashes every single time you compare since one of the strings never changes.)
If you can get away with it, I strongly recommend the latter if you're in a crunch for time and want something fast. Otherwise, red-black trees are worthwhile since they're extremely useful in practice when you need to roll your own height-balanced binary trees.
Finally, addressing your code above, see the comments in the code below:
int IntBinaryTree::numberNodes(TreeNode *root)
{
if(root = NULL) // You're using '=' where you want '==' -- common mistake.
// Consider getting used to putting the value first -- that is,
// "NULL == root". That way if you make that mistake again, the
// compiler will error in many cases.
return 0;
/*
if(TreeNode.left=null && TreeNode.right==null) // Meant to use '==' again.
{ return 1; }
return numberNodes(node.left) + numberNodes(node.right);
*/
int count = 1; // our actual node
if (left != NULL)
{
// You likely meant 'root.left' on the next line, not 'TreeNode.left'.
count += numberNodes(TreeNode.left);
// That's probably the line that's giving you the error.
}
if (right != NULL)
{
count += numberNodes(root.right);
}
return count;
}