INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Called by the validating_wrapper in the first step ( a ) apply_on_each_func_args for each function input before executing the function. It simply delegates to the validator. The signature of this function is hardcoded to correspond to apply_on_each_func_args s behaviour and should therefore not be changed. | def _assert_input_is_valid(input_value, # type: Any
validators, # type: List[InputValidator]
validated_func, # type: Callable
input_name # type: str
):
"""
Called by the `validating_wrappe... |
Overrides the base behaviour defined in ValidationError in order to add details about the function.: return: | def get_what_txt(self):
"""
Overrides the base behaviour defined in ValidationError in order to add details about the function.
:return:
"""
return 'input [{var}] for function [{func}]'.format(var=self.get_variable_str(),
... |
Overrides the base behaviour defined in ValidationError in order to add details about the class field.: return: | def get_what_txt(self):
"""
Overrides the base behaviour defined in ValidationError in order to add details about the class field.
:return:
"""
return 'field [{field}] for class [{clazz}]'.format(field=self.get_variable_str(),
... |
Generate unique nonce with counter uuid and rng. | def generate_nonce_timestamp():
""" Generate unique nonce with counter, uuid and rng."""
global count
rng = botan.rng().get(30)
uuid4 = uuid.uuid4().bytes # 16 byte
tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng
nonce = tmpnonce[:41] # 41 byte (328 bit)
count += 1
return ... |
recursively merges dict s. not just simple a [ key ] = b [ key ] if both a and bhave a key who s value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. | def dict_merge(*dict_list):
"""recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.
"""
result = collections.defaultdict(dict)
dicts_items = itert... |
Dispatch jobs to remotecis. | def schedule_jobs(user):
"""Dispatch jobs to remotecis.
The remoteci can use this method to request a new job.
Before a job is dispatched, the server will flag as 'killed' all the
running jobs that were associated with the remoteci. This is because they
will never be finished.
"""
values ... |
Create a new job in the same topic as the job_id provided and associate the latest components of this topic. | def create_new_update_job_from_an_existing_job(user, job_id):
"""Create a new job in the same topic as the job_id provided and
associate the latest components of this topic."""
values = {
'id': utils.gen_uuid(),
'created_at': datetime.datetime.utcnow().isoformat(),
'updated_at': dat... |
Create a new job in the next topic of the topic of the provided job_id. | def create_new_upgrade_job_from_an_existing_job(user):
"""Create a new job in the 'next topic' of the topic of
the provided job_id."""
values = schemas.job_upgrade.post(flask.request.json)
values.update({
'id': utils.gen_uuid(),
'created_at': datetime.datetime.utcnow().isoformat(),
... |
Get all jobs. | def get_all_jobs(user, topic_id=None):
"""Get all jobs.
If topic_id is not None, then return all the jobs with a topic
pointed by topic_id.
"""
# get the diverse parameters
args = schemas.args(flask.request.args.to_dict())
# build the query thanks to the QueryBuilder class
query = v1_u... |
Update a job | def update_job_by_id(user, job_id):
"""Update a job
"""
# get If-Match header
if_match_etag = utils.check_and_get_etag(flask.request.headers)
# get the diverse parameters
values = schemas.job.put(flask.request.json)
job = v1_utils.verify_existence_and_get(job_id, _TABLE)
job = dict(job... |
Get all results from job. | def get_all_results_from_jobs(user, j_id):
"""Get all results from job.
"""
job = v1_utils.verify_existence_and_get(j_id, _TABLE)
if not user.is_in_team(job['team_id']) and not user.is_read_only_user():
raise dci_exc.Unauthorized()
# get testscases from tests_results
query = sql.selec... |
Retrieve all tags attached to a job. | def get_tags_from_job(user, job_id):
"""Retrieve all tags attached to a job."""
job = v1_utils.verify_existence_and_get(job_id, _TABLE)
if not user.is_in_team(job['team_id']) and not user.is_read_only_user():
raise dci_exc.Unauthorized()
JTT = models.JOIN_JOBS_TAGS
query = (sql.select([mod... |
Add a tag to a job. | def add_tag_to_job(user, job_id):
"""Add a tag to a job."""
job = v1_utils.verify_existence_and_get(job_id, _TABLE)
if not user.is_in_team(job['team_id']):
raise dci_exc.Unauthorized()
values = {
'job_id': job_id
}
job_tagged = tags.add_tag_to_resource(values, models.JOIN_JOBS... |
Delete a tag from a job. | def delete_tag_from_job(user, job_id, tag_id):
"""Delete a tag from a job."""
_JJT = models.JOIN_JOBS_TAGS
job = v1_utils.verify_existence_and_get(job_id, _TABLE)
if not user.is_in_team(job['team_id']):
raise dci_exc.Unauthorized()
v1_utils.verify_existence_and_get(tag_id, models.TAGS)
... |
Return the parent of the given node based on an internal dictionary mapping of child nodes to the child s parent required since ElementTree doesn t make info about node ancestry/ parentage available. | def _lookup_node_parent(self, node):
"""
Return the parent of the given node, based on an internal dictionary
mapping of child nodes to the child's parent required since
ElementTree doesn't make info about node ancestry/parentage available.
"""
# Basic caching of our inte... |
Return True if the given node is an ElementTree Element a fact that can be tricky to determine if the cElementTree implementation is used. | def _is_node_an_element(self, node):
"""
Return True if the given node is an ElementTree Element, a fact that
can be tricky to determine if the cElementTree implementation is
used.
"""
# Try the simplest approach first, works for plain old ElementTree
if isinstanc... |
Return result of performing the given XPath query on the given node. | def xpath_on_node(self, node, xpath, **kwargs):
"""
Return result of performing the given XPath query on the given node.
All known namespace prefix-to-URI mappings in the document are
automatically included in the XPath invocation.
If an empty/default namespace (i.e. None) is d... |
List the entries to be purged from the database. | def get_to_purge_archived_resources(user, table):
"""List the entries to be purged from the database. """
if user.is_not_super_admin():
raise dci_exc.Unauthorized()
archived_resources = get_archived_resources(table)
return flask.jsonify({table.name: archived_resources,
... |
Remove the entries to be purged from the database. | def purge_archived_resources(user, table):
"""Remove the entries to be purged from the database. """
if user.is_not_super_admin():
raise dci_exc.Unauthorized()
where_clause = sql.and_(
table.c.state == 'archived'
)
query = table.delete().where(where_clause)
flask.g.db_conn.exec... |
Refresh the resource API Secret. | def refresh_api_secret(user, resource, table):
"""Refresh the resource API Secret. """
resource_name = table.name[0:-1]
where_clause = sql.and_(
table.c.etag == resource['etag'],
table.c.id == resource['id'],
)
values = {
'api_secret': signature.gen_secret(),
'etag... |
Generate a package. json file. | def npm(package_json, output_file, pinned_file):
"""Generate a package.json file."""
amd_build_deprecation_warning()
try:
version = get_distribution(current_app.name).version
except DistributionNotFound:
version = ''
output = {
'name': current_app.name,
'version': ma... |
Returns a list of the latest root cause analysis results for a specified check. | def getAnalyses(self, **kwargs):
"""Returns a list of the latest root cause analysis results for a
specified check.
Optional Parameters:
* limit -- Limits the number of returned results to the
specified quantity.
Type: Integer
... |
Update check details returns dictionary of details | def getDetails(self):
"""Update check details, returns dictionary of details"""
response = self.pingdom.request('GET', 'checks/%s' % self.id)
self.__addDetails__(response.json()['check'])
return response.json()['check'] |
Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value provide an empty value. Please note that you cannot change the type of a check once it has been created. | def modify(self, **kwargs):
"""Modify settings for a check. The provided settings will overwrite
previous values. Settings not provided will stay the same as before
the update. To clear an existing value, provide an empty value.
Please note that you cannot change the type of ... |
Get the average time/ uptime value for a specified check and time period. | def averages(self, **kwargs):
"""Get the average time / uptime value for a specified check and time
period.
Optional parameters:
* time_from -- Start time of period. Format is UNIX timestamp
Type: Integer
Default: 0
* time_to... |
Get a list of probes that performed tests for a specified check during a specified period. | def probes(self, fromtime, totime=None):
"""Get a list of probes that performed tests for a specified check
during a specified period."""
args = {'from': fromtime}
if totime:
args['to'] = totime
response = self.pingdom.request('GET', 'summary.probes/%s' % self.i... |
Activate public report for this check. | def publishPublicReport(self):
"""Activate public report for this check.
Returns status message"""
response = self.pingdom.request('PUT', 'reports.public/%s' % self.id)
return response.json()['message'] |
Deactivate public report for this check. | def removePublicReport(self):
"""Deactivate public report for this check.
Returns status message"""
response = self.pingdom.request('DELETE',
'reports.public/%s' % self.id)
return response.json()['message'] |
Extract the dependencies from the bundle and its sub - bundles. | def extract_deps(bundles, log=None):
"""Extract the dependencies from the bundle and its sub-bundles."""
def _flatten(bundle):
deps = []
if hasattr(bundle, 'npm'):
deps.append(bundle.npm)
for content in bundle.contents:
if isinstance(content, BundleBase):
... |
Make a semantic version from Python PEP440 version. | def make_semver(version_str):
"""Make a semantic version from Python PEP440 version.
Semantic versions does not handle post-releases.
"""
v = parse_version(version_str)
major = v._version.release[0]
try:
minor = v._version.release[1]
except IndexError:
minor = 0
try:
... |
Calculate the max number of item that an option can stored in the pool at give time. | def get_max_size(pool, num_option, item_length):
"""
Calculate the max number of item that an option can stored in the pool at give time.
This is to limit the pool size to POOL_SIZE
Args:
option_index (int): the index of the option to calculate the size for
pool (dict): answer pool
... |
submit a student answer to the answer pool | def offer_answer(pool, answer, rationale, student_id, algo, options):
"""
submit a student answer to the answer pool
The answer maybe selected to stay in the pool depending on the selection algorithm
Args:
pool (dict): answer pool
Answer pool format:
{
o... |
The simple selection algorithm. | def offer_simple(pool, answer, rationale, student_id, options):
"""
The simple selection algorithm.
This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches
the limit
"""
existing = pool.setdefault(answer, {})
if len(existing) >= get_max_si... |
The random selection algorithm. The same as simple algorithm | def offer_random(pool, answer, rationale, student_id, options):
"""
The random selection algorithm. The same as simple algorithm
"""
offer_simple(pool, answer, rationale, student_id, options) |
This validator checks if the answers includes all possible options | def validate_seeded_answers_simple(answers, options, algo):
"""
This validator checks if the answers includes all possible options
Args:
answers (str): the answers to be checked
options (dict): all options that should exist in the answers
algo (str): selection algorithm
Returns... |
Validate answers based on selection algorithm | def validate_seeded_answers(answers, options, algo):
"""
Validate answers based on selection algorithm
This is called when instructor setup the tool and providing seeded answers to the question.
This function is trying to validate if instructor provided enough seeds for a give algorithm.
e.g. we re... |
Select other student s answers from answer pool or seeded answers based on the selection algorithm | def get_other_answers(pool, seeded_answers, get_student_item_dict, algo, options):
"""
Select other student's answers from answer pool or seeded answers based on the selection algorithm
Args:
pool (dict): answer pool, format:
{
option1_index: {
studen... |
Get answers from others with simple algorithm which picks one answer for each option. | def get_other_answers_simple(pool, seeded_answers, get_student_item_dict, num_responses):
"""
Get answers from others with simple algorithm, which picks one answer for each option.
Args:
see `get_other_answers`
num_responses (int): the number of responses to be returned. This value may not ... |
Get answers from others with random algorithm which randomly select answer from the pool. | def get_other_answers_random(pool, seeded_answers, get_student_item_dict, num_responses):
"""
Get answers from others with random algorithm, which randomly select answer from the pool.
Student may get three answers for option 1 or one answer for option 1 and two answers for option 2.
Args:
see... |
Convert seeded answers into the format that can be merged into student answers. | def convert_seeded_answers(answers):
"""
Convert seeded answers into the format that can be merged into student answers.
Args:
answers (list): seeded answers
Returns:
dict: seeded answers with student answers format:
{
0: {
'seeded0': 'ra... |
Batch processors stopped polling at version 2 so they no longer needed the idleInterval attribute. They also gained a scheduled attribute which tracks their interaction with the scheduler. Since they stopped polling we also set them up as a timed event here to make sure that they don t silently disappear never to be se... | def upgradeProcessor1to2(oldProcessor):
"""
Batch processors stopped polling at version 2, so they no longer needed the
idleInterval attribute. They also gained a scheduled attribute which
tracks their interaction with the scheduler. Since they stopped polling,
we also set them up as a timed event... |
Create an Axiom Item type which is suitable to use as a batch processor for the given Axiom Item type. | def processor(forType):
"""
Create an Axiom Item type which is suitable to use as a batch processor for
the given Axiom Item type.
Processors created this way depend on a L{iaxiom.IScheduler} powerup on the
on which store they are installed.
@type forType: L{item.MetaItem}
@param forType: ... |
Adapt a L { Store } to L { IBatchService }. | def storeBatchServiceSpecialCase(st, pups):
"""
Adapt a L{Store} to L{IBatchService}.
If C{st} is a substore, return a simple wrapper that delegates to the site
store's L{IBatchService} powerup. Return C{None} if C{st} has no
L{BatchProcessingControllerService}.
"""
if st.parent is not Non... |
Mark the unit of work as failed in the database and update the listener so as to skip it next time. | def mark(self):
"""
Mark the unit of work as failed in the database and update the listener
so as to skip it next time.
"""
self.reliableListener.lastRun = extime.Time()
BatchProcessingError(
store=self.reliableListener.store,
processor=self.reliab... |
Try to run one unit of work through one listener. If there are more listeners or more work reschedule this item to be run again in C { self. busyInterval } milliseconds otherwise unschedule it. | def run(self):
"""
Try to run one unit of work through one listener. If there are more
listeners or more work, reschedule this item to be run again in
C{self.busyInterval} milliseconds, otherwise unschedule it.
@rtype: L{extime.Time} or C{None}
@return: The next time at... |
Add the given Item to the set which will be notified of Items available for processing. | def addReliableListener(self, listener, style=iaxiom.LOCAL):
"""
Add the given Item to the set which will be notified of Items
available for processing.
Note: Each Item is processed synchronously. Adding too many
listeners to a single batch processor will cause the L{step}
... |
Remove a previously added listener. | def removeReliableListener(self, listener):
"""
Remove a previously added listener.
"""
self.store.query(_ReliableListener,
attributes.AND(_ReliableListener.processor == self,
_ReliableListener.listener == listener)).delete... |
Return an iterable of the listeners which have been added to this batch processor. | def getReliableListeners(self):
"""
Return an iterable of the listeners which have been added to
this batch processor.
"""
for rellist in self.store.query(_ReliableListener, _ReliableListener.processor == self):
yield rellist.listener |
Return an iterable of two - tuples of listeners which raised an exception from C { processItem } and the item which was passed as the argument to that method. | def getFailedItems(self):
"""
Return an iterable of two-tuples of listeners which raised an
exception from C{processItem} and the item which was passed as
the argument to that method.
"""
for failed in self.store.query(BatchProcessingError, BatchProcessingError.processor ... |
Called to indicate that a new item of the type monitored by this batch processor is being added to the database. | def itemAdded(self):
"""
Called to indicate that a new item of the type monitored by this batch
processor is being added to the database.
If this processor is not already scheduled to run, this will schedule
it. It will also start the batch process if it is not yet running and
... |
Invoke the given bound item method in the batch process. | def call(self, itemMethod):
"""
Invoke the given bound item method in the batch process.
Return a Deferred which fires when the method has been invoked.
"""
item = itemMethod.im_self
method = itemMethod.im_func.func_name
return self.batchController.getProcess().a... |
Run tasks until stopService is called. | def processWhileRunning(self):
"""
Run tasks until stopService is called.
"""
work = self.step()
for result, more in work:
yield result
if not self.running:
break
if more:
delay = 0.1
else:
... |
find every column in every sheet and put it in a new sheet or book. | def getcols(sheetMatch=None,colMatch="Decay"):
"""find every column in every sheet and put it in a new sheet or book."""
book=BOOK()
if sheetMatch is None:
matchingSheets=book.sheetNames
print('all %d sheets selected '%(len(matchingSheets)))
else:
matchingSheets=[x for x in book.... |
Recursively upgrade C { store }. | def upgradeStore(self, store):
"""
Recursively upgrade C{store}.
"""
self.upgradeEverything(store)
upgradeExplicitOid(store)
for substore in store.query(SubStore):
print 'Upgrading: {!r}'.format(substore)
self.upgradeStore(substore.open()) |
Upgrade C { store } performing C { count } upgrades per transaction. | def perform(self, store, count):
"""
Upgrade C{store} performing C{count} upgrades per transaction.
Also, catch any exceptions and print out something useful.
"""
self.count = count
try:
self.upgradeStore(store)
print 'Upgrade complete'
e... |
Override L { code. InteractiveConsole. runcode } to run the code in a transaction unless the local C { autocommit } is currently set to a true value. | def runcode(self, code):
"""
Override L{code.InteractiveConsole.runcode} to run the code in a
transaction unless the local C{autocommit} is currently set to a true
value.
"""
if not self.locals.get('autocommit', None):
return self.locals['db'].transact(code.In... |
Return a dictionary representing the namespace which should be available to the user. | def namespace(self):
"""
Return a dictionary representing the namespace which should be
available to the user.
"""
self._ns = {
'db': self.store,
'store': store,
'autocommit': False,
}
return self._ns |
Create a new account in the given store. | def addAccount(self, siteStore, username, domain, password):
"""
Create a new account in the given store.
@param siteStore: A site Store to which login credentials will be
added.
@param username: Local part of the username for the credentials to add.
@param domain: Domai... |
Create a new L { Item } subclass with L { numAttributes } integers in its schema. | def itemTypeWithSomeAttributes(attributeTypes):
"""
Create a new L{Item} subclass with L{numAttributes} integers in its
schema.
"""
class SomeItem(Item):
typeName = 'someitem_' + str(typeNameCounter())
for i, attributeType in enumerate(attributeTypes):
locals()['attr_' + ... |
Create some instances of a particular type in a store. | def createSomeItems(store, itemType, values, counter):
"""
Create some instances of a particular type in a store.
"""
for i in counter:
itemType(store=store, **values) |
save the instance or create a new one.. | def save(self, commit=True):
"""save the instance or create a new one.."""
# walk through the document fields
for field_name, field in iter_valid_fields(self._meta):
setattr(self.instance, field_name, self.cleaned_data.get(field_name))
if commit:
self.instance.s... |
Return a callable which will invoke C { func } in a transaction using the C { store } attribute of the first parameter passed to it. Typically this is used to create Item methods which are automatically run in a transaction. | def transacted(func):
"""
Return a callable which will invoke C{func} in a transaction using the
C{store} attribute of the first parameter passed to it. Typically this is
used to create Item methods which are automatically run in a transaction.
The attributes of the returned callable will resemble... |
Collect all the items that should be deleted when an item or items of a particular item type are deleted. | def dependentItems(store, tableClass, comparisonFactory):
"""
Collect all the items that should be deleted when an item or items
of a particular item type are deleted.
@param tableClass: An L{Item} subclass.
@param comparison: A one-argument callable taking an attribute and
returning an L{iaxi... |
Returns a C { bool } indicating whether deletion of an item or items of a particular item type should be allowed to proceed. | def allowDeletion(store, tableClass, comparisonFactory):
"""
Returns a C{bool} indicating whether deletion of an item or items of a
particular item type should be allowed to proceed.
@param tableClass: An L{Item} subclass.
@param comparison: A one-argument callable taking an attribute and
retu... |
Generate a dummy subclass of Item that will have the given attributes and the base Item methods but no methods of its own. This is for use with upgrading. | def declareLegacyItem(typeName, schemaVersion, attributes, dummyBases=()):
"""
Generate a dummy subclass of Item that will have the given attributes,
and the base Item methods, but no methods of its own. This is for use
with upgrading.
@param typeName: a string, the Axiom TypeName to have attribut... |
Class decorator for indicating a powerup s powerup interfaces. | def empowerment(iface, priority=0):
"""
Class decorator for indicating a powerup's powerup interfaces.
The class will also be declared as implementing the interface.
@type iface: L{zope.interface.Interface}
@param iface: The powerup interface.
@type priority: int
@param priority: The prio... |
Installs a powerup ( e. g. plugin ) on an item or store. | def powerUp(self, powerup, interface=None, priority=0):
"""
Installs a powerup (e.g. plugin) on an item or store.
Powerups will be returned in an iterator when queried for using the
'powerupsFor' method. Normally they will be returned in order of
installation [this may change i... |
Remove a powerup. | def powerDown(self, powerup, interface=None):
"""
Remove a powerup.
If no interface is specified, and the type of the object being
installed has a "powerupInterfaces" attribute (containing
either a sequence of interfaces, or a sequence of (interface,
priority) tuples), t... |
Returns powerups installed using C { powerUp } in order of descending priority. | def powerupsFor(self, interface):
"""
Returns powerups installed using C{powerUp}, in order of descending
priority.
Powerups found to have been deleted, either during the course of this
powerupsFor iteration, during an upgrader, or previously, will not be
returned.
... |
Return an iterator of the interfaces for which the given powerup is installed on this object. | def interfacesFor(self, powerup):
"""
Return an iterator of the interfaces for which the given powerup is
installed on this object.
This is not implemented for in-memory powerups. It will probably fail
in an unpredictable, implementation-dependent way if used on one.
""... |
Collect powerup interfaces this object declares that it can be installed on. | def _getPowerupInterfaces(self):
"""
Collect powerup interfaces this object declares that it can be
installed on.
"""
powerupInterfaces = getattr(self.__class__, "powerupInterfaces", ())
pifs = []
for x in powerupInterfaces:
if isinstance(x, type(Inter... |
Is this object currently valid as a reference? Objects which will be deleted in this transaction or objects which are not in the same store are not valid. See attributes. reference. __get__. | def _currentlyValidAsReferentFor(self, store):
"""
Is this object currently valid as a reference? Objects which will be
deleted in this transaction, or objects which are not in the same store
are not valid. See attributes.reference.__get__.
"""
if store is None:
... |
Prepare each attribute in my schema for insertion into a given store either by upgrade or by creation. This makes sure all references point to this store and all relative paths point to this store s files directory. | def _schemaPrepareInsert(self, store):
"""
Prepare each attribute in my schema for insertion into a given store,
either by upgrade or by creation. This makes sure all references point
to this store and all relative paths point to this store's files
directory.
"""
... |
Create and return a new instance from a row from the store. | def existingInStore(cls, store, storeID, attrs):
"""Create and return a new instance from a row from the store."""
self = cls.__new__(cls)
self.__justCreated = False
self.__subinit__(__store=store,
storeID=storeID,
__everInserted=True)
... |
return all persistent class attributes | def getSchema(cls):
"""
return all persistent class attributes
"""
schema = []
for name, atr in cls.__attributes__:
atr = atr.__get__(None, cls)
if isinstance(atr, SQLAttribute):
schema.append((name, atr))
cls.getSchema = staticmeth... |
Return a dictionary of all attributes which will be/ have been/ are being stored in the database. | def persistentValues(self):
"""
Return a dictionary of all attributes which will be/have been/are being
stored in the database.
"""
return dict((k, getattr(self, k)) for (k, attr) in self.getSchema()) |
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__:
self.store.objectCache.uncache(self.storeID, self)
self._... |
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. | def checkpoint(self):
"""
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 'autocommi... |
Register a callable which can perform a schema upgrade between two particular versions. | def registerUpgrader(upgrader, typeName, oldVersion, newVersion):
"""
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.
... |
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. | def registerAttributeCopyingUpgrader(itemType, fromVersion, toVersion, postCopy=None):
"""
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 u... |
Register an upgrader for C { itemType } from C { fromVersion } to C { toVersion } which will delete the item from the database. | def registerDeletionUpgrader(itemType, fromVersion, toVersion):
"""
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
"""
# XXX This should actually do something... |
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. | 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.
"""
if _hasExplicitOid(store, table):
return
store.executeSchemaSQL(
'ALTER TABLE *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(
_upgradeTableOid, store, 'axiom_objects',
lambda: store.ex... |
Upgrade a store to use explicit oid columns. This allows VACUUMing the database without corrupting it. | def upgradeExplicitOid(store):
"""
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... |
Check that all of the accumulated old Item types have a way to get from their current version to the latest version. | def checkUpgradePaths(self):
"""
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
"""
... |
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. | def upgradeItem(self, thisItem):
"""
Upgrade a legacy item.
@raise axiom.errors.UpgraderRecursion: If the given item is already in
the process of being upgraded.
"""
sid = thisItem.storeID
if sid in self._currentlyUpgrading:
raise UpgraderRecursio... |
Upgrade the entire store in batches yielding after each batch. | def upgradeBatch(self, n):
"""
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... |
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 | def open(self):
"""
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
"""
self.vg.open()
self._... |
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. | def size(self, units="MiB"):
"""
Returns the logical volume size in the given units. Default units are MiB.
*Args:*
* units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB.
"""
self.open()
size = lvm_lv_get_size(self.__lvh)
self.close(... |
Activates the logical volume. | def activate(self):
"""
Activates the logical volume.
*Raises:*
* HandleError
"""
self.open()
a = lvm_lv_activate(self.handle)
self.close()
if a != 0:
raise CommitError("Failed to activate LV.") |
Deactivates the logical volume. | def deactivate(self):
"""
Deactivates the logical volume.
*Raises:*
* HandleError
"""
self.open()
d = lvm_lv_deactivate(self.handle)
self.close()
if d != 0:
raise CommitError("Failed to deactivate LV.") |
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 | def open(self):
"""
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
"""
self.vg.open()
self._... |
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. | def size(self, units="MiB"):
"""
Returns the physical volume size in the given units. Default units are MiB.
*Args:*
* units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB.
"""
self.open()
size = lvm_pv_get_size(self.handle)
self.clos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.