_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1700
|
DataGenerator.from_config
|
train
|
def from_config(self, k, v):
"""
Hook method that allows converting values from the dictionary.
:param k: the key in the dictionary
:type k: str
:param v: the value
:type v: object
:return: the potentially parsed value
:rtype: object
|
python
|
{
"resource": ""
}
|
q1701
|
SimpleExperiment.configure_splitevaluator
|
train
|
def configure_splitevaluator(self):
"""
Configures and returns the SplitEvaluator and Classifier instance as tuple.
:return: evaluator and classifier
:rtype: tuple
"""
if self.classification:
speval = javabridge.make_instance("weka/experiment/ClassifierSplitEvaluator", "()V")
else:
|
python
|
{
"resource": ""
}
|
q1702
|
SimpleExperiment.setup
|
train
|
def setup(self):
"""
Initializes the experiment.
"""
# basic options
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
javabridge.get_env().make_object_array(0, javabridge.get_env().find_class("weka/classifiers/Classifier")))
javabridge.call(
self.jobject, "setUsePropertyIterator", "(Z)V", True)
javabridge.call(
self.jobject, "setRunLower", "(I)V", 1)
javabridge.call(
self.jobject, "setRunUpper", "(I)V", self.runs)
# setup result producer
rproducer, prop_path = self.configure_resultproducer()
javabridge.call(
self.jobject, "setResultProducer", "(Lweka/experiment/ResultProducer;)V", rproducer)
javabridge.call(
self.jobject, "setPropertyPath", "([Lweka/experiment/PropertyNode;)V", prop_path)
# classifiers
classifiers = javabridge.get_env().make_object_array(
len(self.classifiers), javabridge.get_env().find_class("weka/classifiers/Classifier"))
for i, classifier in enumerate(self.classifiers):
if type(classifier) is Classifier:
javabridge.get_env().set_object_array_element(
classifiers, i, classifier.jobject)
else:
javabridge.get_env().set_object_array_element(
classifiers, i, from_commandline(classifier).jobject)
javabridge.call(
self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V",
|
python
|
{
"resource": ""
}
|
q1703
|
SimpleExperiment.run
|
train
|
def run(self):
"""
Executes the experiment.
"""
logger.info("Initializing...")
javabridge.call(self.jobject, "initialize", "()V")
logger.info("Running...")
|
python
|
{
"resource": ""
}
|
q1704
|
SimpleExperiment.load
|
train
|
def load(cls, filename):
"""
Loads the experiment from disk.
:param filename: the filename of the experiment to load
:type filename: str
:return: the experiment
:rtype: Experiment
"""
jobject = javabridge.static_call(
|
python
|
{
"resource": ""
}
|
q1705
|
SimpleRandomSplitExperiment.configure_resultproducer
|
train
|
def configure_resultproducer(self):
"""
Configures and returns the ResultProducer and PropertyPath as tuple.
:return: producer and property path
:rtype: tuple
"""
rproducer = javabridge.make_instance("weka/experiment/RandomSplitResultProducer", "()V")
javabridge.call(rproducer, "setRandomizeData", "(Z)V", not self.preserve_order)
javabridge.call(rproducer, "setTrainPercent", "(D)V", self.percentage)
speval, classifier = self.configure_splitevaluator()
javabridge.call(rproducer, "setSplitEvaluator", "(Lweka/experiment/SplitEvaluator;)V", speval)
prop_path = javabridge.get_env().make_object_array(
2, javabridge.get_env().find_class("weka/experiment/PropertyNode"))
cls = javabridge.get_env().find_class("weka/experiment/RandomSplitResultProducer")
desc = javabridge.make_instance(
"java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "splitEvaluator", cls)
node = javabridge.make_instance(
"weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V",
|
python
|
{
"resource": ""
}
|
q1706
|
ResultMatrix.set_row_name
|
train
|
def set_row_name(self, index, name):
"""
Sets the row name.
:param index: the 0-based row index
:type index: int
:param name: the name of the row
:type name: str
|
python
|
{
"resource": ""
}
|
q1707
|
ResultMatrix.set_col_name
|
train
|
def set_col_name(self, index, name):
"""
Sets the column name.
:param index: the 0-based row index
:type index: int
:param name: the name of the column
:type name: str
|
python
|
{
"resource": ""
}
|
q1708
|
RCRequest.validate
|
train
|
def validate(self):
"""Checks that at least required params exist"""
required = ['token', 'content']
valid_data = {
'exp_record': (['type', 'format'], 'record',
'Exporting record but content is not record'),
'imp_record': (['type', 'overwriteBehavior', 'data', 'format'],
'record', 'Importing record but content is not record'),
'metadata': (['format'], 'metadata',
'Requesting metadata but content != metadata'),
'exp_file': (['action', 'record', 'field'], 'file',
'Exporting file but content is not file'),
'imp_file': (['action', 'record', 'field'], 'file',
'Importing file but content is not file'),
'del_file': (['action', 'record', 'field'], 'file',
'Deleteing file but content is not file'),
'exp_event': (['format'], 'event',
'Exporting events but content is not event'),
'exp_arm': (['format'], 'arm',
'Exporting arms but content is not arm'),
'exp_fem': (['format'], 'formEventMapping',
'Exporting form-event mappings but content != formEventMapping'),
'exp_user': (['format'], 'user',
'Exporting users but content is not user'),
|
python
|
{
"resource": ""
}
|
q1709
|
RCRequest.execute
|
train
|
def execute(self, **kwargs):
"""Execute the API request and return data
Parameters
----------
kwargs :
passed to requests.post()
Returns
-------
response : list, str
data object from JSON decoding process if format=='json',
else return raw
|
python
|
{
"resource": ""
}
|
q1710
|
RCRequest.get_content
|
train
|
def get_content(self, r):
"""Abstraction for grabbing content from a returned response"""
if self.type == 'exp_file':
# don't use the decoded r.text
return r.content
elif self.type == 'version':
return r.content
else:
if self.fmt == 'json':
content = {}
|
python
|
{
"resource": ""
}
|
q1711
|
RCRequest.raise_for_status
|
train
|
def raise_for_status(self, r):
"""Given a response, raise for bad status for certain actions
Some redcap api methods don't return error messages
that the user could test for or otherwise use. Therefore, we
need to do the testing ourself
Raising for everything wouldn't let the user see the
(hopefully helpful) error message"""
|
python
|
{
"resource": ""
}
|
q1712
|
Project.__basepl
|
train
|
def __basepl(self, content, rec_type='flat', format='json'):
"""Return a dictionary which can be used as is or added to for
payloads"""
d
|
python
|
{
"resource": ""
}
|
q1713
|
Project.filter_metadata
|
train
|
def filter_metadata(self, key):
"""
Return a list of values for the metadata key from each field
of the project's metadata.
Parameters
----------
key: str
A known key in the metadata
|
python
|
{
"resource": ""
}
|
q1714
|
Project.export_fem
|
train
|
def export_fem(self, arms=None, format='json', df_kwargs=None):
"""
Export the project's form to event mapping
Parameters
----------
arms : list
Limit exported form event mappings to these arm numbers
format : (``'json'``), ``'csv'``, ``'xml'``
Return the form event mappings in native objects,
csv or xml, ``'df''`` will return a ``pandas.DataFrame``
df_kwargs : dict
Passed to pandas.read_csv to control construction of
returned DataFrame
Returns
-------
fem : list, str, ``pandas.DataFrame``
form-event mapping for the project
"""
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
pl = self.__basepl('formEventMapping', format=ret_format)
to_add = [arms]
str_add =
|
python
|
{
"resource": ""
}
|
q1715
|
Project.export_metadata
|
train
|
def export_metadata(self, fields=None, forms=None, format='json',
df_kwargs=None):
"""
Export the project's metadata
Parameters
----------
fields : list
Limit exported metadata to these fields
forms : list
Limit exported metadata to these forms
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Return the metadata in native objects, csv or xml.
``'df'`` will return a ``pandas.DataFrame``.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default ``{'index_col': 'field_name'}``
Returns
-------
metadata : list, str, ``pandas.DataFrame``
metadata sttructure for the project.
"""
ret_format = format
if format == 'df':
from pandas import read_csv
ret_format = 'csv'
|
python
|
{
"resource": ""
}
|
q1716
|
Project.export_records
|
train
|
def export_records(self, records=None, fields=None, forms=None,
events=None, raw_or_label='raw', event_name='label',
format='json', export_survey_fields=False,
export_data_access_groups=False, df_kwargs=None,
export_checkbox_labels=False, filter_logic=None):
"""
Export data from the REDCap project.
Parameters
----------
records : list
array of record names specifying specific records to export.
by default, all records are exported
fields : list
array of field names specifying specific fields to pull
by default, all fields are exported
forms : list
array of form names to export. If in the web UI, the form
name has a space in it, replace the space with an underscore
by default, all forms are exported
events : list
an array of unique event names from which to export records
:note: this only applies to longitudinal projects
raw_or_label : (``'raw'``), ``'label'``, ``'both'``
export the raw coded values or labels for the options of
multiple choice fields, or both
event_name : (``'label'``), ``'unique'``
export the unique event name or the event label
format : (``'json'``), ``'csv'``, ``'xml'``, ``'df'``
Format of returned data. ``'json'`` returns json-decoded
objects while ``'csv'`` and ``'xml'`` return other formats.
``'df'`` will attempt to return a ``pandas.DataFrame``.
export_survey_fields : (``False``), True
specifies whether or not to export the survey identifier
field (e.g., "redcap_survey_identifier") or survey timestamp
fields (e.g., form_name+"_timestamp") when surveys are
utilized in the project.
export_data_access_groups : (``False``), ``True``
specifies whether or not to export the
``"redcap_data_access_group"`` field when data access groups
are utilized in the project.
:note: This flag is only viable if the user whose token is
being used to make the API request is *not* in a data
access group. If the user is in a group, then this flag
will revert to its default value.
df_kwargs : dict
Passed to ``pandas.read_csv`` to control construction of
returned DataFrame.
by default, ``{'index_col': self.def_field}``
export_checkbox_labels : (``False``), ``True``
specify whether to export checkbox
|
python
|
{
"resource": ""
}
|
q1717
|
Project.__meta_metadata
|
train
|
def __meta_metadata(self, field, key):
"""Return the value for key for the field in the metadata"""
mf = ''
try:
mf = str([f[key] for f in self.metadata
if f['field_name'] == field][0])
|
python
|
{
"resource": ""
}
|
q1718
|
Project.filter
|
train
|
def filter(self, query, output_fields=None):
"""Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields desired for matching subjects
Returns
-------
A list of dictionaries whose keys contains at least the default field
and at most each key passed in with output_fields, each dictionary
representing a surviving row in the database.
"""
query_keys = query.fields()
if not set(query_keys).issubset(set(self.field_names)):
|
python
|
{
"resource": ""
}
|
q1719
|
Project.names_labels
|
train
|
def names_labels(self, do_print=False):
"""Simple helper function to get all field names and labels """
if do_print:
|
python
|
{
"resource": ""
}
|
q1720
|
Project.import_records
|
train
|
def import_records(self, to_import, overwrite='normal', format='json',
return_format='json', return_content='count',
date_format='YMD', force_auto_number=False):
"""
Import data into the RedCap Project
Parameters
----------
to_import : array of dicts, csv/xml string, ``pandas.DataFrame``
:note:
If you pass a csv or xml string, you should use the
``format`` parameter appropriately.
:note:
Keys of the dictionaries should be subset of project's,
fields, but this isn't a requirement. If you provide keys
that aren't defined fields, the returned response will
contain an ``'error'`` key.
overwrite : ('normal'), 'overwrite'
``'overwrite'`` will erase values previously stored in the
database if not specified in the to_import dictionaries.
format : ('json'), 'xml', 'csv'
Format of incoming data. By default, to_import will be json-encoded
return_format : ('json'), 'csv', 'xml'
Response format. By default, response will be json-decoded.
return_content : ('count'), 'ids', 'nothing'
By default, the response contains a 'count' key with the number of
records just imported. By specifying 'ids', a list of ids
imported will be returned. 'nothing' will only return
the HTTP status code and no message.
date_format : ('YMD'), 'DMY', 'MDY'
Describes the formatting of dates. By default, date strings
are formatted as 'YYYY-MM-DD' corresponding to 'YMD'. If date
strings are formatted as 'MM/DD/YYYY' set this parameter as
'MDY' and if formatted as 'DD/MM/YYYY' set as 'DMY'. No
other formattings are allowed.
force_auto_number : ('False') Enables automatic assignment of record IDs
of imported records by REDCap. If this is set to true, and auto-numbering
for records is enabled for the project, auto-numbering of imported records
will be enabled.
Returns
-------
response : dict, str
response from REDCap API, json-decoded if ``return_format`` == ``'json'``
|
python
|
{
"resource": ""
}
|
q1721
|
Project.export_file
|
train
|
def export_file(self, record, field, event=None, return_format='json'):
"""
Export the contents of a file stored for a particular record
Notes
-----
Unlike other export methods, this works on a single record.
Parameters
----------
record : str
record ID
field : str
field name containing the file to be exported.
event: str
for longitudinal projects, specify the unique event here
return_format: ('json'), 'csv', 'xml'
format of error message
Returns
-------
content : bytes
content of the file
content_map : dict
content-type dictionary
"""
self._check_file_field(field)
# load up payload
pl = self.__basepl(content='file', format=return_format)
# there's no format field in this call
del pl['format']
pl['returnFormat'] = return_format
pl['action'] = 'export'
pl['field'] = field
|
python
|
{
"resource": ""
}
|
q1722
|
Project.import_file
|
train
|
def import_file(self, record, field, fname, fobj, event=None,
return_format='json'):
"""
Import the contents of a file represented by fobj to a
particular records field
Parameters
----------
record : str
record ID
field : str
field name where the file will go
fname : str
file name visible in REDCap UI
fobj : file object
file object as returned by `open`
event : str
|
python
|
{
"resource": ""
}
|
q1723
|
Project.delete_file
|
train
|
def delete_file(self, record, field, return_format='json', event=None):
"""
Delete a file from REDCap
Notes
-----
There is no undo button to this.
Parameters
----------
record : str
record ID
field : str
field name
return_format : (``'json'``), ``'csv'``, ``'xml'``
return format for error message
event : str
If longitudinal project, event to delete file from
Returns
-------
response : dict, str
|
python
|
{
"resource": ""
}
|
q1724
|
Project._check_file_field
|
train
|
def _check_file_field(self, field):
"""Check that field exists and is a file field"""
is_field = field in self.field_names
is_file = self.__meta_metadata(field, 'field_type')
|
python
|
{
"resource": ""
}
|
q1725
|
Project.export_users
|
train
|
def export_users(self, format='json'):
"""
Export the users of the Project
Notes
-----
Each user will have the following keys:
* ``'firstname'`` : User's first name
* ``'lastname'`` : User's last name
* ``'email'`` : Email address
* ``'username'`` : User's username
* ``'expiration'`` : Project access expiration date
* ``'data_access_group'`` : data access group ID
* ``'data_export'`` : (0=no access, 2=De-Identified, 1=Full Data Set)
|
python
|
{
"resource": ""
}
|
q1726
|
Project.export_survey_participant_list
|
train
|
def export_survey_participant_list(self, instrument, event=None, format='json'):
"""
Export the Survey Participant List
Notes
-----
The passed instrument must be set up as a survey instrument.
Parameters
----------
instrument: str
Name of instrument as seen
|
python
|
{
"resource": ""
}
|
q1727
|
create_new_username
|
train
|
def create_new_username(ip, devicetype=None, timeout=_DEFAULT_TIMEOUT):
"""Interactive helper function to generate a new anonymous username.
Args:
ip: ip address of the bridge
devicetype (optional): devicetype to register with the bridge. If
unprovided, generates a device type based on the local hostname.
timeout (optional, default=5): request timeout in seconds
Raises:
QhueException if something went wrong with username generation (for
example, if the bridge button wasn't pressed).
"""
res = Resource(_api_url(ip), timeout)
prompt = "Press the Bridge button, then press Return: "
# Deal with one of the sillier
|
python
|
{
"resource": ""
}
|
q1728
|
GordonRouter.run
|
train
|
async def run(self):
"""Entrypoint to route messages between plugins."""
logging.info('Starting message router...')
coroutines = set()
while True:
coro =
|
python
|
{
"resource": ""
}
|
q1729
|
shutdown
|
train
|
async def shutdown(sig, loop):
"""Gracefully cancel current tasks when app receives a shutdown signal."""
logging.info(f'Received exit signal {sig.name}...')
tasks = [task for task in asyncio.Task.all_tasks() if task is not
asyncio.tasks.Task.current_task()]
for task in tasks:
logging.debug(f'Cancelling task: {task}')
|
python
|
{
"resource": ""
}
|
q1730
|
_deep_merge_dict
|
train
|
def _deep_merge_dict(a, b):
"""Additively merge right side dict into left side dict."""
for k, v in b.items():
if k in a and isinstance(a[k], dict) and
|
python
|
{
"resource": ""
}
|
q1731
|
load_plugins
|
train
|
def load_plugins(config, plugin_kwargs):
"""
Discover and instantiate plugins.
Args:
config (dict): loaded configuration for the Gordon service.
plugin_kwargs (dict): keyword arguments to give to plugins
during instantiation.
Returns:
Tuple of 3 lists: list of names of plugins, list of
instantiated plugin objects, and any errors encountered while
loading/instantiating plugins. A tuple of three empty lists is
returned if there are no plugins found or activated in gordon
config.
"""
installed_plugins = _gather_installed_plugins()
metrics_plugin = _get_metrics_plugin(config, installed_plugins)
if metrics_plugin:
plugin_kwargs['metrics'] = metrics_plugin
active_plugins = _get_activated_plugins(config, installed_plugins)
|
python
|
{
"resource": ""
}
|
q1732
|
UDPClientProtocol.connection_made
|
train
|
def connection_made(self, transport):
"""Create connection, use to send message and close.
Args:
transport (asyncio.DatagramTransport): Transport used for sending.
"""
|
python
|
{
"resource": ""
}
|
q1733
|
UDPClient.send
|
train
|
async def send(self, metric):
"""Transform metric to JSON bytestring and send to server.
Args:
metric (dict): Complete metric to send
|
python
|
{
"resource": ""
}
|
q1734
|
RecordChecker.check_record
|
train
|
async def check_record(self, record, timeout=60):
"""Measures the time for a DNS record to become available.
Query a provided DNS server multiple times until the reply matches the
information in the record or until timeout is reached.
Args:
record (dict): DNS record as a dict with record properties.
timeout (int): Time threshold to query the DNS server.
"""
start_time = time.time()
name, rr_data, r_type, ttl = self._extract_record_data(record)
r_type_code = async_dns.types.get_code(r_type)
resolvable_record = False
retries = 0
sleep_time = 5
while not resolvable_record and \
timeout > retries * sleep_time:
retries += 1
resolver_res = await self._resolver.query(name, r_type_code)
possible_ans = resolver_res.an
resolvable_record = \
await self._check_resolver_ans(possible_ans, name,
|
python
|
{
"resource": ""
}
|
q1735
|
RecordChecker._check_resolver_ans
|
train
|
async def _check_resolver_ans(
self, dns_answer_list, record_name,
record_data_list, record_ttl, record_type_code):
"""Check if resolver answer is equal to record data.
Args:
dns_answer_list (list): DNS answer list contains record objects.
record_name (str): Record name.
record_data_list (list): List of data values for the record.
record_ttl (int): Record time-to-live info.
record_type_code (int): Record type code.
Returns:
boolean indicating if DNS answer data
|
python
|
{
"resource": ""
}
|
q1736
|
LoggerAdapter.log
|
train
|
def log(self, metric):
"""Format and output metric.
Args:
metric (dict): Complete metric.
"""
|
python
|
{
"resource": ""
}
|
q1737
|
Atbash.encipher
|
train
|
def encipher(self,string,keep_punct=False):
"""Encipher string using Atbash cipher.
Example::
ciphertext = Atbash().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The enciphered string.
|
python
|
{
"resource": ""
}
|
q1738
|
PolybiusSquare.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Polybius square cipher according to initialised key.
Example::
ciphertext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The ciphertext will be twice the length of the plaintext.
"""
|
python
|
{
"resource": ""
}
|
q1739
|
PolybiusSquare.decipher
|
train
|
def decipher(self,string):
"""Decipher string using Polybius square cipher according to initialised key.
Example::
plaintext = Polybius('APCZWRLFBDKOTYUQGENHXMIVS',5,'MKSBU').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintext will be half the length of the ciphertext.
"""
|
python
|
{
"resource": ""
}
|
q1740
|
ADFGVX.decipher
|
train
|
def decipher(self,string):
"""Decipher string using ADFGVX cipher according to initialised key information. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ADFGVX('ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8','HELLO').decipher(ciphertext)
:param string: The string to decipher.
:returns: The enciphered string.
|
python
|
{
"resource": ""
}
|
q1741
|
Enigma.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Enigma M3 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Enigma(settings=('A','A','A'),rotors=(1,2,3),reflector='B',
ringstellung=('F','V','N'),steckers=[('P','O'),('M','L'),
|
python
|
{
"resource": ""
}
|
q1742
|
ic
|
train
|
def ic(ctext):
''' takes ciphertext, calculates index of coincidence.'''
counts = ngram_count(ctext,N=1)
icval = 0
for k in counts.keys():
|
python
|
{
"resource": ""
}
|
q1743
|
restore_punctuation
|
train
|
def restore_punctuation(original,modified):
''' If punctuation was accidently removed, use this function to restore it.
requires the orignial string with punctuation. '''
ret = ''
count = 0
try:
for c in original:
if c.isalpha():
ret+=modified[count]
count+=1
|
python
|
{
"resource": ""
}
|
q1744
|
Playfair.encipher
|
train
|
def encipher(self, string):
"""Encipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Playfair(key='zgptfoihmuwdrcnykeqaxvsbl').encipher(plaintext)
|
python
|
{
"resource": ""
}
|
q1745
|
Playfair.decipher
|
train
|
def decipher(self, string):
"""Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
Example::
plaintext = Playfair(key='zgptfoihmuwdrcnykeqaxvsbl').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string.
"""
|
python
|
{
"resource": ""
}
|
q1746
|
Delastelle.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Delastelle cipher according to initialised key.
Example::
ciphertext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The ciphertext will be 3 times the length of the plaintext.
"""
|
python
|
{
"resource": ""
}
|
q1747
|
Delastelle.decipher
|
train
|
def decipher(self,string):
"""Decipher string using Delastelle cipher according to initialised key.
Example::
plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintext will be 1/3 the length of the ciphertext.
"""
|
python
|
{
"resource": ""
}
|
q1748
|
Foursquare.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. If the input plaintext is not an even number of characters, an 'X' will be appended.
Example::
ciphertext = Foursquare(key1='zgptfoihmuwdrcnykeqaxvsbl',key2='mfnbdcrhsaxyogvituewlqzkp').encipher(plaintext)
|
python
|
{
"resource": ""
}
|
q1749
|
Foursquare.decipher
|
train
|
def decipher(self,string):
"""Decipher string using Foursquare cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
Example::
|
python
|
{
"resource": ""
}
|
q1750
|
Rot13.encipher
|
train
|
def encipher(self,string,keep_punct=False):
r"""Encipher string using rot13 cipher.
Example::
ciphertext = Rot13().encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The enciphered string.
"""
|
python
|
{
"resource": ""
}
|
q1751
|
Porta.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Porta cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Porta('HELLO').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
ret = ''
for (i,c) in enumerate(string):
i = i%len(self.key)
if self.key[i] in 'AB': ret += 'NOPQRSTUVWXYZABCDEFGHIJKLM'[self.a2i(c)]
elif self.key[i] in 'YZ': ret += 'ZNOPQRSTUVWXYBCDEFGHIJKLMA'[self.a2i(c)]
elif self.key[i] in 'WX': ret += 'YZNOPQRSTUVWXCDEFGHIJKLMAB'[self.a2i(c)]
elif self.key[i] in 'UV': ret += 'XYZNOPQRSTUVWDEFGHIJKLMABC'[self.a2i(c)]
elif self.key[i] in 'ST': ret += 'WXYZNOPQRSTUVEFGHIJKLMABCD'[self.a2i(c)]
elif self.key[i] in 'QR':
|
python
|
{
"resource": ""
}
|
q1752
|
M209.encipher
|
train
|
def encipher(self,message):
"""Encipher string using M209 cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example (continuing from the example above)::
ciphertext = m.encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
"""
message = self.remove_punctuation(message)
effective_ch = [0,0,0,0,0,0,0] # these are the wheels which are effective currently, 1 for yes, 0 no
# -the zero at the beginning is extra, indicates lug was in pos 0
ret = ''
# from now we no longer need the wheel starts, we can
|
python
|
{
"resource": ""
}
|
q1753
|
FracMorse.encipher
|
train
|
def encipher(self,string):
"""Encipher string using FracMorse cipher according to initialised key.
Example::
ciphertext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
"""
string = string.upper()
#print string
morsestr = self.enmorse(string)
# make sure the morse string is a multiple of 3 in length
if len(morsestr) % 3 == 1:
|
python
|
{
"resource": ""
}
|
q1754
|
FracMorse.decipher
|
train
|
def decipher(self,string):
"""Decipher string using FracMorse cipher according to initialised key.
Example::
plaintext = FracMorse('ROUNDTABLECFGHIJKMPQSVWXYZ').decipher(ciphertext)
|
python
|
{
"resource": ""
}
|
q1755
|
ColTrans.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = ColTrans('GERMAN').encipher(plaintext)
|
python
|
{
"resource": ""
}
|
q1756
|
ColTrans.decipher
|
train
|
def decipher(self,string):
'''Decipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ColTrans('GERMAN').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string.
'''
string = self.remove_punctuation(string)
ret = ['_']*len(string)
L,M = len(string),len(self.keyword)
|
python
|
{
"resource": ""
}
|
q1757
|
Railfence.encipher
|
train
|
def encipher(self,string,keep_punct=False):
"""Encipher string using Railfence cipher according to initialised key.
Example::
ciphertext = Railfence(3).encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
|
python
|
{
"resource": ""
}
|
q1758
|
Railfence.decipher
|
train
|
def decipher(self,string,keep_punct=False):
"""Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
|
python
|
{
"resource": ""
}
|
q1759
|
Affine.decipher
|
train
|
def decipher(self,string,keep_punct=False):
"""Decipher string using affine cipher according to initialised key.
Example::
plaintext = Affine(a,b).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
|
python
|
{
"resource": ""
}
|
q1760
|
Autokey.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Autokey cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Autokey('HELLO').encipher(plaintext)
:param string: The string
|
python
|
{
"resource": ""
}
|
q1761
|
Bifid.encipher
|
train
|
def encipher(self,string):
"""Encipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string.
"""
string = self.remove_punctuation(string)
step1 = self.pb.encipher(string)
evens =
|
python
|
{
"resource": ""
}
|
q1762
|
Bifid.decipher
|
train
|
def decipher(self,string):
"""Decipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string.
"""
ret = ''
string = string.upper()
rowseq,colseq = [],[]
# take blocks of length period, reform rowseq,colseq from them
for i in range(0,len(string),self.period):
tempseq = []
for j in range(0,self.period):
|
python
|
{
"resource": ""
}
|
q1763
|
SimpleSubstitution.decipher
|
train
|
def decipher(self,string,keep_punct=False):
"""Decipher string using Simple Substitution cipher according to initialised key.
Example::
plaintext = SimpleSubstitution('AJPCZWRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string.
"""
# if we have not yet calculated the inverse key, calculate it now
if self.invkey == '':
|
python
|
{
"resource": ""
}
|
q1764
|
kron
|
train
|
def kron(a, b):
"""Kronecker product of two TT-matrices or two TT-vectors"""
if hasattr(a, '__kron__'):
return a.__kron__(b)
if a is None:
return b
else:
|
python
|
{
"resource": ""
}
|
q1765
|
dot
|
train
|
def dot(a, b):
"""Dot product of two TT-matrices or two TT-vectors"""
if hasattr(a, '__dot__'):
return a.__dot__(b)
if a is None:
return b
else:
raise
|
python
|
{
"resource": ""
}
|
q1766
|
mkron
|
train
|
def mkron(a, *args):
"""Kronecker product of all the arguments"""
if not isinstance(a, list):
a = [a]
a = list(a) # copy list
for i in args:
if isinstance(i, list):
a.extend(i)
else:
a.append(i)
c = _vector.vector()
|
python
|
{
"resource": ""
}
|
q1767
|
concatenate
|
train
|
def concatenate(*args):
"""Concatenates given TT-vectors.
For two tensors :math:`X(i_1,\\ldots,i_d),Y(i_1,\\ldots,i_d)` returns :math:`(d+1)`-dimensional
tensor :math:`Z(i_0,i_1,\\ldots,i_d)`, :math:`i_0=\\overline{0,1}`, such that
.. math::
Z(0, i_1, \\ldots, i_d) = X(i_1, \\ldots, i_d),
Z(1, i_1, \\ldots, i_d) = Y(i_1, \\ldots, i_d).
"""
tmp = _np.array([[1] +
|
python
|
{
"resource": ""
}
|
q1768
|
sum
|
train
|
def sum(a, axis=-1):
"""Sum TT-vector over specified axes"""
d = a.d
crs = _vector.vector.to_list(a.tt if isinstance(a, _matrix.matrix) else a)
if axis < 0:
axis = range(a.d)
elif isinstance(axis, int):
axis = [axis]
axis = list(axis)[::-1]
for ax in axis:
|
python
|
{
"resource": ""
}
|
q1769
|
ones
|
train
|
def ones(n, d=None):
""" Creates a TT-vector of all ones"""
c = _vector.vector()
if d is None:
c.n = _np.array(n, dtype=_np.int32)
c.d = c.n.size
else:
c.n = _np.array([n] * d, dtype=_np.int32)
|
python
|
{
"resource": ""
}
|
q1770
|
rand
|
train
|
def rand(n, d=None, r=2, samplefunc=_np.random.randn):
"""Generate a random d-dimensional TT-vector with ranks ``r``.
Distribution to sample cores is provided by the samplefunc.
Default is to sample from normal distribution.
"""
n0 = _np.asanyarray(n, dtype=_np.int32)
|
python
|
{
"resource": ""
}
|
q1771
|
eye
|
train
|
def eye(n, d=None):
""" Creates an identity TT-matrix"""
c = _matrix.matrix()
c.tt = _vector.vector()
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
c.tt.d = n0.size
else:
n0 = _np.asanyarray([n] * d, dtype=_np.int32)
c.tt.d = d
c.n = n0.copy()
c.m = n0.copy()
c.tt.n = (c.n) * (c.m)
|
python
|
{
"resource": ""
}
|
q1772
|
cores_orthogonalization_step
|
train
|
def cores_orthogonalization_step(coresX, dim, left_to_right=True):
"""TT-Tensor X orthogonalization step.
The function can change the shape of some cores.
"""
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(coresX) - 1)
|
python
|
{
"resource": ""
}
|
q1773
|
unfolding
|
train
|
def unfolding(tens, i):
"""Compute the i-th unfolding
|
python
|
{
"resource": ""
}
|
q1774
|
gcd
|
train
|
def gcd(a, b):
'''Greatest common divider'''
|
python
|
{
"resource": ""
}
|
q1775
|
ksl
|
train
|
def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:param use_normest: Use matrix norm estimation instead of the true 1-norm in KSL procedure. 0 -use true norm, 1 - Higham norm estimator, 2 - fixed norm=1.0 (for testing purposes only)
:type use_normest: int, default: 1
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0
"""
y0 = y0.round(1e-14) # This will fix ranks
|
python
|
{
"resource": ""
}
|
q1776
|
diag_ksl
|
train
|
def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation
for the equation
.. math ::
\\frac{dy}{dt} = V y, \\quad y(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
1. Christian Lubich, Ivan Oseledets, and Bart Vandereycken.
Time integration of tensor trains. arXiv preprint 1407.2042, 2014.
http://arxiv.org/abs/1407.2042
2. Christian Lubich and Ivan V. Oseledets. A projector-splitting integrator
for dynamical low-rank approximation. BIT, 54(1):171-188, 2014.
http://dx.doi.org/10.1007/s10543-013-0454-0
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial condition in the TT-format,
:type y0: tensor
:param tau: Timestep
:type tau: float
:param scheme: The integration scheme, possible values: 'symm' -- second order, 'first' -- first order
:type scheme: str
:param space: Maximal dimension of the Krylov space for the local EXPOKIT solver.
:type space: int
:rtype: tensor
:Example:
>>> import tt
>>> import tt.ksl
>>> import numpy as np
>>> d = 8
>>> a = tt.qlaplace_dd([d, d, d])
>>> y0, ev = tt.eigb.eigb(a, tt.rand(2 , 24, 2), 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 1 eigenvalues with accuracy 1E-06
swp: 1 er = 1.1408 rmax:2
swp: 2 er = 190.01 rmax:2
swp: 3 er = 2.72582E-08 rmax:2
Total number of matvecs: 0
>>> y1 = tt.ksl.ksl(a, y0, 1e-2)
Solving a real-valued dynamical problem with tau=1E-02
>>> print tt.dot(y1, y0) / (y1.norm() * y0.norm()) - 1 #Eigenvectors should not change
0.0
"""
y0 = y0.round(1e-14) # This will fix ranks
# to be no more than maximal reasonable.
|
python
|
{
"resource": ""
}
|
q1777
|
matrix.T
|
train
|
def T(self):
"""Transposed TT-matrix"""
mycrs = matrix.to_list(self)
trans_crs = []
for cr in mycrs:
|
python
|
{
"resource": ""
}
|
q1778
|
matrix.real
|
train
|
def real(self):
"""Return real part of a matrix."""
|
python
|
{
"resource": ""
}
|
q1779
|
matrix.imag
|
train
|
def imag(self):
"""Return imaginary part of a matrix."""
|
python
|
{
"resource": ""
}
|
q1780
|
matrix.c2r
|
train
|
def c2r(self):
"""Get real matrix from complex one suitable for solving complex linear system with real solver.
For matrix :math:`M(i_1,j_1,\\ldots,i_d,j_d) = \\Re M + i\\Im M` returns (d+1)-dimensional matrix
:math:`\\tilde{M}(i_1,j_1,\\ldots,i_d,j_d,i_{d+1},j_{d+1})` of form
:math:`\\begin{bmatrix}\\Re M & -\\Im M \\\\ \\Im M & \\Re M \\end{bmatrix}`. This function
is useful for solving complex linear system :math:`\\mathcal{A}X = B` with real solver by
transforming it into
.. math::
\\begin{bmatrix}\\Re\\mathcal{A} & -\\Im\\mathcal{A} \\\\
|
python
|
{
"resource": ""
}
|
q1781
|
matrix.round
|
train
|
def round(self, eps=1e-14, rmax=100000):
""" Computes an approximation to a
TT-matrix in with accuracy
|
python
|
{
"resource": ""
}
|
q1782
|
matrix.copy
|
train
|
def copy(self):
""" Creates a copy of the TT-matrix """
c = matrix()
c.tt = self.tt.copy()
|
python
|
{
"resource": ""
}
|
q1783
|
matrix.full
|
train
|
def full(self):
""" Transforms a TT-matrix into a full matrix"""
N = self.n.prod()
M = self.m.prod()
a = self.tt.full()
d = self.tt.d
sz = _np.vstack((self.n, self.m)).flatten('F')
a = a.reshape(sz, order='F')
|
python
|
{
"resource": ""
}
|
q1784
|
vector.from_list
|
train
|
def from_list(a, order='F'):
"""Generate TT-vectorr object from given TT cores.
:param a: List of TT cores.
:type a: list
:returns: vector -- TT-vector constructed from the given cores.
"""
d = len(a) # Number of cores
res = vector()
|
python
|
{
"resource": ""
}
|
q1785
|
vector.erank
|
train
|
def erank(self):
""" Effective rank of the TT-vector """
r = self.r
n = self.n
d = self.d
if d <= 1:
er = 0e0
else:
sz = _np.dot(n * r[0:d], r[1:])
if sz == 0:
er = 0e0
else:
b = r[0] * n[0] + n[d - 1] * r[d]
|
python
|
{
"resource": ""
}
|
q1786
|
vector.rmean
|
train
|
def rmean(self):
""" Calculates the mean rank of a TT-vector."""
if not _np.all(self.n):
return 0
# Solving quadratic equation ar^2 + br + c = 0;
a = _np.sum(self.n[1:-1])
b = self.n[0] + self.n[-1]
|
python
|
{
"resource": ""
}
|
q1787
|
eigb
|
train
|
def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
""" Approximate computation of minimal eigenvalues in tensor train format
This function uses alternating least-squares algorithm for the computation of several
minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function.
:Reference:
S. V. Dolgov, B. N. Khoromskij, I. V. Oseledets, and D. V. Savostyanov.
Computation of extreme eigenvalues in higher dimensions using block tensor train format. Computer Phys. Comm.,
185(4):1207-1216, 2014. http://dx.doi.org/10.1016/j.cpc.2013.12.017
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial guess in the block TT-format, r(d+1) is the number of eigenvalues sought
:type y0: tensor
:param eps: Accuracy required
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:param kickrank: Addition rank, the larger the more robus the method,
:type kickrank: int
:rtype: A tuple (ev, tensor), where ev is a list of eigenvalues, tensor is an approximation to eigenvectors.
:Example:
>>> import tt
>>> import tt.eigb
>>> d = 8; f = 3
>>> r = [8] * (d * f + 1); r[d * f] = 8; r[0] = 1
>>> x = tt.rand(n, d * f, r)
|
python
|
{
"resource": ""
}
|
q1788
|
encode_for_locale
|
train
|
def encode_for_locale(s):
"""
Encode text items for system locale. If encoding fails, fall back to ASCII.
"""
try:
return s.encode(LOCALE_ENCODING, 'ignore')
|
python
|
{
"resource": ""
}
|
q1789
|
fib
|
train
|
def fib(n):
"""Terrible Fibonacci number generator."""
|
python
|
{
"resource": ""
}
|
q1790
|
Brain.format_message
|
train
|
def format_message(self, msg, botreply=False):
"""Format a user's message for safe processing.
This runs substitutions on the message and strips out any remaining
symbols (depending on UTF-8 mode).
:param str msg: The user's message.
:param bool botreply: Whether this formatting is being done for the
bot's last reply (e.g. in a ``%Previous`` command).
:return str: The formatted message.
"""
# Make sure the string is Unicode for Python 2.
if sys.version_info[0] < 3 and isinstance(msg, str):
msg = msg.decode()
# Lowercase it.
msg = msg.lower()
# Run substitutions on it.
msg = self.substitute(msg, "sub")
# In UTF-8 mode, only strip metacharacters and HTML brackets
# (to protect from obvious XSS attacks).
if self.utf8:
msg = re.sub(RE.utf8_meta, '', msg)
msg = re.sub(self.master.unicode_punctuation, '', msg)
|
python
|
{
"resource": ""
}
|
q1791
|
Brain.do_expand_array
|
train
|
def do_expand_array(self, array_name, depth=0):
"""Do recurrent array expansion, returning a set of keywords.
Exception is thrown when there are cyclical dependencies between
arrays or if the ``@array`` name references an undefined array.
:param str array_name: The name of the array to expand.
:param int depth: The recursion depth counter.
:return set: The final set of array entries.
"""
if depth > self.master._depth:
raise Exception("deep recursion detected")
if not array_name in self.master._array:
|
python
|
{
"resource": ""
}
|
q1792
|
Brain.expand_array
|
train
|
def expand_array(self, array_name):
"""Expand variables and return a set of keywords.
:param str array_name: The name of the array to expand.
:return list: The final array contents.
Warning is issued when exceptions occur."""
ret = self.master._array[array_name] if array_name in self.master._array else []
try:
|
python
|
{
"resource": ""
}
|
q1793
|
Brain.substitute
|
train
|
def substitute(self, msg, kind):
"""Run a kind of substitution on a message.
:param str msg: The message to run substitutions against.
:param str kind: The kind of substitution to run,
one of ``subs`` or ``person``.
"""
# Safety checking.
if 'lists' not in self.master._sorted:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
if kind not in self.master._sorted["lists"]:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
# Get the substitution map.
subs = None
if kind == 'sub':
subs = self.master._sub
else:
subs = self.master._person
# Make placeholders each time we substitute something.
ph = []
i = 0
for pattern in self.master._sorted["lists"][kind]:
result = subs[pattern]
# Make a placeholder.
|
python
|
{
"resource": ""
}
|
q1794
|
PyRiveObjects.load
|
train
|
def load(self, name, code):
"""Prepare a Python code object given by the RiveScript interpreter.
:param str name: The name of the Python object macro.
:param []str code: The Python source code for the object macro.
"""
# We need to make a dynamic Python method.
source = "def RSOBJ(rs, args):\n"
for line in code:
source = source + "\t" + line + "\n"
source += "self._objects[name] = RSOBJ\n"
|
python
|
{
"resource": ""
}
|
q1795
|
PyRiveObjects.call
|
train
|
def call(self, rs, name, user, fields):
"""Invoke a previously loaded object.
:param RiveScript rs: the parent RiveScript instance.
:param str name: The name of the object macro to be called.
:param str user: The user ID invoking the object macro.
:param []str fields: Array of words sent as the object's arguments.
:return str: The output of the object macro.
"""
# Call the dynamic method.
if name not in self._objects:
return '[ERR: Object Not Found]'
|
python
|
{
"resource": ""
}
|
q1796
|
get_topic_triggers
|
train
|
def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
"""Recursively scan a topic and return a list of all triggers.
Arguments:
rs (RiveScript): A reference to the parent RiveScript instance.
topic (str): The original topic name.
thats (bool): Are we getting triggers for 'previous' replies?
depth (int): Recursion step counter.
inheritance (int): The inheritance level counter, for topics that
inherit other topics.
inherited (bool): Whether the current topic is inherited by others.
Returns:
[]str: List of all triggers found.
"""
# Break if we're in too deep.
if depth > rs._depth:
rs._warn("Deep recursion while scanning topic inheritance")
# Keep in mind here that there is a difference between 'includes' and
# 'inherits' -- topics that inherit other topics are able to OVERRIDE
# triggers that appear in the inherited topic. This means that if the top
# topic has a trigger of simply '*', then NO triggers are capable of
# matching in ANY inherited topic, because even though * has the lowest
# priority, it has an automatic priority over all inherited topics.
#
# The getTopicTriggers method takes this into account. All topics that
# inherit other topics will have their triggers prefixed with a fictional
# {inherits} tag, which would start at {inherits=0} and increment if this
# topic has other inheriting topics. So we can use this tag to make sure
# topics that inherit things will have their triggers always be on top of
# the stack, from inherits=0 to inherits=n.
# Important info about the depth vs inheritance params to this function:
# depth increments by 1 each time this function recursively calls itrs.
# inheritance increments by 1 only when this topic inherits another
# topic.
#
# This way, '> topic alpha includes beta inherits gamma' will have this
# effect:
# alpha and beta's triggers are combined together into one matching
# pool, and then those triggers have higher matching priority than
# gamma's.
#
# The inherited option is True if this is a recursive call, from a topic
# that inherits other topics. This forces the {inherits} tag to be added
# to the triggers. This only applies when the top topic 'includes'
# another topic.
rs._say("\tCollecting trigger list for topic " + topic + "(depth="
+ str(depth) + "; inheritance=" + str(inheritance) + "; "
+ "inherited=" + str(inherited) + ")")
# topic: the name of the topic
# depth: starts at 0 and ++'s with each recursion
# Topic doesn't exist?
if not topic in rs._topics:
rs._warn("Inherited or included topic {} doesn't exist or has no triggers".format(
topic
))
return []
# Collect an array of triggers to return.
triggers = []
# Get those
|
python
|
{
"resource": ""
}
|
q1797
|
word_count
|
train
|
def word_count(trigger, all=False):
"""Count the words that aren't wildcards or options in a trigger.
:param str trigger: The trigger to count words for.
:param bool all: Count purely based on whitespace separators, or
consider wildcards not to be their own words.
:return int: The word count."""
words = []
|
python
|
{
"resource": ""
}
|
q1798
|
PerlObject.load
|
train
|
def load(self, name, code):
"""Prepare a Perl code object given by
|
python
|
{
"resource": ""
}
|
q1799
|
hello_rivescript
|
train
|
def hello_rivescript():
"""Receive an inbound SMS and send a reply from RiveScript."""
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.