INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Serialize self to text stream.
Matches convention of mongooplog. | def dump(self, stream):
"""Serialize self to text stream.
Matches convention of mongooplog.
"""
items = (
('time', self.time),
('inc', self.inc),
)
# use ordered dict to retain order
ts = collections.OrderedDict(items)
json.dump(di... |
Load a serialized version of self from text stream.
Expects the format used by mongooplog. | def load(cls, stream):
"""Load a serialized version of self from text stream.
Expects the format used by mongooplog.
"""
data = json.load(stream)['ts']
return cls(data['time'], data['inc']) |
Given a timedelta window, return a timestamp representing
that time. | def for_window(cls, window):
"""
Given a timedelta window, return a timestamp representing
that time.
"""
utcnow = datetime.datetime.utcnow()
return cls(utcnow - window, 0) |
Save timestamp to file. | def save(self, ts):
"""
Save timestamp to file.
"""
with open(self, 'w') as f:
Timestamp.wrap(ts).dump(f) |
Splits a string into tokens ready to be inserted into the search index.
This tokenizer will convert its parameter to a string by calling `str` and
then will split this string on characters matching `separator`.
Lists will have their elements converted to strings and wrapped in a lunr
`Token`.
Opti... | def Tokenizer(obj, metadata=None, separator=SEPARATOR):
"""Splits a string into tokens ready to be inserted into the search index.
This tokenizer will convert its parameter to a string by calling `str` and
then will split this string on characters matching `separator`.
Lists will have their elements co... |
Yield all databases except excluded (default
excludes 'local'). | def all_databases(client, exclude=['local']):
"""
Yield all databases except excluded (default
excludes 'local').
"""
return (
client[db_name]
for db_name in client.list_database_names()
if db_name not in exclude
) |
Yield all non-sytem collections in db. | def all_collections(db):
"""
Yield all non-sytem collections in db.
"""
include_pattern = r'(?!system\.)'
return (
db[name]
for name in db.list_collection_names()
if re.match(include_pattern, name)
) |
Cannot remove documents from capped collections
in later versions of MongoDB, so drop the
collection instead. | def safe_purge_collection(coll):
"""
Cannot remove documents from capped collections
in later versions of MongoDB, so drop the
collection instead.
"""
op = (
drop_collection
if coll.options().get('capped', False)
else purge_collection
)
return op(coll) |
Builds a stopWordFilter function from the provided list of stop words.
The built in `stop_word_filter` is built using this factory and can be used
to generate custom `stop_word_filter` for applications or non English
languages. | def generate_stop_word_filter(stop_words, language=None):
"""Builds a stopWordFilter function from the provided list of stop words.
The built in `stop_word_filter` is built using this factory and can be used
to generate custom `stop_word_filter` for applications or non English
languages.
"""
d... |
Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:raises: MissingParameterValue if a requ... | def get_boot_device(self):
"""Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:... |
Printable E.123 (Notation for national and international telephone numbers
from ITU) numbers.
:param number: string
:param areasize: int
:param groupsize: int
:param national: bool
>>> print(e123(155542315678))
+1 555 4231 5678
>>> print(e123('+31654231567', areasize=1))
+31 6 5423... | def e123(number, areasize=3, groupsize=4, national=False):
'''
Printable E.123 (Notation for national and international telephone numbers
from ITU) numbers.
:param number: string
:param areasize: int
:param groupsize: int
:param national: bool
>>> print(e123(155542315678))
+1 555 4... |
Printable a 26 Latin letters (A to Z) phone number to the 12-key telephone
keypad number.
:param number: string
:param alphabet: dict
>>> print(e161('0800-PIZZA123'))
080074992123
>>> e161('0800^PIZZA123')
Traceback (most recent call last):
...
ValueError: Character "^" (0x5e) ... | def e161(number, alphabet=PHONE_E161_ALPHABET):
'''
Printable a 26 Latin letters (A to Z) phone number to the 12-key telephone
keypad number.
:param number: string
:param alphabet: dict
>>> print(e161('0800-PIZZA123'))
080074992123
>>> e161('0800^PIZZA123')
Traceback (most recent c... |
Printable E.164 (The international public telecommunication numbering plan
from ITU) numbers.
:param number: string
>>> print(e164(155542315678))
+155542315678
>>> print(e164('+31 20 5423 1567'))
+312054231567 | def e164(number):
'''
Printable E.164 (The international public telecommunication numbering plan
from ITU) numbers.
:param number: string
>>> print(e164(155542315678))
+155542315678
>>> print(e164('+31 20 5423 1567'))
+312054231567
'''
if isinstance(number, six.integer_types):
... |
Printable DNS ENUM (telephone number mapping) record.
:param number: string
:param zone: string
>>> print(enum('+31 20 5423 1567'))
7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa.
>>> print(enum('+31 97 99 6642', zone='e164.spacephone.org'))
2.4.6.6.9.9.7.9.1.3.e164.spacephone.org. | def enum(number, zone='e164.arpa'):
'''
Printable DNS ENUM (telephone number mapping) record.
:param number: string
:param zone: string
>>> print(enum('+31 20 5423 1567'))
7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa.
>>> print(enum('+31 97 99 6642', zone='e164.spacephone.org'))
2.4.6.6.9.9.7.9.... |
Printable International Mobile Station Equipment Identity (IMEI) numbers.
:param number: string or int
>>> print(imei(12345678901234))
12-345678-901234-7
>>> print(imei(1234567890123456))
12-345678-901234-56 | def imei(number):
'''
Printable International Mobile Station Equipment Identity (IMEI) numbers.
:param number: string or int
>>> print(imei(12345678901234))
12-345678-901234-7
>>> print(imei(1234567890123456))
12-345678-901234-56
'''
number = to_decimal(number)
length = len(num... |
Printable International Mobile Subscriber Identity (IMSI) numbers. Mind
that there is no validation done on the actual correctness of the MCC/MNC.
If you wish to validate IMSI numbers, take a look at `python-stdnum`_.
:param number: string or int
>>> print(imsi(2042312345))
204-23-12345
.. _p... | def imsi(number):
'''
Printable International Mobile Subscriber Identity (IMSI) numbers. Mind
that there is no validation done on the actual correctness of the MCC/MNC.
If you wish to validate IMSI numbers, take a look at `python-stdnum`_.
:param number: string or int
>>> print(imsi(2042312345... |
Printable Mobile Equipment Identifier (MEID) number.
>>> print(meid(123456789012345678))
1B 69B4BA 630F34 6
>>> print(meid('1B69B4BA630F34'))
1B 69B4BA 630F34 6 | def meid(number, separator=u' '):
'''
Printable Mobile Equipment Identifier (MEID) number.
>>> print(meid(123456789012345678))
1B 69B4BA 630F34 6
>>> print(meid('1B69B4BA630F34'))
1B 69B4BA 630F34 6
'''
if isinstance(number, six.string_types):
number = re.sub(r'[\s-]', '', numb... |
Printable Pseudo Electronic Serial Number.
:param number: hexadecimal string
>>> print(pesn('1B69B4BA630F34E'))
805F9EF7 | def pesn(number, separator=u''):
'''
Printable Pseudo Electronic Serial Number.
:param number: hexadecimal string
>>> print(pesn('1B69B4BA630F34E'))
805F9EF7
'''
number = re.sub(r'[\s-]', '', meid(number))
serial = hashlib.sha1(unhexlify(number[:14]))
return separator.join(['80', ... |
Convert a file size into natural readable format. Multiple formats are
supported.
:param value: size
:param format: default ``decimal``, choices ``binary``, ``decimal`` or
``gnu``
:param digits: default ``2``
>>> print(filesize(123))
123.00 B
>>> print(filesize(123456))
... | def filesize(value, format='decimal', digits=2):
'''
Convert a file size into natural readable format. Multiple formats are
supported.
:param value: size
:param format: default ``decimal``, choices ``binary``, ``decimal`` or
``gnu``
:param digits: default ``2``
>>> print... |
Decorator that transforms the decorated function into a chi.Experiment
:param start_chiboard:
:param f:
:param local_dependencies:
:return: | def experiment(f=None, local_dependencies=None, start_chiboard=True, default_logdir=""):
"""
Decorator that transforms the decorated function into a chi.Experiment
:param start_chiboard:
:param f:
:param local_dependencies:
:return:
"""
if not f:
return lambda f: experiment(f, local_dependencies, st... |
Creates filter object for given class name, and DN values. | def create_dn_in_filter(filter_class, filter_value, helper):
""" Creates filter object for given class name, and DN values."""
in_filter = FilterFilter()
in_filter.AddChild(create_dn_wcard_filter(filter_class, filter_value))
return in_filter |
Creates wild card filter object for given class name, and values.
:param filter_class: class name
:param filter_value: filter property value
:return WcardFilter: WcardFilter object | def create_dn_wcard_filter(filter_class, filter_value):
""" Creates wild card filter object for given class name, and values.
:param filter_class: class name
:param filter_value: filter property value
:return WcardFilter: WcardFilter object
"""
wcard_filter = WcardFilter()
wcard_filter.Cla... |
Creates UCS Manager handle object and establishes a session with
UCS Manager.
:param hostname: UCS Manager hostname or IP-address
:param username: Username to login to UCS Manager
:param password: Login user password
:raises UcsConnectionError: In case of error. | def generate_ucsm_handle(hostname, username, password):
""" Creates UCS Manager handle object and establishes a session with
UCS Manager.
:param hostname: UCS Manager hostname or IP-address
:param username: Username to login to UCS Manager
:param password: Login user password
:rais... |
Configure the specified MO in UCS Manager.
:param uuid: MO config
:param p_dn: parent MO DN
:param p_class_id: parent MO class ID
:param class_id: MO class ID
:param MO configuration: MO config
:param mo_dn: MO DN value
:param handle: optional UCS Manager handle ... | def config_managed_object(p_dn, p_class_id, class_id,
mo_config, mo_dn, handle=None, delete=True):
"""Configure the specified MO in UCS Manager.
:param uuid: MO config
:param p_dn: parent MO DN
:param p_class_id: parent MO class ID
:param class_id: MO class... |
Build a projection for MongoDB.
Due to https://jira.mongodb.org/browse/SERVER-3156, until MongoDB 2.6,
the values must be integers and not boolean.
>>> project(a=True) == {'a': 1}
True
Once MongoDB 2.6 is released, replace use of this function with a simple
dict. | def project(*args, **kwargs):
"""
Build a projection for MongoDB.
Due to https://jira.mongodb.org/browse/SERVER-3156, until MongoDB 2.6,
the values must be integers and not boolean.
>>> project(a=True) == {'a': 1}
True
Once MongoDB 2.6 is released, replace use of this function with a simp... |
Simulate MongoDB 3.0 explain result on prior versions.
http://docs.mongodb.org/v3.0/reference/explain-results/ | def compat_explain(cur):
"""
Simulate MongoDB 3.0 explain result on prior versions.
http://docs.mongodb.org/v3.0/reference/explain-results/
"""
res = cur.explain()
if 'nscannedObjects' in res:
res['executionStats'] = dict(
nReturned=res.pop('n'),
totalKeysExamined... |
Fetch exactly one matching document or upsert
the document if not found, returning the matching
or upserted document.
See https://jira.mongodb.org/browse/SERVER-28434
describing the condition where MongoDB is uninterested in
providing an upsert and fetch behavior.
>>> instance = getfixture('mo... | def upsert_and_fetch(coll, doc, **kwargs):
"""
Fetch exactly one matching document or upsert
the document if not found, returning the matching
or upserted document.
See https://jira.mongodb.org/browse/SERVER-28434
describing the condition where MongoDB is uninterested in
providing an upsert... |
Synchronize state with switch. | def update(self, retry=2) -> None:
"""Synchronize state with switch."""
try:
_LOGGER.debug("Updating device state.")
key = ON_KEY if not self._flip_on_off else OFF_KEY
self.state = self._device.readCharacteristic(HANDLE) == key
except (bluepy.btle.BTLEExceptio... |
An instance of lunr.MatchData will be created for every term that
matches a document.
However only one instance is required in a lunr.Index~Result. This
method combines metadata from another instance of MatchData with this
object's metadata. | def combine(self, other):
"""An instance of lunr.MatchData will be created for every term that
matches a document.
However only one instance is required in a lunr.Index~Result. This
method combines metadata from another instance of MatchData with this
object's metadata.
... |
Add metadata for a term/field pair to this instance of match data | def add(self, term, field, metadata):
"""Add metadata for a term/field pair to this instance of match data"""
if term not in self.metadata:
self.metadata[term] = {field: metadata}
return
if field not in self.metadata[term]:
self.metadata[term][field] = metada... |
Get current power state of this node
:param node: Ironic node one of :class:`ironic.db.models.Node`
:raises: InvalidParameterValue if required Ucs parameters are
missing
:raises: UcsOperationError: on an error from Ucs.
:returns: Power state of the given node | def get_power_state(self):
"""Get current power state of this node
:param node: Ironic node one of :class:`ironic.db.models.Node`
:raises: InvalidParameterValue if required Ucs parameters are
missing
:raises: UcsOperationError: on an error from Ucs.
:ret... |
Set power state of this node
:param node: Ironic node one of :class:`ironic.db.models.Node`
:raises: InvalidParameterValue if required seamicro parameters are
missing.
:raises: UcsOperationError on an error from UcsHandle Client.
:returns: Power state of... | def set_power_state(self, desired_state):
"""Set power state of this node
:param node: Ironic node one of :class:`ironic.db.models.Node`
:raises: InvalidParameterValue if required seamicro parameters are
missing.
:raises: UcsOperationError on an error from U... |
Hard reset the power of this node. | def reboot(self):
"""Hard reset the power of this node.
"""
if self.get_power_state() == LsPower.CONST_STATE_DOWN:
self.set_power_state(LsPower.CONST_STATE_UP)
else:
self.set_power_state(LsPower.CONST_STATE_HARD_RESET_IMMEDIATE) |
Use the factory to establish a connection to uri. | def connect(uri, factory=pymongo.MongoClient):
"""
Use the factory to establish a connection to uri.
"""
warnings.warn(
"do not use. Just call MongoClient directly.", DeprecationWarning)
return factory(uri) |
Use pymongo to parse a uri (possibly including database name) into
a connected database object.
This serves as a convenience function for the common use case where one
wishes to get the Database object and is less concerned about the
intermediate MongoClient object that pymongo creates (though the
... | def connect_db(
uri, default_db_name=None, factory=pymongo.MongoClient):
"""
Use pymongo to parse a uri (possibly including database name) into
a connected database object.
This serves as a convenience function for the common use case where one
wishes to get the Database object and is less ... |
Construct a GridFS instance for a MongoDB URI. | def connect_gridfs(uri, db=None):
"""
Construct a GridFS instance for a MongoDB URI.
"""
return gridfs.GridFS(
db or connect_db(uri),
collection=get_collection(uri) or 'fs',
) |
Compares managed objects.
- referenceObject specifies objects used as a reference for comparison.
- differenceObject specifies objects that are compared to the reference objects.
- excludeDifferent, if set as True then displays only the properties of compared objects that are equal.
- includeEqual, set... | def CompareManagedObject(referenceObject, differenceObject, excludeDifferent=YesOrNo.FALSE, includeEqual=YesOrNo.FALSE,
noVersionFilter=YesOrNo.FALSE, includeOperational=YesOrNo.FALSE, xlateOrg=None, xlateMap=None):
"""
Compares managed objects.
- referenceObject specifies objects used as a reference f... |
Internal method to support CompareManagedObject functionality. | def Compare(fromMo, toMo, diff):
""" Internal method to support CompareManagedObject functionality. """
from UcsBase import UcsUtils
if (fromMo.classId != toMo.classId):
return CompareStatus.TypesDifferent
for prop in UcsUtils.GetUcsPropertyMetaAttributeList(str(fromMo.classId)):
propMeta = UcsUtils.IsPropert... |
Method used to translate a managedobject. This method is used in CompareManagedObject. | def TranslateManagedObject(mObj, xlateOrg, xlateMap):
""" Method used to translate a managedobject. This method is used in CompareManagedObject. """
from UcsBase import UcsUtils, WriteUcsWarning
from Mos import OrgOrg
xMO = mObj.Clone()
xMO.SetHandle(mObj.GetHandle())
if (xlateOrg != None):
matchObj = re.match... |
This operation will do a login to each UCS which is present in credential file.
- filePath specifies the path of the credential file.
- key specifies string used for secure encryption while ExportUcsSession operation. | def ImportUcsSession(filePath, key):
"""
This operation will do a login to each UCS which is present in credential file.
- filePath specifies the path of the credential file.
- key specifies string used for secure encryption while ExportUcsSession operation.
"""
from UcsBase import UcsUtils, WriteUcs... |
Stores the credential of currently logged in UCS in current session to a file. Password will be stored in encrypted format using key.
- filePath specifies the path of the credential file.
- key specifies any string used for secure encryption.
- merge should be set as False unless user wants to append the e... | def ExportUcsSession(filePath, key, merge=YesOrNo.FALSE):
"""
Stores the credential of currently logged in UCS in current session to a file. Password will be stored in encrypted format using key.
- filePath specifies the path of the credential file.
- key specifies any string used for secure encryption.
... |
Constructs the connection URI from name, noSsl and port instance variables. | def Uri(self):
""" Constructs the connection URI from name, noSsl and port instance variables. """
return ("%s://%s%s" % (("https", "http")[self._noSsl == True], self._name, (":" + str(self._port), "")[
(((self._noSsl == False) and (self._port == 80)) or ((self._noSsl == True) and (self._port == 443)))])) |
Cancels any running transaction. | def UndoTransaction(self):
""" Cancels any running transaction. """
from Ucs import ConfigMap
self._transactionInProgress = False
self._configMap = ConfigMap() |
Completes a transaction.
This method completes a transaction by sending the final configuration (modification queries stored in configMap) to UCS and
returns the result. | def CompleteTransaction(self, dumpXml=None):
"""
Completes a transaction.
This method completes a transaction by sending the final configuration (modification queries stored in configMap) to UCS and
returns the result.
"""
from Ucs import ConfigMap, Pair
from UcsBase import Manage... |
Accepts any ExternalMethod stores any modification query locally if transaction is in progress (and returns temporary result)
prepares xml query as per the writeXmlOption from external method. Opens a connection to url, sends the xmlQuery string to url
location, and returns result. Prepares objects fro... | def XmlQuery(self, method, options, dumpXml=None):
"""
Accepts any ExternalMethod stores any modification query locally if transaction is in progress (and returns temporary result)
prepares xml query as per the writeXmlOption from external method. Opens a connection to url, sends the xmlQuery string t... |
Accepts xmlQuery String and returns xml response String. No object manipulation is done in this method. | def XmlRawQuery(self, xml, dumpXml=None):
""" Accepts xmlQuery String and returns xml response String. No object manipulation is done in this method. """
if (dumpXml == None):
dumpXml = self._dumpXml
uri = self.Uri() + '/nuova'
if (dumpXml in _AffirmativeList):
print '%s ====> %s' % (self._ucs, xml)
#... |
Login method authenticates and connects to UCS.
- name specifies the IP Address IMC Server.
- username specifies the username credential.
- password specifies the password credential.
- noSsl specifies if the connection is made via http(True) or https(False). Default is False.
-... | def Login(self, name, username=None, password=None, noSsl=False, port=None, dumpXml=None, proxy=None,
autoRefresh=YesOrNo.FALSE):
"""
Login method authenticates and connects to UCS.
- name specifies the IP Address IMC Server.
- username specifies the username credential.
- passwo... |
Logout method disconnects from UCS. | def Logout(self, dumpXml=None):
""" Logout method disconnects from UCS. """
from UcsBase import UcsException
if (self._cookie == None):
return True
if self._refreshTimer:
self._refreshTimer.cancel()
response = self.AaaLogout(dumpXml)
self._cookie = None
self._lastUpdateTime = str(time.asctime())
... |
Internal method to support auto-refresh functionality. | def _Start_refresh_timer(self):
""" Internal method to support auto-refresh functionality. """
if self._refreshPeriod > 60:
interval = self._refreshPeriod - 60
else:
interval = 60
self._refreshTimer = Timer(self._refreshPeriod, self.Refresh)
# TODO:handle exit and logout active connections. revert from ... |
Sends the aaaRefresh query to the UCS to refresh the connection (to prevent session expiration). | def Refresh(self, autoRelogin=False, dumpXml=YesOrNo.FALSE):
"""
Sends the aaaRefresh query to the UCS to refresh the connection (to prevent session expiration).
"""
self._Stop_refresh_timer()
response = self.AaaRefresh(self._username, self._password, dumpXml)
if (response.errorCode != 0):
self._cookie ... |
Internal method used by AddEventHandler.
Provides functionality of enqueue/dequeue of the events and triggering callbacks. | def _enqueue_function(self):
"""
Internal method used by AddEventHandler.
Provides functionality of enqueue/dequeue of the events and triggering callbacks.
"""
from UcsBase import _GenericMO, UcsUtils, WriteObject
myThread = self._enqueueThread
self._enqueueThreadSignal.acquire()
try:
xmlQuery ... |
Internal method to start the enqueue thread which adds the events in an internal queue. | def _start_enqueue_thread(self):
""" Internal method to start the enqueue thread which adds the events in an internal queue. """
self._enqueueThreadSignal.acquire()
self._enqueueThread = Thread(target=self._enqueue_function)
self._enqueueThread.daemon = True
self._enqueueThread.start()
self._enqueueThreadSi... |
Internal method to add a watch block for starting event monitoring. | def _add_watch_block(self, params, filterCb, capacity=500, cb=None):
""" Internal method to add a watch block for starting event monitoring. """
if (self._wbslock == None):
self._wbslock = Lock()
self._wbslock.acquire()
wb = WatchBlock(params, filterCb, capacity, cb) # Add a List of Watchers
if ((wb != N... |
Internal method to remove a watch block for stopping event monitoring. | def _remove_watch_block(self, wb):
""" Internal method to remove a watch block for stopping event monitoring. """
if (self._wbslock == None):
self._wbslock = Lock()
self._wbslock.acquire()
self._wbs.remove(wb)
if len(self._wbs) == 0:
self._stop_enqueue_thread()
self._stop_dequeue_thread()
self._w... |
Adds an event handler.
An event handler can be added using this method where an user can subscribe for the event channel from UCS and can monitor those events for any
specific success value or failure value for a managed object.
- classId specifies the class name for which events should be monitored.
- mana... | def AddEventHandler(self, classId=None, managedObject=None, prop=None, successValue=[], failureValue=[],
transientValue=[], pollSec=None, timeoutSec=None, callBack=None):
"""
Adds an event handler.
An event handler can be added using this method where an user can subscribe for the event channel from UCS ... |
Removes an event handler. | def RemoveEventHandler(self, wb):
""" Removes an event handler. """
from UcsBase import WriteUcsWarning
if wb in self._wbs:
self._remove_watch_block(wb)
else:
WriteUcsWarning("Event handler not found") |
Internal method to start dequeue thread. | def _start_dequeue_thread(self):
""" Internal method to start dequeue thread. """
self._dequeueThread = Thread(target=self._dequeue_function)
self._dequeueThread.daemon = True
self._dequeueThread.start() |
Internal method to dequeue to events. | def _dequeue_function(self):
""" Internal method to dequeue to events. """
from UcsBase import WriteUcsWarning, _GenericMO, WriteObject, UcsUtils
while len(self._wbs):
lowestTimeout = None
for wb in self._wbs:
pollSec = wb.params["pollSec"]
managedObject = wb.params["managedObject"]
timeoutSec ... |
Starts KVM session.
launches the KVM session for the specific service profile, blade or rackUnit.
- serviceProfile specifies an object of type lsServer. Launches KVM session with which the service profile is associated.
- blade specifies an object of type computeBlade. Launches KVM session of blade server.
... | def StartKvmSession(self, serviceProfile=None, blade=None, rackUnit=None, frameTitle=None, dumpXml=None):
"""
Starts KVM session.
launches the KVM session for the specific service profile, blade or rackUnit.
- serviceProfile specifies an object of type lsServer. Launches KVM session with which the service pr... |
Launches the UCSM GUI via specific UCS handle. | def StartGuiSession(self):
""" Launches the UCSM GUI via specific UCS handle. """
from UcsBase import WriteUcsWarning, UcsUtils, UcsValidationException
import urllib, tempfile, fileinput, os, subprocess, platform
osSupport = ["Windows", "Linux", "Microsoft"]
if platform.system() not in osSupport:
raise U... |
Imports backUp.
This operation will upload the UCSM backup taken earlier via GUI or BackupUcs operation for all configuration, system configuration, and
logical configuration files. User can perform an import while the system is up and running.
- path specifies path of the backup file.
- merge specifies whe... | def ImportUcsBackup(self, path=None, merge=False, dumpXml=False):
"""
Imports backUp.
This operation will upload the UCSM backup taken earlier via GUI or BackupUcs operation for all configuration, system configuration, and
logical configuration files. User can perform an import while the system is up and ru... |
Creates and downloads the backup of UCS.
- type specifies the type of backup i.e. fullstate/config-logical/config-system/config-all.
- pathPattern specifies the path of the Backup file.
- timeoutSec specifies the time in seconds for which method waits for the backUp file to generate else exit. | def BackupUcs(self, type, pathPattern, timeoutSec=600, preservePooledValues=False, dumpXml=None):
"""
Creates and downloads the backup of UCS.
- type specifies the type of backup i.e. fullstate/config-logical/config-system/config-all.
- pathPattern specifies the path of the Backup file.
- timeoutSec speci... |
Uploads a specific CCO Image on UCS.
- path specifies the path of the image to be uploaded. | def SendUcsFirmware(self, path=None, dumpXml=False):
"""
Uploads a specific CCO Image on UCS.
- path specifies the path of the image to be uploaded.
"""
from UcsBase import WriteUcsWarning, UcsUtils, ManagedObject, WriteObject, UcsUtils, UcsValidationException, \
UcsException
from Ucs import ConfigCon... |
Creates and downloads the technical support data for the respective UCSM.
- pathPattern specifies the path of the tech support file to be downloaded. File should be a tar file.
- ucsManager, if provided as True then technical support data for the entire UCSM instance will be created and downloaded.
- ucsMgmt, ... | def GetTechSupport(self, pathPattern, ucsManager=False, ucsMgmt=False, chassisId=None, cimcId=None, adapterId=None,
iomId=None, fexId=None, rackServerId=None, rackAdapterId=None, timeoutSec=600,
removeFromUcs=False, dumpXml=None):
"""
Creates and downloads the technical support data for the respecti... |
Syncs Managed Object.
Method takes the difference object (output of CompareManagedObject) and applies the differences on reference Managed Object.
- difference specifies the Difference object (output of ComparesManagedObject) which has differences of the properties of two or more Managed Objects.
- deleteNotPr... | def SyncManagedObject(self, difference, deleteNotPresent=False, noVersionFilter=False, dumpXml=None):
"""
Syncs Managed Object.
Method takes the difference object (output of CompareManagedObject) and applies the differences on reference Managed Object.
- difference specifies the Difference object (output of ... |
Gets Child Managed Object from UCS.
- in_mo, if provided, it acts as a parent for the present operation. (required if in_dn is None).
- in_dn, parent mo dn (required if in_mo is None)
- class_id of the managed object/s to get.(optional)
- in_hierarchical, Explores hierarchy if true, else returns managed object... | def GetUcsChild(self, inMo=None, inDn=None, classId=None, inHierarchical=False, dumpXml=None):
"""
Gets Child Managed Object from UCS.
- in_mo, if provided, it acts as a parent for the present operation. (required if in_dn is None).
- in_dn, parent mo dn (required if in_mo is None)
- class_id of the managed ... |
Adds a Managed Object to UCS.
- inMo, if provided, it acts as a parent for the present operation. It should be None unless a user wants to define a parent scope.
It can be a single MO or a list containing multiple managed objects.
- classId of the managed object/s to be added.
- params contains semicolon ... | def AddManagedObject(self, inMo=None, classId=None, params=None, modifyPresent=False, dumpXml=None):
"""
Adds a Managed Object to UCS.
- inMo, if provided, it acts as a parent for the present operation. It should be None unless a user wants to define a parent scope.
It can be a single MO or a list contain... |
Modifies Managed Object in UCS.
- inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an
inMo. It can be a single MO or a list containing multiple managed objects.
- classId of the managed object/s to be modified.
- params contains se... | def SetManagedObject(self, inMo, classId=None, params=None, dumpXml=None):
"""
Modifies Managed Object in UCS.
- inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an
inMo. It can be a single MO or a list containing multiple managed ... |
Removes Managed Object in UCS.
- inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an
inMo. It can be a single MO or a list containing multiple managed objects.
- classId of the managed object/s to be removed.
- params contains semi... | def RemoveManagedObject(self, inMo=None, classId=None, params=None, dumpXml=None):
"""
Removes Managed Object in UCS.
- inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an
inMo. It can be a single MO or a list containing multiple m... |
Opens a file for access with the given mode. This function
transparently wraps gzip and xz files as well as normal files.
You can also open zip files using syntax like:
f = utils.open_file('../semcor-parsed.zip:semcor000.txt') | def open_file(filename, mode='rb'):
"""
Opens a file for access with the given mode. This function
transparently wraps gzip and xz files as well as normal files.
You can also open zip files using syntax like:
f = utils.open_file('../semcor-parsed.zip:semcor000.txt')
"""
if (('r' not in mod... |
Transform a sentence using the code spelling alphabet, multiple
international code alphabets are supported.
====== ====================================================================
format description
====== ====================================================================
army US (internati... | def code(sentence, pad=' ', format='army'):
'''
Transform a sentence using the code spelling alphabet, multiple
international code alphabets are supported.
====== ====================================================================
format description
====== ====================================... |
Transform a sentence using the NATO spelling alphabet.
:param sentence: input sentence
:param pad: default ``' '``
:param format: default ``telephony``, options ``telephony`` or ``phonetic``
>>> print(nato('Python'))
papa yankee tango hotel oscar november
>>> print(nato('Python', format='phon... | def nato(sentence, pad=' ', format='telephony'):
'''
Transform a sentence using the NATO spelling alphabet.
:param sentence: input sentence
:param pad: default ``' '``
:param format: default ``telephony``, options ``telephony`` or ``phonetic``
>>> print(nato('Python'))
papa yankee tango ho... |
Architecture according to:
http://www.nature.com/nature/journal/v518/n7540/full/nature14236.html | def deep_q_network():
""" Architecture according to:
http://www.nature.com/nature/journal/v518/n7540/full/nature14236.html
"""
@tt.model(tracker=tf.train.ExponentialMovingAverage(1 - .0005), # TODO: replace with original weight freeze
optimizer=tf.train.RMSPropOptimizer(.0002... |
Architecture according to Duelling DQN:
https://arxiv.org/abs/1511.06581 | def delling_network():
""" Architecture according to Duelling DQN:
https://arxiv.org/abs/1511.06581
"""
@tt.model(tracker=tf.train.ExponentialMovingAverage(1 - .0005), # TODO: replace with original weight freeze
optimizer=tf.train.RMSPropOptimizer(6.25e-5, .95, .95, .01))
... |
braceexpand(pattern) -> iterator over generated strings
Returns an iterator over the strings resulting from brace expansion
of pattern. This function implements Brace Expansion as described in
bash(1), with the following limitations:
* A pattern containing unbalanced braces will raise an
Unbalan... | def braceexpand(pattern, escape=True):
"""braceexpand(pattern) -> iterator over generated strings
Returns an iterator over the strings resulting from brace expansion
of pattern. This function implements Brace Expansion as described in
bash(1), with the following limitations:
* A pattern containing... |
Adds a `lunr.Clause` to this query.
Unless the clause contains the fields to be matched all fields will be
matched. In addition a default boost of 1 is applied to the clause.
If the first argument is a `lunr.Clause` it will be mutated and added,
otherwise args and kwargs will be used i... | def clause(self, *args, **kwargs):
"""Adds a `lunr.Clause` to this query.
Unless the clause contains the fields to be matched all fields will be
matched. In addition a default boost of 1 is applied to the clause.
If the first argument is a `lunr.Clause` it will be mutated and added,
... |
Adds a term to the current query, creating a Clause and adds it to
the list of clauses making up this Query.
The term is not tokenized and used "as is". Any conversion to token
or token-like strings should be performed before calling this method.
For example:
query.term(lun... | def term(self, term, **kwargs):
"""Adds a term to the current query, creating a Clause and adds it to
the list of clauses making up this Query.
The term is not tokenized and used "as is". Any conversion to token
or token-like strings should be performed before calling this method.
... |
A negated query is one in which every clause has a presence of
prohibited. These queries require some special processing to return
the expected results. | def is_negated(self):
"""A negated query is one in which every clause has a presence of
prohibited. These queries require some special processing to return
the expected results.
"""
return all(
clause.presence == QueryPresence.PROHIBITED for clause in self.clauses
... |
recipients can be either a list of emails or a list of users,
if it is users the system will change to the language that the
user has set as theyr mother toungue | def send_templated_email(recipients, template_path, context=None,
from_email=settings.DEFAULT_FROM_EMAIL,
fail_silently=False, extra_headers=None):
"""
recipients can be either a list of emails or a list of users,
if it is users the system will change to the l... |
Wraps all word transitions with a boundary token character (\x00).
If desired (with ``force_edges`` set to ``True``), this inserts
the boundary character at the beginning and end of the string.
Arguments:
- `seq`:
- `force_edges = True`: | def boundary_transform(seq, force_edges = True):
'''
Wraps all word transitions with a boundary token character (\x00).
If desired (with ``force_edges`` set to ``True``), this inserts
the boundary character at the beginning and end of the string.
Arguments:
- `seq`:
- `force_edges = True`:
... |
Wraps all word transitions with a boundary token character (\x00).
Arguments:
- `seq`: | def boundary_words(seq):
'''
Wraps all word transitions with a boundary token character (\x00).
Arguments:
- `seq`:
'''
in_word = None
for char in seq:
if char == '\x00' and in_word is not None:
in_word = not in_word
elif char in WHITESPACE_CHARS:
if ... |
Removes duplicate boundary token characters from the given
character iterable.
Arguments:
- `seq`: | def remove_duplicates(seq):
'''
Removes duplicate boundary token characters from the given
character iterable.
Arguments:
- `seq`:
'''
last_boundary = False
for char in seq:
if char == '\x00':
if not last_boundary:
last_boundary = True
... |
Depth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`. | def dfs(self):
'''
Depth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`.
'''
yield (self.root, None)
todo = [(self.root[char], self.root) for char in self.root]
while todo:
current, paren... |
Breadth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`. | def bfs(self):
'''
Breadth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`.
'''
yield (self.root, None)
todo = deque([(self.root[char], self.root) for char in self.root])
while todo:
curre... |
Create a string to pretty-print this trie to standard output. | def pretty_print_str(self):
'''
Create a string to pretty-print this trie to standard output.
'''
retval = ''
# dfs
todo = [self.root]
while todo:
current = todo.pop()
for char in reversed(sorted(current.keys())):
todo.appen... |
Reset all suffix links in all nodes in this trie. | def _reset_suffix_links(self):
'''
Reset all suffix links in all nodes in this trie.
'''
self._suffix_links_set = False
for current, _parent in self.dfs():
current.suffix = None
current.dict_suffix = None
current.longest_prefix = None |
Sets all suffix links in all nodes in this trie. | def _set_suffix_links(self):
'''
Sets all suffix links in all nodes in this trie.
'''
self._suffix_links_set = True
for current, parent in self.bfs():
# skip the root node
if parent is None:
continue
current.longest_prefix = par... |
Generator expression. Yields tuples of `(begin, length, value)`,
where:
- `begin` is an integer identifying the character index where
the match begins (0-based)
- `length` is an integer indicating the length of the match (1
or more characters)
- `value` is the value... | def find_all(self, seq):
'''
Generator expression. Yields tuples of `(begin, length, value)`,
where:
- `begin` is an integer identifying the character index where
the match begins (0-based)
- `length` is an integer indicating the length of the match (1
or mo... |
Performs search and replace on the given input string `seq` using
the values stored in this trie. This method uses a O(n**2)
chart-parsing algorithm to find the optimal way of replacing
matches in the input.
Arguments:
- `seq`: | def replace(self, seq):
'''
Performs search and replace on the given input string `seq` using
the values stored in this trie. This method uses a O(n**2)
chart-parsing algorithm to find the optimal way of replacing
matches in the input.
Arguments:
- `seq`:
... |
Greedily matches strings in ``seq``, and replaces them with their
node values.
Arguments:
- `seq`: an iterable of characters to perform search-and-replace on | def greedy_replace(self, seq):
'''
Greedily matches strings in ``seq``, and replaces them with their
node values.
Arguments:
- `seq`: an iterable of characters to perform search-and-replace on
'''
if not self._suffix_links_set:
self._set_suffix_links(... |
Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned. | def get_page_number_from_request(
request, querystring_key=PAGE_LABEL, default=1):
"""Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned.
"""
try:
if request.method == 'POST':
... |
Method to return string representation of a managed object. | def _write_mo(mo):
""" Method to return string representation of a managed object. """
# from UcsBase import UcsUtils
classNotFound = False
if (UcsUtils.FindClassIdInMoMetaIgnoreCase(mo.classId) == None):
classNotFound = True
tabsize = 8
outstr = "\n"
if classNotFound:
outstr += "Managed Object\t\t\t:\t" + ... |
Writes the difference managedObject(output of CompareManagedObject) on the terminal. | def WriteMoDiff(diffObj):
""" Writes the difference managedObject(output of CompareManagedObject) on the terminal. """
tabsize = 8
print str(diffObj.Dn).ljust(tabsize * 10), str(diffObj.InputObject.propMoMeta.name).ljust(tabsize * 4), str(
diffObj.SideIndicator).ljust(tabsize * 3), str(diffObj.DiffProperty) |
Writes the managed object on the terminal in form of key value pairs. | def WriteObject(moList):
""" Writes the managed object on the terminal in form of key value pairs. """
from Ucs import Dn
from UcsHandle import UcsMoDiff
tabsize = 8
if (isinstance(moList, _GenericMO) == True):
print str(moList)
elif (isinstance(moList, ExternalMethod) == True):
if (hasattr(moList, "OutConfi... |
Method writes the xml representation for the object. | def childWriteXml(self, w, option):
"""Method writes the xml representation for the object."""
ch = []
for c in self.child:
ch.append(c.WriteXml(w, option))
return ch |
This method sets attribute of a Managed Object. | def setattr(self, key, value):
""" This method sets attribute of a Managed Object. """
if (UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) != None):
if (key in _ManagedObjectMeta[self.classId]):
propMeta = UcsUtils.GetUcsPropertyMeta(self.classId, key)
if (propMeta.ValidatePropertyValue(value) == F... |
This method gets attribute value of a Managed Object. | def getattr(self, key):
""" This method gets attribute value of a Managed Object. """
if ((key == "classId") and (self.__dict__.has_key(key))):
return self.__dict__[key]
if UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId):
if self.__dict__.has_key(key):
if key in _ManagedObjectMeta[self.classId]:
... |
This method marks the managed object dirty. | def MarkDirty(self):
""" This method marks the managed object dirty. """
if ((UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) == None) and (not self.IsDirty())):
self.dirtyMask = ManagedObject.DUMMYDIRTY
else:
self.dirtyMask = self.propMoMeta.mask |
This method returns the Rn for a managed object. | def MakeRn(self):
""" This method returns the Rn for a managed object. """
rnPattern = self.propMoMeta.rn
for prop in re.findall("\[([^\]]*)\]", rnPattern):
if prop in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId):
if (self.getattr(prop) != None):
rnPattern = re.sub('\[%s\]' % prop, '%s' % se... |
Method writes the xml representation of the managed object. | def WriteXml(self, w, option, elementName=None):
""" Method writes the xml representation of the managed object. """
if (option == WriteXmlOption.Dirty and not self.IsDirty()):
return
if elementName == None:
x = w.createElement(self.propMoMeta.xmlAttribute)
else:
x = w.createElement(elementName)
if U... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.