text stringlengths 81 112k |
|---|
Receive a message from a declared queue by name.
:returns: A :class:`Message` object if a message was received,
``None`` otherwise. If ``None`` was returned, it probably means
there was no messages waiting on the queue.
def get(self, queue, no_ack=False):
"""Receive a message f... |
Returns an iterator that waits for one message at a time.
def consume(self, limit=None):
"""Returns an iterator that waits for one message at a time."""
for total_message_count in count():
if limit and total_message_count >= limit:
raise StopIteration
if not sel... |
Cancel a channel by consumer tag.
def cancel(self, consumer_tag):
"""Cancel a channel by consumer tag."""
if not self.channel.connection:
return
self.channel.basic_cancel(consumer_tag) |
Close the channel if open.
def close(self):
"""Close the channel if open."""
if self._channel and self._channel.is_open:
self._channel.close()
self._channel_ref = None |
Request specific Quality of Service.
def qos(self, prefetch_size, prefetch_count, apply_global=False):
"""Request specific Quality of Service."""
self.channel.basic_qos(prefetch_size, prefetch_count,
apply_global) |
If no channel exists, a new one is requested.
def channel(self):
"""If no channel exists, a new one is requested."""
if not self._channel:
self._channel_ref = weakref.ref(self.connection.get_channel())
return self._channel |
Establish connection to the AMQP broker.
def establish_connection(self):
"""Establish connection to the AMQP broker."""
conninfo = self.connection
if not conninfo.hostname:
raise KeyError("Missing hostname for AMQP connection.")
if conninfo.userid is None:
raise ... |
Declare a consumer.
def declare_consumer(self, queue, no_ack, callback, consumer_tag,
nowait=False):
"""Declare a consumer."""
return self.channel.basic_consume(queue=queue,
no_ack=no_ack,
callback=callback,... |
Returns an iterator that waits for one message at a time.
def consume(self, limit=None):
"""Returns an iterator that waits for one message at a time."""
for total_message_count in count():
if limit and total_message_count >= limit:
raise StopIteration
if not sel... |
Cancel a channel by consumer tag.
def cancel(self, consumer_tag):
"""Cancel a channel by consumer tag."""
if not self.channel.conn:
return
self.channel.basic_cancel(consumer_tag) |
Encapsulate data into a AMQP message.
def prepare_message(self, message_data, delivery_mode, priority=None,
content_type=None, content_encoding=None):
"""Encapsulate data into a AMQP message."""
return amqp.Message(message_data, properties={
"delivery_mode": delivery_mod... |
Special case serializer.
def raw_encode(data):
"""Special case serializer."""
content_type = 'application/data'
payload = data
if isinstance(payload, unicode):
content_encoding = 'utf-8'
payload = payload.encode(content_encoding)
else:
content_encoding = 'binary'
return ... |
Register a encoder/decoder for JSON serialization.
def register_json():
"""Register a encoder/decoder for JSON serialization."""
from anyjson import serialize as json_serialize
from anyjson import deserialize as json_deserialize
registry.register('json', json_serialize, json_deserialize,
... |
Register a encoder/decoder for YAML serialization.
It is slower than JSON, but allows for more data types
to be serialized. Useful if you need to send data such as dates
def register_yaml():
"""Register a encoder/decoder for YAML serialization.
It is slower than JSON, but allows for more data types
... |
The fastest serialization method, but restricts
you to python clients.
def register_pickle():
"""The fastest serialization method, but restricts
you to python clients."""
import cPickle
registry.register('pickle', cPickle.dumps, cPickle.loads,
content_type='application/x-pytho... |
See http://msgpack.sourceforge.net/
def register_msgpack():
"""See http://msgpack.sourceforge.net/"""
try:
import msgpack
registry.register('msgpack', msgpack.packs, msgpack.unpacks,
content_type='application/x-msgpack',
content_encoding='binary')
except Impo... |
Register a new encoder/decoder.
:param name: A convenience name for the serialization method.
:param encoder: A method that will be passed a python data structure
and should return a string representing the serialized data.
If ``None``, then only a decoder will be registered. E... |
Set the default serialization method used by this library.
:param name: The name of the registered serialization method.
For example, ``json`` (default), ``pickle``, ``yaml``,
or any custom methods registered using :meth:`register`.
:raises SerializerNotInstalled: If the serial... |
Serialize a data structure into a string suitable for sending
as an AMQP message body.
:param data: The message data to send. Can be a list,
dictionary or a string.
:keyword serializer: An optional string representing
the serialization method you want the data marshalle... |
Deserialize a data stream as serialized using ``encode``
based on :param:`content_type`.
:param data: The message data to deserialize.
:param content_type: The content-type of the data.
(e.g., ``application/json``).
:param content_encoding: The content-encoding of the data... |
Acknowledge this message as being processed.,
This will remove the message from the queue.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected.
def ack(self):
"""Acknowledge this message as being processed.,
This will remove the message... |
Returns an iterator that waits for one message at a time.
def consume(self, limit=None):
"""Returns an iterator that waits for one message at a time."""
for total_message_count in count():
if limit and total_message_count >= limit:
raise StopIteration
self.drain_... |
Create a bit string of the given length, with the probability of
each bit being set equal to bit_prob, which defaults to .5.
Usage:
# Create a random BitString of length 10 with mostly zeros.
bits = BitString.random(10, bit_prob=.1)
Arguments:
length: An int... |
Create a crossover template with the given number of points. The
crossover template can be used as a mask to crossover two
bitstrings of the same length.
Usage:
assert len(parent1) == len(parent2)
template = BitString.crossover_template(len(parent1))
inv_temp... |
Create a new bit condition that matches the provided bit string,
with the indicated per-index wildcard probability.
Usage:
condition = BitCondition.cover(bitstring, .33)
assert condition(bitstring)
Arguments:
bits: A BitString which the resulting condition m... |
Perform 2-point crossover on this bit condition and another of
the same length, returning the two resulting children.
Usage:
offspring1, offspring2 = condition1.crossover_with(condition2)
Arguments:
other: A second BitCondition of the same length as this one.
... |
Get the currently used backend class.
def get_backend_cls(self):
"""Get the currently used backend class."""
backend_cls = self.backend_cls
if not backend_cls or isinstance(backend_cls, basestring):
backend_cls = get_backend_cls(backend_cls)
return backend_cls |
Ensure we have a connection to the server.
If not retry establishing the connection with the settings
specified.
:keyword errback: Optional callback called each time the connection
can't be established. Arguments provided are the exception
raised and the interval that will ... |
Close the currently open connection.
def close(self):
"""Close the currently open connection."""
try:
if self._connection:
backend = self.create_backend()
backend.close_connection(self._connection)
except socket.error:
pass
self._c... |
Get connection info.
def info(self):
"""Get connection info."""
backend_cls = self.backend_cls or "amqplib"
port = self.port or self.create_backend().default_port
return {"hostname": self.hostname,
"userid": self.userid,
"password": self.password,
... |
Deserialize the message body, returning the original
python structure sent by the publisher.
def decode(self):
"""Deserialize the message body, returning the original
python structure sent by the publisher."""
return serialization.decode(self.body, self.content_type,
... |
The decoded message.
def payload(self):
"""The decoded message."""
if not self._decoded_cache:
self._decoded_cache = self.decode()
return self._decoded_cache |
Acknowledge this message as being processed.,
This will remove the message from the queue.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected.
def ack(self):
"""Acknowledge this message as being processed.,
This will remove the message... |
Reject this message.
The message will be discarded by the server.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected.
def reject(self):
"""Reject this message.
The message will be discarded by the server.
:raises MessageStat... |
Reject this message and put it back on the queue.
You must not use this method as a means of selecting messages
to process.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected.
def requeue(self):
"""Reject this message and put it back ... |
Generate a unique id, having - hopefully - a very small chance of
collission.
For now this is provided by :func:`uuid.uuid4`.
def gen_unique_id():
"""Generate a unique id, having - hopefully - a very small chance of
collission.
For now this is provided by :func:`uuid.uuid4`.
"""
# Workaro... |
Retry the function over and over until max retries is exceeded.
For each retry we sleep a for a while before we try again, this interval
is increased for every retry until the max seconds is reached.
:param fun: The function to try
:param catch: Exceptions to catch, can be either tuple or a single
... |
Get the next waiting message from the queue.
:returns: A :class:`Message` instance, or ``None`` if there is
no messages waiting.
def get(self, *args, **kwargs):
"""Get the next waiting message from the queue.
:returns: A :class:`Message` instance, or ``None`` if there is
... |
Discard all messages in the queue.
def queue_purge(self, queue, **kwargs):
"""Discard all messages in the queue."""
qsize = mqueue.qsize()
mqueue.queue.clear()
return qsize |
Prepare message for sending.
def prepare_message(self, message_data, delivery_mode,
content_type, content_encoding, **kwargs):
"""Prepare message for sending."""
return (message_data, content_type, content_encoding) |
Return a numerical value representing the expected future payoff
of the previously selected action, given only the current match
set. The match_set argument is a MatchSet instance representing the
current match set.
Usage:
match_set = model.match(situation)
expec... |
Return a Boolean indicating whether covering is required for the
current match set. The match_set argument is a MatchSet instance
representing the current match set before covering is applied.
Usage:
match_set = model.match(situation)
if model.algorithm.covering_is_requi... |
Return a new classifier rule that can be added to the match set,
with a condition that matches the situation of the match set and an
action selected to avoid duplication of the actions already
contained therein. The match_set argument is a MatchSet instance
representing the match set to ... |
Distribute the payoff received in response to the selected
action of the given match set among the rules in the action set
which deserve credit for recommending the action. The match_set
argument is the MatchSet instance which suggested the selected
action and earned the payoff.
... |
Update the classifier set from which the match set was drawn,
e.g. by applying a genetic algorithm. The match_set argument is the
MatchSet instance whose classifier set should be updated.
Usage:
match_set = model.match(situation)
match_set.select_action()
mat... |
Reduce the classifier set's population size, if necessary, by
removing lower-quality *rules. Return a list containing any rules
whose numerosities dropped to zero as a result of this call. (The
list may be empty, if no rule's numerosity dropped to 0.) The
model argument is a ClassifierSe... |
Update the fitness values of the rules belonging to this action
set.
def _update_fitness(self, action_set):
"""Update the fitness values of the rules belonging to this action
set."""
# Compute the accuracy of each rule. Accuracy is inversely
# proportional to error. Below a cert... |
Perform action set subsumption.
def _action_set_subsumption(self, action_set):
"""Perform action set subsumption."""
# Select a condition with maximum bit count among those having
# sufficient experience and sufficiently low error.
selected_rule = None
selected_bit_count = None
... |
Return the average time stamp for the rules in this action
set.
def _get_average_time_stamp(action_set):
"""Return the average time stamp for the rules in this action
set."""
# This is the average value of the iteration counter upon the most
# recent update of each rule in this ... |
Select a rule from this action set, with probability
proportionate to its fitness, to act as a parent for a new rule in
the classifier set. Return the selected rule.
def _select_parent(action_set):
"""Select a rule from this action set, with probability
proportionate to its fitness, to ... |
Create a new condition from the given one by probabilistically
applying point-wise mutations. Bits that were originally wildcarded
in the parent condition acquire their values from the provided
situation, to ensure the child condition continues to match it.
def _mutate(self, condition, situatio... |
Establish connection to the AMQP broker.
def establish_connection(self):
"""Establish connection to the AMQP broker."""
conninfo = self.connection
if not conninfo.port:
conninfo.port = self.default_port
credentials = pika.PlainCredentials(conninfo.userid,
... |
Discard all messages in the queue. This will delete the messages
and results in an empty queue.
def queue_purge(self, queue, **kwargs):
"""Discard all messages in the queue. This will delete the messages
and results in an empty queue."""
return self.channel.queue_purge(queue=queue).mess... |
Declare a named queue.
def queue_declare(self, queue, durable, exclusive, auto_delete,
warn_if_exists=False, arguments=None):
"""Declare a named queue."""
return self.channel.queue_declare(queue=queue,
durable=durable,
... |
Declare a consumer.
def declare_consumer(self, queue, no_ack, callback, consumer_tag,
nowait=False):
"""Declare a consumer."""
@functools.wraps(callback)
def _callback_decode(channel, method, header, body):
return callback((channel, method, header, body))
retur... |
Close the channel if open.
def close(self):
"""Close the channel if open."""
if self._channel and not self._channel.handler.channel_close:
self._channel.close()
self._channel_ref = None |
Encapsulate data into a AMQP message.
def prepare_message(self, message_data, delivery_mode, priority=None,
content_type=None, content_encoding=None):
"""Encapsulate data into a AMQP message."""
properties = pika.BasicProperties(priority=priority,
c... |
Publish a message to a named exchange.
def publish(self, message, exchange, routing_key, mandatory=None,
immediate=None, headers=None):
"""Publish a message to a named exchange."""
body, properties = message
if headers:
properties.headers = headers
ret = self.c... |
Generate a unique consumer tag.
:rtype string:
def _generate_consumer_tag(self):
"""Generate a unique consumer tag.
:rtype string:
"""
return "%s.%s%s" % (
self.__class__.__module__,
self.__class__.__name__,
self._next_consumer_... |
Declares the queue, the exchange and binds the queue to
the exchange.
def declare(self):
"""Declares the queue, the exchange and binds the queue to
the exchange."""
arguments = None
routing_key = self.routing_key
if self.exchange_type == "headers":
arguments,... |
Internal method used when a message is received in consume mode.
def _receive_callback(self, raw_message):
"""Internal method used when a message is received in consume mode."""
message = self.backend.message_to_python(raw_message)
if self.auto_ack and not message.acknowledged:
mes... |
Receive the next message waiting on the queue.
:returns: A :class:`carrot.backends.base.BaseMessage` instance,
or ``None`` if there's no messages to be received.
:keyword enable_callbacks: Enable callbacks. The message will be
processed with all registered callbacks. Default is... |
This method is called when a new message is received by
running :meth:`wait`, :meth:`process_next` or :meth:`iterqueue`.
When a message is received, it passes the message on to the
callbacks listed in the :attr:`callbacks` attribute.
You can register callbacks using :meth:`register_call... |
Discard all waiting messages.
:param filterfunc: A filter function to only discard the messages this
filter returns.
:returns: the number of messages discarded.
*WARNING*: All incoming messages will be ignored and not processed.
Example using filter:
>>> def ... |
Declare consumer.
def consume(self, no_ack=None):
"""Declare consumer."""
no_ack = no_ack or self.no_ack
self.backend.declare_consumer(queue=self.queue, no_ack=no_ack,
callback=self._receive_callback,
consumer_tag=self.... |
Go into consume mode.
Mostly for testing purposes and simple programs, you probably
want :meth:`iterconsume` or :meth:`iterqueue` instead.
This runs an infinite loop, processing all incoming messages
using :meth:`receive` to apply the message to all registered
callbacks.
def w... |
Infinite iterator yielding pending messages, by using
synchronous direct access to the queue (``basic_get``).
:meth:`iterqueue` is used where synchronous functionality is more
important than performance. If you can, use :meth:`iterconsume`
instead.
:keyword limit: If set, the i... |
Cancel a running :meth:`iterconsume` session.
def cancel(self):
"""Cancel a running :meth:`iterconsume` session."""
if self.channel_open:
try:
self.backend.cancel(self.consumer_tag)
except KeyError:
pass |
Close the channel to the queue.
def close(self):
"""Close the channel to the queue."""
self.cancel()
self.backend.close()
self._closed = True |
Request specific Quality of Service.
This method requests a specific quality of service. The QoS
can be specified for the current channel or for all channels
on the connection. The particular properties and semantics of
a qos method always depend on the content class semantics.
... |
Declare the exchange.
Creates the exchange on the broker.
def declare(self):
"""Declare the exchange.
Creates the exchange on the broker.
"""
self.backend.exchange_declare(exchange=self.exchange,
type=self.exchange_type,
... |
With any data, serialize it and encapsulate it in a AMQP
message with the proper headers set.
def create_message(self, message_data, delivery_mode=None, priority=None,
content_type=None, content_encoding=None,
serializer=None):
"""With any data, serialize i... |
Send a message.
:param message_data: The message data to send. Can be a list,
dictionary or a string.
:keyword routing_key: A custom routing key for the message.
If not set, the default routing key set in the :attr:`routing_key`
attribute is used.
:keyword ... |
See :meth:`Publisher.send`
def send(self, message_data, delivery_mode=None):
"""See :meth:`Publisher.send`"""
self.publisher.send(message_data, delivery_mode=delivery_mode) |
Close any open channels.
def close(self):
"""Close any open channels."""
self.consumer.close()
self.publisher.close()
self._closed = True |
Internal method used when a message is received in consume mode.
def _receive_callback(self, raw_message):
"""Internal method used when a message is received in consume mode."""
message = self.backend.message_to_python(raw_message)
if self.auto_ack and not message.acknowledged:
mess... |
Add another consumer from dictionary configuration.
def add_consumer_from_dict(self, queue, **options):
"""Add another consumer from dictionary configuration."""
options.setdefault("routing_key", options.pop("binding_key", None))
consumer = Consumer(self.connection, queue=queue,
... |
Add another consumer from a :class:`Consumer` instance.
def add_consumer(self, consumer):
"""Add another consumer from a :class:`Consumer` instance."""
consumer.backend = self.backend
self.consumers.append(consumer) |
Declare consumer so messages can be received from it using
:meth:`iterconsume`.
def _declare_consumer(self, consumer, nowait=False):
"""Declare consumer so messages can be received from it using
:meth:`iterconsume`."""
if consumer.queue not in self._open_consumers:
# Use the... |
Declare consumers.
def consume(self):
"""Declare consumers."""
head = self.consumers[:-1]
tail = self.consumers[-1]
[self._declare_consumer(consumer, nowait=True)
for consumer in head]
self._declare_consumer(tail, nowait=False) |
Cycle between all consumers in consume mode.
See :meth:`Consumer.iterconsume`.
def iterconsume(self, limit=None):
"""Cycle between all consumers in consume mode.
See :meth:`Consumer.iterconsume`.
"""
self.consume()
return self.backend.consume(limit=limit) |
Cancel a running :meth:`iterconsume` session.
def cancel(self):
"""Cancel a running :meth:`iterconsume` session."""
for consumer_tag in self._open_consumers.values():
try:
self.backend.cancel(consumer_tag)
except KeyError:
pass
self._open_... |
Try to convert the source, an .md (markdown) file, to an .rst
(reStructuredText) file at the destination. If the destination isn't
provided, it defaults to be the same as the source path except for the
filename extension. If the destination file already exists, it will be
overwritten. In the event of an... |
Call the conversion routine on README.md to generate README.rst.
Why do all this? Because pypi requires reStructuredText, but markdown
is friendlier to work with and is nicer for GitHub.
def build_readme(base_path=None):
"""Call the conversion routine on README.md to generate README.rst.
Why do all thi... |
Return a situation, encoded as a bit string, which represents
the observable state of the environment.
Usage:
situation = scenario.sense()
assert isinstance(situation, BitString)
Arguments: None
Return:
The current situation.
def sense(self):
... |
Execute the indicated action within the environment and
return the resulting immediate reward dictated by the reward
program.
Usage:
immediate_reward = scenario.execute(selected_action)
Arguments:
action: The action to be executed within the current situation.
... |
Reset the scenario, starting it over for a new run.
Usage:
if not scenario.more():
scenario.reset()
Arguments: None
Return: None
def reset(self):
"""Reset the scenario, starting it over for a new run.
Usage:
if not scenario.more():
... |
Return a situation, encoded as a bit string, which represents
the observable state of the environment.
Usage:
situation = scenario.sense()
assert isinstance(situation, BitString)
Arguments: None
Return:
The current situation.
def sense(self):
... |
Execute the indicated action within the environment and
return the resulting immediate reward dictated by the reward
program.
Usage:
immediate_reward = scenario.execute(selected_action)
Arguments:
action: The action to be executed within the current situation.
... |
Return a sequence containing the possible actions that can be
executed within the environment.
Usage:
possible_actions = scenario.get_possible_actions()
Arguments: None
Return:
A sequence containing the possible actions which can be
executed within t... |
Return a situation, encoded as a bit string, which represents
the observable state of the environment.
Usage:
situation = scenario.sense()
assert isinstance(situation, BitString)
Arguments: None
Return:
The current situation.
def sense(self):
... |
Execute the indicated action within the environment and
return the resulting immediate reward dictated by the reward
program.
Usage:
immediate_reward = scenario.execute(selected_action)
Arguments:
action: The action to be executed within the current situation.
... |
Return a Boolean indicating whether additional actions may be
executed, per the reward program.
Usage:
while scenario.more():
situation = scenario.sense()
selected_action = choice(possible_actions)
reward = scenario.execute(selected_action)
... |
Execute the indicated action within the environment and
return the resulting immediate reward dictated by the reward
program.
Usage:
immediate_reward = scenario.execute(selected_action)
Arguments:
action: The action to be executed within the current situation.
... |
Return the classifications made by the algorithm for this
scenario.
Usage:
model.run(scenario, learn=False)
classifications = scenario.get_classifications()
Arguments: None
Return:
An indexable sequence containing the classifications made by
... |
Create and return a new classifier set initialized for handling
the given scenario.
Usage:
scenario = MUXProblem()
model = algorithm.new_model(scenario)
model.run(scenario, learn=True)
Arguments:
scenario: A Scenario instance.
Return:
... |
Run the algorithm, utilizing a classifier set to choose the
most appropriate action for each situation produced by the
scenario. Improve the situation/action mapping on each reward
cycle to maximize reward. Return the classifier set that was
created.
Usage:
scenario ... |
Compute the combined prediction and prediction weight for this
action set. The combined prediction is the weighted average of the
individual predictions of the classifiers. The combined prediction
weight is the sum of the individual prediction weights of the
classifiers.
Usage:
... |
The highest value from among the predictions made by the action
sets in this match set.
def best_prediction(self):
"""The highest value from among the predictions made by the action
sets in this match set."""
if self._best_prediction is None and self._action_sets:
self._best... |
A tuple containing the actions whose action sets have the best
prediction.
def best_actions(self):
"""A tuple containing the actions whose action sets have the best
prediction."""
if self._best_actions is None:
best_prediction = self.best_prediction
self._best_ac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.