text
stringlengths
81
112k
Called after the database is brought into a consistent state with this object. def committed(self): """ Called after the database is brought into a consistent state with this object. """ if self.__deleting: self.deleted() if not self.__legacy__: ...
Update the database to reflect in-memory changes made to this item; for example, to make it show up in store.query() calls where it is now valid, but was not the last time it was persisted to the database. This is called automatically when in 'autocommit mode' (i.e. not in a transaction...
Register a callable which can perform a schema upgrade between two particular versions. @param upgrader: A one-argument callable which will upgrade an object. It is invoked with an instance of the old version of the object. @param typeName: The database typename for which this is an upgrader. @par...
Register an upgrader for C{itemType}, from C{fromVersion} to C{toVersion}, which will copy all attributes from the legacy item to the new item. If postCopy is provided, it will be called with the new item after upgrading. @param itemType: L{axiom.item.Item} subclass @param postCopy: a callable of one ...
Register an upgrader for C{itemType}, from C{fromVersion} to C{toVersion}, which will delete the item from the database. @param itemType: L{axiom.item.Item} subclass @return: None def registerDeletionUpgrader(itemType, fromVersion, toVersion): """ Register an upgrader for C{itemType}, from C{fromV...
Does the given table have an explicit oid column? def _hasExplicitOid(store, table): """ Does the given table have an explicit oid column? """ return any(info[1] == 'oid' for info in store.querySchemaSQL( 'PRAGMA *DATABASE*.table_info({})'.format(table)))
Upgrade a table to have an explicit oid. Must be called in a transaction to avoid corrupting the database. def _upgradeTableOid(store, table, createTable, postCreate=lambda: None): """ Upgrade a table to have an explicit oid. Must be called in a transaction to avoid corrupting the database. """ ...
Upgrade the system tables to use explicit oid columns. def upgradeSystemOid(store): """ Upgrade the system tables to use explicit oid columns. """ store.transact( _upgradeTableOid, store, 'axiom_types', lambda: store.executeSchemaSQL(CREATE_TYPES)) store.transact( _upgradeTa...
Upgrade a store to use explicit oid columns. This allows VACUUMing the database without corrupting it. This requires copying all of axiom_objects and axiom_types, as well as all item tables that have not yet been upgraded. Consider VACUUMing the database afterwards to reclaim space. def upgradeE...
Check that all of the accumulated old Item types have a way to get from their current version to the latest version. @raise axiom.errors.NoUpgradePathAvailable: for any, and all, Items that do not have a valid upgrade path def checkUpgradePaths(self): """ Check that all of ...
Queue a type upgrade for C{oldtype}. def queueTypeUpgrade(self, oldtype): """ Queue a type upgrade for C{oldtype}. """ if oldtype not in self._oldTypesRemaining: self._oldTypesRemaining.append(oldtype)
Upgrade a legacy item. @raise axiom.errors.UpgraderRecursion: If the given item is already in the process of being upgraded. def upgradeItem(self, thisItem): """ Upgrade a legacy item. @raise axiom.errors.UpgraderRecursion: If the given item is already in the p...
Upgrade the entire store in batches, yielding after each batch. @param n: Number of upgrades to perform per transaction @type n: C{int} @raise axiom.errors.ItemUpgradeError: if an item upgrade failed @return: A generator that yields after each batch upgrade. This needs to ...
Obtains the lvm, vg_t and lv_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError def open(self): """ Obtains the lvm, vg_t and lv_t handle. Usually y...
Returns the logical volume name. def name(self): """ Returns the logical volume name. """ self.open() name = lvm_lv_get_name(self.__lvh) self.close() return name
Returns True if the logical volume is active, False otherwise. def is_active(self): """ Returns True if the logical volume is active, False otherwise. """ self.open() active = lvm_lv_is_active(self.__lvh) self.close() return bool(active)
Returns True if the logical volume is suspended, False otherwise. def is_suspended(self): """ Returns True if the logical volume is suspended, False otherwise. """ self.open() susp = lvm_lv_is_suspended(self.__lvh) self.close() return bool(susp)
Returns the logical volume size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. def size(self, units="MiB"): """ Returns the logical volume size in the given units. Default units are MiB. *Args:* ...
Activates the logical volume. *Raises:* * HandleError def activate(self): """ Activates the logical volume. *Raises:* * HandleError """ self.open() a = lvm_lv_activate(self.handle) self.close() if a != 0: ...
Deactivates the logical volume. *Raises:* * HandleError def deactivate(self): """ Deactivates the logical volume. *Raises:* * HandleError """ self.open() d = lvm_lv_deactivate(self.handle) self.close() if d != 0: ...
Obtains the lvm, vg_t and pv_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wrappers in conversion.py *Raises:* * HandleError def open(self): """ Obtains the lvm, vg_t and pv_t handle. Usually y...
Returns the physical volume device path. def name(self): """ Returns the physical volume device path. """ self.open() name = lvm_pv_get_name(self.handle) self.close() return name
Returns the physical volume mda count. def mda_count(self): """ Returns the physical volume mda count. """ self.open() mda = lvm_pv_get_mda_count(self.handle) self.close() return mda
Returns the physical volume size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. def size(self, units="MiB"): """ Returns the physical volume size in the given units. Default units are MiB. *Args:...
Returns the device size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. def dev_size(self, units="MiB"): """ Returns the device size in the given units. Default units are MiB. *Args:* * ...
Returns the free size in the given units. Default units are MiB. *Args:* * units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB. def free(self, units="MiB"): """ Returns the free size in the given units. Default units are MiB. *Args:* * uni...
A wrapper function to validate formdata against mongoengine-field validator and raise a proper django.forms ValidationError if there are any problems. def mongoengine_validate_wrapper(old_clean, new_clean): """ A wrapper function to validate formdata against mongoengine-field validator and raise a ...
walk through the available valid fields.. def iter_valid_fields(meta): """walk through the available valid fields..""" # fetch field configuration and always add the id_field as exclude meta_fields = getattr(meta, 'fields', ()) meta_exclude = getattr(meta, 'exclude', ()) meta_exclude += (meta.docu...
This function behaves like L{axiom.attributes.reference} but with an extra behaviour: when this item is installed (via L{axiom.dependency.installOn} on a target item, the type named here will be instantiated and installed on the target as well. For example:: class Foo(Item): counte...
Remove this object from the target, as well as any dependencies that it automatically installed which were not explicitly "pinned" by calling "install", and raising an exception if anything still depends on this. def uninstallFrom(self, target): """ Remove this object from the target, as well as an...
If this item is installed on another item, return the install target. Otherwise return None. def installedOn(self): """ If this item is installed on another item, return the install target. Otherwise return None. """ try: return self.store.findUnique(_DependencyConnector, ...
Return an iterable of things installed on the target that require this item. def installedDependents(self, target): """ Return an iterable of things installed on the target that require this item. """ for dc in self.store.query(_DependencyConnector, _DependencyCon...
Return an iterable of things installed on the target that this item requires and are not required by anything else. def installedUniqueRequirements(self, target): """ Return an iterable of things installed on the target that this item requires and are not required by anything else. """ myDepen...
Return an iterable of things installed on the target that this item requires. def installedRequirements(self, target): """ Return an iterable of things installed on the target that this item requires. """ myDepends = dependentsOf(self.__class__) for dc in self.store.query(_DependencyConnect...
Adapt a store to L{IServiceCollection}. @param st: The L{Store} to adapt. @param pups: A list of L{IServiceCollection} powerups on C{st}. @return: An L{IServiceCollection} which has all of C{pups} as children. def storeServiceSpecialCase(st, pups): """ Adapt a store to L{IServiceCollection}. ...
This function creates (or returns a previously created) L{IScheduler} powerup. If L{IScheduler} powerups were found on C{empowered}, the first of those is given priority. Otherwise, a site L{Store} or a user L{Store} will have any pre-existing L{IScheduler} powerup associated with them (on the hac...
Format a schema mismatch for human consumption. @param diskSchema: The on-disk schema. @param memorySchema: The in-memory schema. @rtype: L{bytes} @return: A description of the schema differences. def _diffSchema(diskSchema, memorySchema): """ Format a schema mismatch for human consumption. ...
Close this file and commit it to its permanent location. @return: a Deferred which fires when the file has been moved (and backed up to tertiary storage, if necessary). def close(self): """ Close this file and commit it to its permanent location. @return: a Deferred which fire...
A debugging API, exposing SQLite's I{EXPLAIN} statement. While this is not a private method, you also probably don't have any use for it unless you understand U{SQLite opcodes<http://www.sqlite.org/opcode.html>} very well. Once you do, it can be handy to call this interactively to get ...
Generate the SQL string which follows the "FROM" string and before the "WHERE" string in the final SQL statement. def _computeFromClause(self, tables): """ Generate the SQL string which follows the "FROM" string and before the "WHERE" string in the final SQL statement. """ ...
Return a generator which yields the massaged results of this query with a particular SQL verb. For an attribute query, massaged results are of the type of that attribute. For an item query, they are items of the type the query is supposed to return. @param verb: a str containi...
This method is deprecated, a holdover from when queries were iterators, rather than iterables. @return: one element of massaged data. def next(self): """ This method is deprecated, a holdover from when queries were iterators, rather than iterables. @return: one element...
Split up the work of gathering a result set into multiple smaller 'pages', allowing very large queries to be iterated without blocking for long periods of time. While simply iterating C{paginate()} is very similar to iterating a query directly, using this method allows the work to obtai...
Convert a row into an Item instance by loading cached items or creating new ones based on query results. @param row: an n-tuple, where n is the number of columns specified by my item type. @return: an instance of the type specified by this query. def _massageData(self, row): "...
Get an L{iaxiom.IQuery} whose results will be values of a single attribute rather than an Item. @param attributeName: a L{str}, the name of a Python attribute, that describes a column on the Item subclass that this query was specified for. @return: an L{AttributeQuery} for the ...
Delete all the Items which are found by this query. def deleteFromStore(self): """ Delete all the Items which are found by this query. """ if (self.limit is None and not isinstance(self.sort, attributes.UnspecifiedOrdering)): # The ORDER BY is pointless here, and...
Return a list of tables involved in this query, first checking that no required tables (those in the query target) have been omitted from the comparison. def _involvedTables(self): """ Return a list of tables involved in this query, first checking that no required tables (those ...
Convert a row into a tuple of Item instances, by slicing it according to the number of columns for each instance, and then proceeding as for ItemQuery._massageData. @param row: an n-tuple, where n is the total number of columns specified by all the item types in this query. @re...
Clone the original query which this distinct query wraps, and return a new wrapper around that clone. def cloneQuery(self, limit=_noItem, sort=_noItem): """ Clone the original query which this distinct query wraps, and return a new wrapper around that clone. """ newq = s...
Count the number of distinct results of the wrapped query. @return: an L{int} representing the number of distinct results. def count(self): """ Count the number of distinct results of the wrapped query. @return: an L{int} representing the number of distinct results. """ ...
Convert a raw database row to the type described by an attribute. For example, convert a database integer into an L{extime.Time} instance for an L{attributes.timestamp} attribute. @param row: a 1-tuple, containing the in-database value from my attribute. @return: a value of th...
Return the sum of all the values returned by this query. If no results are specified, return None. Note: for non-numeric column types the result of this method will be nonsensical. @return: a number or None. def sum(self): """ Return the sum of all the values returned...
Return the average value (as defined by the AVG implementation in the database) of the values specified by this query. Note: for non-numeric column types the result of this method will be nonsensical. @return: a L{float} representing the 'average' value of this column. def average(sel...
attach a child database, returning an identifier for it def _attachChild(self, child): "attach a child database, returning an identifier for it" self._childCounter += 1 databaseName = 'child_db_%d' % (self._childCounter,) self._attachedChildren[databaseName] = child # ATTACH DAT...
Called during __init__. Check consistency of schema in database with classes in memory. Load all Python modules for stored items, and load version information for upgrader service to run later. def _startup(self): """ Called during __init__. Check consistency of schema in database wi...
Usage:: s.findOrCreate(userItemClass [, function] [, x=1, y=2, ...]) Example:: class YourItemType(Item): a = integer() b = text() c = integer() def f(x): print x, \"-- it's new!\" s.findOrCreate(Y...
Open a new file somewhere in this Store's file area. @param path: a sequence of path segments. @return: an L{AtomicFile}. def newFile(self, *path): """ Open a new file somewhere in this Store's file area. @param path: a sequence of path segments. @return: an L{Atomic...
Load all of the stored schema information for all types known by this store. It's important to load everything all at once (rather than loading the schema for each type separately as it is needed) to keep store opening fast. A single query with many results is much faster than many que...
Called for all known types at database startup: make sure that what we know (in memory) about this type agrees with what is stored about this type in the database. @param actualType: A L{MetaItem} instance which is associated with a table in this store. The schema it defines in mem...
Note that this database contains old versions of a particular type. Create the appropriate dummy item subclass and queue the type to be upgraded. @param typename: The I{typeName} associated with the schema for which to create a dummy item class. @param version: The I{schema...
Find an Item in the database which should be unique. If it is found, return it. If it is not found, return 'default' if it was passed, otherwise raise L{errors.ItemNotFound}. If more than one item is found, raise L{errors.DuplicateUniqueItem}. @param comparison: implementor of L{iaxi...
Usage:: s.findFirst(tableClass [, query arguments except 'limit']) Example:: class YourItemType(Item): a = integer() b = text() c = integer() ... it = s.findFirst(YourItemType, AND(You...
Return a generator of instances of C{tableClass}, or tuples of instances if C{tableClass} is a tuple of classes. Examples:: fastCars = s.query(Vehicle, axiom.attributes.AND( Vehicle.wheels == 4, Vehicle.maxKPH > 200), ...
Create multiple items in the store without loading corresponding Python objects into memory. the items' C{stored} callback will not be called. Example:: myData = [(37, u"Fred", u"Wichita"), (28, u"Jim", u"Fresno"), (43, u"Betty", u"Du...
An item in this store was changed. Add it to the current transaction's list of changed items, if a transaction is currently underway, or raise an exception if this L{Store} is currently in a state which does not allow changes. def changed(self, item): """ An item in this store ...
Execute C{f(*a, **k)} in the context of a database transaction. Any changes made to this L{Store} by C{f} will be committed when C{f} returns. If C{f} raises an exception, those changes will be reverted instead. If a transaction is already in progress (in this thread - ie, if a ...
Return the unqualified (ie, no database name) name of the given attribute of the given table. @type tableClass: L{MetaItem} @param tableClass: The Python class associated with a table in the database. @param attrname: A sequence of the names of the columns of the ...
Retrieve the fully qualified name of the table holding items of a particular class in this store. If the table does not exist in the database, it will be created as a side-effect. @param tableClass: an Item subclass @raises axiom.errors.ItemClassesOnly: if an object other than a ...
Retreive the fully qualified column name for a particular attribute in this store. The attribute must be bound to an Item subclass (its type must be valid). If the underlying table does not exist in the database, it will be created as a side-effect. @param tableClass: an Item s...
Retrieve the typeID associated with a particular table in the in-database schema for this Store. A typeID is an opaque integer representing the Item subclass, and the associated table in this Store's SQLite database. @param tableClass: a subclass of Item @return: an integer d...
Execute the table creation DDL for an Item subclass. Indexes are *not* created. @type tableClass: type @param tableClass: an Item subclass def _justCreateTable(self, tableClass): """ Execute the table creation DDL for an Item subclass. Indexes are *not* created. ...
A type ID has been requested for an Item subclass whose table was not present when this Store was opened. Attempt to create the table, and if that fails because another Store object (perhaps in another process) has created the table, re-read the schema. When that's done, return the typ...
Create any indexes which don't exist and are required by the schema defined by C{tableClass}. @param tableClass: A L{MetaItem} instance which may define a schema which includes indexes. @param extantIndexes: A container (anything which can be the right-hand argument to ...
Retrieve an item by its storeID, and return it. Note: most of the failure modes of this method are catastrophic and should not be handled by application code. The only one that application programmers should be concerned with is KeyError. They are listed for educational purposes. ...
For use with SELECT (or SELECT-like PRAGMA) statements. def querySQL(self, sql, args=()): """For use with SELECT (or SELECT-like PRAGMA) statements. """ if self.debug: result = timeinto(self.queryTimes, self._queryandfetch, sql, args) else: result = self._queryan...
For use with auto-committing statements such as CREATE TABLE or CREATE INDEX. def createSQL(self, sql, args=()): """ For use with auto-committing statements such as CREATE TABLE or CREATE INDEX. """ before = time.time() self._execSQL(sql, args) after = ti...
For use with UPDATE or INSERT statements. def executeSQL(self, sql, args=()): """ For use with UPDATE or INSERT statements. """ sql = self._execSQL(sql, args) result = self.cursor.lastRowID() if self.executedThisTransaction is not None: self.executedThisTrans...
given a filename to a file containing a __counter__ variable, open it, read the count, add one, rewrite the file. This: __counter__=123 Becomes: __counter__=124 def updateVersion(fname): """ given a filename to a file containing a __counter__ variable, open it, read the count, ...
Add the scheduler attribute to the given L{_SubSchedulerParentHook}. def upgradeParentHook1to2(oldHook): """ Add the scheduler attribute to the given L{_SubSchedulerParentHook}. """ newHook = oldHook.upgradeVersion( oldHook.typeName, 1, 2, loginAccount=oldHook.loginAccount, sche...
Copy C{loginAccount} to C{subStore} and remove the installation marker. def upgradeParentHook3to4(old): """ Copy C{loginAccount} to C{subStore} and remove the installation marker. """ new = old.upgradeVersion( old.typeName, 3, 4, subStore=old.loginAccount) uninstallFrom(new, new.store) ...
Run my runnable, and reschedule or delete myself based on its result. Must be run in a transaction. def invokeRunnable(self): """ Run my runnable, and reschedule or delete myself based on its result. Must be run in a transaction. """ runnable = self.runnable if r...
An error occurred running my runnable. Check my runnable for an error-handling method called 'timedEventErrorHandler' that will take the given failure as an argument, and execute that if available: otherwise, create a TimedEventFailureLog with information about what happened to this eve...
Remove from given item from the schedule. If runnable is scheduled to run multiple times, only the temporally first is removed. def unscheduleFirst(self, runnable): """ Remove from given item from the schedule. If runnable is scheduled to run multiple times, only the temporall...
Return an iterable of the times at which the given item is scheduled to run. def scheduledTimes(self, runnable): """ Return an iterable of the times at which the given item is scheduled to run. """ events = self.store.query( TimedEvent, TimedEvent.runnable ==...
Start calling persistent timed events whose time has come. def startService(self): """ Start calling persistent timed events whose time has come. """ super(_SiteScheduler, self).startService() self._transientSchedule(self.now(), self.now())
Stop calling persistent timed events. def stopService(self): """ Stop calling persistent timed events. """ super(_SiteScheduler, self).stopService() if self.timer is not None: self.timer.cancel() self.timer = None
If the service is currently running, schedule a tick to happen no later than C{when}. @param when: The time at which to tick. @type when: L{epsilon.extime.Time} @param now: The current time. @type now: L{epsilon.extime.Time} def _transientSchedule(self, when, now): """...
If this service's store is attached to its parent, ask the parent to schedule this substore to tick at the given time. @param when: The time at which to tick. @type when: L{epsilon.extime.Time} @param now: Present for signature compatibility with L{_SiteScheduler._transient...
Remove the components in the site store for this SubScheduler. def migrateDown(self): """ Remove the components in the site store for this SubScheduler. """ subStore = self.store.parent.getItemByID(self.store.idInParent) ssph = self.store.parent.findUnique( _SubSched...
Recreate the hooks in the site store to trigger this SubScheduler. def migrateUp(self): """ Recreate the hooks in the site store to trigger this SubScheduler. """ te = self.store.findFirst(TimedEvent, sort=TimedEvent.time.descending) if te is not None: self._transien...
Whenever L{Scheduler} or L{SubScheduler} is created, either newly or when loaded from a database, emit a deprecation warning referring people to L{IScheduler}. def activate(self): """ Whenever L{Scheduler} or L{SubScheduler} is created, either newly or when loaded from a databas...
Ensure that this hook is scheduled to run at or before C{when}. def _schedule(self, when): """ Ensure that this hook is scheduled to run at or before C{when}. """ sched = IScheduler(self.store) for scheduledAt in sched.scheduledTimes(self): if when < scheduledAt: ...
Tokenize a text, index a term matrix, and build out a graph. Args: path (str): The file path. term_depth (int): Consider the N most frequent terms. skim_depth (int): Connect each word to the N closest siblings. d_weights (bool): If true, give "close" nodes low weights. Returns:...
Render a spring layout. def draw_spring(self, **kwargs): """ Render a spring layout. """ nx.draw_spring( self.graph, with_labels=True, font_size=10, edge_color='#dddddd', node_size=0, **kwargs ) p...
1. For each term in the passed matrix, score its KDE similarity with all other indexed terms. 2. With the ordered stack of similarities in hand, skim off the top X pairs and add them as edges. Args: text (Text): The source text instance. matrix (Matrix): An inde...
Gets a named section from the configuration source. :param section: a :class:`str` representing the section you want to retrieve from the configuration source. If ``None`` this will fallback to the :attr:`plaster.PlasterURL.fragment`. :param defaults: a :class:`dict` that will g...
Reads the configuration source and finds and loads a WSGI application defined by the entry with name ``name`` per the PasteDeploy configuration format and loading mechanism. :param name: The named WSGI app to find, load and return. Defaults to ``None`` which becomes ``main`` inside ...
Reads the configuration source and finds and loads a WSGI server defined by the server entry with the name ``name`` per the PasteDeploy configuration format and loading mechanism. :param name: The named WSGI server to find, load and return. Defaults to ``None`` which becomes ``main`...
Reads the configuration soruce and finds and loads a WSGI filter defined by the filter entry with the name ``name`` per the PasteDeploy configuration format and loading mechanism. :param name: The named WSGI filter to find, load and return. Defaults to ``None`` which becomes ``main`...
Return an :class:`collections.OrderedDict` representing the application config for a WSGI application named ``name`` in the PasteDeploy config file specified by ``self.uri``. ``defaults``, if passed, should be a dictionary used as variable assignments like ``{'http_port': 8080}``. This...