INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get supported languages ( by querying the server ).
def _get_languages(cls) -> set: """Get supported languages (by querying the server).""" if not cls._server_is_alive(): cls._start_server_on_free_port() url = urllib.parse.urljoin(cls._url, 'Languages') languages = set() for e in cls._get_root(url, num_tries=1): ...
Get matches element attributes.
def _get_attrib(cls): """Get matches element attributes.""" if not cls._server_is_alive(): cls._start_server_on_free_port() params = {'language': FAILSAFE_LANGUAGE, 'text': ''} data = urllib.parse.urlencode(params).encode() root = cls._get_root(cls._url, data, num_tri...
Patched method for PageAdmin. get_form.
def get_form(self, request, obj=None, **kwargs): """ Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the pag...
Create the cache key for the current page and language
def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = page.node.site_id except AttributeError: # CMS_3_4 site_id = page.site_id return _get_cache_key('page_meta', page, language, ...
Retrieves all the meta information for the page in the given language
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from ....
Initialize communication with the MPR121.
def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults...
Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 ( inclusive ).
def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). """ assert touch >= 0 and touch <= 255, 'touch must be between 0-255 (inclusive)' ...
Return filtered data register value for the provided pin ( 0 - 11 ). Useful for debugging.
def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2)
Return baseline data register value for the provided pin ( 0 - 11 ). Useful for debugging.
def baseline_data(self, pin): """Return baseline data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' bl = self._i2c_retry(self._device.readU8, MPR121_BASELINE_0 + pin) return bl <<...
Return touch state of all pins as a 12 - bit value where each bit represents a pin with a value of 1 being touched and 0 not being touched.
def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. """ t = self._i2c_retry(self._device.readU16LE, MPR121_TOUCHSTATUS_L) return t & 0x0FFF
Return True if the specified pin is being touched otherwise returns False.
def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
Decorator straight up stolen from stackoverflow
def profileit(func): """ Decorator straight up stolen from stackoverflow """ def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile" # Name the data file sensibly prof = cProfile.Profile() prof.enable() retval = prof.runcall(func, *args, **kwargs) prof.d...
Filter: class:. Line objects by IP range.
def filter_ip_range(ip_range): """Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: ...
Filter: class:. Line objects by their response time.
def filter_slow_requests(slowness): """Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that...
Filter: class:. Line objects by their queueing time in HAProxy.
def filter_wait_on_queues(max_waiting): """Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted....
Filter: class:. Line objects by their connection time.
def filter_time_frame(start, delta): """Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument o...
Filter: class:. Line objects by the response size ( in bytes ).
def filter_response_size(size): """Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rty...
Gets all of the fields on the model.
def _get_fields_for_model(model): """ Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple """ fields = [] for name in model._sa_class_manag...
Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships.
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships o...
Creates a ResourceBase subclass by inspecting a SQLAlchemy Model. This is somewhat more restrictive than explicitly creating managers and resources. However if you only need any of the basic CRUD + L operations
def create_resource(model, session_handler, resource_bases=(CRUDL,), relationships=None, links=None, preprocessors=None, postprocessors=None, fields=None, paginate_by=100, auto_relationships=True, pks=None, create_fields=None, update_fields...
Logic to decide if the file should be processed or just needs to be loaded from its pickle data.
def _is_pickle_valid(self): """Logic to decide if the file should be processed or just needs to be loaded from its pickle data. """ if not os.path.exists(self._pickle_file): return False else: file_mtime = os.path.getmtime(self.logfile) pickle_...
Load data from a pickle file.
def _load(self): """Load data from a pickle file. """ with open(self._pickle_file, 'rb') as source: pickler = pickle.Unpickler(source) for attribute in self._pickle_attributes: pickle_data = pickler.load() setattr(self, attribute, pickle_data)
Save the attributes defined on _pickle_attributes in a pickle file.
def _save(self): """Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time. """ with open(self._pickle_file, 'wb') as source: pickler = pickle.Pickler(source, pickle...
Parse data from data stream and replace object lines.
def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ for line in logfile: stripped_line = line.strip() parsed_line = Line(stripped_line) ...
Filter current log lines by a given filter function.
def filter(self, filter_func, reverse=False): """Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further p...
Returns a list of all methods that start with cmd_.
def commands(cls): """Returns a list of all methods that start with ``cmd_``.""" cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')] return cmds
Reports a breakdown of how many requests have been made per HTTP method ( GET POST... ).
def cmd_http_methods(self): """Reports a breakdown of how many requests have been made per HTTP method (GET, POST...). """ methods = defaultdict(int) for line in self._valid_lines: methods[line.http_request_method] += 1 return methods
Reports a breakdown of how many requests have been made per IP.
def cmd_ip_counter(self): """Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured. """ ip_...
Generate statistics about HTTP status codes. 404 500 and so on.
def cmd_status_codes_counter(self): """Generate statistics about HTTP status codes. 404, 500 and so on. """ status_codes = defaultdict(int) for line in self._valid_lines: status_codes[line.status_code] += 1 return status_codes
Generate statistics about HTTP requests path.
def cmd_request_path_counter(self): """Generate statistics about HTTP requests' path.""" paths = defaultdict(int) for line in self._valid_lines: paths[line.http_request_path] += 1 return paths
List all requests that took a certain amount of time to be processed.
def cmd_slow_requests(self): """List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally. ...
Returns the average response time of all non aborted requests.
def cmd_average_response_time(self): """Returns the average response time of all, non aborted, requests.""" average = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response >= 0 ] divisor = float(len(average)) if di...
Returns the average queue time of all non aborted requests.
def cmd_average_waiting_time(self): """Returns the average queue time of all, non aborted, requests.""" average = [ line.time_wait_queues for line in self._valid_lines if line.time_wait_queues >= 0 ] divisor = float(len(average)) if divisor > ...
Generate statistics regarding how many requests were processed by each downstream server.
def cmd_server_load(self): """Generate statistics regarding how many requests were processed by each downstream server. """ servers = defaultdict(int) for line in self._valid_lines: servers[line.server_name] += 1 return servers
Generate a list of the requests peaks on the queue.
def cmd_queue_peaks(self): """Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which pe...
Generates statistics on how many requests are made via HTTP and how many are made via SSL.
def cmd_connection_type(self): """Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they s...
Generates statistics on how many requests were made per minute.
def cmd_requests_per_minute(self): """Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise. """ if len(self._valid_lines) == 0: re...
Returns the raw lines to be printed.
def cmd_print(self): """Returns the raw lines to be printed.""" if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow thus even if one connection is logged later it could have been accepted before others that are already processed and logged.
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are...
Sorts a dictionary with at least two fields on each of them sorting by the second element.
def _sort_and_trim(data, reverse=False): """Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or global...
Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run.
def db_access_point(func): """ Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database. """ @wraps(func) def wrapper(self, *args,...
Gets the python type for the attribute on the model with the name provided.
def _get_field_python_type(model, name): """ Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. ...
Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be.
def get_field_type(cls, name): """ Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that...
Creates a new instance of the self. model and persists it to the database.
def create(self, session, values, *args, **kwargs): """ Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to...
Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail.
def retrieve(self, session, lookup_keys, *args, **kwargs): """ Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_k...
Retrieves a list of the model for this manager. It is restricted by the filters provided.
def retrieve_list(self, session, filters, *args, **kwargs): """ Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned m...
Updates the model with the specified lookup_keys and returns the dictified object.
def update(self, session, lookup_keys, updates, *args, **kwargs): """ Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and...
Deletes the model found using the lookup_keys
def delete(self, session, lookup_keys, *args, **kwargs): """ Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dicti...
Takes a model and serializes the fields provided into a dictionary.
def serialize_model(self, model, field_dict=None): """ Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized m...
A recursive function for serializing a model into a json ready format.
def _serialize_model_helper(self, model, field_dict=None): """ A recursive function for serializing a model into a json ready format. """ field_dict = field_dict or self.dot_field_list_to_dict() if model is None: return None if isinstance(model, Query...
Gets the sqlalchemy Model instance associated with the lookup keys.
def _get_model(self, lookup_keys, session): """ Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqla...
Updates the values with the specified values.
def _set_values_on_model(self, model, values, fields=None): """ Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strin...
Prints all commands available from Log with their description.
def print_commands(): """Prints all commands available from Log with their description. """ dummy_log_file = Log() commands = Log.commands() commands.sort() for cmd in commands: cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd)) description = cmd.__doc__ if descrip...
Prints all filters available with their description.
def print_filters(): """Prints all filters available with their description.""" for filter_name in VALID_FILTERS: filter_func = getattr(filters, 'filter_{0}'.format(filter_name)) description = filter_func.__doc__ if description: description = re.sub(r'\n\s+', ' ', description...
Adds weak ref to an observer.
def add_observer(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class """ if not isinstance(observer, Powe...
Removes all registered observers.
def remove_all_observers(self): """ Removes all registered observers. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: self.remove_observer(observer)
Spawns new NSThread to handle notifications.
def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None) self._thread.start()
Stops spawned NSThread.
def stopThread(self): """Stops spawned NSThread.""" if self._thread is not None: self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES) self._thread = None
Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.
def runPowerNotificationsThread(self): """Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" pool = NSAutoreleasePool.alloc().init() @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_source_notification(context): w...
Removes the only source from NSRunLoop and cancels thread.
def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThread.currentThread().cancel()
Adds weak ref to an observer.
def addObserver(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() """ with self._lock: self._weak_observers.append(weakref.ref(observer)) if len(self._weak_observers) == 1:...
Removes an observer.
def removeObserver(self, observer): """ Removes an observer. @param observer: Previously added observer """ with self._lock: self._weak_observers.remove(weakref.ref(observer)) if len(self._weak_observers) == 0: self.stopThread()
Called in response to IOPSNotificationCreateRunLoopSource () event.
def on_power_source_notification(self): """ Called in response to IOPSNotificationCreateRunLoopSource() event. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_sources_change(self) ...
In Mac OS X 10. 7 + Uses IOPSGetTimeRemainingEstimate to get time remaining estimate.
def get_time_remaining_estimate(self): """ In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. ...
Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop
def add_observer(self, observer): """ Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ super(PowerManagement, self).add_observer(observer) if len(self._weak_observers) == 1: if not self._cf_run_loop:...
Stops thread and invalidates source.
def remove_observer(self, observer): """ Stops thread and invalidates source. """ super(PowerManagement, self).remove_observer(observer) if len(self._weak_observers) == 0: if not self._cf_run_loop: PowerManagement.notifications_observer.removeObserver(...
Returns GetSystemPowerStatus (). ACLineStatus
def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() ...
Returns warning according to GetSystemPowerStatus (). BatteryLifeTime/ BatteryLifePercent
def get_low_battery_warning_level(self): """ Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_sta...
Returns time remaining estimate according to GetSystemPowerStatus (). BatteryLifeTime
def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[powe...
FreeBSD use sysctl hw. acpi. acline to tell if Mains ( 1 ) is used or Battery ( 0 ). Beware that on a Desktop machines this hw. acpi. acline oid may not exist.
def power_source_type(): """ FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported...
TODO
def get_battery_state(): """ TODO @return: Tuple (energy_full, energy_now, power_now) """ energy_now = float(100.0) power_now = float(100.0) energy_full = float(100.0) return energy_full, energy_now, power_now
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary whatever found first is returned.
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found fi...
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries.
def get_low_battery_warning_level(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """...
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online.
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_power_now = [] try: type = self.power_source_type...
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary whatever found first is returned.
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found fi...
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online.
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_energy_not_discharging = [] all_power_now = [] for su...
Packages msg according to Scratch message specification ( encodes and appends length prefix to msg ). Credit to chalkmarrow from the scratch. mit. edu forums for the prefix encoding code.
def _pack(self, msg): """ Packages msg according to Scratch message specification (encodes and appends length prefix to msg). Credit to chalkmarrow from the scratch.mit.edu forums for the prefix encoding code. """ n = len(msg) a = array.array('c') a.app...
Converts a string from Scratch to its proper type in Python. Expects a string with its delimiting quotes in place. Returns either a string int or float.
def _get_type(self, s): """ Converts a string from Scratch to its proper type in Python. Expects a string with its delimiting quotes in place. Returns either a string, int or float. """ # TODO: what if the number is bigger than an int or float? if s.startswith('...
Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string.
def _escape(self, msg): """ Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string. """ escaped = '' for c in msg: escaped += c if c ...
Removes double quotes that were used to escape double quotes. Expects a string without its delimiting quotes or a number. Returns a new unescaped string.
def _unescape(self, msg): """ Removes double quotes that were used to escape double quotes. Expects a string without its delimiting quotes, or a number. Returns a new unescaped string. """ if isinstance(msg, (int, float, long)): return msg unescaped =...
Returns True if message is a proper Scratch message else return False.
def _is_msg(self, msg): """ Returns True if message is a proper Scratch message, else return False. """ if not msg or len(msg) < self.prefix_len: return False length = self._extract_len(msg[:self.prefix_len]) msg_type = msg[self.prefix_len:].split(' ', 1)[0] ...
Given a broacast message returns the message that was broadcast.
def _parse_broadcast(self, msg): """ Given a broacast message, returns the message that was broadcast. """ # get message, remove surrounding quotes, and unescape return self._unescape(self._get_type(msg[self.broadcast_prefix_len:]))
Given a sensor - update message returns the sensors/ variables that were updated as a dict that maps sensors/ variables to their updated values.
def _parse_sensorupdate(self, msg): """ Given a sensor-update message, returns the sensors/variables that were updated as a dict that maps sensors/variables to their updated values. """ update = msg[self.sensorupdate_prefix_len:] parsed = [] # each element is either a sen...
Parses a Scratch message and returns a tuple with the first element as the message type and the second element as the message payload. The payload for a broadcast message is a string and the payload for a sensor - update message is a dict whose keys are variables and values are updated variable values. Returns None if ...
def _parse(self, msg): """ Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' message is a dict whose ke...
Writes string data out to Scratch
def _write(self, data): """ Writes string data out to Scratch """ total_sent = 0 length = len(data) while total_sent < length: try: sent = self.socket.send(data[total_sent:]) except socket.error as (err, msg): self.c...
Reads size number of bytes from Scratch and returns data as a string
def _read(self, size): """ Reads size number of bytes from Scratch and returns data as a string """ data = '' while len(data) < size: try: chunk = self.socket.recv(size-len(data)) except socket.error as (err, msg): self.conn...
Receives and returns a message from Scratch
def _recv(self): """ Receives and returns a message from Scratch """ prefix = self._read(self.prefix_len) msg = self._read(self._extract_len(prefix)) return prefix + msg
Connects to Scratch.
def connect(self): """ Connects to Scratch. """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self.host, self.port)) except socket.error as (err, msg): self.connected = False raise ScratchErro...
Closes connection to Scratch
def disconnect(self): """ Closes connection to Scratch """ try: # connection may already be disconnected, so catch exceptions self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect except socket.error: pass self.socket.close() self.co...
Given a dict of sensors and values updates those sensors with the values in Scratch.
def sensorupdate(self, data): """ Given a dict of sensors and values, updates those sensors with the values in Scratch. """ if not isinstance(data, dict): raise TypeError('Expected a dict') msg = 'sensor-update ' for key in data.keys(): ms...
Broadcasts msg to Scratch. msg can be a single message or an iterable ( list tuple set generator etc. ) of messages.
def broadcast(self, msg): """ Broadcasts msg to Scratch. msg can be a single message or an iterable (list, tuple, set, generator, etc.) of messages. """ if getattr(msg, '__iter__', False): # iterable for m in msg: self._send('broadcast "%s"' % self._e...
Tests a simple topology. Simple means there it has no branches or cycles. emitters is a list of emitters starting with a spout followed by 0 or more bolts that run in a chain.
def run_simple_topology(cls, config, emitters, result_type=NAMEDTUPLE, max_spout_emits=None): """Tests a simple topology. "Simple" means there it has no branches or cycles. "emitters" is a list of emitters, starting with a spout followed by 0 or more bolts that run in a chain.""" ...
Writes the topology to a stream or file.
def write(self, stream): """Writes the topology to a stream or file.""" topology = self.createTopology() def write_it(stream): transportOut = TMemoryBuffer() protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut) topology.write(protocolOut) by...
Reads the topology from a stream or file.
def read(self, stream): """Reads the topology from a stream or file.""" def read_it(stream): bytes = stream.read() transportIn = TMemoryBuffer(bytes) protocolIn = TBinaryProtocol.TBinaryProtocol(transportIn) topology = StormTopology() topology....
Build a StormTopology. jar which encapsulates the topology defined in topology_dir. Optionally override the module and function names. This feature supports the definition of multiple topologies in a single directory.
def build_jar(source_jar_path, dest_jar_path, config, venv=None, definition=None, logdir=None): """Build a StormTopology .jar which encapsulates the topology defined in topology_dir. Optionally override the module and function names. This feature supports the definition of multiple topologies in a single ...
This function is kind of a hack but useful when a Python task encounters a fatal exception. msg should be a simple string like E_SPOUTFAILED. This function sends msg as - is to the Storm worker which tries to parse it as JSON. The hacky aspect is that we * deliberately * make it fail by sending it non - JSON data. This...
def sendFailureMsgToParent(msg): """This function is kind of a hack, but useful when a Python task encounters a fatal exception. "msg" should be a simple string like "E_SPOUTFAILED". This function sends "msg" as-is to the Storm worker, which tries to parse it as JSON. The hacky aspect is that we *de...
A more efficient way to emit a number of tuples at once.
def emitMany(*args, **kwargs): """A more efficient way to emit a number of tuples at once.""" global MODE if MODE == Bolt: emitManyBolt(*args, **kwargs) elif MODE == Spout: emitManySpout(*args, **kwargs)
Handler to allow process to be remotely debugged.
def remote_debug(sig,frame): """Handler to allow process to be remotely debugged.""" def _raiseEx(ex): """Raise specified exception in the remote process""" _raiseEx.ex = ex _raiseEx.ex = None try: # Provide some useful functions. locs = {'_raiseEx' : _raiseEx} ...
Interrupt a running process and debug it.
def debug_process(pid): """Interrupt a running process and debug it.""" os.kill(pid, signal.SIGUSR1) # Signal process. pipe = NamedPipe(pipename(pid), 1) try: while pipe.is_open(): txt=raw_input(pipe.get()) + '\n' pipe.put(txt) except EOFError: pass # Exit. ...
UTF8 encodes all of the NVP values.
def _encode_utf8(self, **kwargs): """ UTF8 encodes all of the NVP values. """ if is_py3: # This is only valid for Python 2. In Python 3, unicode is # everywhere (yay). return kwargs unencoded_pairs = kwargs for i in unencoded_pairs.key...