Access values of dropActions in model (PySide/PyQt/Qt) - qt

In a QTableModel when I enter the following:
print model.supportedDropActions()
I just get:
<PyQt4.QtCore.DropActions object at 0x00000000081172E8>
How can I access an actual list of the supported drop actions from this object? At the documentation, it says, "The DropActions type is a typedef for QFlags. It stores an OR combination of DropAction values."
Note I am doing this in Python (PySide).
Related posts:
Drag and drop rows within QTableWidget

Background
First, make sure you understand how the bitwise-encoding works for these flags. There are really good descriptions in the accepted answers here:
What are bitwise operators?
How to find specific Qt.ItemFlag occurrence into custom Qt.ItemFlags instance in PyQt?
Everyone that uses Qt and its relatives should read them, they will save a lot of headache if you ever want to extract information from the bitwise-encoded values.
Solution
While the following isn't for drop actions, but for item data roles, the principles are the exact same. As mentioned in the comments on the original post, you can recast the encoded value as an int and then decode it to a human-readable format using the enumeration (i.e., the translation between integer and role) provided by Qt online. I don't know why sometimes the docs represent the integers as hex versus decimals.
In what follows, I represented the enumeration that I found online in a dictionary with the int as key, and the human-readable string description as value. Then use a function that casts the role as an int to do the translation, using that dictionary.
#Create a dictionary of all data roles
dataRoles = {0: 'DisplayRole', 1: 'DecorationRole', 2: 'EditRole', 3: 'ToolTipRole',\
4: 'StatusTipRole', 5: 'WhatsThisRole', 6: 'FontRole', 7: 'TextAlignmentRole',\
8: 'BackgroundRole', 9: 'ForegroundRole', 10: 'CheckStateRole', 13: 'SizeHintRole',\
14: 'InitialSortOrderRole', 32: 'UserRole'}
#Return role in a human-readable format
def roleToString(flagDict, role):
recastRole = int(role) #recast role as int
roleDescription = flagDict[recastRole]
return roleDescription
Then to use it, for instance in a model where roles are being thrown around and I want to see what's doing:
print "Current data role: ", roleToString(dataRoles, role)
There are different ways to do it, but I find this very intuitive and easy to use.

Related

Consequences of using dynamic in a struct

I would like to use struct to make sure that everything inside is copied by value, but I would like it to be flexible enough to carry different types. What kind of bad things, especially in terms of performance, may happen when using dynamic field in a struct?
public struct Group
{
public double A;
public double B;
public dynamic Data;
}
This struct is expected to contain information about a single element on the chart and will be used in a collection that on average will contain ~1000 and up to 100K elements.
IList<Group> bars = new List<Group>(1000)
Field Data in this struct is expected to contain various types
double
OHLC bar represented as 4 doubles
up or down arrow represented as 1 double and 1 bool
Is there a way to avoid using dynamic here and still represent data of different types in unified format? If not possible, what is the downside of using dynamic as a field type?
Couple of bad things that I can think of are casting, boxing, and use of cached delegates for different types. Is there anything worse?

How does one convert string to number in JDOQL?

I have a JDOQL/DataNucleus storage layer which stores values that can have multiple primitive types in a varchar field. Some of them are numeric, and I need to compare (</>/...) them with numeric constants. How does one achieve that? I was trying to use e.g. (java.lang.)Long.parse on the field or value (e.g. java.lang.Long.parseLong(field) > java.lang.Long.parseLong(string_param)), supplying a parameter of type long against string field, etc. but it doesn't work. In fact, I very rarely get any errors, for various combinations it would return all values or no values for no easily discernible reasons.
Is there documentation for this?
Clarification: the field is of string type (actually a string collection from which I do a get). For some subset of values they may store ints, e.g. "3" string, and I need to do e.g. value >= 2 filters.
I tried using casts, but not much, they do produce errors, let me investigate some more
JDO has a well documented set of methods that are valid for use with JDOQL, upon which DataNucleus JDO adds some additional ones and allows users to add on support for others as per
http://www.datanucleus.org/products/accessplatform_3_3/jdo/jdoql.html#methods
then you also can use JDOQL casts (on the same page as that link).

How can I look for objects with missing value or None as key?

