code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Bale Bot Authorization Token
updater = Updater("TOKEN")
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Bale
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e mes... | def main() | Start the bot. | 3.005488 | 2.771432 | 1.084453 |
global global_config
if not config:
config = global_config
queue_store_factory = resolve_name(config.get('coilmq', 'qstore.factory'))
subscriber_scheduler_factory = resolve_name(config.get(
'coilmq', 'scheduler.subscriber_priority_factory'))
queue_scheduler_factory = resolv... | def server_from_config(config=None, server_class=None, additional_kwargs=None) | Gets a configured L{coilmq.server.StompServer} from specified config.
If `config` is None, global L{coilmq.config.config} var will be used instead.
The `server_class` and `additional_kwargs` are primarily hooks for using this method
from a testing environment.
@param config: A C{ConfigParser.ConfigPa... | 3.08194 | 2.880705 | 1.069856 |
global global_config
server = None
try:
with context:
# There's a possibility here that init_logging() will throw an exception. If it does,
# AND we're in a daemon context, then we're not going to be able to do anything with it.
# We've got no stderr/stdout... | def context_serve(context, configfile, listen_addr, listen_port, logfile,
debug, daemon, uid, gid, pidfile, umask, rundir) | Takes a context object, which implements the __enter__/__exit__ "with" interface
and starts a server within that context.
This method is a refactored single-place for handling the server-run code whether
running in daemon or non-daemon mode. It is invoked with a dummy (passthrough)
context object fo... | 4.755749 | 4.707648 | 1.010218 |
_main(**locals()) | def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir) | Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will b... | 50.74435 | 293.555969 | 0.172861 |
configuration = dict(config.items('coilmq'))
engine = engine_from_config(configuration, 'qstore.sqlalchemy.')
init_model(engine)
store = SAQueue()
return store | def make_sa() | Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration. | 16.720367 | 7.008345 | 2.38578 |
meta.engine = engine
meta.metadata = MetaData(bind=meta.engine)
meta.Session = scoped_session(sessionmaker(bind=meta.engine))
model.setup_tables(create=create, drop=drop) | def init_model(engine, create=True, drop=False) | Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module.
@param engine: The SQLAlchemy engine instance.
@type engine: C{sqlalchemy.Engine}
@param create: Whether to create the tables (if they do not exist).
@type create: C{bool}
@param drop: Whether to drop the tables (if t... | 3.560927 | 4.410101 | 0.807448 |
session = meta.Session()
message_id = frame.headers.get('message-id')
if not message_id:
raise ValueError("Cannot queue a frame without message-id set.")
ins = model.frames_table.insert().values(
message_id=message_id, destination=destination, frame=frame... | def enqueue(self, destination, frame) | Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination.
@type frame: C{stompclient.frame.Frame} | 4.417357 | 4.828199 | 0.914908 |
session = meta.Session()
try:
selstmt = select(
[model.frames_table.c.message_id, model.frames_table.c.frame])
selstmt = selstmt.where(
model.frames_table.c.destination == destination)
selstmt = selstmt.order_by(
... | def dequeue(self, destination) | Removes and returns an item from the queue (or C{None} if no items in queue).
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: The first frame in the specified queue, or C{None} if there are none.
@rtype: C{stompclient.frame.Frame} | 2.574311 | 2.709808 | 0.949998 |
session = meta.Session()
sel = select([model.frames_table.c.message_id]).where(
model.frames_table.c.destination == destination)
result = session.execute(sel)
first = result.fetchone()
return first is not None | def has_frames(self, destination) | Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool} | 4.692797 | 5.850822 | 0.802075 |
session = meta.Session()
sel = select([func.count(model.frames_table.c.message_id)]).where(
model.frames_table.c.destination == destination)
result = session.execute(sel)
first = result.fetchone()
if not first:
return 0
else:
r... | def size(self, destination) | Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int} | 3.922654 | 4.514731 | 0.868857 |
session = meta.Session()
sel = select([distinct(model.frames_table.c.destination)])
result = session.execute(sel)
return set([r[0] for r in result.fetchall()]) | def destinations(self) | Provides a list of destinations (queue "addresses") available.
@return: A list of the detinations available.
@rtype: C{set} | 6.71862 | 7.667263 | 0.876274 |
global frames_table
frames_table = Table('frames', meta.metadata,
Column('message_id', String(255), primary_key=True),
Column('sequence', BigInteger,
primary_key=False, autoincrement=True),
Column('de... | def setup_tables(create=True, drop=False) | Binds the model classes to registered metadata and engine and (potentially)
creates the db tables.
This function expects that you have bound the L{meta.metadata} and L{meta.engine}.
@param create: Whether to create the tables (if they do not exist).
@type create: C{bool}
@param drop: Whether to ... | 3.374834 | 3.330232 | 1.013393 |
self.log.debug("Subscribing %s to %s" % (connection, destination))
self._topics[destination].add(connection) | def subscribe(self, connection, destination) | Subscribes a connection to the specified topic destination.
@param connection: The client connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | 3.303865 | 3.278898 | 1.007614 |
self.log.debug("Unsubscribing %s from %s" % (connection, destination))
if connection in self._topics[destination]:
self._topics[destination].remove(connection)
if not self._topics[destination]:
del self._topics[destination] | def unsubscribe(self, connection, destination) | Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | 2.223129 | 2.214702 | 1.003805 |
self.log.debug("Disconnecting %s" % connection)
for dest in list(self._topics.keys()):
if connection in self._topics[dest]:
self._topics[dest].remove(connection)
if not self._topics[dest]:
# This won't trigger RuntimeError, since we're usi... | def disconnect(self, connection) | Removes a subscriber connection.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection} | 3.951704 | 3.939731 | 1.003039 |
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
bad_subscribers = set()
... | def send(self, message) | Sends a message to all subscribers of destination.
@param message: The message frame. (The frame will be modified to set command
to MESSAGE and set a message id.)
@type message: L{stompclient.frame.Frame} | 4.627301 | 4.217165 | 1.097254 |
self.connected = False
self.queue_manager.disconnect(self.connection)
self.topic_manager.disconnect(self.connection) | def unbind(self) | Unbinds this connection from queue and topic managers (freeing up resources)
and resets state. | 6.46166 | 3.293901 | 1.961704 |
self.log.info("Shutting down queue manager.")
if hasattr(self.store, 'close'):
self.store.close()
if hasattr(self.subscriber_scheduler, 'close'):
self.subscriber_scheduler.close()
if hasattr(self.queue_scheduler, 'close'):
self.queue_schedul... | def close(self) | Closes all resources/backends associated with this queue manager. | 3.223788 | 2.629879 | 1.225831 |
if destination:
return len(self._queues[destination])
else:
# total them up
total = 0
for k in self._queues.keys():
total += len(self._queues[k])
return total | def subscriber_count(self, destination=None) | Returns a count of the number of subscribers.
If destination is specified then it only returns count of subscribers
for that specific destination.
@param destination: The optional topic/queue destination (e.g. '/queue/foo')
@type destination: C{str} | 3.336254 | 3.664395 | 0.910451 |
self.log.debug("Subscribing %s to %s" % (connection, destination))
self._queues[destination].add(connection)
self._send_backlog(connection, destination) | def subscribe(self, connection, destination) | Subscribes a connection to the specified destination (topic or queue).
@param connection: The connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str} | 3.709958 | 4.175291 | 0.888551 |
self.log.debug("Unsubscribing %s from %s" % (connection, destination))
if connection in self._queues[destination]:
self._queues[destination].remove(connection)
if not self._queues[destination]:
del self._queues[destination] | def unsubscribe(self, connection, destination) | Unsubscribes a connection from a destination (topic or queue).
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str} | 2.228568 | 2.401122 | 0.928136 |
self.log.debug("Disconnecting %s" % connection)
if connection in self._pending:
pending_frame = self._pending[connection]
self.store.requeue(pending_frame.headers.get(
'destination'), pending_frame)
del self._pending[connection]
for d... | def disconnect(self, connection) | Removes a subscriber connection, ensuring that any pending commands get requeued.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection} | 3.979661 | 3.657193 | 1.088174 |
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
# Grab all subscribers for t... | def send(self, message) | Sends a MESSAGE frame to an eligible subscriber connection.
Note that this method will modify the incoming message object to
add a message-id header (if not present) and to change the command
to 'MESSAGE' (if it is not).
@param message: The message frame.
@type message: C{stom... | 4.34811 | 3.874081 | 1.122359 |
self.log.debug("ACK %s for %s" % (frame, connection))
if connection in self._pending:
pending_frame = self._pending[connection]
# Make sure that the frame being acknowledged matches
# the expected frame
if pending_frame.headers.get('message-id') ... | def ack(self, connection, frame, transaction=None) | Acknowledge receipt of a message.
If the `transaction` parameter is non-null, the frame being ack'd
will be queued so that it can be requeued if the transaction
is rolled back.
@param connection: The connection that is acknowledging the frame.
@type connection: L{coilmq.server... | 3.957176 | 3.909863 | 1.012101 |
for frame in self._transaction_frames[connection][transaction]:
self.send(frame) | def resend_transaction_frames(self, connection, transaction) | Resend the messages that were ACK'd in specified transaction.
This is called by the engine when there is an abort command.
@param connection: The client connection that aborted the transaction.
@type connection: L{coilmq.server.StompConnection}
@param transaction: The transaction id (... | 6.621177 | 8.492866 | 0.779616 |
if destination is None:
# Find all destinations that have frames and that contain this
# connection (subscriber).
eligible_queues = dict([(dest, q) for (dest, q) in self._queues.items()
if connection in q and self.store.has_frames(... | def _send_backlog(self, connection, destination=None) | Sends any queued-up messages for the (optionally) specified destination to connection.
If the destination is not provided, a destination is chosen using the
L{QueueManager.queue_scheduler} scheduler algorithm.
(This method assumes it is being called from within a lock-guarded public
m... | 3.164358 | 2.987046 | 1.05936 |
assert connection is not None
assert frame is not None
self.log.debug("Delivering frame %s to connection %s" %
(frame, connection))
if connection.reliable_subscriber:
if connection in self._pending:
raise RuntimeError("Connect... | def _send_frame(self, connection, frame) | Sends a frame to a specific subscriber connection.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The subscriber connection object to send to.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame to s... | 4.006683 | 4.15443 | 0.964436 |
try:
data_dir = config.get('coilmq', 'qstore.dbm.data_dir')
cp_ops = config.getint('coilmq', 'qstore.dbm.checkpoint_operations')
cp_timeout = config.getint('coilmq', 'qstore.dbm.checkpoint_timeout')
except ConfigParser.NoOptionError as e:
raise ConfigError('Missing configura... | def make_dbm() | Creates a DBM queue store, pulling config values from the CoilMQ configuration. | 3.193257 | 2.73997 | 1.165435 |
message_id = frame.headers.get('message-id')
if not message_id:
raise ValueError("Cannot queue a frame without message-id set.")
if not destination in self.queue_metadata:
self.log.info(
"Destination %s not in metadata; creating new entry and que... | def enqueue(self, destination, frame) | Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination.
@type frame: C{stompclient.frame.Frame} | 3.849026 | 3.706594 | 1.038427 |
if not self.has_frames(destination):
return None
message_id = self.queue_metadata[destination]['frames'].pop()
self.queue_metadata[destination]['dequeued'] += 1
frame = self.frame_store[message_id]
del self.frame_store[message_id]
self._opcount += ... | def dequeue(self, destination) | Removes and returns an item from the queue (or C{None} if no items in queue).
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: The first frame in the specified queue, or C{None} if there are none.
@rtype: C{stompclient.frame.Frame} | 4.468211 | 4.315401 | 1.03541 |
return (destination in self.queue_metadata) and bool(self.queue_metadata[destination]['frames']) | def has_frames(self, destination) | Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool} | 9.349757 | 7.56729 | 1.235549 |
if not destination in self.queue_metadata:
return 0
else:
return len(self.queue_metadata[destination]['frames']) | def size(self, destination) | Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int} | 5.62519 | 4.281318 | 1.313892 |
if (self._opcount > self.checkpoint_operations or
datetime.now() > self._last_sync + self.checkpoint_timeout):
self.log.debug("Synchronizing queue metadata.")
self.queue_metadata.sync()
self._last_sync = datetime.now()
self._opcount = 0
... | def _sync(self) | Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method wraps calls to C{shelve.Shelf#sync}. | 4.399618 | 3.218585 | 1.366942 |
if not config_values:
raise RheaError('Cannot read config_value: `{}`'.format(config_values))
config_values = to_list(config_values)
config = {}
for config_value in config_values:
config_value = ConfigSpec.get_from(value=config_value)
config_value.check_type()
conf... | def read(config_values) | Reads an ordered list of configuration values and deep merge the values in reverse order. | 3.331692 | 3.217695 | 1.035428 |
preamble_lines = list(map(
lambda x: six.u(x).decode(),
iter(lambda: buff.readline().strip(), b''))
)
if not preamble_lines:
raise EmptyBuffer()
return preamble_lines[0], OrderedDict([l.split(':') for l in preamble_lines[1:]]) | def parse_headers(buff) | Parses buffer and returns command and headers as strings | 5.006876 | 4.612751 | 1.085442 |
self.headers.setdefault('content-length', len(self.body))
# Convert and append any existing headers to a string as the
# protocol describes.
headerparts = ("{0}:{1}\n".format(key, value)
for key, value in self.headers.items())
# Frame is Command... | def pack(self) | Create a string representation from object state.
@return: The string (bytes) for this stomp frame.
@rtype: C{str} | 6.125372 | 5.242818 | 1.168336 |
# (mbytes, hbytes) = self._find_message_bytes(self.buffer)
# if not mbytes:
# return None
#
# msgdata = self.buffer[:mbytes]
# self.buffer = self.buffer[mbytes:]
# hdata = msgdata[:hbytes]
# # Strip off any leading whitespace from headers; thi... | def extract_frame(self) | Pulls one complete frame off the buffer and returns it.
If there is no complete message in the buffer, returns None.
Note that the buffer can contain more than once message. You
should therefore call this method in a loop (or use iterator
functionality exposed by class) until None retu... | 4.38642 | 4.225835 | 1.038001 |
if not subscribers:
return None
reliable_subscribers = [
s for s in subscribers if s.reliable_subscriber]
if reliable_subscribers:
return random.choice(reliable_subscribers)
else:
return random.choice(subscribers) | def choice(self, subscribers, message) | Choose a random connection, favoring those that are reliable from
subscriber pool to deliver specified message.
@param subscribers: Collection of subscribed connections to destination.
@type subscribers: C{list} of L{coilmq.server.StompConnection}
@param message: The message to be del... | 2.941662 | 3.009678 | 0.977401 |
if not queues:
return None
return random.choice(list(queues.keys())) | def choice(self, queues, connection) | Chooses a random queue for messages to specified connection.
@param queues: A C{dict} mapping queue name to queues (sets of frames) to which
specified connection is subscribed.
@type queues: C{dict} of C{str} to C{set} of L{stompclient.frame.Frame}
@param connection: ... | 5.123532 | 4.61272 | 1.11074 |
if is_list:
return self._get_typed_list_value(key=key,
target_type=int,
type_convert=int,
is_optional=is_optional,
... | def get_int(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `int`/`list(int)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_l... | 1.681235 | 1.785962 | 0.941361 |
if is_list:
return self._get_typed_list_value(key=key,
target_type=float,
type_convert=float,
is_optional=is_optional,
... | def get_float(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `float`/`list(float)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
... | 1.670733 | 1.782248 | 0.93743 |
if is_list:
return self._get_typed_list_value(key=key,
target_type=bool,
type_convert=lambda x: bool(strtobool(x)),
is_optional=is_optional,
... | def get_boolean(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `bool`/`list(str)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_... | 1.661955 | 1.748879 | 0.950297 |
if is_list:
return self._get_typed_list_value(key=key,
target_type=str,
type_convert=str,
is_optional=is_optional,
... | def get_string(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `str`/`list(str)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_l... | 1.691543 | 1.810358 | 0.934369 |
def convert_to_dict(x):
x = json.loads(x)
if not isinstance(x, Mapping):
raise RheaError("Cannot convert value `{}` (key: `{}`) to `dict`".format(x, key))
return x
if is_list:
return self._get_typed_list_value(key=key,
... | def get_dict(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `dict`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If th... | 2.017533 | 2.04421 | 0.98695 |
value = self.get_dict(
key=key,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options,
)
if not value:
return default
for k in value:
if n... | def get_dict_of_dicts(self,
key,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `dict`.
Add an extra validation that all keys have a dict as values.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If... | 3.064229 | 3.414918 | 0.897307 |
if is_list:
return self._get_typed_list_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
... | def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If ... | 1.86872 | 1.817836 | 1.027992 |
if is_list:
return self._get_typed_list_value(key=key,
target_type=AuthSpec,
type_convert=self.parse_auth_spec,
is_optional=is_optional,
... | def get_auth(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts it to `AuthSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If... | 1.782425 | 1.783425 | 0.999439 |
def parse_list(v):
parts = v.split(',')
results = []
for part in parts:
part = part.strip()
if part:
results.append(part)
return results
return self._get_typed_value(key=key,
... | def get_list(self,
key,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None) | Get a the value corresponding to the key and converts comma separated values to a list.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
d... | 2.365921 | 2.453327 | 0.964372 |
try:
value = self._get(key)
except KeyError:
if not is_optional:
raise RheaError(
'No value was provided for the non optional key `{}`.'.format(key))
return default
if isinstance(value, six.string_types):
... | def _get_typed_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
... | Return the value corresponding to the key converted to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an err... | 2.097305 | 2.096987 | 1.000151 |
value = self._get_typed_value(key=key,
target_type=list,
type_convert=json.loads,
is_optional=is_optional,
is_secret=is_secret,
... | def _get_typed_list_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
... | Return the value corresponding to the key converted first to list
than each element to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
... | 2.19703 | 2.231805 | 0.984418 |
authfile = config.get('coilmq', 'auth.simple.file')
if not authfile:
raise ConfigError('Missing configuration parameter: auth.simple.file')
sa = SimpleAuthenticator()
sa.from_configfile(authfile)
return sa | def make_simple() | Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error. | 6.40908 | 4.317583 | 1.484414 |
cfg = ConfigParser()
if hasattr(configfile, 'read'):
cfg.read_file(configfile)
else:
filesread = cfg.read(configfile)
if not filesread:
raise ValueError('Could not parse auth file: %s' % configfile)
if not cfg.has_section('aut... | def from_configfile(self, configfile) | Initialize the authentication store from a "config"-style file.
Auth "config" file is parsed with C{ConfigParser.RawConfigParser} and must contain
an [auth] section which contains the usernames (keys) and passwords (values).
Example auth file::
[auth]
someuser = somepa... | 3.218206 | 2.733558 | 1.177296 |
return login in self.store and self.store[login] == passcode | def authenticate(self, login, passcode) | Authenticate the login and passcode.
@return: Whether provided login and password match values in store.
@rtype: C{bool} | 6.239187 | 11.952074 | 0.522017 |
cmd_method = frame.cmd.lower()
if not cmd_method in VALID_COMMANDS:
raise ProtocolError("Invalid STOMP command: {}".format(frame.cmd))
method = getattr(self, cmd_method, None)
if not self.engine.connected and method not in (self.connect, self.stomp):
r... | def process_frame(self, frame) | Dispatches a received frame to the appropriate internal method.
@param frame: The frame that was received.
@type frame: C{stompclient.frame.Frame} | 3.721867 | 3.559301 | 1.045674 |
self.engine.log.debug("CONNECT")
if self.engine.authenticator:
login = frame.headers.get('login')
passcode = frame.headers.get('passcode')
if not self.engine.authenticator.authenticate(login, passcode):
raise AuthError("Authentication failed ... | def connect(self, frame, response=None) | Handle CONNECT command: Establishes a new connection and checks auth (if applicable). | 4.724058 | 4.328526 | 1.091378 |
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for SEND command.')
if dest.startswith('/queue/'):
self.engine.queue_manager.send(frame)
else:
self.engine.topic_manager.send(frame) | def send(self, frame) | Handle the SEND command: Delivers a message to a queue or topic (default). | 4.592636 | 3.57257 | 1.285527 |
ack = frame.headers.get('ack')
reliable = ack and ack.lower() == 'client'
self.engine.connection.reliable_subscriber = reliable
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for SUBSCRIBE command.')
i... | def subscribe(self, frame) | Handle the SUBSCRIBE command: Adds this connection to destination. | 4.266912 | 3.552682 | 1.20104 |
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for UNSUBSCRIBE command.')
if dest.startswith('/queue/'):
self.engine.queue_manager.unsubscribe(self.engine.connection, dest)
else:
self.engine.topi... | def unsubscribe(self, frame) | Handle the UNSUBSCRIBE command: Removes this connection from destination. | 3.524753 | 2.961869 | 1.190044 |
if not frame.transaction:
raise ProtocolError("Missing transaction for BEGIN command.")
self.engine.transactions[frame.transaction] = [] | def begin(self, frame) | Handles BEGING command: Starts a new transaction. | 14.460546 | 9.447052 | 1.530694 |
if not frame.transaction:
raise ProtocolError("Missing transaction for COMMIT command.")
if not frame.transaction in self.engine.transactions:
raise ProtocolError("Invalid transaction: %s" % frame.transaction)
for tframe in self.engine.transactions[frame.transa... | def commit(self, frame) | Handles COMMIT command: Commits specified transaction. | 4.192263 | 3.581588 | 1.170504 |
if not frame.transaction:
raise ProtocolError("Missing transaction for ABORT command.")
if not frame.transaction in self.engine.transactions:
raise ProtocolError("Invalid transaction: %s" % frame.transaction)
self.engine.queue_manager.resend_transaction_frames(... | def abort(self, frame) | Handles ABORT command: Rolls back specified transaction. | 4.906315 | 3.94908 | 1.242395 |
if not frame.message_id:
raise ProtocolError("No message-id specified for ACK command.")
self.engine.queue_manager.ack(self.engine.connection, frame) | def ack(self, frame) | Handles the ACK command: Acknowledges receipt of a message. | 8.21413 | 6.488841 | 1.265886 |
self.engine.log.debug("Disconnect")
self.engine.unbind() | def disconnect(self, frame) | Handles the DISCONNECT command: Unbinds the connection.
Clients are supposed to send this command, but in practice it should not be
relied upon. | 14.268657 | 9.950598 | 1.43395 |
if not frame.headers.get('message-id'):
raise ProtocolError("No message-id specified for NACK command.")
if not frame.headers.get('subscription'):
raise ProtocolError("No subscription specified for NACK command.") | def nack(self, frame) | Handles the NACK command: Unacknowledges receipt of a message.
For now, this is just a placeholder to implement this version of the protocol | 3.305153 | 2.917852 | 1.132735 |
global config
if config_file and os.path.exists(config_file):
read = config.read([config_file])
if not read:
raise ValueError(
"Could not read configuration from file: %s" % config_file) | def init_config(config_file=None) | Initialize the configuration from a config file.
The values in config_file will override those already loaded from the default
configuration file (defaults.cfg, in current package).
This method does not setup logging.
@param config_file: The path to a configuration file.
@type config_file: C{str}... | 3.476948 | 3.752136 | 0.926658 |
# If a config file was specified, we will use that in place of the
# explicitly
use_configfile = False
if configfile and os.path.exists(configfile):
testcfg = ConfigParser()
read = testcfg.read(configfile)
use_configfile = (read and testcfg.has_section('loggers'))
if us... | def init_logging(logfile=None, loglevel=logging.INFO, configfile=None) | Configures the logging using either basic filename + loglevel or passed config file path.
This is performed separately from L{init_config()} in order to support the case where
logging should happen independent of (usu. *after*) other aspects of the configuration
initialization. For example, if logging ma... | 3.080299 | 3.171608 | 0.97121 |
if ':' in name:
# Normalize foo.bar.baz:main to foo.bar.baz.main
# (since our logic below will handle that)
name = '%s.%s' % tuple(name.split(':'))
name = name.split('.')
used = name.pop(0)
found = __import__(used)
for n in name:
used = used + '.' + n
t... | def resolve_name(name) | Resolve a dotted name to some object (usually class, module, or function).
Supported naming formats include:
1. path.to.module:method
2. path.to.module.ClassName
>>> resolve_name('coilmq.store.memory.MemoryQueue')
<class 'coilmq.store.memory.MemoryQueue'>
>>> t = resolve_name('coilmq.s... | 3.44471 | 3.729297 | 0.923689 |
# self.request is the TCP socket connected to the client
try:
while not self.server._shutdown_request_event.is_set():
try:
data = self.request.recv(8192)
if not data:
break
if self.de... | def handle(self) | Handle a new socket connection. | 3.559997 | 3.336659 | 1.066935 |
packed = frame.pack()
if self.debug: # pragma: no cover
self.log.debug("SEND: %r" % packed)
self.request.sendall(packed) | def send_frame(self, frame) | Sends a frame to connected socket client.
@param frame: The frame to send.
@type frame: C{stompclient.frame.Frame} | 4.554768 | 4.942225 | 0.921603 |
self.log.debug("Closing the socket server connection.")
TCPServer.server_close(self)
self.queue_manager.close()
self.topic_manager.close()
if hasattr(self.authenticator, 'close'):
self.authenticator.close()
self.shutdown() | def server_close(self) | Closes the socket server and any associated resources. | 4.711894 | 4.220572 | 1.116411 |
self._serving_event.set()
self._shutdown_request_event.clear()
TCPServer.serve_forever(self, poll_interval=poll_interval) | def serve_forever(self, poll_interval=0.5) | Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread. | 4.281061 | 4.33615 | 0.987295 |
coords = range(width)
texel = (ctypes.c_byte * width**3)()
half = 0 #width * scale / 2.0
for z in coords:
for y in coords:
for x in coords:
v = snoise3(x * scale - half, y * scale - half, z * scale - half, octaves=4, persistence=0.25)
texel[x + (y * width) + (z * width**2)] = int(v * 127.0)
glPixe... | def create_3d_texture(width, scale) | Create a grayscale 3d texture map with the specified
pixel width on each side and load it into the current texture
unit. The luminace of each texel is derived using the input
function as:
v = func(x * scale, y * scale, z * scale)
where x, y, z = 0 in the center texel of the texture.
func(x, y, z) is assumed t... | 2.681295 | 2.557645 | 1.048345 |
if period is not None:
self.period = period
perm = list(range(self.period))
perm_right = self.period - 1
for i in list(perm):
j = self.randint_function(0, perm_right)
perm[i], perm[j] = perm[j], perm[i]
self.permutation = tuple(perm) * 2 | def randomize(self, period=None) | Randomize the permutation table used by the noise functions. This
makes them generate a different noise pattern for the same inputs. | 3.321461 | 3.081129 | 1.078001 |
# Skew input space to determine which simplex (triangle) we are in
s = (x + y) * _F2
i = floor(x + s)
j = floor(y + s)
t = (i + j) * _G2
x0 = x - (i - t) # "Unskewed" distances from cell origin
y0 = y - (j - t)
if x0 > y0:
i1 = 1; j1 = 0 # Lower triangle, XY order: (0,0)->(1,0)->(1,1)
else:
... | def noise2(self, x, y) | 2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above). | 1.866338 | 1.811262 | 1.030408 |
i = int(fmod(floor(x), repeat))
j = int(fmod(floor(y), repeat))
k = int(fmod(floor(z), repeat))
ii = (i + 1) % repeat
jj = (j + 1) % repeat
kk = (k + 1) % repeat
if base:
i += base; j += base; k += base
ii += base; jj += base; kk += base
x -= floor(x); y -= floor(y); z -= floor(z)
fx = x**3 ... | def noise3(self, x, y, z, repeat, base=0.0) | Tileable 3D noise.
repeat specifies the integer interval in each dimension
when the noise pattern repeats.
base allows a different texture to be generated for
the same repeat interval. | 1.586025 | 1.644043 | 0.964711 |
glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16,
self.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA,
GL_UNSIGNED_SHORT, ctypes.byref(self.data)) | def load(self) | Load the noise texture data into the current texture unit | 2.806402 | 2.35214 | 1.193127 |
glEnable(GL_TEXTURE_3D)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_3D, GL... | def enable(self) | Convenience method to enable 3D texturing state so the texture may be used by the
ffpnoise shader function | 1.361329 | 1.287657 | 1.057214 |
# Normalize angle to [-180,180]
output = []
angle = ((angle + math.pi) % (math.pi * 2)) - math.pi
for target in self.targets:
proposed = target.compute(now, x, y, angle)
if proposed:
output.append(proposed)
if not output:
... | def compute(self, now, x, y, angle) | Call this when vision processing should be enabled
:param now: The value passed to ``update_sim``
:param x: Returned from physics_controller.get_position
:param y: Returned from physics_controller.get_position
:param angle: Returned from physics_control... | 4.104498 | 3.654727 | 1.123066 |
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
plt.figure()
smooth = SuperSmoother()
smooth.specify_data_set(x, y, sort_data=True)
smooth.compute()
plt.plot(x, y, '.', label='Data')
plt.plot(smooth.x, smooth.smooth_result, 'o', label='Smooth')
plt.grid(color='... | def run_friedman82_super() | Run Friedman's test of fixed-span smoothers from Figure 2b. | 3.663619 | 3.501216 | 1.046385 |
expr_list = [
"max(-_.千幸福的笑脸{घोड़ा=馬, "
"dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 "
"times 3 && "
"(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and "
"count(fizzle) lt 0or count(baz) > 1)".decode('utf8'),
"max(foo{hostname=mini-mon,千=千}, 120) > 100 and (m... | def main() | Used for development and testing. | 6.528985 | 6.476934 | 1.008036 |
result = u"{}({}".format(self.normalized_func,
self._metric_name)
if self._dimensions is not None:
result += "{" + self.dimensions_str + "}"
if self._period != _DEFAULT_PERIOD:
result += ", {}".format(self._period)
resu... | def fmtd_sub_expr_str(self) | Get the entire sub expressions as a string with spaces. | 4.017251 | 3.768928 | 1.065887 |
if self._operator.lower() == "lt" or self._operator == "<":
return u"LT"
elif self._operator.lower() == "gt" or self._operator == ">":
return u"GT"
elif self._operator.lower() == "lte" or self._operator == "<=":
return u"LTE"
elif self._operat... | def normalized_operator(self) | Get the operator as one of LT, GT, LTE, or GTE. | 1.766947 | 1.509717 | 1.170383 |
appliedVoltage = self._nominalVoltage * motor_pct
appliedVoltage = math.copysign(
max(abs(appliedVoltage) - self._vintercept, 0), appliedVoltage
)
# Heun's method (taken from Ether's drivetrain calculator)
# -> yn+1 = yn + (h/2) (f(xn, yn) + f(xn + h, yn + ... | def compute(self, motor_pct: float, tm_diff: float) -> float | :param motor_pct: Percentage of power for motor in range [1..-1]
:param tm_diff: Time elapsed since this function was last called
:returns: velocity | 4.686455 | 4.556017 | 1.02863 |
r
# Check input units
# -> pint doesn't seem to support default args in check()
Helpers.ensure_mass(robot_mass)
Helpers.ensure_length(x_wheelbase)
Helpers.ensure_length(robot_width)
Helpers.ensure_length(robot_length)
Helpers.ensure_length(wheel_diameter)... | def theory(
cls,
motor_config: MotorModelConfig,
robot_mass: units.Quantity,
gearing: float,
nmotors: int = 1,
x_wheelbase: units.Quantity = _kitbot_wheelbase,
robot_width: units.Quantity = _kitbot_width,
robot_length: units.Quantity = _kitbot_length,
... | r"""
Use this to create the drivetrain model when you haven't measured
``kv`` and ``ka`` for your robot.
:param motor_config: Specifications for your motor
:param robot_mass: Mass of the robot
:param gearing: Gear ratio .. so for a... | 3.253978 | 2.983923 | 1.090503 |
# This isn't quite right, the right way is to use matrix math. However,
# this is Good Enough for now...
x = 0
y = 0
angle = 0
# split the time difference into timestep_ms steps
total_time = int(tm_diff * 100000)
steps = total_time // self._time... | def get_distance(
self, l_motor: float, r_motor: float, tm_diff: float
) -> typing.Tuple[float, float] | Given motor values and the amount of time elapsed since this was last
called, retrieves the x,y,angle that the robot has moved. Pass these
values to :meth:`PhysicsInterface.distance_drive`.
To update your encoders, use the ``l_position`` and ``r_position``
at... | 4.613397 | 4.561308 | 1.01142 |
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
# plt.plot(x, y, '.', label='Data')
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
friedman_smooth, _resids = run_friedman_smooth(x, y, span)
... | def validate_basic_smoother() | Run Friedman's test from Figure 2b. | 4.940858 | 4.664754 | 1.059189 |
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
_friedman_smooth, resids = run_friedman_smooth(x, y, span) # pylint: disable=unused-variable
plt.... | def validate_basic_smoother_resid() | Compare residuals. | 5.750437 | 5.614471 | 1.024217 |
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
x, y = sort_data(x, y)
my_smoother = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmootherWithPlots)
# smoother.DEFAULT_BASIC_SMOOTHER = BasicFixedSpanSmootherBreiman
supsmu_result = run_freidman_supsmu(x, y,... | def validate_supersmoother() | Validate the supersmoother. | 5.612864 | 5.640128 | 0.995166 |
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
plt.figure()
plt.plot(x, y, '.', label='Data')
for bass in range(0, 10, 3):
smooth = supersmoother.SuperSmoother()
smooth.set_bass_enhancement(bass)
smooth.specify_data_set(x, y)
smooth.compute()
... | def validate_supersmoother_bass() | Validate the supersmoother with extra bass. | 4.212188 | 4.096812 | 1.028162 |
N = 200
num_trials = 400
avg = numpy.zeros(N)
for i in range(num_trials):
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82(N=N)
my_smoother = smoother.perform_smooth(
x, y, smoother_cls=supersmoother.SuperSmoother
)
avg += my_smoother._... | def validate_average_best_span() | Figure 2d? from Friedman. | 5.610224 | 5.241282 | 1.070392 |
plt.figure()
N = 100
x = numpy.linspace(-1, 1, N)
y = numpy.sin(4 * x)
smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmootherSlowUpdate
smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)
plt.plot(x, smooth.smooth_result, label='Slow')
smoothe... | def validate_known_curve() | Validate on a sin function. | 2.994466 | 2.810602 | 1.065418 |
plt.legend()
plt.grid(color='0.7')
plt.xlabel('x')
plt.ylabel('y')
plt.show() | def finish_plot() | Helper for plotting. | 3.167063 | 3.187506 | 0.993587 |
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.supsmu(x, y, weight, 1, 0.0, bass_enhancement, results, flags)
return results | def run_freidman_supsmu(x, y, bass_enhancement=0.0) | Run the FORTRAN supersmoother. | 4.291965 | 4.056644 | 1.058009 |
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
residuals = numpy.zeros(N)
mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals)
return results, residuals | def run_friedman_smooth(x, y, span) | Run the FORTRAN smoother. | 4.096658 | 4.010959 | 1.021366 |
def run_mace_smothr(x, y, bass_enhancement=0.0): # pylint: disable=unused-argument
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.smothr(1, x, y, weight, results, flags)
return results | Run the FORTRAN SMOTHR. | null | null | null | |
xy = sorted(zip(x, y))
x, y = zip(*xy)
return x, y | def sort_data(x, y) | Sort the data. | 2.833672 | 2.868455 | 0.987874 |
self.smooth_result, self.cross_validated_residual = run_friedman_smooth(
self.x, self.y, self._span
) | def compute(self) | Run smoother. | 16.464989 | 11.640295 | 1.414482 |
self.smooth_result = run_freidman_supsmu(self.x, self.y)
self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result))) | def compute(self) | Run SuperSmoother. | 13.259179 | 10.596355 | 1.251296 |
host_key = (host, port)
if host_key not in self.conns:
self.conns[host_key] = KafkaConnection(
host,
port,
timeout=self.timeout
)
return self.conns[host_key] | def _get_conn(self, host, port) | Get or create a connection to a broker using host and port | 2.683891 | 2.516182 | 1.066652 |
resp = self.send_consumer_metadata_request(group)
# If there's a problem with finding the coordinator, raise the
# provided error
kafka_common.check_error(resp)
# Otherwise return the BrokerMetadata
return BrokerMetadata(resp.nodeId, resp.host, resp.port) | def _get_coordinator_for_group(self, group) | Returns the coordinator broker for a consumer group.
ConsumerCoordinatorNotAvailableCode will be raised if the coordinator
does not currently exist for the group.
OffsetsLoadInProgressCode is raised if the coordinator is available
but is still loading offsets from the internal topic | 9.99631 | 7.455415 | 1.340812 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.