def toXml(self, xparent): """ Saves the index data for this column to XML. :param xparent | <xml.etree.ElementTree.Element> :return <xml.etree.ElementTree.Element> """ xpipe = ElementTree.SubElement(xparent, 'pipe') xpipe.set('name', self.name()) if self._unique: xpipe.set('unique', 'True') if self.cached(): xpipe.set('cached', nstr(self.cached())) xpipe.set('timeout', nstr(self._cacheTimeout)) ElementTree.SubElement(xpipe, 'through').text = self._pipeReference ElementTree.SubElement(xpipe, 'source').text = self._sourceColumn ElementTree.SubElement(xpipe, 'target').text = self._targetColumn if self._targetReference: ElementTree.SubElement(xpipe, 'table').text = self._targetReference return xpipe
def toXml(self, xparent): """ Saves this database instance to xml under the inputted parent. :param xparent | <xml.etree.ElementTree.Element> :return <xml.etree.ElementTree.Element> """ xdatabase = ElementTree.SubElement(xparent, 'database') xdatabase.set('name', self._name) xdatabase.set('default', nstr(self._default)) xdatabase.set('timeout', str(self._maximumTimeout)) if self.databaseType(): xdatabase.set('type', self.databaseType()) if self._host: ElementTree.SubElement(xdatabase, 'host').text = nstr(self._host) if self._port: ElementTree.SubElement(xdatabase, 'port').text = nstr(self._port) if self._username: ElementTree.SubElement(xdatabase, 'username').text = self._username if self._password: ElementTree.SubElement(xdatabase, 'password').text = self._password if self._databaseName: ElementTree.SubElement(xdatabase, 'dbname').text = self._databaseName if self._applicationToken: ElementTree.SubElement(xdatabase, 'token').text = self._applicationToken return xdatabase
def dropEvent(self, event): """ Listens for query's being dragged and dropped onto this tree. :param event | <QDropEvent> """ # overload the current filtering options data = event.mimeData() if data.hasFormat('application/x-orb-table') and \ data.hasFormat('application/x-orb-query'): tableName = self.tableTypeName() if nstr(data.data('application/x-orb-table')) == tableName: data = nstr(data.data('application/x-orb-query')) query = Q.fromXmlString(data) self.setQuery(query) return elif self.tableType() and data.hasFormat('application/x-orb-records'): from projexui.widgets.xorbtreewidget import XOrbTreeWidget records = XOrbTreeWidget.dataRestoreRecords(data) for record in records: if isinstance(record, self.tableType()): self.setCurrentRecord(record) return super(XOrbRecordBox, self).dropEvent(event)
def restore(self, column, db_value): """ Restores the inputted value from the database to a Python value. :param column | <orb.Column> db_value | <variant> :return <variant> | python value """ if not column: return db_value col_type = orb.ColumnType.base(column.columnType()) if db_value is None: return db_value elif col_type == orb.ColumnType.Pickle: try: return cPickle.loads(nstr(db_value)) except StandardError: raise orb.errors.DataStoreError('Failed to restore pickle.') elif col_type == orb.ColumnType.Yaml: try: return yaml.loads(nstr(db_value)) except StandardError: raise orb.errors.DataStoreError('Failed to restore yaml.') elif col_type == orb.ColumnType.JSON: try: return projex.rest.unjsonify(db_value) except StandardError: raise orb.errors.DataStoreError('Failed to restore JSON.') elif col_type == orb.ColumnType.Query: if type(db_value) == dict: return orb.Query.fromDict(db_value) else: try: return orb.Query.fromXmlString(nstr(db_value)) except StandardError: raise orb.errors.DataStoreError('Failed to restore query.') elif col_type in (orb.ColumnType.Timestamp, orb.ColumnType.Timestamp_UTC): if isinstance(db_value, (int, float)): return datetime.datetime.fromtimestamp(db_value) elif col_type == orb.ColumnType.Dict: return projex.rest.unjsonify(nstr(db_value)) elif column.isString(): return projex.text.decoded(db_value) elif type(db_value) == decimal.Decimal: return float(db_value) else: return db_value
def setProperty(self, prop, value): """ Sets the custom property to the inputted value. :param prop | <str> value | <str> """ self._properties[nstr(prop)] = nstr(value)
def setProperty(self, key, value): """ Sets the property value for the given key, value pairing. :param key | <str> value | <str> """ self._properties[nstr(key)] = nstr(value)
def add_sub_element(field, value): if isinstance(value, tuple): attrib, value = value attrib = dict((k, nstr(v)) for k, v in attrib.iteritems()) else: attrib = {} sub_element = ElementTree.SubElement(request, field, **attrib) sub_element.text = nstr(value)
def property(self, key, default=''): """ Returns the property value for the inputted key string. :param key | <str> default | <str> :return <str> """ return self._properties.get(nstr(key), nstr(default))
def convert(self, value): """ Converts the inputted value to a Python value. :param value | <variant> :return <variant> """ val_name = type(value).__name__ if val_name == 'QString': return nstr(value.toUtf8()) elif val_name == 'QVariant': return value.toPyObject() elif val_name == 'QDate': return value.toPyDate() elif val_name == 'QDateTime': return value.toPyDateTime() elif val_name == 'QTime': return value.toPyTime() elif val_name == 'QColor': return value.name() elif val_name == 'QIcon': try: pixmap = value.pixmap(value.actualSize(QtCore.QSize(256, 256))) arr = QtCore.QByteArray() buf = QtCore.QBuffer() buf.setBuffer(arr) buf.open(QtCore.QBuffer.WriteOnly) pixmap.save(buf, 'PNG') buf.close() return binascii.b2a_base64(nstr(arr)) except ImportError: log.error('Cannot store QIcon, xqt.QtCore not defined.') elif val_name == 'QPixmap': try: arr = QtCore.QByteArray() buf = QtCore.QBuffer() buf.setBuffer(arr) buf.open(QtCore.QBuffer.WriteOnly) value.save(buf, 'PNG') buf.close() return binascii.b2a_base64(nstr(arr)) except ImportError: log.error('Cannot store QPixmap, xqt.QtCore not defined.') return super(QDataConverter, self).convert(value)
def addset(self, wordset): """ Defines a wordset that will be used as a grouping of synonyms within the thesaurus. A wordset is a comma separated list of synonyms. :param wordset | <str> || <list> || <set> """ if type(wordset) in (list, tuple, set): wordset = set([nstr(word) for word in wordset]) else: wordset = set(nstr(wordset).split(',')) self._wordsets.append(wordset)
def toXml(self, xparent): """ Converts this environment to XML data and returns it. :param xparent | <xml.etree.ElementTree.Element> """ xenv = ElementTree.SubElement(xparent, 'environment') xenv.set('name', nstr(self.name())) xenv.set('default', nstr(self.isDefault())) ElementTree.SubElement(xenv, 'description').text = self.description() xdbs = ElementTree.SubElement(xenv, 'databases') for db in self._databases.values(): db.toXml(xdbs) return xenv
def setName(self, name): """ Sets the database name for this instance to the given name. :param databaseName <str> """ self._name = nstr(name)
def setPassword(self, password): """ Sets the password for the connection for this database. :param password <str> """ self._password = nstr(password)
def setRootUrl(self, url): """ Sets the root url for the url handler to the inputted url. :param url | <str> """ self._rootUrl = nstr(url)
def setName(self, name): """ Sets the name for this index to this index. :param name | <str> """ self.__name__ = nstr(name)
def setStaticUrl(self, url): """ Sets the static url for the handler to the inputted url. :param url | <str> """ self._staticUrl = nstr(url)
def recordCommand(column, value): """ Converts the inputted value from a record instance to a mongo id pointer, provided the value is a table type. If not, the inputted value is returned unchanged. :param column | <orb.Column> value | <variant> :return <variant> """ # handle conversions of non record values to mongo object ids when # necessary if not (orb.Table.recordcheck(value) or orb.View.recordcheck(value)): return value pkey = value.primaryKey() if not pkey: raise errors.PrimaryKeyNotDefined(value) if type(pkey) in (list, tuple, set): if len(pkey) == 1: pkey = pkey[0] else: pkey = tuple(pkey) return nstr(pkey)
def setUsername(self, username): """ Sets the username used for this database connection. :param username <str> """ self.__username = nstr(username)
def __init__(self, column): try: text = column.name() except AttributeError: text = nstr(column) super(ColumnRequired, self).__init__('{0} is a required column.'.format(text))
def setDatabaseName(self, databaseName): """ Sets the database name that this schema will be linked to. :param databaseName | <str> """ self._databaseName = nstr(databaseName)
def setName(self, name): """ Sets the name for this environment to the inputted name. :param name | <str> """ self._name = nstr(name)
def saveAs(self, filename, encrypted=False): """ Saves the current orb structure out to the inputted file. :param filename | <str> encrypted | <bool> :return <bool> | success """ if not filename: return False filename = nstr(filename) xorb = ElementTree.Element('orb') xorb.set('version', orb.__version__) # save out references xrefs = ElementTree.SubElement(xorb, 'references') for ref_file in sorted(self._referenceFiles): rel_path = os.path.relpath(ref_file, filename) xref = ElementTree.SubElement(xrefs, 'reference') xref.set('path', rel_path) # save out properties xprops = ElementTree.SubElement(xorb, 'properties') for key, value in sorted(self._properties.items()): xprop = ElementTree.SubElement(xprops, 'property') xprop.set('key', key) xprop.set('value', value) # save out the environments xenvs = ElementTree.SubElement(xorb, 'environments') for env in sorted(self.environments(), key=lambda x: x.name()): if not env.isReferenced(): env.toXml(xenvs) # save out the global databases xdbs = ElementTree.SubElement(xorb, 'databases') for db in sorted(self.databases(), key=lambda x: x.name()): if not db.isReferenced(): db.toXml(xdbs) # save out the groups xgroups = ElementTree.SubElement(xorb, 'groups') for grp in sorted(self.groups(), key=lambda x: x.name()): if grp.isReferenced(): continue grp.toXml(xgroups) projex.text.xmlindent(xorb) data = ElementTree.tostring(xorb) if encrypted: data = self.encrypt(data) f = open(filename, 'w') f.write(data) f.close() return True
def __hash__(self): """ Returns a hash representation for this instance. :return <hash> """ return hash(nstr(self))
def splitterms(self, text): """ Splits the inputted search text into search terms. This will use the phrasing patterns within this thesaurus to determine groups of words. :param text | <str> :return [<str>, ..] """ text = nstr(text) repl = [] # pre-process all phrases into their own groups for phrase in self.phrases(): grp = re.search(phrase, text) while grp and grp.group(): result = grp.group() text = text.replace(result, '`REGEXGRP{0}`'.format(len(repl))) repl.append(result) grp = re.search(phrase, text) # split the terms into their own words, grouped together with phrases output = [] for term in text.split(): term = term.strip() grp = re.match('`REGEXGRP(\d+)`(.*)', term) if grp: index, remain = grp.groups() term = repl[int(index)] + remain output.append(term) return output
def setDatabaseType(self, databaseType): """ Sets the database type that will be used for this instance. :param databaseType | <str> """ self._databaseType = nstr(databaseType)
def remove(self, word, synonym): """ Removes a given synonym from the inputted word in a wordset. :param word | <str> synonym | <str> """ word = nstr(word) synonym = nstr(synonym) for wordset in self._wordsets: if word in wordset: try: wordset.remove(synonym) except KeyError: pass return
def setProperty(self, key, value): """ Sets the custom data at the given key to the inputted value. :param key | <str> value | <variant> """ self._properties[nstr(key)] = value
def setTableLookupIndex(self, index): """ Sets the name of the index method that will be used to lookup records for this combo box. :param index | <str> """ self._tableLookupIndex = nstr(index)
def add(self, word, synonym): """ Adds a new synonym for a given word. :param word | <str> synonym | <str> """ word = nstr(word) synonym = nstr(synonym) # lookup wordsets for wordset in self._wordsets: if word in wordset: wordset.add(synonym) # define new wordset self._wordsets.append({word, synonym})
def __init__(self, column): try: text = column.name() except AttributeError: text = nstr(column) msg = '{0} is a foreign key with no reference table.' super(ReferenceNotFound, self).__init__(msg.format(text))
def property(self, propname, default=''): """ Returns the property value for this manager from the given name. \ If no property is set, then the default value will be returned. :return <str> """ return self._properties.get(propname, nstr(default))
def setTableTypeName(self, name): """ Sets the table type name for this record box to the inputed name. :param name | <str> """ self._tableTypeName = nstr(name) self._tableType = None
def __init__(self, column): try: text = column.name() except AttributeError: text = nstr(column) super(ColumnRequired, self).__init__(u'{0} is a required column.'.format(text))
def __init__(self, column): try: text = column.name() except AttributeError: text = nstr(column) msg = u'{0} is a foreign key with no reference table.' super(ReferenceNotFound, self).__init__(msg.format(text))
def setHost(self, host): """ Sets the host path location assigned to this database object. :param host <str> """ self._host = nstr(host)
def __init__(self, column): try: text = column.name() except AttributeError: text = nstr(column) super(ColumnReadOnly, self).__init__('{0} is a read-only column.'.format(text))
def setStringFormat(self, text): """ Sets a string format to be used when rendering a view using the str() method. This is a python string format with dictionary keys for the column values that you want to display. :param format | <str> """ self._stringFormat = nstr(text)