INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Method updates the object from the xml representation of the managed object. | def LoadFromXml(self, node, handle):
""" Method updates the object from the xml representation of the managed object. """
self.SetHandle(handle)
if node.hasAttributes():
# attributes = node._get_attributes()
# attCount = attributes._get_length()
attributes = node.attributes
attCount = len(attributes)
... |
This method sets the attribute of external method object. | def setattr(self, key, value):
""" This method sets the attribute of external method object. """
if key in _MethodFactoryMeta[self.classId]:
self.__dict__[key] = value
elif key == 'errorCode':
self.errorCode = value
elif key == 'errorDescr':
self.errorDescr = value
elif key == 'invocationResult':
... |
This method gets the attribute value of external method object. | def getattr(self, key):
""" This method gets the attribute value of external method object. """
if key in _MethodFactoryMeta[self.classId]:
""" property exists """
return self.__dict__[key]
else:
""" property does not exist """
return None |
This methods sets error attributes of an external method object. | def getErrorResponse(self, errorCode, errorDescr):
""" This methods sets error attributes of an external method object. """
self.errorCode = errorCode
self.errorDescr = errorDescr
self.response = "yes"
return self |
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 elementName == None:
x = w.createElement(self.propMoMeta.xmlAttribute)
else:
x = w.createElement(elementName)
for at in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId):
atMeta ... |
Method updates/fills the object from the xml representation of the managed object. | def LoadFromXml(self, node, handle):
""" Method updates/fills the object from the xml representation of the managed object. """
from Ucs import ClassFactory
self.SetHandle(handle)
if node.hasAttributes():
# attributes = node._get_attributes()
# attCount = attributes._get_length()
attributes = node.att... |
Methods returns the property meta of the provided key for the given classId. | def GetUcsPropertyMeta(classId, key):
""" Methods returns the property meta of the provided key for the given classId. """
if classId in _ManagedObjectMeta:
if key in _ManagedObjectMeta[classId]:
return _ManagedObjectMeta[classId][key]
return None |
Methods returns the method meta of the ExternalMethod. | def GetUcsMethodMeta(classId, key):
""" Methods returns the method meta of the ExternalMethod. """
if classId in _MethodFactoryMeta:
if key in _MethodFactoryMeta[classId]:
return _MethodFactoryMeta[classId][key]
return None |
Methods returns the class meta. | def GetUcsPropertyMetaAttributeList(classId):
""" Methods returns the class meta. """
if classId in _ManagedObjectMeta:
attrList = _ManagedObjectMeta[classId].keys()
attrList.remove("Meta")
return attrList
if classId in _MethodFactoryMeta:
attrList = _MethodFactoryMeta[classId].keys()
attrList.remo... |
Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. | def IsPropertyInMetaIgnoreCase(classId, key):
""" Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. """
if classId in _ManagedObjectMeta:
for prop in _ManagedObjectMeta[classId]:
if (prop.lower() == key.lower()):
return _ManagedObjectMeta[classId... |
Methods whether classId is valid or not . Given class is case insensitive. | def FindClassIdInMoMetaIgnoreCase(classId):
""" Methods whether classId is valid or not . Given class is case insensitive. """
if not classId:
return None
if classId in _ManagedObjectMeta:
return classId
lClassId = classId.lower()
for key in _ManagedObjectMeta.keys():
if (key.lower() == lClassId):
... |
Methods whether classId is valid or not . Given class is case insensitive. | def FindClassIdInMethodMetaIgnoreCase(classId):
""" Methods whether classId is valid or not . Given class is case insensitive. """
if classId in _MethodFactoryMeta:
return classId
lClassId = classId.lower()
for key in _MethodFactoryMeta.keys():
if (key.lower() == classId.lower()):
return key
return ... |
Method checks the filter count and if the filter count exceeds the maxComponents(number of filters), then the given filter
objects get distributed among small groups and then again binded together in complex filters(like and , or) so that the
count of filters can be reduced. | def HandleFilterMaxComponentLimit(handle, lfilter):
"""
Method checks the filter count and if the filter count exceeds the maxComponents(number of filters), then the given filter
objects get distributed among small groups and then again binded together in complex filters(like and , or) so that the
count of filt... |
Method checks for the java in the registry entries. | def CheckRegistryKey(javaKey):
""" Method checks for the java in the registry entries. """
from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx
path = None
try:
aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
rk = OpenKey(aReg, javaKey)
for i in range(1024):
currentVersi... |
Method returns the java installation path in the windows or Linux environment. | def GetJavaInstallationPath():
""" Method returns the java installation path in the windows or Linux environment. """
import os, platform
# Get JavaPath for Ubuntu
# if os.name == "posix":
if platform.system() == "Linux":
path = os.environ.get('JAVA_HOME')
if not path:
raise UcsValidationException(... |
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to
download the files from the Ucs. | def DownloadFile(hUcs, source, destination):
"""
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to
download the files from the Ucs.
"""
import urllib2
from sys import stdout
from time import sleep
httpAddress = "%s/%s" % (hUcs.Uri(),... |
Method returs the path of SyncMoConfig.xml file. | def GetSyncMoConfigFilePath():
""" Method returs the path of SyncMoConfig.xml file. """
return os.path.join(os.path.join(os.path.dirname(__file__), "resources"), "SyncMoConfig.xml") |
Internal support method for SyncManagedObject. | def GetSyncMoConfig(ConfigDoc):
""" Internal support method for SyncManagedObject. """
moConfigMap = {}
configList = ConfigDoc.getElementsByTagName("mo")
for moConfigNode in configList:
classId = None
noun = None
version = None
actionVersion = None
action = None
ignoreReason = None
status ... |
Internal method supporting encryption and decryption functionality. | def Expandkey(key, clen):
""" Internal method supporting encryption and decryption functionality. """
import sha
from string import join
from array import array
blocks = (clen + 19) / 20
xkey = []
seed = key
for i in xrange(blocks):
seed = sha.new(key + seed).digest()
xkey.append(seed)
j = join... |
Encrypts the password using the given key. | def EncryptPassword(password, key):
""" Encrypts the password using the given key. """
from time import time
from array import array
import hmac
import sha
import os
import base64
H = UcsUtils.GetShaHash
uhash = H(','.join(str(x) for x in [`time()`, `os.getpid()`, `len(password)`, password, key]))[:... |
Decrypts the password using the given key with which the password was encrypted first. | def DecryptPassword(cipher, key):
""" Decrypts the password using the given key with which the password was encrypted first. """
import base64
import hmac
import sha
from array import array
H = UcsUtils.GetShaHash
cipher = cipher + "\n"
cipher = base64.decodestring(cipher)
n = len(cipher) - 16 - 8
... |
Method updates the object from the xml. | def LoadFromXml(self, node):
""" Method updates the object from the xml. """
import os
self.classId = node.localName
metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId)
if metaClassId:
self.classId = metaClassId
if node.hasAttribute(NamingPropertyId.DN):
self.dn = node.getAttribute(N... |
Method writes the xml representation of the generic managed object. | def WriteXml(self, w, option, elementName=None):
""" Method writes the xml representation of the generic managed object. """
if elementName == None:
x = w.createElement(self.classId)
else:
x = w.createElement(elementName)
for prop in self.__dict__['properties']:
x.setAttribute(UcsUtils.WordL(prop), se... |
Method creates and returns an object of ManagedObject class using the classId and information from the
Generic managed object. | def ToManagedObject(self):
"""
Method creates and returns an object of ManagedObject class using the classId and information from the
Generic managed object.
"""
from Ucs import ClassFactory
cln = UcsUtils.WordU(self.classId)
mo = ClassFactory(cln)
if mo and (isinstance(mo, ManagedObject) == True):
... |
Method creates and returns an object of _GenericMO class using the classId and other information from the
managed object. | def FromManagedObject(self):
"""
Method creates and returns an object of _GenericMO class using the classId and other information from the
managed object.
"""
import os
if (isinstance(self.mo, ManagedObject) == True):
self.classId = self.mo.classId
if self.mo.getattr('Dn'):
self.dn = self.mo.get... |
Method extracts and returns the child object list same as the given classId | def GetChildClassId(self, classId):
"""
Method extracts and returns the child object list same as the given classId
"""
childList = []
for ch in self.child:
if ch.classId.lower() == classId.lower():
childList.append(ch)
return childList |
Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243 | def _total_seconds(t):
'''
Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243
'''
return sum([
int(t.days * 86400 + t.seconds),
... |
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.datetime` object.
>>> _to_datetime('2013-12-11')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('Wed, 11 Dec 2013')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('Wed, 11 Dec 13')
datetime.datet... | def _to_datetime(t):
'''
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.datetime` object.
>>> _to_datetime('2013-12-11')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('Wed, 11 Dec 2013')
datetime.datetime(2013, 12, 11, 0, 0)
>>> _to_datetime('We... |
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.date` object.
>>> _to_date('2013-12-11')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 2013')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 13')
datetime.date(2013, 12, 11) | def _to_date(t):
'''
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.date` object.
>>> _to_date('2013-12-11')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 2013')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 13')
datetime.date(2013, 12... |
Calculates the estimated delta between two time objects in human-readable
format. Used internally by the :func:`day` and :func:`duration` functions.
:param t1: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
:param t2: timestamp, :class:`datetime.date` or :class:`datet... | def delta(t1, t2, words=True, justnow=datetime.timedelta(seconds=10)):
'''
Calculates the estimated delta between two time objects in human-readable
format. Used internally by the :func:`day` and :func:`duration` functions.
:param t1: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
... |
Date delta compared to ``t``. You can override ``now`` to specify what date
to compare to.
You can override the date format by supplying a ``format`` parameter.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
:param now: default ``None``, optionally a :cl... | def day(t, now=None, format='%B %d'):
'''
Date delta compared to ``t``. You can override ``now`` to specify what date
to compare to.
You can override the date format by supplying a ``format`` parameter.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
... |
Time delta compared to ``t``. You can override ``now`` to specify what time
to compare to.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
:param now: default ``None``, optionally a :class:`datetime.datetime`
object
:param precision: defaul... | def duration(t, now=None, precision=1, pad=', ', words=None,
justnow=datetime.timedelta(seconds=10)):
'''
Time delta compared to ``t``. You can override ``now`` to specify what time
to compare to.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
objec... |
Convert the input to compressed format, works with a
:class:`datetime.timedelta` object or a number that represents the number
of seconds you want to compress. If you supply a timestamp or a
:class:`datetime.datetime` object, it will give the delta relative to the
current time.
You can enable show... | def compress(t, sign=False, pad=''):
'''
Convert the input to compressed format, works with a
:class:`datetime.timedelta` object or a number that represents the number
of seconds you want to compress. If you supply a timestamp or a
:class:`datetime.datetime` object, it will give the delta relative ... |
Performs a search against the index using lunr query syntax.
Results will be returned sorted by their score, the most relevant
results will be returned first.
For more programmatic querying use `lunr.Index.query`.
Args:
query_string (str): A string to parse into a Query.
... | def search(self, query_string):
"""Performs a search against the index using lunr query syntax.
Results will be returned sorted by their score, the most relevant
results will be returned first.
For more programmatic querying use `lunr.Index.query`.
Args:
query_stri... |
Convenience method to create a Query with the Index's fields.
Args:
fields (iterable, optional): The fields to include in the Query,
defaults to the Index's `all_fields`.
Returns:
Query: With the specified fields or all the fields in the Index. | def create_query(self, fields=None):
"""Convenience method to create a Query with the Index's fields.
Args:
fields (iterable, optional): The fields to include in the Query,
defaults to the Index's `all_fields`.
Returns:
Query: With the specified fields o... |
Performs a query against the index using the passed lunr.Query
object.
If performing programmatic queries against the index, this method is
preferred over `lunr.Index.search` so as to avoid the additional query
parsing overhead.
Args:
query (lunr.Query): A configure... | def query(self, query=None, callback=None):
"""Performs a query against the index using the passed lunr.Query
object.
If performing programmatic queries against the index, this method is
preferred over `lunr.Index.search` so as to avoid the additional query
parsing overhead.
... |
Load a serialized index | def load(cls, serialized_index):
"""Load a serialized index"""
from lunr import __TARGET_JS_VERSION__
if isinstance(serialized_index, basestring):
serialized_index = json.loads(serialized_index)
if serialized_index["version"] != __TARGET_JS_VERSION__:
logger.war... |
Pymongo has deprecated the save logic, even though
MongoDB still advertizes that logic in the core API:
https://docs.mongodb.com/manual/reference/method/db.collection.save/
This function provides a compatible interface. | def save(coll, to_save):
"""
Pymongo has deprecated the save logic, even though
MongoDB still advertizes that logic in the core API:
https://docs.mongodb.com/manual/reference/method/db.collection.save/
This function provides a compatible interface.
"""
filter = Projection(['_id'], to_save)
upsert_replace = fun... |
Configuration settings. | def configure(logstash_host=None, logstash_port=None, logdir=None):
'''Configuration settings.'''
if not (logstash_host or logstash_port or logdir):
raise ValueError('you must specify at least one parameter')
config.logstash.host = logstash_host or config.logstash.host
config.logstash.port = l... |
Return new logger which will log both to logstash and to file in JSON
format.
Log files are stored in <logdir>/name.json | def new_logger(name):
'''Return new logger which will log both to logstash and to file in JSON
format.
Log files are stored in <logdir>/name.json
'''
log = get_task_logger(name)
handler = logstash.LogstashHandler(
config.logstash.host, config.logstash.port)
log.addHandler(handler)... |
A ZeroMQ socket context that both constructs a socket and closes it. | def _zmq_socket_context(context, socket_type, bind_endpoints):
"""A ZeroMQ socket context that both constructs a socket and closes it."""
socket = context.socket(socket_type)
try:
for endpoint in bind_endpoints:
try:
socket.bind(endpoint)
except Exception:
... |
Get a configuration value, using fallback for missing values.
Parameters:
config -- the configparser to try to extract the option value from.
section -- the section to extract value from.
option -- the name of the option to extract value from.
fallback -- fallback value to return if no value w... | def _get_with_fallback(config, section, option, fallback):
"""Get a configuration value, using fallback for missing values.
Parameters:
config -- the configparser to try to extract the option value from.
section -- the section to extract value from.
option -- the name of the option to extract ... |
Actually execute the program.
Calling this method can be done from tests to simulate executing the
application from command line.
Parameters:
options -- `optionparser` from config file.
exit_codeword -- an optional exit_message that will shut down Rewind. Used
for testin... | def run(options, exit_codeword=None):
"""Actually execute the program.
Calling this method can be done from tests to simulate executing the
application from command line.
Parameters:
options -- `optionparser` from config file.
exit_codeword -- an optional exit_message that will shut down... |
Entry point for Rewind.
Parses input and calls run() for the real work.
Parameters:
argv -- sys.argv arguments. Can be set for testing purposes.
returns -- the proposed exit code for the program. | def main(argv=None):
"""Entry point for Rewind.
Parses input and calls run() for the real work.
Parameters:
argv -- sys.argv arguments. Can be set for testing purposes.
returns -- the proposed exit code for the program.
"""
parser = argparse.ArgumentParser(
description='Event ... |
Generate a new string and return it. | def generate(self):
"""Generate a new string and return it."""
key = self._propose_new_key()
while self.key_exists(key):
_logger.warning('Previous candidate was used.'
' Regenerating another...')
key = self._propose_new_key()
return key |
Handle one single incoming message on any socket.
This is the inner loop of the main application loop.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
It is crucial that this class function always respond with a
query_socket.sent... | def _handle_one_message(self):
"""Handle one single incoming message on any socket.
This is the inner loop of the main application loop.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
It is crucial that this class function alway... |
Handle an unknown RES command.
The function makes sure to recv all message parts and respond with an
error. | def _handle_unknown_command(self):
"""Handle an unknown RES command.
The function makes sure to recv all message parts and respond with an
error.
"""
while self.query_socket.getsockopt(zmq.RCVMORE):
# Making sure we 'empty' enveloped message. Otherwise, we can't
... |
Handle an incoming event query. | def _handle_event_query(self):
"""Handle an incoming event query."""
assert self.query_socket.getsockopt(zmq.RCVMORE)
fro = self.query_socket.recv().decode()
assert self.query_socket.getsockopt(zmq.RCVMORE)
to = self.query_socket.recv().decode()
assert not self.query_sock... |
Handle an incoming event.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
TODO: Move the content of this function into `_handle_one_message`.
This class function does not simply handle incoming events. | def _handle_incoming_event(self):
"""Handle an incoming event.
Returns True if further messages should be received, False otherwise
(it should quit, that is).
TODO: Move the content of this function into `_handle_one_message`.
This class function does not simply handle incoming... |
A function to calculate the inverse document frequency for a posting.
This is shared between the builder and the index. | def idf(posting, document_count):
"""A function to calculate the inverse document frequency for a posting.
This is shared between the builder and the index.
"""
documents_with_term = 0
for field_name in posting:
if field_name == "_index":
continue
documents_with_term += l... |
Construct the event store to write and write from/to.
The event store is constructed from an optionally given configuration file
and/or command line arguments. Command line arguments has higher
presendence over configuration file attributes.
If a defined event store is missing, `InMemoryEventStore` wi... | def construct_eventstore(config, section=None):
"""Construct the event store to write and write from/to.
The event store is constructed from an optionally given configuration file
and/or command line arguments. Command line arguments has higher
presendence over configuration file attributes.
If a ... |
Helper method to check options.
Arguments:
_class -- the original class that takes received the options.
required_options -- the options that are required. If they are not
present, a ConfigurationError is raised. Given as a
tuple.
optional_optio... | def check_config_options(_class, required_options, optional_options, options):
"""Helper method to check options.
Arguments:
_class -- the original class that takes received the options.
required_options -- the options that are required. If they are not
present, a Conf... |
Retrieve how long ago a file has been created.
:param filename: name of the file
>>> print created('/') # doctest: +SKIP
8 weeks ago | def created(filename):
'''
Retrieve how long ago a file has been created.
:param filename: name of the file
>>> print created('/') # doctest: +SKIP
8 weeks ago
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_CTI... |
Retrieve how long ago a file has been accessed.
:param filename: name of the file
>>> print accessed(__file__) # doctest: +SKIP
just now | def accessed(filename):
'''
Retrieve how long ago a file has been accessed.
:param filename: name of the file
>>> print accessed(__file__) # doctest: +SKIP
just now
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_ATI... |
Retrieve how long ago a file has been modified.
:param filename: name of the file
>>> print modified('/') # doctest: +SKIP
3 days ago | def modified(filename):
'''
Retrieve how long ago a file has been modified.
:param filename: name of the file
>>> print modified('/') # doctest: +SKIP
3 days ago
'''
if isinstance(filename, file):
filename = filename.name
return duration(os.stat(filename)[stat.ST_M... |
Retrieve the size of a file.
:param filename: name of the file
>>> size('/etc/mime.types') # doctest: +SKIP
23.70 kB | def size(filename, format='decimal'):
'''
Retrieve the size of a file.
:param filename: name of the file
>>> size('/etc/mime.types') # doctest: +SKIP
23.70 kB
'''
if isinstance(filename, file):
filename = filename.name
return filesize(os.stat(filename)[stat.ST_SIZE], ... |
Paper: First, to encode a single frame we take the maximum value for each pixel colour
value over the frame being encoded and the previous frame. This was necessary to
remove flickering that is present in games where some objects appear only in even
frames while other obj... | def _observation(self, observation):
""" Paper: First, to encode a single frame we take the maximum value for each pixel colour
value over the frame being encoded and the previous frame. This was necessary to
remove flickering that is present in games where some objects appear on... |
Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loading text too::
{% show_more "even more" "working" %}
Must... | def show_more(context, label=None, loading=settings.LOADING):
"""Show the link to get the next page in a Twitter-like pagination.
Usage::
{% show_more %}
Alternatively you can override the label passed to the default template::
{% show_more "even more" %}
You can override the loadin... |
Show the link to get the next page in a Twitter-like pagination in a
template for table.
Usage::
{% show_more_table %}
Alternatively you can override the label passed to the default template::
{% show_more_table "even more" %}
You can override the loading text too::
{% show... | def show_more_table(context, label=None, loading=settings.LOADING):
"""Show the link to get the next page in a Twitter-like pagination in a
template for table.
Usage::
{% show_more_table %}
Alternatively you can override the label passed to the default template::
{% show_more_table ... |
Returns a trimmer function from a string of word characters.
TODO: lunr-languages ships with lists of word characters for each language
I haven't found an equivalent in Python, we may need to copy it. | def generate_trimmer(word_characters):
"""Returns a trimmer function from a string of word characters.
TODO: lunr-languages ships with lists of word characters for each language
I haven't found an equivalent in Python, we may need to copy it.
"""
start_re = r"^[^{}]+".format(word_characters)
en... |
Return a string in lowerCamelCase
Examples:
"people" -> "people"
"profile images" -> "profileImages" | def camelcase(string):
'''Return a string in lowerCamelCase
Examples:
"people" -> "people"
"profile images" -> "profileImages"
'''
out = slug(string).replace('-', ' ').title().replace(' ', '')
return out[0].lower() + out[1:] |
Calculates the position within the vector to insert a given index.
This is used internally by insert and upsert. If there are duplicate
indexes then the position is returned as if the value for that index
were to be updated, but it is the callers responsibility to check
whether there is... | def position_for_index(self, index):
"""Calculates the position within the vector to insert a given index.
This is used internally by insert and upsert. If there are duplicate
indexes then the position is returned as if the value for that index
were to be updated, but it is the callers ... |
Inserts an element at an index within the vector.
Does not allow duplicates, will throw an error if there is already an
entry for this index. | def insert(self, insert_index, val):
"""Inserts an element at an index within the vector.
Does not allow duplicates, will throw an error if there is already an
entry for this index.
"""
def prevent_duplicates(index, val):
raise BaseLunrException("Duplicate index")
... |
Inserts or updates an existing index within the vector.
Args:
- insert_index (int): The index at which the element should be
inserted.
- val (int|float): The value to be inserted into the vector.
- fn (callable, optional): An optional callable taking two
... | def upsert(self, insert_index, val, fn=None):
"""Inserts or updates an existing index within the vector.
Args:
- insert_index (int): The index at which the element should be
inserted.
- val (int|float): The value to be inserted into the vector.
- fn (... |
Converts the vector to an array of the elements within the vector | def to_list(self):
"""Converts the vector to an array of the elements within the vector"""
output = []
for i in range(1, len(self.elements), 2):
output.append(self.elements[i])
return output |
Calculates the dot product of this vector and another vector. | def dot(self, other):
"""Calculates the dot product of this vector and another vector."""
dot_product = 0
a = self.elements
b = other.elements
a_len = len(a)
b_len = len(b)
i = j = 0
while i < a_len and j < b_len:
a_val = a[i]
b_va... |
Calculates the cosine similarity between this vector and another
vector. | def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude |
Printable Basic Bank Account Number in base-10.
:param number: string
>>> bban_base10('01234567')
'45670123'
>>> bban_base10('ABCD')
'10111213' | def bban_base10(number):
'''
Printable Basic Bank Account Number in base-10.
:param number: string
>>> bban_base10('01234567')
'45670123'
>>> bban_base10('ABCD')
'10111213'
'''
number = bban_compact(number)
number = number[4:] + number[:4]
return ''.join([str(IBAN_ALPHABET.... |
Printable Basic Bank Account Number (BBAN) for the given country code. The
``country`` must be a valid ISO 3166-2 country code.
:param value: string or int
:param country: string
>>> bban('068-9999995-01', 'BE')
'068999999501'
>>> bban('555', 'NL')
'555'
>>> bban('555', 'NL', validate=... | def bban(value, country=None, validate=False):
'''
Printable Basic Bank Account Number (BBAN) for the given country code. The
``country`` must be a valid ISO 3166-2 country code.
:param value: string or int
:param country: string
>>> bban('068-9999995-01', 'BE')
'068999999501'
>>> bban... |
Printable International Bank Account Number (IBAN) as specified in ISO
13616.
:param number: string
>>> iban('BE43068999999501')
'BE43 0689 9999 9501'
>>> iban('XY32012341234123', validate=True)
Traceback (most recent call last):
...
ValueError: Invalid IBAN, country unknown
>>... | def iban(number, validate=False):
'''
Printable International Bank Account Number (IBAN) as specified in ISO
13616.
:param number: string
>>> iban('BE43068999999501')
'BE43 0689 9999 9501'
>>> iban('XY32012341234123', validate=True)
Traceback (most recent call last):
...
Va... |
urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so. | def _add_scheme():
"""
urllib.parse doesn't support the mongodb scheme, but it's easy
to make it so.
"""
lists = [
urllib.parse.uses_relative,
urllib.parse.uses_netloc,
urllib.parse.uses_query,
]
for l in lists:
l.append('mongodb') |
Adds a field to the list of document fields that will be indexed.
Every document being indexed should have this field. None values for
this field in indexed documents will not cause errors but will limit
the chance of that document being retrieved by searches.
All fields should be adde... | def field(self, field_name, boost=1, extractor=None):
"""Adds a field to the list of document fields that will be indexed.
Every document being indexed should have this field. None values for
this field in indexed documents will not cause errors but will limit
the chance of that documen... |
A parameter to tune the amount of field length normalisation that is
applied when calculating relevance scores.
A value of 0 will completely disable any normalisation and a value of 1
will fully normalise field lengths. The default is 0.75. Values of b
will be clamped to the range 0 - 1... | def b(self, number):
"""A parameter to tune the amount of field length normalisation that is
applied when calculating relevance scores.
A value of 0 will completely disable any normalisation and a value of 1
will fully normalise field lengths. The default is 0.75. Values of b
wi... |
Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (by default
this is 'id') and it should h... | def add(self, doc, attributes=None):
"""Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (... |
Builds the index, creating an instance of `lunr.Index`.
This completes the indexing process and should only be called once all
documents have been added to the index. | def build(self):
"""Builds the index, creating an instance of `lunr.Index`.
This completes the indexing process and should only be called once all
documents have been added to the index.
"""
self._calculate_average_field_lengths()
self._create_field_vectors()
sel... |
Creates a token set of all tokens in the index using `lunr.TokenSet` | def _create_token_set(self):
"""Creates a token set of all tokens in the index using `lunr.TokenSet`
"""
self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys()))) |
Calculates the average document length for this index | def _calculate_average_field_lengths(self):
"""Calculates the average document length for this index"""
accumulator = defaultdict(int)
documents_with_field = defaultdict(int)
for field_ref, length in self.field_lengths.items():
_field_ref = FieldRef.from_string(field_ref)
... |
Builds a vector space model of every document using lunr.Vector. | def _create_field_vectors(self):
"""Builds a vector space model of every document using lunr.Vector."""
field_vectors = {}
term_idf_cache = {}
for field_ref, term_frequencies in self.field_term_frequencies.items():
_field_ref = FieldRef.from_string(field_ref)
fie... |
Estimate the number of documents in the collection
matching the filter.
Sample may be a fixed number of documents to sample
or a percentage of the total collection size.
>>> coll = getfixture('bulky_collection')
>>> estimate(coll)
100
>>> query = {"val": {"$gte": 50}}
>>> val = estimat... | def estimate(coll, filter={}, sample=1):
"""
Estimate the number of documents in the collection
matching the filter.
Sample may be a fixed number of documents to sample
or a percentage of the total collection size.
>>> coll = getfixture('bulky_collection')
>>> estimate(coll)
100
>>... |
Convert native data to JSON API
Tries each of the methods in `wrappers`, using the first successful
one, or raises `WrapperNotApplicable`. | def render(self, data, accepted_media_type=None, renderer_context=None):
"""Convert native data to JSON API
Tries each of the methods in `wrappers`, using the first successful
one, or raises `WrapperNotApplicable`.
"""
wrapper = None
success = False
for wrapper... |
Convert parser errors to the JSON API Error format
Parser errors have a status code of 400, like field errors, but have
the same native format as generic errors. Also, the detail message is
often specific to the input, so the error is listed as a 'detail'
rather than a 'title'. | def wrap_parser_error(self, data, renderer_context):
"""
Convert parser errors to the JSON API Error format
Parser errors have a status code of 400, like field errors, but have
the same native format as generic errors. Also, the detail message is
often specific to the input, so... |
Convert field error native data to the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for field errors is a dictionary where the keys are
field names (or 'non_field_errors' for additional errors) and the
values are a list of error ... | def wrap_field_error(self, data, renderer_context):
"""
Convert field error native data to the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for field errors is a dictionary where the keys are
field names (or 'non_field_er... |
Convert generic error native data using the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for errors that are not bad requests, such as
authentication issues or missing content, is a dictionary with a
'detail' key and a string val... | def wrap_generic_error(self, data, renderer_context):
"""
Convert generic error native data using the JSON API Error format
See the note about the JSON API Error format on `wrap_error`.
The native format for errors that are not bad requests, such as
authentication issues or mis... |
Convert error native data to the JSON API Error format
JSON API has a different format for errors, but Django REST Framework
doesn't have a separate rendering path for errors. This results in
some guesswork to determine if data is an error, what kind, and how
to handle it.
As ... | def wrap_error(
self, data, renderer_context, keys_are_fields, issue_is_title):
"""Convert error native data to the JSON API Error format
JSON API has a different format for errors, but Django REST Framework
doesn't have a separate rendering path for errors. This results in
... |
Wrap OPTIONS data as JSON API meta value | def wrap_options(self, data, renderer_context):
'''Wrap OPTIONS data as JSON API meta value'''
request = renderer_context.get("request", None)
method = request and getattr(request, 'method')
if method != 'OPTIONS':
raise WrapperNotApplicable("Request method must be OPTIONS")
... |
Convert paginated data to JSON API with meta | def wrap_paginated(self, data, renderer_context):
"""Convert paginated data to JSON API with meta"""
pagination_keys = ['count', 'next', 'previous', 'results']
for key in pagination_keys:
if not (data and key in data):
raise WrapperNotApplicable('Not paginated result... |
Convert native data to a JSON API resource collection
This wrapper expects a standard DRF data object (a dict-like
object with a `fields` dict-like attribute), or a list of
such data objects. | def wrap_default(self, data, renderer_context):
"""Convert native data to a JSON API resource collection
This wrapper expects a standard DRF data object (a dict-like
object with a `fields` dict-like attribute), or a list of
such data objects.
"""
wrapper = self.dict_cla... |
For a naive utc_datetime, return the same time in the local timezone
(also naive). | def _make_local(utc_datetime):
"""
For a naive utc_datetime, return the same time in the local timezone
(also naive).
"""
return utc_datetime.replace(
tzinfo=dateutil.tz.tzutc()
).astimezone(dateutil.tz.tzlocal()).replace(
tzinfo=None
) |
Acquire the lock. Blocks indefinitely until lock is available
unless `lock_timeout` was supplied. If the lock_timeout elapses,
raises LockTimeout. | def acquire_lock(self):
"""
Acquire the lock. Blocks indefinitely until lock is available
unless `lock_timeout` was supplied. If the lock_timeout elapses,
raises LockTimeout.
"""
# first ensure that a record exists for this session id
try:
self.collection.insert_one(dict(_id=self.id))
except pymongo.... |
doublec(j) is TRUE <=> j,(j-1) contain a double consonant. | def doublec(self, j):
"""doublec(j) is TRUE <=> j,(j-1) contain a double consonant."""
if j < (self.k0 + 1):
return 0
if self.b[j] != self.b[j - 1]:
return 0
return self.cons(j) |
cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray. | def cvc(self, i):
"""cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
"""
... |
ends(s) is TRUE <=> k0,...k ends with the string s. | def ends(self, s):
"""ends(s) is TRUE <=> k0,...k ends with the string s."""
length = len(s)
if s[length - 1] != self.b[self.k]: # tiny speed-up
return 0
if length > (self.k - self.k0 + 1):
return 0
if self.b[self.k - length + 1 : self.k + 1] != s:
... |
step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting ... | def step1ab(self):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> ... |
step1c() turns terminal y to i when there is another vowel in the stem. | def step1c(self):
"""step1c() turns terminal y to i when there is another vowel in the stem."""
if self.ends("y") and self.vowelinstem():
self.b = self.b[: self.k] + "i" + self.b[self.k + 1 :] |
step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0. | def step2(self):
"""step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0.
"""
if self.b[self.k - 1] == "a":
if self.ends("ational"):
self.r("ate")
... |
step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1. | def step5(self):
"""step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1.
"""
self.j = self.k
if self.b[self.k] == "e":
a = self.m()
if a > 1 or (a == 1 and not self.cvc(self.k - 1)):
self.k = self.k - 1
if self.b... |
In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == '\0'). The
stemmer adjusts the characters p[i] ... p[j] and returns the new
end-point of the string, k. ... | def stem(self, p, metadata=None):
"""In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == '\0'). The
stemmer adjusts the characters p[i] ... p[j] and returns... |
Set the boot device for the node.
Set the boot device to use on next reboot of the node.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if the boot device will
persist to all future boots, ... | def set_boot_device(self, device, persistent=False):
"""Set the boot device for the node.
Set the boot device to use on next reboot of the node.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Boolean value. True if th... |
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 required pa... | 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.
:raises: ... |
A convenience function to configure and construct a lunr.Index.
Args:
ref (str): The key in the documents to be used a the reference.
fields (list): A list of strings defining fields in the documents to
index. Optionally a list of dictionaries with three keys:
`field_name` d... | def lunr(ref, fields, documents, languages=None):
"""A convenience function to configure and construct a lunr.Index.
Args:
ref (str): The key in the documents to be used a the reference.
fields (list): A list of strings defining fields in the documents to
index. Optionally a list of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.