sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
def read_handshake(self):
"""Read and process an initial handshake message from Storm."""
msg = self.read_message()
pid_dir, _conf, _context = msg["pidDir"], msg["conf"], msg["context"]
# Write a blank PID file out to the pidDir
open(join(pid_dir, str(self.pid)), "w").close()
self.send_message({"pid": self.pid})
return _conf, _context | Read and process an initial handshake message from Storm. | entailment |
def send_message(self, message):
"""Send a message to Storm via stdout."""
if not isinstance(message, dict):
logger = self.logger if self.logger else log
logger.error(
"%s.%d attempted to send a non dict message to Storm: " "%r",
self.component_name,
self.pid,
message,
)
return
self.serializer.send_message(message) | Send a message to Storm via stdout. | entailment |
def raise_exception(self, exception, tup=None):
"""Report an exception back to Storm via logging.
:param exception: a Python exception.
:param tup: a :class:`Tuple` object.
"""
if tup:
message = (
"Python {exception_name} raised while processing Tuple "
"{tup!r}\n{traceback}"
)
else:
message = "Python {exception_name} raised\n{traceback}"
message = message.format(
exception_name=exception.__class__.__name__, tup=tup, traceback=format_exc()
)
self.send_message({"command": "error", "msg": str(message)})
self.send_message({"command": "sync"}) | Report an exception back to Storm via logging.
:param exception: a Python exception.
:param tup: a :class:`Tuple` object. | entailment |
def log(self, message, level=None):
"""Log a message to Storm optionally providing a logging level.
:param message: the log message to send to Storm.
:type message: str
:param level: the logging level that Storm should use when writing the
``message``. Can be one of: trace, debug, info, warn, or
error (default: ``info``).
:type level: str
.. warning::
This will send your message to Storm regardless of what level you
specify. In almost all cases, you are better of using
``Component.logger`` and not setting ``pystorm.log.path``, because
that will use a :class:`pystorm.component.StormHandler` to do the
filtering on the Python side (instead of on the Java side after taking
the time to serialize your message and send it to Storm).
"""
level = _STORM_LOG_LEVELS.get(level, _STORM_LOG_INFO)
self.send_message({"command": "log", "msg": str(message), "level": level}) | Log a message to Storm optionally providing a logging level.
:param message: the log message to send to Storm.
:type message: str
:param level: the logging level that Storm should use when writing the
``message``. Can be one of: trace, debug, info, warn, or
error (default: ``info``).
:type level: str
.. warning::
This will send your message to Storm regardless of what level you
specify. In almost all cases, you are better of using
``Component.logger`` and not setting ``pystorm.log.path``, because
that will use a :class:`pystorm.component.StormHandler` to do the
filtering on the Python side (instead of on the Java side after taking
the time to serialize your message and send it to Storm). | entailment |
def emit(
self,
tup,
tup_id=None,
stream=None,
anchors=None,
direct_task=None,
need_task_ids=False,
):
"""Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
JSON-serializable data.
:type tup: :class:`list` or :class:`pystorm.component.Tuple`
:param tup_id: the ID for the Tuple. If omitted by a
:class:`pystorm.spout.Spout`, this emit will be
unreliable.
:type tup_id: str
:param stream: the ID of the stream to emit this Tuple to. Specify
``None`` to emit to default stream.
:type stream: str
:param anchors: IDs the Tuples (or
:class:`pystorm.component.Tuple` instances)
which the emitted Tuples should be anchored to. This is
only passed by :class:`pystorm.bolt.Bolt`.
:type anchors: list
:param direct_task: the task to send the Tuple to.
:type direct_task: int
:param need_task_ids: indicate whether or not you'd like the task IDs
the Tuple was emitted (default: ``False``).
:type need_task_ids: bool
:returns: ``None``, unless ``need_task_ids=True``, in which case it will
be a ``list`` of task IDs that the Tuple was sent to if. Note
that when specifying direct_task, this will be equal to
``[direct_task]``.
"""
if not isinstance(tup, (list, tuple)):
raise TypeError(
"All Tuples must be either lists or tuples, "
"received {!r} instead.".format(type(tup))
)
msg = {"command": "emit", "tuple": tup}
downstream_task_ids = None
if anchors is not None:
msg["anchors"] = anchors
if tup_id is not None:
msg["id"] = tup_id
if stream is not None:
msg["stream"] = stream
if direct_task is not None:
msg["task"] = direct_task
if need_task_ids:
downstream_task_ids = [direct_task]
if not need_task_ids:
# only need to send on False, Storm's default is True
msg["need_task_ids"] = need_task_ids
if need_task_ids and direct_task is None:
# Use both locks so we ensure send_message and read_task_ids are for
# same emit
with self._reader_lock, self._writer_lock:
self.send_message(msg)
downstream_task_ids = self.read_task_ids()
# No locks necessary in simple case because serializer will acquire
# write lock itself
else:
self.send_message(msg)
return downstream_task_ids | Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
JSON-serializable data.
:type tup: :class:`list` or :class:`pystorm.component.Tuple`
:param tup_id: the ID for the Tuple. If omitted by a
:class:`pystorm.spout.Spout`, this emit will be
unreliable.
:type tup_id: str
:param stream: the ID of the stream to emit this Tuple to. Specify
``None`` to emit to default stream.
:type stream: str
:param anchors: IDs the Tuples (or
:class:`pystorm.component.Tuple` instances)
which the emitted Tuples should be anchored to. This is
only passed by :class:`pystorm.bolt.Bolt`.
:type anchors: list
:param direct_task: the task to send the Tuple to.
:type direct_task: int
:param need_task_ids: indicate whether or not you'd like the task IDs
the Tuple was emitted (default: ``False``).
:type need_task_ids: bool
:returns: ``None``, unless ``need_task_ids=True``, in which case it will
be a ``list`` of task IDs that the Tuple was sent to if. Note
that when specifying direct_task, this will be equal to
``[direct_task]``. | entailment |
def run(self):
"""Main run loop for all components.
Performs initial handshake with Storm and reads Tuples handing them off
to subclasses. Any exceptions are caught and logged back to Storm
prior to the Python process exiting.
.. warning::
Subclasses should **not** override this method.
"""
storm_conf, context = self.read_handshake()
self._setup_component(storm_conf, context)
self.initialize(storm_conf, context)
while True:
try:
self._run()
except StormWentAwayError:
log.info("Exiting because parent Storm process went away.")
self._exit(2)
except Exception as e:
log_msg = "Exception in {}.run()".format(self.__class__.__name__)
exc_info = sys.exc_info()
try:
self.logger.error(log_msg, exc_info=True)
self._handle_run_exception(e)
except StormWentAwayError:
log.error(log_msg, exc_info=exc_info)
log.info("Exiting because parent Storm process went away.")
self._exit(2)
except:
log.error(log_msg, exc_info=exc_info)
log.error(
"While trying to handle previous exception...",
exc_info=sys.exc_info(),
)
if self.exit_on_exception:
self._exit(1) | Main run loop for all components.
Performs initial handshake with Storm and reads Tuples handing them off
to subclasses. Any exceptions are caught and logged back to Storm
prior to the Python process exiting.
.. warning::
Subclasses should **not** override this method. | entailment |
def _exit(self, status_code):
"""Properly kill Python process including zombie threads."""
# If there are active threads still running infinite loops, sys.exit
# won't kill them but os._exit will. os._exit skips calling cleanup
# handlers, flushing stdio buffers, etc.
exit_func = os._exit if threading.active_count() > 1 else sys.exit
exit_func(status_code) | Properly kill Python process including zombie threads. | entailment |
def _wrap_stream(stream):
"""Returns a TextIOWrapper around the given stream that handles UTF-8
encoding/decoding.
"""
if hasattr(stream, "buffer"):
return io.TextIOWrapper(stream.buffer, encoding="utf-8")
elif hasattr(stream, "readable"):
return io.TextIOWrapper(stream, encoding="utf-8")
# Python 2.x stdin and stdout are just files
else:
return io.open(stream.fileno(), mode=stream.mode, encoding="utf-8") | Returns a TextIOWrapper around the given stream that handles UTF-8
encoding/decoding. | entailment |
def read_message(self):
"""The Storm multilang protocol consists of JSON messages followed by
a newline and "end\n".
All of Storm's messages (for either bolts or spouts) should be of the
form::
'<command or task_id form prior emit>\\nend\\n'
Command example, an incoming Tuple to a bolt::
'{ "id": "-6955786537413359385", "comp": "1", "stream": "1", "task": 9, "tuple": ["snow white and the seven dwarfs", "field2", 3]}\\nend\\n'
Command example for a spout to emit its next Tuple::
'{"command": "next"}\\nend\\n'
Example, the task IDs a prior emit was sent to::
'[12, 22, 24]\\nend\\n'
The edge case of where we read ``''`` from ``input_stream`` indicating
EOF, usually means that communication with the supervisor has been
severed.
"""
msg = ""
num_blank_lines = 0
while True:
# readline will return trailing \n so that output is unambigious, we
# should only have line == '' if we're at EOF
with self._reader_lock:
line = self.input_stream.readline()
if line == "end\n":
break
elif line == "":
raise StormWentAwayError()
elif line == "\n":
num_blank_lines += 1
if num_blank_lines % 1000 == 0:
log.warn(
"While trying to read a command or pending task "
"ID, Storm has instead sent %s '\\n' messages.",
num_blank_lines,
)
continue
msg = "{}{}\n".format(msg, line[0:-1])
try:
return json.loads(msg)
except Exception:
log.error("JSON decode error for message: %r", msg, exc_info=True)
raise | The Storm multilang protocol consists of JSON messages followed by
a newline and "end\n".
All of Storm's messages (for either bolts or spouts) should be of the
form::
'<command or task_id form prior emit>\\nend\\n'
Command example, an incoming Tuple to a bolt::
'{ "id": "-6955786537413359385", "comp": "1", "stream": "1", "task": 9, "tuple": ["snow white and the seven dwarfs", "field2", 3]}\\nend\\n'
Command example for a spout to emit its next Tuple::
'{"command": "next"}\\nend\\n'
Example, the task IDs a prior emit was sent to::
'[12, 22, 24]\\nend\\n'
The edge case of where we read ``''`` from ``input_stream`` indicating
EOF, usually means that communication with the supervisor has been
severed. | entailment |
def serialize_dict(self, msg_dict):
"""Serialize to JSON a message dictionary."""
serialized = json.dumps(msg_dict, namedtuple_as_object=False)
if PY2:
serialized = serialized.decode("utf-8")
serialized = "{}\nend\n".format(serialized)
return serialized | Serialize to JSON a message dictionary. | entailment |
def read_tuple(self):
"""Read a tuple from the pipe to Storm."""
cmd = self.read_command()
source = cmd["comp"]
stream = cmd["stream"]
values = cmd["tuple"]
val_type = self._source_tuple_types[source].get(stream)
return Tuple(
cmd["id"],
source,
stream,
cmd["task"],
tuple(values) if val_type is None else val_type(*values),
) | Read a tuple from the pipe to Storm. | entailment |
def emit(
self, tup, stream=None, anchors=None, direct_task=None, need_task_ids=False
):
"""Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
JSON-serializable data.
:type tup: :class:`list` or :class:`pystorm.component.Tuple`
:param stream: the ID of the stream to emit this Tuple to. Specify
``None`` to emit to default stream.
:type stream: str
:param anchors: IDs the Tuples (or :class:`pystorm.component.Tuple`
instances) which the emitted Tuples should be anchored
to. If ``auto_anchor`` is set to ``True`` and
you have not specified ``anchors``, ``anchors`` will be
set to the incoming/most recent Tuple ID(s).
:type anchors: list
:param direct_task: the task to send the Tuple to.
:type direct_task: int
:param need_task_ids: indicate whether or not you'd like the task IDs
the Tuple was emitted (default: ``False``).
:type need_task_ids: bool
:returns: ``None``, unless ``need_task_ids=True``, in which case it will
be a ``list`` of task IDs that the Tuple was sent to if. Note
that when specifying direct_task, this will be equal to
``[direct_task]``.
"""
if anchors is None:
anchors = self._current_tups if self.auto_anchor else []
anchors = [a.id if isinstance(a, Tuple) else a for a in anchors]
return super(Bolt, self).emit(
tup,
stream=stream,
anchors=anchors,
direct_task=direct_task,
need_task_ids=need_task_ids,
) | Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
JSON-serializable data.
:type tup: :class:`list` or :class:`pystorm.component.Tuple`
:param stream: the ID of the stream to emit this Tuple to. Specify
``None`` to emit to default stream.
:type stream: str
:param anchors: IDs the Tuples (or :class:`pystorm.component.Tuple`
instances) which the emitted Tuples should be anchored
to. If ``auto_anchor`` is set to ``True`` and
you have not specified ``anchors``, ``anchors`` will be
set to the incoming/most recent Tuple ID(s).
:type anchors: list
:param direct_task: the task to send the Tuple to.
:type direct_task: int
:param need_task_ids: indicate whether or not you'd like the task IDs
the Tuple was emitted (default: ``False``).
:type need_task_ids: bool
:returns: ``None``, unless ``need_task_ids=True``, in which case it will
be a ``list`` of task IDs that the Tuple was sent to if. Note
that when specifying direct_task, this will be equal to
``[direct_task]``. | entailment |
def ack(self, tup):
"""Indicate that processing of a Tuple has succeeded.
:param tup: the Tuple to acknowledge.
:type tup: :class:`str` or :class:`pystorm.component.Tuple`
"""
tup_id = tup.id if isinstance(tup, Tuple) else tup
self.send_message({"command": "ack", "id": tup_id}) | Indicate that processing of a Tuple has succeeded.
:param tup: the Tuple to acknowledge.
:type tup: :class:`str` or :class:`pystorm.component.Tuple` | entailment |
def fail(self, tup):
"""Indicate that processing of a Tuple has failed.
:param tup: the Tuple to fail (its ``id`` if ``str``).
:type tup: :class:`str` or :class:`pystorm.component.Tuple`
"""
tup_id = tup.id if isinstance(tup, Tuple) else tup
self.send_message({"command": "fail", "id": tup_id}) | Indicate that processing of a Tuple has failed.
:param tup: the Tuple to fail (its ``id`` if ``str``).
:type tup: :class:`str` or :class:`pystorm.component.Tuple` | entailment |
def _run(self):
"""The inside of ``run``'s infinite loop.
Separated out so it can be properly unit tested.
"""
tup = self.read_tuple()
self._current_tups = [tup]
if self.is_heartbeat(tup):
self.send_message({"command": "sync"})
elif self.is_tick(tup):
self.process_tick(tup)
if self.auto_ack:
self.ack(tup)
else:
self.process(tup)
if self.auto_ack:
self.ack(tup)
# Reset _current_tups so that we don't accidentally fail the wrong
# Tuples if a successive call to read_tuple fails.
# This is not done in `finally` clause because we want the current
# Tuples to fail when there is an exception.
self._current_tups = [] | The inside of ``run``'s infinite loop.
Separated out so it can be properly unit tested. | entailment |
def _handle_run_exception(self, exc):
"""Process an exception encountered while running the ``run()`` loop.
Called right before program exits.
"""
if len(self._current_tups) == 1:
tup = self._current_tups[0]
self.raise_exception(exc, tup)
if self.auto_fail:
self.fail(tup) | Process an exception encountered while running the ``run()`` loop.
Called right before program exits. | entailment |
def emit(self, tup, **kwargs):
"""Modified emit that will not return task IDs after emitting.
See :class:`pystorm.component.Bolt` for more information.
:returns: ``None``.
"""
kwargs["need_task_ids"] = False
return super(BatchingBolt, self).emit(tup, **kwargs) | Modified emit that will not return task IDs after emitting.
See :class:`pystorm.component.Bolt` for more information.
:returns: ``None``. | entailment |
def process_tick(self, tick_tup):
"""Increment tick counter, and call ``process_batch`` for all current
batches if tick counter exceeds ``ticks_between_batches``.
See :class:`pystorm.component.Bolt` for more information.
.. warning::
This method should **not** be overriden. If you want to tweak
how Tuples are grouped into batches, override ``group_key``.
"""
self._tick_counter += 1
# ACK tick Tuple immediately, since it's just responsible for counter
self.ack(tick_tup)
if self._tick_counter > self.ticks_between_batches and self._batches:
self.process_batches()
self._tick_counter = 0 | Increment tick counter, and call ``process_batch`` for all current
batches if tick counter exceeds ``ticks_between_batches``.
See :class:`pystorm.component.Bolt` for more information.
.. warning::
This method should **not** be overriden. If you want to tweak
how Tuples are grouped into batches, override ``group_key``. | entailment |
def process_batches(self):
"""Iterate through all batches, call process_batch on them, and ack.
Separated out for the rare instances when we want to subclass
BatchingBolt and customize what mechanism causes batches to be
processed.
"""
for key, batch in iteritems(self._batches):
self._current_tups = batch
self._current_key = key
self.process_batch(key, batch)
if self.auto_ack:
for tup in batch:
self.ack(tup)
# Set current batch to [] so that we know it was acked if a
# later batch raises an exception
self._current_key = None
self._batches[key] = []
self._batches = defaultdict(list) | Iterate through all batches, call process_batch on them, and ack.
Separated out for the rare instances when we want to subclass
BatchingBolt and customize what mechanism causes batches to be
processed. | entailment |
def process(self, tup):
"""Group non-tick Tuples into batches by ``group_key``.
.. warning::
This method should **not** be overriden. If you want to tweak
how Tuples are grouped into batches, override ``group_key``.
"""
# Append latest Tuple to batches
group_key = self.group_key(tup)
self._batches[group_key].append(tup) | Group non-tick Tuples into batches by ``group_key``.
.. warning::
This method should **not** be overriden. If you want to tweak
how Tuples are grouped into batches, override ``group_key``. | entailment |
def _handle_run_exception(self, exc):
"""Process an exception encountered while running the ``run()`` loop.
Called right before program exits.
"""
self.raise_exception(exc, self._current_tups)
if self.auto_fail:
failed = set()
for key, batch in iteritems(self._batches):
# Only wipe out batches other than current for exit_on_exception
if self.exit_on_exception or key == self._current_key:
for tup in batch:
self.fail(tup)
failed.add(tup.id)
# Fail current batch or tick Tuple if we have one
for tup in self._current_tups:
if tup.id not in failed:
self.fail(tup)
# Reset current batch info
self._batches[self._current_key] = []
self._current_key = None | Process an exception encountered while running the ``run()`` loop.
Called right before program exits. | entailment |
def _batch_entry_run(self):
"""The inside of ``_batch_entry``'s infinite loop.
Separated out so it can be properly unit tested.
"""
time.sleep(self.secs_between_batches)
with self._batch_lock:
self.process_batches() | The inside of ``_batch_entry``'s infinite loop.
Separated out so it can be properly unit tested. | entailment |
def _batch_entry(self):
"""Entry point for the batcher thread."""
try:
while True:
self._batch_entry_run()
except:
self.exc_info = sys.exc_info()
os.kill(self.pid, signal.SIGUSR1) | Entry point for the batcher thread. | entailment |
def _run(self):
"""The inside of ``run``'s infinite loop.
Separate from BatchingBolt's implementation because
we need to be able to acquire the batch lock after
reading the tuple.
We can't acquire the lock before reading the tuple because if
that hangs (i.e. the topology is shutting down) the lock being
acquired will freeze the rest of the bolt, which is precisely
what this batcher seeks to avoid.
"""
tup = self.read_tuple()
with self._batch_lock:
self._current_tups = [tup]
if self.is_heartbeat(tup):
self.send_message({"command": "sync"})
elif self.is_tick(tup):
self.process_tick(tup)
else:
self.process(tup)
# reset so that we don't accidentally fail the wrong Tuples
# if a successive call to read_tuple fails
self._current_tups = [] | The inside of ``run``'s infinite loop.
Separate from BatchingBolt's implementation because
we need to be able to acquire the batch lock after
reading the tuple.
We can't acquire the lock before reading the tuple because if
that hangs (i.e. the topology is shutting down) the lock being
acquired will freeze the rest of the bolt, which is precisely
what this batcher seeks to avoid. | entailment |
def send_message(self, msg_dict):
"""Serialize a message dictionary and write it to the output stream."""
with self._writer_lock:
try:
self.output_stream.flush()
self.output_stream.write(self.serialize_dict(msg_dict))
self.output_stream.flush()
except IOError:
raise StormWentAwayError()
except:
log.exception("Failed to send message: %r", msg_dict) | Serialize a message dictionary and write it to the output stream. | entailment |
def _void_array_to_list(restuple, _func, _args):
""" Convert the FFI result to Python data structures """
shape = (restuple.e.len, 1)
array_size = np.prod(shape)
mem_size = 8 * array_size
array_str_e = string_at(restuple.e.data, mem_size)
array_str_n = string_at(restuple.n.data, mem_size)
ls_e = np.frombuffer(array_str_e, float, array_size).tolist()
ls_n = np.frombuffer(array_str_n, float, array_size).tolist()
return ls_e, ls_n | Convert the FFI result to Python data structures | entailment |
def load_data_file(filename, encoding='utf-8'):
"""Load a data file and return it as a list of lines.
Parameters:
filename: The name of the file (no directories included).
encoding: The file encoding. Defaults to utf-8.
"""
data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, filename))
return data.decode(encoding).splitlines() | Load a data file and return it as a list of lines.
Parameters:
filename: The name of the file (no directories included).
encoding: The file encoding. Defaults to utf-8. | entailment |
def _load_data():
"""Load the word and character mapping data into a dictionary.
In the data files, each line is formatted like this:
HANZI PINYIN_READING/PINYIN_READING
So, lines need to be split by '\t' and then the Pinyin readings need to be
split by '/'.
"""
data = {}
for name, file_name in (('words', 'hanzi_pinyin_words.tsv'),
('characters', 'hanzi_pinyin_characters.tsv')):
# Split the lines by tabs: [[hanzi, pinyin]...].
lines = [line.split('\t') for line in
dragonmapper.data.load_data_file(file_name)]
# Make a dictionary: {hanzi: [pinyin, pinyin]...}.
data[name] = {hanzi: pinyin.split('/') for hanzi, pinyin in lines}
return data | Load the word and character mapping data into a dictionary.
In the data files, each line is formatted like this:
HANZI PINYIN_READING/PINYIN_READING
So, lines need to be split by '\t' and then the Pinyin readings need to be
split by '/'. | entailment |
def _hanzi_to_pinyin(hanzi):
"""Return the Pinyin reading for a Chinese word.
If the given string *hanzi* matches a CC-CEDICT word, the return value is
formatted like this: [WORD_READING1, WORD_READING2, ...]
If the given string *hanzi* doesn't match a CC-CEDICT word, the return
value is formatted like this: [[CHAR_READING1, CHAR_READING2 ...], ...]
When returning character readings, if a character wasn't recognized, the
original character is returned, e.g. [[CHAR_READING1, ...], CHAR, ...]
"""
try:
return _HANZI_PINYIN_MAP['words'][hanzi]
except KeyError:
return [_CHARACTERS.get(character, character) for character in hanzi] | Return the Pinyin reading for a Chinese word.
If the given string *hanzi* matches a CC-CEDICT word, the return value is
formatted like this: [WORD_READING1, WORD_READING2, ...]
If the given string *hanzi* doesn't match a CC-CEDICT word, the return
value is formatted like this: [[CHAR_READING1, CHAR_READING2 ...], ...]
When returning character readings, if a character wasn't recognized, the
original character is returned, e.g. [[CHAR_READING1, ...], CHAR, ...] | entailment |
def _enclose_readings(container, readings):
"""Enclose a reading within a container, e.g. '[]'."""
container_start, container_end = tuple(container)
enclosed_readings = '%(container_start)s%(readings)s%(container_end)s' % {
'container_start': container_start, 'container_end': container_end,
'readings': readings}
return enclosed_readings | Enclose a reading within a container, e.g. '[]'. | entailment |
def to_pinyin(s, delimiter=' ', all_readings=False, container='[]',
accented=True):
"""Convert a string's Chinese characters to Pinyin readings.
*s* is a string containing Chinese characters. *accented* is a
boolean value indicating whether to return accented or numbered Pinyin
readings.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings* is a boolean value indicating whether or not to return all
possible readings in the case of words/characters that have multiple
readings. *container* is a two character string that is used to
enclose words/characters if *all_readings* is ``True``. The default
``'[]'`` is used like this: ``'[READING1/READING2]'``.
Characters not recognized as Chinese are left untouched.
"""
hanzi = s
pinyin = ''
# Process the given string.
while hanzi:
# Get the next match in the given string.
match = re.search('[^%s%s]+' % (delimiter, zhon.hanzi.punctuation),
hanzi)
# There are no more matches, but the string isn't finished yet.
if match is None and hanzi:
pinyin += hanzi
break
match_start, match_end = match.span()
# Process the punctuation marks that occur before the match.
if match_start > 0:
pinyin += hanzi[0:match_start]
# Get the Chinese word/character readings.
readings = _hanzi_to_pinyin(match.group())
# Process the returned word readings.
if match.group() in _WORDS:
if all_readings:
reading = _enclose_readings(container,
_READING_SEPARATOR.join(readings))
else:
reading = readings[0]
pinyin += reading
# Process the returned character readings.
else:
# Process each character individually.
for character in readings:
# Don't touch unrecognized characters.
if isinstance(character, str):
pinyin += character
# Format multiple readings.
elif isinstance(character, list) and all_readings:
pinyin += _enclose_readings(
container, _READING_SEPARATOR.join(character))
# Select and format the most common reading.
elif isinstance(character, list) and not all_readings:
# Add an apostrophe to separate syllables.
if (pinyin and character[0][0] in zhon.pinyin.vowels and
pinyin[-1] in zhon.pinyin.lowercase):
pinyin += "'"
pinyin += character[0]
# Move ahead in the given string.
hanzi = hanzi[match_end:]
if accented:
return pinyin
else:
return accented_to_numbered(pinyin) | Convert a string's Chinese characters to Pinyin readings.
*s* is a string containing Chinese characters. *accented* is a
boolean value indicating whether to return accented or numbered Pinyin
readings.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings* is a boolean value indicating whether or not to return all
possible readings in the case of words/characters that have multiple
readings. *container* is a two character string that is used to
enclose words/characters if *all_readings* is ``True``. The default
``'[]'`` is used like this: ``'[READING1/READING2]'``.
Characters not recognized as Chinese are left untouched. | entailment |
def to_zhuyin(s, delimiter=' ', all_readings=False, container='[]'):
"""Convert a string's Chinese characters to Zhuyin readings.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings* is a boolean value indicating whether or not to return all
possible readings in the case of words/characters that have multiple
readings. *container* is a two character string that is used to
enclose words/characters if *all_readings* is ``True``. The default
``'[]'`` is used like this: ``'[READING1/READING2]'``.
Characters not recognized as Chinese are left untouched.
"""
numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False)
zhuyin = pinyin_to_zhuyin(numbered_pinyin)
return zhuyin | Convert a string's Chinese characters to Zhuyin readings.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings* is a boolean value indicating whether or not to return all
possible readings in the case of words/characters that have multiple
readings. *container* is a two character string that is used to
enclose words/characters if *all_readings* is ``True``. The default
``'[]'`` is used like this: ``'[READING1/READING2]'``.
Characters not recognized as Chinese are left untouched. | entailment |
def to_ipa(s, delimiter=' ', all_readings=False, container='[]'):
"""Convert a string's Chinese characters to IPA.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings* is a boolean value indicating whether or not to return all
possible readings in the case of words/characters that have multiple
readings. *container* is a two character string that is used to
enclose words/characters if *all_readings* is ``True``. The default
``'[]'`` is used like this: ``'[READING1/READING2]'``.
Characters not recognized as Chinese are left untouched.
"""
numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False)
ipa = pinyin_to_ipa(numbered_pinyin)
return ipa | Convert a string's Chinese characters to IPA.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings* is a boolean value indicating whether or not to return all
possible readings in the case of words/characters that have multiple
readings. *container* is a two character string that is used to
enclose words/characters if *all_readings* is ``True``. The default
``'[]'`` is used like this: ``'[READING1/READING2]'``.
Characters not recognized as Chinese are left untouched. | entailment |
def _load_data():
"""Load the transcription mapping data into a dictionary."""
lines = dragonmapper.data.load_data_file('transcriptions.csv')
pinyin_map, zhuyin_map, ipa_map = {}, {}, {}
for line in lines:
p, z, i = line.split(',')
pinyin_map[p] = {'Zhuyin': z, 'IPA': i}
zhuyin_map[z] = {'Pinyin': p, 'IPA': i}
ipa_map[i] = {'Pinyin': p, 'Zhuyin': z}
return pinyin_map, zhuyin_map, ipa_map | Load the transcription mapping data into a dictionary. | entailment |
def _numbered_vowel_to_accented(vowel, tone):
"""Convert a numbered Pinyin vowel to an accented Pinyin vowel."""
if isinstance(tone, int):
tone = str(tone)
return _PINYIN_TONES[vowel + tone] | Convert a numbered Pinyin vowel to an accented Pinyin vowel. | entailment |
def _accented_vowel_to_numbered(vowel):
"""Convert an accented Pinyin vowel to a numbered Pinyin vowel."""
for numbered_vowel, accented_vowel in _PINYIN_TONES.items():
if vowel == accented_vowel:
return tuple(numbered_vowel) | Convert an accented Pinyin vowel to a numbered Pinyin vowel. | entailment |
def _parse_numbered_syllable(unparsed_syllable):
"""Return the syllable and tone of a numbered Pinyin syllable."""
tone_number = unparsed_syllable[-1]
if not tone_number.isdigit():
syllable, tone = unparsed_syllable, '5'
elif tone_number == '0':
syllable, tone = unparsed_syllable[:-1], '5'
elif tone_number in '12345':
syllable, tone = unparsed_syllable[:-1], tone_number
else:
raise ValueError("Invalid syllable: %s" % unparsed_syllable)
return syllable, tone | Return the syllable and tone of a numbered Pinyin syllable. | entailment |
def _parse_accented_syllable(unparsed_syllable):
"""Return the syllable and tone of an accented Pinyin syllable.
Any accented vowels are returned without their accents.
Implements the following algorithm:
1. If the syllable has an accent mark, convert that vowel to a
regular vowel and add the tone to the end of the syllable.
2. Otherwise, assume the syllable is tone 5 (no accent marks).
"""
if unparsed_syllable[0] == '\u00B7':
# Special case for middle dot tone mark.
return unparsed_syllable[1:], '5'
for character in unparsed_syllable:
if character in _ACCENTED_VOWELS:
vowel, tone = _accented_vowel_to_numbered(character)
return unparsed_syllable.replace(character, vowel), tone
return unparsed_syllable, '5' | Return the syllable and tone of an accented Pinyin syllable.
Any accented vowels are returned without their accents.
Implements the following algorithm:
1. If the syllable has an accent mark, convert that vowel to a
regular vowel and add the tone to the end of the syllable.
2. Otherwise, assume the syllable is tone 5 (no accent marks). | entailment |
def _parse_zhuyin_syllable(unparsed_syllable):
"""Return the syllable and tone of a Zhuyin syllable."""
zhuyin_tone = unparsed_syllable[-1]
if zhuyin_tone in zhon.zhuyin.characters:
syllable, tone = unparsed_syllable, '1'
elif zhuyin_tone in zhon.zhuyin.marks:
for tone_number, tone_mark in _ZHUYIN_TONES.items():
if zhuyin_tone == tone_mark:
syllable, tone = unparsed_syllable[:-1], tone_number
else:
raise ValueError("Invalid syllable: %s" % unparsed_syllable)
return syllable, tone | Return the syllable and tone of a Zhuyin syllable. | entailment |
def _parse_ipa_syllable(unparsed_syllable):
"""Return the syllable and tone of an IPA syllable."""
ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS},
unparsed_syllable)
if not ipa_tone:
syllable, tone = unparsed_syllable, '5'
else:
for tone_number, tone_mark in _IPA_TONES.items():
if ipa_tone.group() == tone_mark:
tone = tone_number
break
syllable = unparsed_syllable[0:ipa_tone.start()]
return syllable, tone | Return the syllable and tone of an IPA syllable. | entailment |
def _restore_case(s, memory):
"""Restore a lowercase string's characters to their original case."""
cased_s = []
for i, c in enumerate(s):
if i + 1 > len(memory):
break
cased_s.append(c if memory[i] else c.upper())
return ''.join(cased_s) | Restore a lowercase string's characters to their original case. | entailment |
def numbered_syllable_to_accented(s):
"""Convert numbered Pinyin syllable *s* to an accented Pinyin syllable.
It implements the following algorithm to determine where to place tone
marks:
1. If the syllable has an 'a', 'e', or 'o' (in that order), put the
tone mark over that vowel.
2. Otherwise, put the tone mark on the last vowel.
"""
if s == 'r5':
return 'r' # Special case for 'r' suffix.
lowercase_syllable, case_memory = _lower_case(s)
syllable, tone = _parse_numbered_syllable(lowercase_syllable)
syllable = syllable.replace('v', '\u00fc')
if re.search('[%s]' % _UNACCENTED_VOWELS, syllable) is None:
return s
if 'a' in syllable:
accented_a = _numbered_vowel_to_accented('a', tone)
accented_syllable = syllable.replace('a', accented_a)
elif 'e' in syllable:
accented_e = _numbered_vowel_to_accented('e', tone)
accented_syllable = syllable.replace('e', accented_e)
elif 'o' in syllable:
accented_o = _numbered_vowel_to_accented('o', tone)
accented_syllable = syllable.replace('o', accented_o)
else:
vowel = syllable[max(map(syllable.rfind, _UNACCENTED_VOWELS))]
accented_vowel = _numbered_vowel_to_accented(vowel, tone)
accented_syllable = syllable.replace(vowel, accented_vowel)
return _restore_case(accented_syllable, case_memory) | Convert numbered Pinyin syllable *s* to an accented Pinyin syllable.
It implements the following algorithm to determine where to place tone
marks:
1. If the syllable has an 'a', 'e', or 'o' (in that order), put the
tone mark over that vowel.
2. Otherwise, put the tone mark on the last vowel. | entailment |
def accented_syllable_to_numbered(s):
"""Convert accented Pinyin syllable *s* to a numbered Pinyin syllable."""
if s[0] == '\u00B7':
lowercase_syllable, case_memory = _lower_case(s[1:])
lowercase_syllable = '\u00B7' + lowercase_syllable
else:
lowercase_syllable, case_memory = _lower_case(s)
numbered_syllable, tone = _parse_accented_syllable(lowercase_syllable)
return _restore_case(numbered_syllable, case_memory) + tone | Convert accented Pinyin syllable *s* to a numbered Pinyin syllable. | entailment |
def pinyin_syllable_to_zhuyin(s):
"""Convert Pinyin syllable *s* to a Zhuyin syllable."""
pinyin_syllable, tone = _parse_pinyin_syllable(s)
try:
zhuyin_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['Zhuyin']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
return zhuyin_syllable + _ZHUYIN_TONES[tone] | Convert Pinyin syllable *s* to a Zhuyin syllable. | entailment |
def pinyin_syllable_to_ipa(s):
"""Convert Pinyin syllable *s* to an IPA syllable."""
pinyin_syllable, tone = _parse_pinyin_syllable(s)
try:
ipa_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['IPA']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
return ipa_syllable + _IPA_TONES[tone] | Convert Pinyin syllable *s* to an IPA syllable. | entailment |
def _zhuyin_syllable_to_numbered(s):
"""Convert Zhuyin syllable *s* to a numbered Pinyin syllable."""
zhuyin_syllable, tone = _parse_zhuyin_syllable(s)
try:
pinyin_syllable = _ZHUYIN_MAP[zhuyin_syllable]['Pinyin']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
return pinyin_syllable + tone | Convert Zhuyin syllable *s* to a numbered Pinyin syllable. | entailment |
def _ipa_syllable_to_numbered(s):
"""Convert IPA syllable *s* to a numbered Pinyin syllable."""
ipa_syllable, tone = _parse_ipa_syllable(s)
try:
pinyin_syllable = _IPA_MAP[ipa_syllable]['Pinyin']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
return pinyin_syllable + tone | Convert IPA syllable *s* to a numbered Pinyin syllable. | entailment |
def _convert(s, re_pattern, syllable_function, add_apostrophes=False,
remove_apostrophes=False, separate_syllables=False):
"""Convert a string's syllables to a different transcription system."""
original = s
new = ''
while original:
match = re.search(re_pattern, original, re.IGNORECASE | re.UNICODE)
if match is None and original:
# There are no more matches, but the given string isn't fully
# processed yet.
new += original
break
match_start, match_end = match.span()
if match_start > 0: # Handle extra characters before matched syllable.
if (new and remove_apostrophes and match_start == 1 and
original[0] == "'"):
pass # Remove the apostrophe between Pinyin syllables.
if separate_syllables: # Separate syllables by a space.
new += ' '
else:
new += original[0:match_start]
else: # Matched syllable starts immediately.
if new and separate_syllables: # Separate syllables by a space.
new += ' '
elif (new and add_apostrophes and
match.group()[0].lower() in _UNACCENTED_VOWELS):
new += "'"
# Convert the matched syllable.
new += syllable_function(match.group())
original = original[match_end:]
return new | Convert a string's syllables to a different transcription system. | entailment |
def numbered_to_accented(s):
"""Convert all numbered Pinyin syllables in *s* to accented Pinyin."""
return _convert(s, zhon.pinyin.syllable, numbered_syllable_to_accented,
add_apostrophes=True) | Convert all numbered Pinyin syllables in *s* to accented Pinyin. | entailment |
def pinyin_to_zhuyin(s):
"""Convert all Pinyin syllables in *s* to Zhuyin.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
"""
return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_zhuyin,
remove_apostrophes=True, separate_syllables=True) | Convert all Pinyin syllables in *s* to Zhuyin.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed. | entailment |
def pinyin_to_ipa(s):
"""Convert all Pinyin syllables in *s* to IPA.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
"""
return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_ipa,
remove_apostrophes=True, separate_syllables=True) | Convert all Pinyin syllables in *s* to IPA.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed. | entailment |
def zhuyin_to_pinyin(s, accented=True):
"""Convert all Zhuyin syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
"""
if accented:
function = _zhuyin_syllable_to_accented
else:
function = _zhuyin_syllable_to_numbered
return _convert(s, zhon.zhuyin.syllable, function) | Convert all Zhuyin syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone. | entailment |
def ipa_to_pinyin(s, accented=True):
"""Convert all IPA syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
"""
if accented:
function = _ipa_syllable_to_accented
else:
function = _ipa_syllable_to_numbered
return _convert(s, _IPA_SYLLABLE, function) | Convert all IPA syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone. | entailment |
def to_pinyin(s, accented=True):
"""Convert *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
"""
identity = identify(s)
if identity == PINYIN:
if _has_accented_vowels(s):
return s if accented else accented_to_numbered(s)
else:
return numbered_to_accented(s) if accented else s
elif identity == ZHUYIN:
return zhuyin_to_pinyin(s, accented=accented)
elif identity == IPA:
return ipa_to_pinyin(s, accented=accented)
else:
raise ValueError("String is not a valid Chinese transcription.") | Convert *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone. | entailment |
def to_zhuyin(s):
"""Convert *s* to Zhuyin."""
identity = identify(s)
if identity == ZHUYIN:
return s
elif identity == PINYIN:
return pinyin_to_zhuyin(s)
elif identity == IPA:
return ipa_to_zhuyin(s)
else:
raise ValueError("String is not a valid Chinese transcription.") | Convert *s* to Zhuyin. | entailment |
def to_ipa(s):
"""Convert *s* to IPA."""
identity = identify(s)
if identity == IPA:
return s
elif identity == PINYIN:
return pinyin_to_ipa(s)
elif identity == ZHUYIN:
return zhuyin_to_ipa(s)
else:
raise ValueError("String is not a valid Chinese transcription.") | Convert *s* to IPA. | entailment |
def _is_pattern_match(re_pattern, s):
"""Check if a re pattern expression matches an entire string."""
match = re.match(re_pattern, s, re.I)
return match.group() == s if match else False | Check if a re pattern expression matches an entire string. | entailment |
def is_pinyin(s):
"""Check if *s* consists of valid Pinyin."""
re_pattern = ('(?:%(word)s|[ \t%(punctuation)s])+' %
{'word': zhon.pinyin.word,
'punctuation': zhon.pinyin.punctuation})
return _is_pattern_match(re_pattern, s) | Check if *s* consists of valid Pinyin. | entailment |
def is_zhuyin_compatible(s):
"""Checks if *s* is consists of Zhuyin-compatible characters.
This does not check if *s* contains valid Zhuyin syllables; for that
see :func:`is_zhuyin`.
Besides Zhuyin characters and tone marks, spaces are also accepted.
This function checks that all characters in *s* exist in
:data:`zhon.zhuyin.characters`, :data:`zhon.zhuyin.marks`, or ``' '``.
"""
printable_zhuyin = zhon.zhuyin.characters + zhon.zhuyin.marks + ' '
return _is_pattern_match('[%s]+' % printable_zhuyin, s) | Checks if *s* is consists of Zhuyin-compatible characters.
This does not check if *s* contains valid Zhuyin syllables; for that
see :func:`is_zhuyin`.
Besides Zhuyin characters and tone marks, spaces are also accepted.
This function checks that all characters in *s* exist in
:data:`zhon.zhuyin.characters`, :data:`zhon.zhuyin.marks`, or ``' '``. | entailment |
def is_ipa(s):
"""Check if *s* consists of valid Chinese IPA."""
re_pattern = ('(?:%(syllable)s|[ \t%(punctuation)s])+' %
{'syllable': _IPA_SYLLABLE,
'punctuation': zhon.pinyin.punctuation})
return _is_pattern_match(re_pattern, s) | Check if *s* consists of valid Chinese IPA. | entailment |
def identify(s):
"""Identify a given string's transcription system.
*s* is the string to identify. The string is checked to see if its
contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`,
:data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the
string's identity.
If *s* is not a valid transcription system, then :data:`UNKNOWN` is
returned.
When checking for valid Pinyin or Zhuyin, testing is done on a syllable
level, not a character level. For example, just because a string is
composed of characters used in Pinyin, doesn't mean that it will identify
as Pinyin; it must actually consist of valid Pinyin syllables. The same
applies for Zhuyin.
When checking for IPA, testing is only done on a character level. In other
words, a string just needs to consist of Chinese IPA characters in order
to identify as IPA.
"""
if is_pinyin(s):
return PINYIN
elif is_zhuyin(s):
return ZHUYIN
elif is_ipa(s):
return IPA
else:
return UNKNOWN | Identify a given string's transcription system.
*s* is the string to identify. The string is checked to see if its
contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`,
:data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the
string's identity.
If *s* is not a valid transcription system, then :data:`UNKNOWN` is
returned.
When checking for valid Pinyin or Zhuyin, testing is done on a syllable
level, not a character level. For example, just because a string is
composed of characters used in Pinyin, doesn't mean that it will identify
as Pinyin; it must actually consist of valid Pinyin syllables. The same
applies for Zhuyin.
When checking for IPA, testing is only done on a character level. In other
words, a string just needs to consist of Chinese IPA characters in order
to identify as IPA. | entailment |
def prepare(self, f):
"""Accept an objective function for optimization."""
self.g = autograd.grad(f)
self.h = autograd.hessian(f) | Accept an objective function for optimization. | entailment |
def optimize(self, x0, target):
"""Calculate an optimum argument of an objective function."""
x = x0
for _ in range(self.maxiter):
delta = np.linalg.solve(self.h(x, target), -self.g(x, target))
x = x + delta
if np.linalg.norm(delta) < self.tol:
break
return x | Calculate an optimum argument of an objective function. | entailment |
def optimize(self, x0, target):
"""Calculate an optimum argument of an objective function."""
x = x0
for i in range(self.maxiter):
g = self.g(x, target)
h = self.h(x, target)
if i == 0:
alpha = 0
m = g
else:
alpha = - np.dot(m, np.dot(h, g)) / np.dot(m, np.dot(h, m))
m = g + np.dot(alpha, m)
t = - np.dot(m, g) / np.dot(m, np.dot(h, m))
delta = np.dot(t, m)
x = x + delta
if np.linalg.norm(delta) < self.tol:
break
return x | Calculate an optimum argument of an objective function. | entailment |
def optimize(self, angles0, target):
"""Calculate an optimum argument of an objective function."""
def new_objective(angles):
return self.f(angles, target)
return scipy.optimize.minimize(
new_objective,
angles0,
**self.optimizer_opt).x | Calculate an optimum argument of an objective function. | entailment |
def optimize(self, angles0, target):
"""Calculate an optimum argument of an objective function."""
def new_objective(angles):
a = angles - angles0
if isinstance(self.smooth_factor, (np.ndarray, list)):
if len(a) == len(self.smooth_factor):
return (self.f(angles, target) +
np.sum(self.smooth_factor * np.power(a, 2)))
else:
raise ValueError('len(smooth_factor) != number of joints')
else:
return (self.f(angles, target) +
self.smooth_factor * np.sum(np.power(a, 2)))
return scipy.optimize.minimize(
new_objective,
angles0,
**self.optimizer_opt).x | Calculate an optimum argument of an objective function. | entailment |
def solve(self, angles):
"""Calculate a position of the end-effector and return it."""
return reduce(
lambda a, m: np.dot(m, a),
reversed(self._matrices(angles)),
np.array([0., 0., 0., 1.])
)[:3] | Calculate a position of the end-effector and return it. | entailment |
def solve(self, angles0, target):
"""Calculate joint angles and returns it."""
return self.optimizer.optimize(np.array(angles0), target) | Calculate joint angles and returns it. | entailment |
def matrix(self, _):
"""Return translation matrix in homogeneous coordinates."""
x, y, z = self.coord
return np.array([
[1., 0., 0., x],
[0., 1., 0., y],
[0., 0., 1., z],
[0., 0., 0., 1.]
]) | Return translation matrix in homogeneous coordinates. | entailment |
def matrix(self, angle):
"""Return rotation matrix in homogeneous coordinates."""
_rot_mat = {
'x': self._x_rot,
'y': self._y_rot,
'z': self._z_rot
}
return _rot_mat[self.axis](angle) | Return rotation matrix in homogeneous coordinates. | entailment |
def set_logger(self, logger):
"""
Set a logger to send debug messages to
Parameters
----------
logger : `Logger <http://docs.python.org/2/library/logging.html>`_
A python logger used to get debugging output from this module.
"""
self.__logger = logger
self.session.set_logger(self.__logger) | Set a logger to send debug messages to
Parameters
----------
logger : `Logger <http://docs.python.org/2/library/logging.html>`_
A python logger used to get debugging output from this module. | entailment |
def version(self):
"""
Return the version number of the Lending Club Investor tool
Returns
-------
string
The version number string
"""
this_path = os.path.dirname(os.path.realpath(__file__))
version_file = os.path.join(this_path, 'VERSION')
return open(version_file).read().strip() | Return the version number of the Lending Club Investor tool
Returns
-------
string
The version number string | entailment |
def authenticate(self, email=None, password=None):
"""
Attempt to authenticate the user.
Parameters
----------
email : string
The email of a user on Lending Club
password : string
The user's password, for authentication.
Returns
-------
boolean
True if the user authenticated or raises an exception if not
Raises
------
session.AuthenticationError
If authentication failed
session.NetworkError
If a network error occurred
"""
if self.session.authenticate(email, password):
return True | Attempt to authenticate the user.
Parameters
----------
email : string
The email of a user on Lending Club
password : string
The user's password, for authentication.
Returns
-------
boolean
True if the user authenticated or raises an exception if not
Raises
------
session.AuthenticationError
If authentication failed
session.NetworkError
If a network error occurred | entailment |
def get_cash_balance(self):
"""
Returns the account cash balance available for investing
Returns
-------
float
The cash balance in your account.
"""
cash = False
try:
response = self.session.get('/browse/cashBalanceAj.action')
json_response = response.json()
if self.session.json_success(json_response):
self.__log('Cash available: {0}'.format(json_response['cashBalance']))
cash_value = json_response['cashBalance']
# Convert currency to float value
# Match values like $1,000.12 or 1,0000$
cash_match = re.search('^[^0-9]?([0-9\.,]+)[^0-9]?', cash_value)
if cash_match:
cash_str = cash_match.group(1)
cash_str = cash_str.replace(',', '')
cash = float(cash_str)
else:
self.__log('Could not get cash balance: {0}'.format(response.text))
except Exception as e:
self.__log('Could not get the cash balance on the account: Error: {0}\nJSON: {1}'.format(str(e), response.text))
raise e
return cash | Returns the account cash balance available for investing
Returns
-------
float
The cash balance in your account. | entailment |
def get_portfolio_list(self, names_only=False):
"""
Get your list of named portfolios from the lendingclub.com
Parameters
----------
names_only : boolean, optional
If set to True, the function will return a list of portfolio names, instead of portfolio objects
Returns
-------
list
A list of portfolios (or names, if `names_only` is True)
"""
folios = []
response = self.session.get('/data/portfolioManagement?method=getLCPortfolios')
json_response = response.json()
# Get portfolios and create a list of names
if self.session.json_success(json_response):
folios = json_response['results']
if names_only is True:
for i, folio in enumerate(folios):
folios[i] = folio['portfolioName']
return folios | Get your list of named portfolios from the lendingclub.com
Parameters
----------
names_only : boolean, optional
If set to True, the function will return a list of portfolio names, instead of portfolio objects
Returns
-------
list
A list of portfolios (or names, if `names_only` is True) | entailment |
def assign_to_portfolio(self, portfolio_name, loan_id, order_id):
"""
Assign a note to a named portfolio. `loan_id` and `order_id` can be either
integer values or lists. If choosing lists, they both **MUST** be the same length
and line up. For example, `order_id[5]` must be the order ID for `loan_id[5]`
Parameters
----------
portfolio_name : string
The name of the portfolio to assign a the loan note to -- new or existing
loan_id : int or list
The loan ID, or list of loan IDs, to assign to the portfolio
order_id : int or list
The order ID, or list of order IDs, that this loan note was invested with.
You can find this in the dict returned from `get_note()`
Returns
-------
boolean
True on success
"""
response = None
assert type(loan_id) == type(order_id), "Both loan_id and order_id need to be the same type"
assert type(loan_id) in (int, list), "loan_id and order_id can only be int or list types"
assert type(loan_id) is int or (type(loan_id) is list and len(loan_id) == len(order_id)), "If order_id and loan_id are lists, they both need to be the same length"
# Data
post = {
'loan_id': loan_id,
'record_id': loan_id,
'order_id': order_id
}
query = {
'method': 'createLCPortfolio',
'lcportfolio_name': portfolio_name
}
# Is it an existing portfolio
existing = self.get_portfolio_list()
for folio in existing:
if folio['portfolioName'] == portfolio_name:
query['method'] = 'addToLCPortfolio'
# Send
response = self.session.post('/data/portfolioManagement', query=query, data=post)
json_response = response.json()
# Failed
if not self.session.json_success(json_response):
raise LendingClubError('Could not assign order to portfolio \'{0}\''.format(portfolio_name), response)
# Success
else:
# Assigned to another portfolio, for some reason, raise warning
if 'portfolioName' in json_response and json_response['portfolioName'] != portfolio_name:
raise LendingClubError('Added order to portfolio "{0}" - NOT - "{1}", and I don\'t know why'.format(json_response['portfolioName'], portfolio_name))
# Assigned to the correct portfolio
else:
self.__log('Added order to portfolio "{0}"'.format(portfolio_name))
return True
return False | Assign a note to a named portfolio. `loan_id` and `order_id` can be either
integer values or lists. If choosing lists, they both **MUST** be the same length
and line up. For example, `order_id[5]` must be the order ID for `loan_id[5]`
Parameters
----------
portfolio_name : string
The name of the portfolio to assign a the loan note to -- new or existing
loan_id : int or list
The loan ID, or list of loan IDs, to assign to the portfolio
order_id : int or list
The order ID, or list of order IDs, that this loan note was invested with.
You can find this in the dict returned from `get_note()`
Returns
-------
boolean
True on success | entailment |
def search(self, filters=None, start_index=0, limit=100):
"""
Search for a list of notes that can be invested in.
(similar to searching for notes in the Browse section on the site)
Parameters
----------
filters : lendingclub.filters.*, optional
The filter to use to search for notes. If no filter is passed, a wildcard search
will be performed.
start_index : int, optional
The result index to start on. By default only 100 records will be returned at a time, so use this
to start at a later index in the results. For example, to get results 200 - 300, set `start_index` to 200.
(default is 0)
limit : int, optional
The number of results to return per request. (default is 100)
Returns
-------
dict
A dictionary object with the list of matching loans under the `loans` key.
"""
assert filters is None or isinstance(filters, Filter), 'filter is not a lendingclub.filters.Filter'
# Set filters
if filters:
filter_string = filters.search_string()
else:
filter_string = 'default'
payload = {
'method': 'search',
'filter': filter_string,
'startindex': start_index,
'pagesize': limit
}
# Make request
response = self.session.post('/browse/browseNotesAj.action', data=payload)
json_response = response.json()
if self.session.json_success(json_response):
results = json_response['searchresult']
# Normalize results by converting loanGUID -> loan_id
for loan in results['loans']:
loan['loan_id'] = int(loan['loanGUID'])
# Validate that fractions do indeed match the filters
if filters is not None:
filters.validate(results['loans'])
return results
return False | Search for a list of notes that can be invested in.
(similar to searching for notes in the Browse section on the site)
Parameters
----------
filters : lendingclub.filters.*, optional
The filter to use to search for notes. If no filter is passed, a wildcard search
will be performed.
start_index : int, optional
The result index to start on. By default only 100 records will be returned at a time, so use this
to start at a later index in the results. For example, to get results 200 - 300, set `start_index` to 200.
(default is 0)
limit : int, optional
The number of results to return per request. (default is 100)
Returns
-------
dict
A dictionary object with the list of matching loans under the `loans` key. | entailment |
def build_portfolio(self, cash, max_per_note=25, min_percent=0, max_percent=20, filters=None, automatically_invest=False, do_not_clear_staging=False):
"""
Returns a list of loan notes that are diversified by your min/max percent request and filters.
One way to invest in these loan notes, is to start an order and use add_batch to add all the
loan fragments to them. (see examples)
Parameters
----------
cash : int
The total amount you want to invest across a portfolio of loans (at least $25).
max_per_note : int, optional
The maximum dollar amount you want to invest per note. Must be a multiple of 25
min_percent : int, optional
THIS IS NOT PER NOTE, but the minimum average percent of return for the entire portfolio.
max_percent : int, optional
THIS IS NOT PER NOTE, but the maxmimum average percent of return for the entire portfolio.
filters : lendingclub.filters.*, optional
The filters to use to search for portfolios
automatically_invest : boolean, optional
If you want the tool to create an order and automatically invest in the portfolio that matches your filter.
(default False)
do_not_clear_staging : boolean, optional
Similar to automatically_invest, don't do this unless you know what you're doing.
Setting this to True stops the method from clearing the loan staging area before returning
Returns
-------
dict
A dict representing a new portfolio or False if nothing was found.
If `automatically_invest` was set to `True`, the dict will contain an `order_id` key with
the ID of the completed investment order.
Notes
-----
**The min/max_percent parameters**
When searching for portfolios, these parameters will match a portfolio of loan notes which have
an **AVERAGE** percent return between these values. If there are multiple portfolio matches, the
one closes to the max percent will be chosen.
Examples
--------
Here we want to invest $400 in a portfolio with only B, C, D and E grade notes with an average overall return between 17% - 19%. This similar to finding a portfolio in the 'Invest' section on lendingclub.com::
>>> from lendingclub import LendingClub
>>> from lendingclub.filters import Filter
>>> lc = LendingClub()
>>> lc.authenticate()
Email:[email protected]
Password:
True
>>> filters = Filter() # Set the search filters (only B, C, D and E grade notes)
>>> filters['grades']['C'] = True
>>> filters['grades']['D'] = True
>>> filters['grades']['E'] = True
>>> lc.get_cash_balance() # See the cash you have available for investing
463.80000000000001
>>> portfolio = lc.build_portfolio(400, # Invest $400 in a portfolio...
min_percent=17.0, # Return percent average between 17 - 19%
max_percent=19.0,
max_per_note=50, # As much as $50 per note
filters=filters) # Search using your filters
>>> len(portfolio['loan_fractions']) # See how many loans are in this portfolio
16
>>> loans_notes = portfolio['loan_fractions']
>>> order = lc.start_order() # Start a new order
>>> order.add_batch(loans_notes) # Add the loan notes to the order
>>> order.execute() # Execute the order
1861880
Here we do a similar search, but automatically invest the found portfolio. **NOTE** This does not allow
you to review the portfolio before you invest in it.
>>> from lendingclub import LendingClub
>>> from lendingclub.filters import Filter
>>> lc = LendingClub()
>>> lc.authenticate()
Email:[email protected]
Password:
True
# Filter shorthand
>>> filters = Filter({'grades': {'B': True, 'C': True, 'D': True, 'E': True}})
>>> lc.get_cash_balance() # See the cash you have available for investing
463.80000000000001
>>> portfolio = lc.build_portfolio(400,
min_percent=17.0,
max_percent=19.0,
max_per_note=50,
filters=filters,
automatically_invest=True) # Same settings, except invest immediately
>>> portfolio['order_id'] # See order ID
1861880
"""
assert filters is None or isinstance(filters, Filter), 'filter is not a lendingclub.filters.Filter'
assert max_per_note >= 25, 'max_per_note must be greater than or equal to 25'
# Set filters
if filters:
filter_str = filters.search_string()
else:
filter_str = 'default'
# Start a new order
self.session.clear_session_order()
# Make request
payload = {
'amount': cash,
'max_per_note': max_per_note,
'filter': filter_str
}
self.__log('POST VALUES -- amount: {0}, max_per_note: {1}, filter: ...'.format(cash, max_per_note))
response = self.session.post('/portfolio/lendingMatchOptionsV2.action', data=payload)
json_response = response.json()
# Options were found
if self.session.json_success(json_response) and 'lmOptions' in json_response:
options = json_response['lmOptions']
# Nothing found
if type(options) is not list or json_response['numberTicks'] == 0:
self.__log('No lending portfolios were returned with your search')
return False
# Choose an investment option based on the user's min/max values
i = 0
match_index = -1
match_option = None
for option in options:
# A perfect match
if option['percentage'] == max_percent:
match_option = option
match_index = i
break
# Over the max
elif option['percentage'] > max_percent:
break
# Higher than the minimum percent and the current matched option
elif option['percentage'] >= min_percent and (match_option is None or match_option['percentage'] < option['percentage']):
match_option = option
match_index = i
i += 1
# Nothing matched
if match_option is None:
self.__log('No portfolios matched your percentage requirements')
return False
# Mark this portfolio for investing (in order to get a list of all notes)
payload = {
'order_amount': cash,
'lending_match_point': match_index,
'lending_match_version': 'v2'
}
self.session.get('/portfolio/recommendPortfolio.action', query=payload)
# Get all loan fractions
payload = {
'method': 'getPortfolio'
}
response = self.session.get('/data/portfolio', query=payload)
json_response = response.json()
# Extract fractions from response
fractions = []
if 'loanFractions' in json_response:
fractions = json_response['loanFractions']
# Normalize by converting loanFractionAmount to invest_amount
for frac in fractions:
frac['invest_amount'] = frac['loanFractionAmount']
# Raise error if amount is greater than max_per_note
if frac['invest_amount'] > max_per_note:
raise LendingClubError('ERROR: LendingClub tried to invest ${0} in a loan note. Your max per note is set to ${1}. Portfolio investment canceled.'.format(frac['invest_amount'], max_per_note))
if len(fractions) == 0:
self.__log('The selected portfolio didn\'t have any loans')
return False
match_option['loan_fractions'] = fractions
# Validate that fractions do indeed match the filters
if filters is not None:
filters.validate(fractions)
# Not investing -- reset portfolio search session and return
if automatically_invest is not True:
if do_not_clear_staging is not True:
self.session.clear_session_order()
# Invest in this porfolio
elif automatically_invest is True: # just to be sure
order = self.start_order()
# This should probably only be ever done here...ever.
order._Order__already_staged = True
order._Order__i_know_what_im_doing = True
order.add_batch(match_option['loan_fractions'])
order_id = order.execute()
match_option['order_id'] = order_id
return match_option
else:
raise LendingClubError('Could not find any portfolio options that match your filters', response)
return False | Returns a list of loan notes that are diversified by your min/max percent request and filters.
One way to invest in these loan notes, is to start an order and use add_batch to add all the
loan fragments to them. (see examples)
Parameters
----------
cash : int
The total amount you want to invest across a portfolio of loans (at least $25).
max_per_note : int, optional
The maximum dollar amount you want to invest per note. Must be a multiple of 25
min_percent : int, optional
THIS IS NOT PER NOTE, but the minimum average percent of return for the entire portfolio.
max_percent : int, optional
THIS IS NOT PER NOTE, but the maxmimum average percent of return for the entire portfolio.
filters : lendingclub.filters.*, optional
The filters to use to search for portfolios
automatically_invest : boolean, optional
If you want the tool to create an order and automatically invest in the portfolio that matches your filter.
(default False)
do_not_clear_staging : boolean, optional
Similar to automatically_invest, don't do this unless you know what you're doing.
Setting this to True stops the method from clearing the loan staging area before returning
Returns
-------
dict
A dict representing a new portfolio or False if nothing was found.
If `automatically_invest` was set to `True`, the dict will contain an `order_id` key with
the ID of the completed investment order.
Notes
-----
**The min/max_percent parameters**
When searching for portfolios, these parameters will match a portfolio of loan notes which have
an **AVERAGE** percent return between these values. If there are multiple portfolio matches, the
one closes to the max percent will be chosen.
Examples
--------
Here we want to invest $400 in a portfolio with only B, C, D and E grade notes with an average overall return between 17% - 19%. This similar to finding a portfolio in the 'Invest' section on lendingclub.com::
>>> from lendingclub import LendingClub
>>> from lendingclub.filters import Filter
>>> lc = LendingClub()
>>> lc.authenticate()
Email:[email protected]
Password:
True
>>> filters = Filter() # Set the search filters (only B, C, D and E grade notes)
>>> filters['grades']['C'] = True
>>> filters['grades']['D'] = True
>>> filters['grades']['E'] = True
>>> lc.get_cash_balance() # See the cash you have available for investing
463.80000000000001
>>> portfolio = lc.build_portfolio(400, # Invest $400 in a portfolio...
min_percent=17.0, # Return percent average between 17 - 19%
max_percent=19.0,
max_per_note=50, # As much as $50 per note
filters=filters) # Search using your filters
>>> len(portfolio['loan_fractions']) # See how many loans are in this portfolio
16
>>> loans_notes = portfolio['loan_fractions']
>>> order = lc.start_order() # Start a new order
>>> order.add_batch(loans_notes) # Add the loan notes to the order
>>> order.execute() # Execute the order
1861880
Here we do a similar search, but automatically invest the found portfolio. **NOTE** This does not allow
you to review the portfolio before you invest in it.
>>> from lendingclub import LendingClub
>>> from lendingclub.filters import Filter
>>> lc = LendingClub()
>>> lc.authenticate()
Email:[email protected]
Password:
True
# Filter shorthand
>>> filters = Filter({'grades': {'B': True, 'C': True, 'D': True, 'E': True}})
>>> lc.get_cash_balance() # See the cash you have available for investing
463.80000000000001
>>> portfolio = lc.build_portfolio(400,
min_percent=17.0,
max_percent=19.0,
max_per_note=50,
filters=filters,
automatically_invest=True) # Same settings, except invest immediately
>>> portfolio['order_id'] # See order ID
1861880 | entailment |
def my_notes(self, start_index=0, limit=100, get_all=False, sort_by='loanId', sort_dir='asc'):
"""
Return all the loan notes you've already invested in. By default it'll return 100 results at a time.
Parameters
----------
start_index : int, optional
The result index to start on. By default only 100 records will be returned at a time, so use this
to start at a later index in the results. For example, to get results 200 - 300, set `start_index` to 200.
(default is 0)
limit : int, optional
The number of results to return per request. (default is 100)
get_all : boolean, optional
Return all results in one request, instead of 100 per request.
sort_by : string, optional
What key to sort on
sort_dir : {'asc', 'desc'}, optional
Which direction to sort
Returns
-------
dict
A dictionary with a list of matching notes on the `loans` key
"""
index = start_index
notes = {
'loans': [],
'total': 0,
'result': 'success'
}
while True:
payload = {
'sortBy': sort_by,
'dir': sort_dir,
'startindex': index,
'pagesize': limit,
'namespace': '/account'
}
response = self.session.post('/account/loansAj.action', data=payload)
json_response = response.json()
# Notes returned
if self.session.json_success(json_response):
notes['loans'] += json_response['searchresult']['loans']
notes['total'] = json_response['searchresult']['totalRecords']
# Error
else:
notes['result'] = json_response['result']
break
# Load more
if get_all is True and len(notes['loans']) < notes['total']:
index += limit
# End
else:
break
return notes | Return all the loan notes you've already invested in. By default it'll return 100 results at a time.
Parameters
----------
start_index : int, optional
The result index to start on. By default only 100 records will be returned at a time, so use this
to start at a later index in the results. For example, to get results 200 - 300, set `start_index` to 200.
(default is 0)
limit : int, optional
The number of results to return per request. (default is 100)
get_all : boolean, optional
Return all results in one request, instead of 100 per request.
sort_by : string, optional
What key to sort on
sort_dir : {'asc', 'desc'}, optional
Which direction to sort
Returns
-------
dict
A dictionary with a list of matching notes on the `loans` key | entailment |
def get_note(self, note_id):
"""
Get a loan note that you've invested in by ID
Parameters
----------
note_id : int
The note ID
Returns
-------
dict
A dictionary representing the matching note or False
Examples
--------
>>> from lendingclub import LendingClub
>>> lc = LendingClub(email='[email protected]', password='secret123')
>>> lc.authenticate()
True
>>> notes = lc.my_notes() # Get the first 100 loan notes
>>> len(notes['loans'])
100
>>> notes['total'] # See the total number of loan notes you have
630
>>> notes = lc.my_notes(start_index=100) # Get the next 100 loan notes
>>> len(notes['loans'])
100
>>> notes = lc.my_notes(get_all=True) # Get all notes in one request (may be slow)
>>> len(notes['loans'])
630
"""
index = 0
while True:
notes = self.my_notes(start_index=index, sort_by='noteId')
if notes['result'] != 'success':
break
# If the first note has a higher ID, we've passed it
if notes['loans'][0]['noteId'] > note_id:
break
# If the last note has a higher ID, it could be in this record set
if notes['loans'][-1]['noteId'] >= note_id:
for note in notes['loans']:
if note['noteId'] == note_id:
return note
index += 100
return False | Get a loan note that you've invested in by ID
Parameters
----------
note_id : int
The note ID
Returns
-------
dict
A dictionary representing the matching note or False
Examples
--------
>>> from lendingclub import LendingClub
>>> lc = LendingClub(email='[email protected]', password='secret123')
>>> lc.authenticate()
True
>>> notes = lc.my_notes() # Get the first 100 loan notes
>>> len(notes['loans'])
100
>>> notes['total'] # See the total number of loan notes you have
630
>>> notes = lc.my_notes(start_index=100) # Get the next 100 loan notes
>>> len(notes['loans'])
100
>>> notes = lc.my_notes(get_all=True) # Get all notes in one request (may be slow)
>>> len(notes['loans'])
630 | entailment |
def search_my_notes(self, loan_id=None, order_id=None, grade=None, portfolio_name=None, status=None, term=None):
"""
Search for notes you are invested in. Use the parameters to define how to search.
Passing no parameters is the same as calling `my_notes(get_all=True)`
Parameters
----------
loan_id : int, optional
Search for notes for a specific loan. Since a loan is broken up into a pool of notes, it's possible
to invest multiple notes in a single loan
order_id : int, optional
Search for notes from a particular investment order.
grade : {A, B, C, D, E, F, G}, optional
Match by a particular loan grade
portfolio_name : string, optional
Search for notes in a portfolio with this name (case sensitive)
status : string, {issued, in-review, in-funding, current, charged-off, late, in-grace-period, fully-paid}, optional
The funding status string.
term : {60, 36}, optional
Term length, either 60 or 36 (for 5 year and 3 year, respectively)
Returns
-------
dict
A dictionary with a list of matching notes on the `loans` key
"""
assert grade is None or type(grade) is str, 'grade must be a string'
assert portfolio_name is None or type(portfolio_name) is str, 'portfolio_name must be a string'
index = 0
found = []
sort_by = 'orderId' if order_id is not None else 'loanId'
group_id = order_id if order_id is not None else loan_id # first match by order, then by loan
# Normalize grade
if grade is not None:
grade = grade[0].upper()
# Normalize status
if status is not None:
status = re.sub('[^a-zA-Z\-]', ' ', status.lower()) # remove all non alpha characters
status = re.sub('days', ' ', status) # remove days
status = re.sub('\s+', '-', status.strip()) # replace spaces with dash
status = re.sub('(^-+)|(-+$)', '', status)
while True:
notes = self.my_notes(start_index=index, sort_by=sort_by)
if notes['result'] != 'success':
break
# If the first note has a higher ID, we've passed it
if group_id is not None and notes['loans'][0][sort_by] > group_id:
break
# If the last note has a higher ID, it could be in this record set
if group_id is None or notes['loans'][-1][sort_by] >= group_id:
for note in notes['loans']:
# Order ID, no match
if order_id is not None and note['orderId'] != order_id:
continue
# Loan ID, no match
if loan_id is not None and note['loanId'] != loan_id:
continue
# Grade, no match
if grade is not None and note['rate'][0] != grade:
continue
# Portfolio, no match
if portfolio_name is not None and note['portfolioName'][0] != portfolio_name:
continue
# Term, no match
if term is not None and note['loanLength'] != term:
continue
# Status
if status is not None:
# Normalize status message
nstatus = re.sub('[^a-zA-Z\-]', ' ', note['status'].lower()) # remove all non alpha characters
nstatus = re.sub('days', ' ', nstatus) # remove days
nstatus = re.sub('\s+', '-', nstatus.strip()) # replace spaces with dash
nstatus = re.sub('(^-+)|(-+$)', '', nstatus)
# No match
if nstatus != status:
continue
# Must be a match
found.append(note)
index += 100
return found | Search for notes you are invested in. Use the parameters to define how to search.
Passing no parameters is the same as calling `my_notes(get_all=True)`
Parameters
----------
loan_id : int, optional
Search for notes for a specific loan. Since a loan is broken up into a pool of notes, it's possible
to invest multiple notes in a single loan
order_id : int, optional
Search for notes from a particular investment order.
grade : {A, B, C, D, E, F, G}, optional
Match by a particular loan grade
portfolio_name : string, optional
Search for notes in a portfolio with this name (case sensitive)
status : string, {issued, in-review, in-funding, current, charged-off, late, in-grace-period, fully-paid}, optional
The funding status string.
term : {60, 36}, optional
Term length, either 60 or 36 (for 5 year and 3 year, respectively)
Returns
-------
dict
A dictionary with a list of matching notes on the `loans` key | entailment |
def add(self, loan_id, amount):
"""
Add a loan and amount you want to invest, to your order.
If this loan is already in your order, it's amount will be replaced
with the this new amount
Parameters
----------
loan_id : int or dict
The ID of the loan you want to add or a dictionary containing a `loan_id` value
amount : int % 25
The dollar amount you want to invest in this loan, as a multiple of 25.
"""
assert amount > 0 and amount % 25 == 0, 'Amount must be a multiple of 25'
assert type(amount) in (float, int), 'Amount must be a number'
if type(loan_id) is dict:
loan = loan_id
assert 'loan_id' in loan and type(loan['loan_id']) is int, 'loan_id must be a number or dictionary containing a loan_id value'
loan_id = loan['loan_id']
assert type(loan_id) in [str, unicode, int], 'Loan ID must be an integer number or a string'
self.loans[loan_id] = amount | Add a loan and amount you want to invest, to your order.
If this loan is already in your order, it's amount will be replaced
with the this new amount
Parameters
----------
loan_id : int or dict
The ID of the loan you want to add or a dictionary containing a `loan_id` value
amount : int % 25
The dollar amount you want to invest in this loan, as a multiple of 25. | entailment |
def add_batch(self, loans, batch_amount=None):
"""
Add a batch of loans to your order.
Parameters
----------
loans : list
A list of dictionary objects representing each loan and the amount you want to invest in it (see examples below).
batch_amount : int, optional
The dollar amount you want to set on ALL loans in this batch.
**NOTE:** This will override the invest_amount value for each loan.
Examples
--------
Each item in the loans list can either be a loan ID OR a dictionary object containing `loan_id` and
`invest_amount` values. The invest_amount value is the dollar amount you wish to invest in this loan.
**List of IDs**::
# Invest $50 in 3 loans
order.add_batch([1234, 2345, 3456], 50)
**List of Dictionaries**::
# Invest different amounts in each loans
order.add_batch([
{'loan_id': 1234, invest_amount: 50},
{'loan_id': 2345, invest_amount: 25},
{'loan_id': 3456, invest_amount: 150}
])
"""
assert batch_amount is None or batch_amount % 25 == 0, 'batch_amount must be a multiple of 25'
# Add each loan
assert type(loans) is list, 'The loans property must be a list. (not {0})'.format(type(loans))
for loan in loans:
loan_id = loan
amount = batch_amount
# Extract ID and amount from loan dict
if type(loan) is dict:
assert 'loan_id' in loan, 'Each loan dict must have a loan_id value'
assert batch_amount or 'invest_amount' in loan, 'Could not determine how much to invest in loan {0}'.format(loan['loan_id'])
loan_id = loan['loan_id']
if amount is None and 'invest_amount' in loan:
amount = loan['invest_amount']
assert amount is not None, 'Could not determine how much to invest in loan {0}'.format(loan_id)
assert amount % 25 == 0, 'Amount to invest must be a multiple of 25 (loan_id: {0})'.format(loan_id)
self.add(loan_id, amount) | Add a batch of loans to your order.
Parameters
----------
loans : list
A list of dictionary objects representing each loan and the amount you want to invest in it (see examples below).
batch_amount : int, optional
The dollar amount you want to set on ALL loans in this batch.
**NOTE:** This will override the invest_amount value for each loan.
Examples
--------
Each item in the loans list can either be a loan ID OR a dictionary object containing `loan_id` and
`invest_amount` values. The invest_amount value is the dollar amount you wish to invest in this loan.
**List of IDs**::
# Invest $50 in 3 loans
order.add_batch([1234, 2345, 3456], 50)
**List of Dictionaries**::
# Invest different amounts in each loans
order.add_batch([
{'loan_id': 1234, invest_amount: 50},
{'loan_id': 2345, invest_amount: 25},
{'loan_id': 3456, invest_amount: 150}
]) | entailment |
def execute(self, portfolio_name=None):
"""
Place the order with LendingClub
Parameters
----------
portfolio_name : string
The name of the portfolio to add the invested loan notes to.
This can be a new or existing portfolio name.
Raises
------
LendingClubError
Returns
-------
int
The completed order ID
"""
assert self.order_id == 0, 'This order has already been place. Start a new order.'
assert len(self.loans) > 0, 'There aren\'t any loans in your order'
# Place the order
self.__stage_order()
token = self.__get_strut_token()
self.order_id = self.__place_order(token)
self.__log('Order #{0} was successfully submitted'.format(self.order_id))
# Assign to portfolio
if portfolio_name:
return self.assign_to_portfolio(portfolio_name)
return self.order_id | Place the order with LendingClub
Parameters
----------
portfolio_name : string
The name of the portfolio to add the invested loan notes to.
This can be a new or existing portfolio name.
Raises
------
LendingClubError
Returns
-------
int
The completed order ID | entailment |
def assign_to_portfolio(self, portfolio_name=None):
"""
Assign all the notes in this order to a portfolio
Parameters
----------
portfolio_name -- The name of the portfolio to assign it to (new or existing)
Raises
------
LendingClubError
Returns
-------
boolean
True on success
"""
assert self.order_id > 0, 'You need to execute this order before you can assign to a portfolio.'
# Get loan IDs as a list
loan_ids = self.loans.keys()
# Make a list of 1 order ID per loan
order_ids = [self.order_id]*len(loan_ids)
return self.lc.assign_to_portfolio(portfolio_name, loan_ids, order_ids) | Assign all the notes in this order to a portfolio
Parameters
----------
portfolio_name -- The name of the portfolio to assign it to (new or existing)
Raises
------
LendingClubError
Returns
-------
boolean
True on success | entailment |
def __stage_order(self):
"""
Add all the loans to the LC order session
"""
# Skip staging...probably not a good idea...you've been warned
if self.__already_staged is True and self.__i_know_what_im_doing is True:
self.__log('Not staging the order...I hope you know what you\'re doing...'.format(len(self.loans)))
return
self.__log('Staging order for {0} loan notes...'.format(len(self.loans)))
# Create a fresh order session
self.lc.session.clear_session_order()
#
# Stage all the loans to the order
#
loan_ids = self.loans.keys()
self.__log('Staging loans {0}'.format(loan_ids))
# LendingClub requires you to search for the loans before you can stage them
f = FilterByLoanID(loan_ids)
results = self.lc.search(f, limit=len(self.loans))
if len(results['loans']) == 0 or results['totalRecords'] != len(self.loans):
raise LendingClubError('Could not stage the loans. The number of loans in your batch does not match totalRecords. {0} != {1}'.format(len(self.loans), results['totalRecords']), results)
# Stage each loan
for loan_id, amount in self.loans.iteritems():
payload = {
'method': 'addToPortfolio',
'loan_id': loan_id,
'loan_amount': amount,
'remove': 'false'
}
response = self.lc.session.get('/data/portfolio', query=payload)
json_response = response.json()
# Ensure it was successful before moving on
if not self.lc.session.json_success(json_response):
raise LendingClubError('Could not stage loan {0} on the order: {1}'.format(loan_id, response.text), response)
#
# Add all staged loans to the order
#
payload = {
'method': 'addToPortfolioNew'
}
response = self.lc.session.get('/data/portfolio', query=payload)
json_response = response.json()
if self.lc.session.json_success(json_response):
self.__log(json_response['message'])
return True
else:
raise self.__log('Could not add loans to the order: {0}'.format(response.text))
raise LendingClubError('Could not add loans to the order', response.text) | Add all the loans to the LC order session | entailment |
def __get_strut_token(self):
"""
Move the staged loan notes to the order stage and get the struts token
from the place order HTML.
The order will not be placed until calling _confirm_order()
Returns
-------
dict
A dict with the token name and value
"""
try:
# Move to the place order page and get the struts token
response = self.lc.session.get('/portfolio/placeOrder.action')
soup = BeautifulSoup(response.text, "html5lib")
# Example HTML with the stuts token:
"""
<input type="hidden" name="struts.token.name" value="token" />
<input type="hidden" name="token" value="C4MJZP39Q86KDX8KN8SBTVCP0WSFBXEL" />
"""
# 'struts.token.name' defines the field name with the token value
strut_tag = None
strut_token_name = soup.find('input', {'name': 'struts.token.name'})
if strut_token_name and strut_token_name['value'].strip():
# Get form around the strut.token.name element
form = soup.form # assumed
for parent in strut_token_name.parents:
if parent and parent.name == 'form':
form = parent
break
# Get strut token value
strut_token_name = strut_token_name['value']
strut_tag = soup.find('input', {'name': strut_token_name})
if strut_tag and strut_tag['value'].strip():
return {'name': strut_token_name, 'value': strut_tag['value'].strip()}
# No strut token found
self.__log('No struts token! HTML: {0}'.format(response.text))
raise LendingClubError('No struts token. Please report this error.', response)
except Exception as e:
self.__log('Could not get struts token. Error message: {0}'.format(str(e)))
raise LendingClubError('Could not get struts token. Error message: {0}'.format(str(e))) | Move the staged loan notes to the order stage and get the struts token
from the place order HTML.
The order will not be placed until calling _confirm_order()
Returns
-------
dict
A dict with the token name and value | entailment |
def __place_order(self, token):
"""
Use the struts token to place the order.
Parameters
----------
token : string
The struts token received from the place order page
Returns
-------
int
The completed order ID.
"""
order_id = 0
response = None
if not token or token['value'] == '':
raise LendingClubError('The token parameter is False, None or unknown.')
# Process order confirmation page
try:
# Place the order
payload = {}
if token:
payload['struts.token.name'] = token['name']
payload[token['name']] = token['value']
response = self.lc.session.post('/portfolio/orderConfirmed.action', data=payload)
# Process HTML for the order ID
html = response.text
soup = BeautifulSoup(html, 'html5lib')
# Order num
order_field = soup.find(id='order_id')
if order_field:
order_id = int(order_field['value'])
# Did not find an ID
if order_id == 0:
self.__log('An investment order was submitted, but a confirmation ID could not be determined')
raise LendingClubError('No order ID was found when placing the order.', response)
else:
return order_id
except Exception as e:
raise LendingClubError('Could not place the order: {0}'.format(str(e)), response) | Use the struts token to place the order.
Parameters
----------
token : string
The struts token received from the place order page
Returns
-------
int
The completed order ID. | entailment |
def __continue_session(self):
"""
Check if the time since the last HTTP request is under the
session timeout limit. If it's been too long since the last request
attempt to authenticate again.
"""
now = time.time()
diff = abs(now - self.last_request_time)
timeout_sec = self.session_timeout * 60 # convert minutes to seconds
if diff >= timeout_sec:
self.__log('Session timed out, attempting to authenticate')
self.authenticate() | Check if the time since the last HTTP request is under the
session timeout limit. If it's been too long since the last request
attempt to authenticate again. | entailment |
def build_url(self, path):
"""
Build a LendingClub URL from a URL path (without the domain).
Parameters
----------
path : string
The path part of the URL after the domain. i.e. https://www.lendingclub.com/<path>
"""
url = '{0}{1}'.format(self.base_url, path)
url = re.sub('([^:])//', '\\1/', url) # Remove double slashes
return url | Build a LendingClub URL from a URL path (without the domain).
Parameters
----------
path : string
The path part of the URL after the domain. i.e. https://www.lendingclub.com/<path> | entailment |
def authenticate(self, email=None, password=None):
"""
Authenticate with LendingClub and preserve the user session for future requests.
This will raise an exception if the login appears to have failed, otherwise it returns True.
Since Lending Club doesn't seem to have a login API, the code has to try to decide if the login
worked or not by looking at the URL redirect and parsing the returned HTML for errors.
Parameters
----------
email : string
The email of a user on Lending Club
password : string
The user's password, for authentication.
Returns
-------
boolean
True on success or throws an exception on failure.
Raises
------
session.AuthenticationError
If authentication failed
session.NetworkError
If a network error occurred
"""
# Get email and password
if email is None:
email = self.email
else:
self.email = email
if password is None:
password = self.__pass
else:
self.__pass = password
# Get them from the user
if email is None:
email = raw_input('Email:')
self.email = email
if password is None:
password = getpass.getpass()
self.__pass = password
self.__log('Attempting to authenticate: {0}'.format(self.email))
# Start session
self.__session = requests.Session()
self.__session.headers = {
'Referer': 'https://www.lendingclub.com/',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31'
}
# Set last request time to now
self.last_request_time = time.time()
# Send login request to LC
payload = {
'login_email': email,
'login_password': password
}
response = self.post('/account/login.action', data=payload, redirects=False)
# Get URL redirect URL and save the last part of the path as the endpoint
response_url = response.url
if response.status_code == 302:
response_url = response.headers['location']
endpoint = response_url.split('/')[-1]
# Debugging
self.__log('Status code: {0}'.format(response.status_code))
self.__log('Redirected to: {0}'.format(response_url))
self.__log('Cookies: {0}'.format(str(response.cookies.keys())))
# Show query and data that the server received
if 'x-echo-query' in response.headers:
self.__log('Query: {0}'.format(response.headers['x-echo-query']))
if 'x-echo-data' in response.headers:
self.__log('Data: {0}'.format(response.headers['x-echo-data']))
# Parse any errors from the HTML
soup = BeautifulSoup(response.text, "html5lib")
errors = soup.find(id='master_error-list')
if errors:
errors = errors.text.strip()
# Remove extra spaces and newlines from error message
errors = re.sub('\t+', '', errors)
errors = re.sub('\s*\n+\s*', ' * ', errors)
if errors == '':
errors = None
# Raise error
if errors is not None:
raise AuthenticationError(errors)
# Redirected back to the login page...must be an error
if endpoint == 'login.action':
raise AuthenticationError('Unknown! Redirected back to the login page without an error message')
return True | Authenticate with LendingClub and preserve the user session for future requests.
This will raise an exception if the login appears to have failed, otherwise it returns True.
Since Lending Club doesn't seem to have a login API, the code has to try to decide if the login
worked or not by looking at the URL redirect and parsing the returned HTML for errors.
Parameters
----------
email : string
The email of a user on Lending Club
password : string
The user's password, for authentication.
Returns
-------
boolean
True on success or throws an exception on failure.
Raises
------
session.AuthenticationError
If authentication failed
session.NetworkError
If a network error occurred | entailment |
def is_site_available(self):
"""
Returns true if we can access LendingClub.com
This is also a simple test to see if there's a network connection
Returns
-------
boolean
True or False
"""
try:
response = requests.head(self.base_url)
status = response.status_code
return 200 <= status < 400 # Returns true if the status code is greater than 200 and less than 400
except Exception:
return False | Returns true if we can access LendingClub.com
This is also a simple test to see if there's a network connection
Returns
-------
boolean
True or False | entailment |
def request(self, method, path, query=None, data=None, redirects=True):
"""
Sends HTTP request to LendingClub.
Parameters
----------
method : {GET, POST, HEAD, DELETE}
The HTTP method to use: GET, POST, HEAD or DELETE
path : string
The path that will be appended to the domain defined in :attr:`base_url`.
query : dict
A dictionary of query string parameters
data : dict
A dictionary of POST data values
redirects : boolean
True to follow redirects, False to return the original response from the server.
Returns
-------
requests.Response
A `requests.Response <http://docs.python-requests.org/en/latest/api/#requests.Response>`_ object
"""
# Check session time
self.__continue_session()
try:
url = self.build_url(path)
method = method.upper()
self.__log('{0} request to: {1}'.format(method, url))
if method == 'POST':
request = self.__session.post(url, params=query, data=data, allow_redirects=redirects)
elif method == 'GET':
request = self.__session.get(url, params=query, data=data, allow_redirects=redirects)
elif method == 'HEAD':
request = self.__session.head(url, params=query, data=data, allow_redirects=redirects)
elif method == 'DELETE':
request = self.__session.delete(url, params=query, data=data, allow_redirects=redirects)
else:
raise SessionError('{0} is not a supported HTTP method'.format(method))
self.last_response = request
self.__log('Status code: {0}'.format(request.status_code))
# Update session time
self.last_request_time = time.time()
except (RequestException, ConnectionError, TooManyRedirects, HTTPError) as e:
raise NetworkError('{0} failed to: {1}'.format(method, url), e)
except Timeout:
raise NetworkError('{0} request timed out: {1}'.format(method, url), e)
return request | Sends HTTP request to LendingClub.
Parameters
----------
method : {GET, POST, HEAD, DELETE}
The HTTP method to use: GET, POST, HEAD or DELETE
path : string
The path that will be appended to the domain defined in :attr:`base_url`.
query : dict
A dictionary of query string parameters
data : dict
A dictionary of POST data values
redirects : boolean
True to follow redirects, False to return the original response from the server.
Returns
-------
requests.Response
A `requests.Response <http://docs.python-requests.org/en/latest/api/#requests.Response>`_ object | entailment |
def post(self, path, query=None, data=None, redirects=True):
"""
POST request wrapper for :func:`request()`
"""
return self.request('POST', path, query, data, redirects) | POST request wrapper for :func:`request()` | entailment |
def get(self, path, query=None, redirects=True):
"""
GET request wrapper for :func:`request()`
"""
return self.request('GET', path, query, None, redirects) | GET request wrapper for :func:`request()` | entailment |
def head(self, path, query=None, data=None, redirects=True):
"""
HEAD request wrapper for :func:`request()`
"""
return self.request('HEAD', path, query, None, redirects) | HEAD request wrapper for :func:`request()` | entailment |
def json_success(self, json):
"""
Check the JSON response object for the success flag
Parameters
----------
json : dict
A dictionary representing a JSON object from lendingclub.com
"""
if type(json) is dict and 'result' in json and json['result'] == 'success':
return True
return False | Check the JSON response object for the success flag
Parameters
----------
json : dict
A dictionary representing a JSON object from lendingclub.com | entailment |
def __merge_values(self, from_dict, to_dict):
"""
Merge dictionary objects recursively, by only updating keys existing in to_dict
"""
for key, value in from_dict.iteritems():
# Only if the key already exists
if key in to_dict:
# Make sure the values are the same datatype
assert type(to_dict[key]) is type(from_dict[key]), 'Data type for {0} is incorrect: {1}, should be {2}'.format(key, type(from_dict[key]), type(to_dict[key]))
# Recursively dive into the next dictionary
if type(to_dict[key]) is dict:
to_dict[key] = self.__merge_values(from_dict[key], to_dict[key])
# Replace value
else:
to_dict[key] = from_dict[key]
return to_dict | Merge dictionary objects recursively, by only updating keys existing in to_dict | entailment |
def __normalize_grades(self):
"""
Adjust the grades list.
If a grade has been set, set All to false
"""
if 'grades' in self and self['grades']['All'] is True:
for grade in self['grades']:
if grade != 'All' and self['grades'][grade] is True:
self['grades']['All'] = False
break | Adjust the grades list.
If a grade has been set, set All to false | entailment |
def __normalize_progress(self):
"""
Adjust the funding progress filter to be a factor of 10
"""
progress = self['funding_progress']
if progress % 10 != 0:
progress = round(float(progress) / 10)
progress = int(progress) * 10
self['funding_progress'] = progress | Adjust the funding progress filter to be a factor of 10 | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.