I would like to perform a search on the zope catalog of the objects with missing index key values. Is it possible?
For example consider the subsequent code lines:
from Products.CMFCore.utils import getToolByName
catalog = getToolByName(context, 'portal_catalog')
results = catalog.searchResults({'portal_type': 'Event', 'review_state': 'pending'})
what to do if I'm interested in objects in which a certain item, instead of portal_type or review_state, has not be inserted?
You can search for both types, but to search for MissingValue entries requires custom handling of the internal catalog data structures.
Indexes take the value from an object, and index that. If there is an AttributeError or similar, the index does not store anything for that object, and if the same field is part of the returned columns, in that case a MissingValue will be given to indicate the index is empty for that field.
In the following examples I assume you have a variable catalog that points to the site's portal_catalog tool; e.g. the result of getToolByName(context, 'portal_catalog') or similar.
Searching for None
You can search for None in many indexes just fine:
catalog(myKeywordIndex=None)
The problem is that most indexe types ignore None as a value. Thus, searching for None will fail on Date and Path indexes; they ignore None on index, and Boolean indexes; they turn None into False when indexing.
Keyword indexes ignore None as well, unless it is part of a sequence. If the indexed method returns [None] it'll happily be indexed, but None on it's own won't be.
Field indexes do store None in the index.
Note that each index can show unique values, so you can check if there are None values stored for a given index by calling:
catalog.uniqueValuesFor(indexname)
Searching for missing values
This is a little trickier. Each index does keep track of what objects it has indexed, to be able to remove data from the index when the object is removed, for example. At the same time, the catalog keeps track of what objects it has indexed as a whole.
Thus, we can calculate the difference between these two sets of information. This is what the catalog does all the time when you call the published APIs, but for this trick there is no such public API. We'll need to reach into the catalog internals and grab these sets for ourselves.
Luckily, these are all BTree sets, and the operations are thus relatively efficient. Here is how I'd do it:
from BTrees.IIBTree import IISet, difference
def missing_entries_for_index(catalog, index_name):
# Return the difference between catalog and index ids
index = catalog._catalog.getIndex(index_name)
referenced = IISet(index.referencedObjects()) # Works with any UnIndex-based index
return (
difference(IISet(catalog._catalog.paths), referenced),
len(catalog) - len(referenced)
)
The missing_entries_for_index method returns an IISet of catalog ids and it's length; each is a pointer to a catalog record for which the named index has no entry. You can then use catalog.getpath to turn that into a full path to objects, or use catalog.getMetadataForRID to get a dictionary of metadata values, or use catalog.getobject to get the original object itself, or use catalog._catalog[] to get catalog brains.
The following method will give you a catalog result set, just like you would get from a regular catalog search:
from ZCatalog.Lazy import LazyMap
def not_indexed_results(catalog, index_name):
rs, length = missing_entries_for_index(catalog, index_name)
return LazyMap(catalog._catalog.__getitem__, rs.keys(), length)
Thanks Ago. Actually reading the link you suggest I discover that it's not possible without a trick. I report from pypi:
Note that negative filtering on an index still restricts items to those having a value in the index. So with 10 documents, 5 of them in the foo index with a value of 1, a query for not 1 will return no items instead of the 5 items without a value. You need to index a dummy/default value if you want to consider all items for a particular index.
So it is necessary to give a default value to your item and look for it.

What is appendNormTransformer in the Symfony FormBuilder?

What is appendNormTransformer in the Symfony FormBuilder? When should I use this instead of appendClientTransformer and prependClientTransformer
Taken from the class documentation block of Form.php:
To implement your own form fields, you need to have a thorough understanding
of the data flow within a form field. A form field stores its data in three
different representations:
(1) the format required by the form's object
(2) a normalized format for internal processing
(3) the format used for display
A date field, for example, may store a date as "Y-m-d" string (1) in the
object. To facilitate processing in the field, this value is normalized
to a DateTime object (2). In the HTML representation of your form, a
localized string (3) is presented to and modified by the user.
So (1) is the app data, (2) is the normalized data and (3) is the client data.
Now, for your question, it depends which data would like to transform. If is the client data you need to transform (from (2) to (3)), then you should use appendClientTransformer or prependClientTransformer.
On the opposite, if you would like to change the normalized data (from (1) to (2)), then you should use appendNormTransformer or prependNormTransformer.
So, normalization transformer sits between (1) and (2) ((1) normalizeTransformer -> (2)). And client transformer sits between (2) and (3) ((2) clientTransformer -> (3))
Also, note that append and prepend methods ([append|prepend][Norm|Client]Transformer) will potentially be replaced by a add methods (add[Norm|Client]Transformer) in Symfony 2.1, see this pull request on GitHub for more information.
Hope this helps,
Matt

optional parameter addition to a colletion (asp.net C#)

Hello friends i am to add optional parameter to pass these in a method the parameter may vary every time.
And i need to pass these parameter to a method, so my question is how should i add these optional parameter to a collection and what kind of collection object should i use and how should i use that.
i elaborate here, i am having following fields.
1)course field(a drop down list) and on selected index change of course a check box list of corresponding branches are visible now i can select branches of choice by putting check mark on check boxes.(both course and branch are compulsory fields)
2)pass_out year which is a compulsory field.(a text field)
3)education gap which is optional so the text box may be empty as well and may having a digit as well.
4)required first year percent, second year, third year, final year, current degree, high school, senior secondary, gradation, post graduation, diploma percent, birth date which are all optional so these fields may also be empty or having a digit in the text box.
5) current backlog(a drop down list)having choices all, yes , no.
6)number of ATKT text box which may also be empty or can have a digit.
So i want to store all these variables value to some collection of object which will passed to a different method by passing all these variable from here,
But i am unable to figure out how should i store these optional variable to some object and how should i pass them to other method where all variable values will be taken out and an appropriate query will be written to interact with the data base to get the data table.
please elucidate me on this please. I am really not getting a feasible solution, i have thought of few options which i can let you know if you demand but those all seems to be tedious and difficult and redundant so i see help from you.
Don't bother with optional parameters or some collection of parameters, just decide how you will represent each value best, including how to represent empty values.
For a string value you can just use a null reference or an empty string. For a numeric value you can use a nullable int (int?). For a list of checkboxes where none is selected you can send an empty list.
When figuring out how to use this in a query to the database, it's easier if you have the values as parameters that always exist even if the values represent an empty value, rather than to have to parse out parameters from a collection where a parameter might be missing. Also, as you have different data types it's better if you can use an appropriate data type for each parameter, instead of casting everything into the same mold just to fit in a collection.

Resources