text:
'''
MAVLink protocol implementation (auto-generated by mavgen.py)

Generated from: minimal.xml

Note: this file has been auto-generated. DO NOT EDIT
'''

import struct, array, time, json, os, sys, platform

from ...generator.mavcrc import x25crc

WIRE_PROTOCOL_VERSION = "1.0"
DIALECT = "minimal"

native_supported = platform.system() != 'Windows' # Not yet supported on other dialects
native_force = 'MAVNATIVE_FORCE' in os.environ # Will force use of native code regardless of what client app wants
native_testing = 'MAVNATIVE_TESTING' in os.environ # Will force both native and legacy code to be used and their results compared

if native_supported:
    try:
        import mavnative
    except ImportError:
        print("ERROR LOADING MAVNATIVE - falling back to python implementation")
        native_supported = False

# some base types from mavlink_types.h
MAVLINK_TYPE_CHAR     = 0
MAVLINK_TYPE_UINT8_T  = 1
MAVLINK_TYPE_INT8_T   = 2
MAVLINK_TYPE_UINT16_T = 3
MAVLINK_TYPE_INT16_T  = 4
MAVLINK_TYPE_UINT32_T = 5
MAVLINK_TYPE_INT32_T  = 6
MAVLINK_TYPE_UINT64_T = 7
MAVLINK_TYPE_INT64_T  = 8
MAVLINK_TYPE_FLOAT    = 9
MAVLINK_TYPE_DOUBLE   = 10

class MAVLink_header(object):
    '''MAVLink message header'''
    def __init__(self, msgId, mlen=0, seq=0, srcSystem=0, srcComponent=0):
        self.mlen = mlen
        self.seq = seq
        self.srcSystem = srcSystem
        self.srcComponent = srcComponent
        self.msgId = msgId

    def pack(self):
        return struct.pack('BBBBBB', 254, self.mlen, self.seq,
                          self.srcSystem, self.srcComponent, self.msgId)

class MAVLink_message(object):
    '''base MAVLink message class'''
    def __init__(self, msgId, name):
        self._header     = MAVLink_header(msgId)
        self._payload    = None
        self._msgbuf     = None
        self._crc        = None
        self._fieldnames = []
        self._type       = name

    def get_msgbuf(self):
        if isinstance(self._msgbuf, bytearray):
            return self._msgbuf
        return bytearray(self._msgbuf)

    def get_header(self):
        return self._header

    def get_payload(self):
        return self._payload

    def get_crc(self):
        return self._crc

    def get_fieldnames(self):
        return self._fieldnames

    def get_type(self):
        return self._type

    def get_msgId(self):
        return self._header.msgId

    def get_srcSystem(self):
        return self._header.srcSystem

    def get_srcComponent(self):
        return self._header.srcComponent

    def get_seq(self):
        return self._header.seq

    def __str__(self):
        ret = '%s {' % self._type
        for a in self._fieldnames:
            v = getattr(self, a)
            ret += '%s : %s, ' % (a, v)
        ret = ret[0:-2] + '}'
        return ret

    def __ne__(self, other):
        return not self.__eq__(other)

    def __eq__(self, other):
        if other == None:
            return False

        if self.get_type() != other.get_type():
            return False

        # We do not compare CRC because native code doesn't provide it
        #if self.get_crc() != other.get_crc():
        #    return False

        if self.get_seq() != other.get_seq():
            return False

        if self.get_srcSystem() != other.get_srcSystem():
            return False

        if self.get_srcComponent() != other.get_srcComponent():
            return False

        for a in self._fieldnames:
            if getattr(self, a) != getattr(other, a):
                return False

        return True

    def to_dict(self):
        d = dict({})
        d['mavpackettype'] = self._type
        for a in self._fieldnames:
          d[a] = getattr(self, a)
        return d

    def to_json(self):
        return json.dumps(self.to_dict())

    def pack(self, mav, crc_extra, payload):
        self._payload = payload
        self._header  = MAVLink_header(self._header.msgId, len(payload), mav.seq,
                                       mav.srcSystem, mav.srcComponent)
        self._msgbuf = self._header.pack() + payload
        crc = x25crc(self._msgbuf[1:])
        if True: # using CRC extra
            crc.accumulate_str(chr(crc_extra))
        self._crc = crc.crc
        self._msgbuf += struct.pack('<H', self._crc)
        return self._msgbuf

# enums

class EnumEntry(object):
    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.param = {}

enums = {}

# MAV_AUTOPILOT
enums['MAV_AUTOPILOT'] = {}
MAV_AUTOPILOT_GENERIC = 0 # Generic autopilot, full support for everything
enums['MAV_AUTOPILOT'][0] = EnumEntry('MAV_AUTOPILOT_GENERIC', '''Generic autopilot, full support for everything''')
MAV_AUTOPILOT_PIXHAWK = 1 # PIXHAWK autopilot, http://pixhawk.ethz.ch
enums['MAV_AUTOPILOT'][1] = EnumEntry('MAV_AUTOPILOT_PIXHAWK', '''PIXHAWK autopilot, http://pixhawk.ethz.ch''')
MAV_AUTOPILOT_SLUGS = 2 # SLUGS autopilot, http://slugsuav.soe.ucsc.edu
enums['MAV_AUTOPILOT'][2] = EnumEntry('MAV_AUTOPILOT_SLUGS', '''SLUGS autopilot, http://slugsuav.soe.ucsc.edu''')
MAV_AUTOPILOT_ARDUPILOTMEGA = 3 # ArduPilotMega / ArduCopter, http://diydrones.com
enums['MAV_AUTOPILOT'][3] = EnumEntry('MAV_AUTOPILOT_ARDUPILOTMEGA', '''ArduPilotMega / ArduCopter, http://diydrones.com''')
MAV_AUTOPILOT_OPENPILOT = 4 # OpenPilot, http://openpilot.org
enums['MAV_AUTOPILOT'][4] = EnumEntry('MAV_AUTOPILOT_OPENPILOT', '''OpenPilot, http://openpilot.org''')
MAV_AUTOPILOT_GENERIC_WAYPOINTS_ONLY = 5 # Generic autopilot only supporting simple waypoints
enums['MAV_AUTOPILOT'][5] = EnumEntry('MAV_AUTOPILOT_GENERIC_WAYPOINTS_ONLY', '''Generic autopilot only supporting simple waypoints''')
MAV_AUTOPILOT_GENERIC_WAYPOINTS_AND_SIMPLE_NAVIGATION_ONLY = 6 # Generic autopilot supporting waypoints and other simple navigation
                        # commands
enums['MAV_AUTOPILOT'][6] = EnumEntry('MAV_AUTOPILOT_GENERIC_WAYPOINTS_AND_SIMPLE_NAVIGATION_ONLY', '''Generic autopilot supporting waypoints and other simple navigation commands''')
MAV_AUTOPILOT_GENERIC_MISSION_FULL = 7 # Generic autopilot supporting the full mission command set
enums['MAV_AUTOPILOT'][7] = EnumEntry('MAV_AUTOPILOT_GENERIC_MISSION_FULL', '''Generic autopilot supporting the full mission command set''')
MAV_AUTOPILOT_INVALID = 8 # No valid autopilot, e.g. a GCS or other MAVLink component
enums['MAV_AUTOPILOT'][8] = EnumEntry('MAV_AUTOPILOT_INVALID', '''No valid autopilot, e.g. a GCS or other MAVLink component''')
MAV_AUTOPILOT_PPZ = 9 # PPZ UAV - http://nongnu.org/paparazzi
enums['MAV_AUTOPILOT'][9] = EnumEntry('MAV_AUTOPILOT_PPZ', '''PPZ UAV - http://nongnu.org/paparazzi''')
MAV_AUTOPILOT_UDB = 10 # UAV Dev Board
enums['MAV_AUTOPILOT'][10] = EnumEntry('MAV_AUTOPILOT_UDB', '''UAV Dev Board''')
MAV_AUTOPILOT_FP = 11 # FlexiPilot
enums['MAV_AUTOPILOT'][11] = EnumEntry('MAV_AUTOPILOT_FP', '''FlexiPilot''')
MAV_AUTOPILOT_ENUM_END = 12 #
enums['MAV_AUTOPILOT'][12] = EnumEntry('MAV_AUTOPILOT_ENUM_END', '''''')

# MAV_TYPE
enums['MAV_TYPE'] = {}
MAV_TYPE_GENERIC = 0 # Generic micro air vehicle.
enums['MAV_TYPE'][0] = EnumEntry('MAV_TYPE_GENERIC', '''Generic micro air vehicle.''')
MAV_TYPE_FIXED_WING = 1 # Fixed wing aircraft.
enums['MAV_TYPE'][1] = EnumEntry('MAV_TYPE_FIXED_WING', '''Fixed wing aircraft.''')
MAV_TYPE_QUADROTOR = 2 # Quadrotor
enums['MAV_TYPE'][2] = EnumEntry('MAV_TYPE_QUADROTOR', '''Quadrotor''')
MAV_TYPE_COAXIAL = 3 # Coaxial helicopter
enums['MAV_TYPE'][3] = EnumEntry('MAV_TYPE_COAXIAL', '''Coaxial helicopter''')
MAV_TYPE_HELICOPTER = 4 # Normal helicopter with tail rotor.
enums['MAV_TYPE'][4] = EnumEntry('MAV_TYPE_HELICOPTER', '''Normal helicopter with tail rotor.''')
MAV_TYPE_ANTENNA_TRACKER = 5 # Ground installation
enums['MAV_TYPE'][5] = EnumEntry('MAV_TYPE_ANTENNA_TRACKER', '''Ground installation''')
MAV_TYPE_GCS = 6 # Operator control unit / ground control station
enums['MAV_TYPE'][6] = EnumEntry('MAV_TYPE_GCS', '''Operator control unit / ground control station''')
MAV_TYPE_AIRSHIP = 7 # Airship, controlled
enums['MAV_TYPE'][7] = EnumEntry('MAV_TYPE_AIRSHIP', '''Airship, controlled''')
MAV_TYPE_FREE_BALLOON = 8 # Free balloon, uncontrolled
enums['MAV_TYPE'][8] = EnumEntry('MAV_TYPE_FREE_BALLOON', '''Free balloon, uncontrolled''')
MAV_TYPE_ROCKET = 9 # Rocket
enums['MAV_TYPE'][9] = EnumEntry('MAV_TYPE_ROCKET', '''Rocket''')
MAV_TYPE_GROUND_ROVER = 10 # Ground rover
enums['MAV_TYPE'][10] = EnumEntry('MAV_TYPE_GROUND_ROVER', '''Ground rover''')
MAV_TYPE_SURFACE_BOAT = 11 # Surface vessel, boat, ship
enums['MAV_TYPE'][11] = EnumEntry('MAV_TYPE_SURFACE_BOAT', '''Surface vessel, boat, ship''')
MAV_TYPE_SUBMARINE = 12 # Submarine
enums['MAV_TYPE'][12] = EnumEntry('MAV_TYPE_SUBMARINE', '''Submarine''')
MAV_TYPE_HEXAROTOR = 13 # Hexarotor
enums['MAV_TYPE'][13] = EnumEntry('MAV_TYPE_HEXAROTOR', '''Hexarotor''')
MAV_TYPE_OCTOROTOR = 14 # Octorotor
enums['MAV_TYPE'][14] = EnumEntry('MAV_TYPE_OCTOROTOR', '''Octorotor''')
MAV_TYPE_TRICOPTER = 15 # Octorotor
enums['MAV_TYPE'][15] = EnumEntry('MAV_TYPE_TRICOPTER', '''Octorotor''')
MAV_TYPE_FLAPPING_WING = 16 # Flapping wing
enums['MAV_TYPE'][16] = EnumEntry('MAV_TYPE_FLAPPING_WING', '''Flapping wing''')
MAV_TYPE_ENUM_END = 17 #
enums['MAV_TYPE'][17] = EnumEntry('MAV_TYPE_ENUM_END', '''''')

# MAV_MODE_FLAG
enums['MAV_MODE_FLAG'] = {}
MAV_MODE_FLAG_CUSTOM_MODE_ENABLED = 1 # 0b00000001 Reserved for future use.
enums['MAV_MODE_FLAG'][1] = EnumEntry('MAV_MODE_FLAG_CUSTOM_MODE_ENABLED', '''0b00000001 Reserved for future use.''')
MAV_MODE_FLAG_TEST_ENABLED = 2 # 0b00000010 system has a test mode enabled. This flag is intended for
                        # temporary system tests and should not be
                        # used for stable implementations.
enums['MAV_MODE_FLAG'][2] = EnumEntry('MAV_MODE_FLAG_TEST_ENABLED', '''0b00000010 system has a test mode enabled. This flag is intended for temporary system tests and should not be used for stable implementations.''')
MAV_MODE_FLAG_AUTO_ENABLED = 4 # 0b00000100 autonomous mode enabled, system finds its own goal
                        # positions. Guided flag can be set or not,
                        # depends on the actual implementation.
enums['MAV_MODE_FLAG'][4] = EnumEntry('MAV_MODE_FLAG_AUTO_ENABLED', '''0b00000100 autonomous mode enabled, system finds its own goal positions. Guided flag can be set or not, depends on the actual implementation.''')
MAV_MODE_FLAG_GUIDED_ENABLED = 8 # 0b00001000 guided mode enabled, system flies MISSIONs / mission items.
enums['MAV_MODE_FLAG'][8] = EnumEntry('MAV_MODE_FLAG_GUIDED_ENABLED', '''0b00001000 guided mode enabled, system flies MISSIONs / mission items.''')
MAV_MODE_FLAG_STABILIZE_ENABLED = 16 # 0b00010000 system stabilizes electronically its attitude (and
                        # optionally position). It needs however
                        # further control inputs to move around.
enums['MAV_MODE_FLAG'][16] = EnumEntry('MAV_MODE_FLAG_STABILIZE_ENABLED', '''0b00010000 system stabilizes electronically its attitude (and optionally position). It needs however further control inputs to move around.''')
MAV_MODE_FLAG_HIL_ENABLED = 32 # 0b00100000 hardware in the loop simulation. All motors / actuators are
                        # blocked, but internal software is full
                        # operational.
enums['MAV_MODE_FLAG'][32] = EnumEntry('MAV_MODE_FLAG_HIL_ENABLED', '''0b00100000 hardware in the loop simulation. All motors / actuators are blocked, but internal software is full operational.''')
MAV_MODE_FLAG_MANUAL_INPUT_ENABLED = 64 # 0b01000000 remote control input is enabled.
enums['MAV_MODE_FLAG'][64] = EnumEntry('MAV_MODE_FLAG_MANUAL_INPUT_ENABLED', '''0b01000000 remote control input is enabled.''')
MAV_MODE_FLAG_SAFETY_ARMED = 128 # 0b10000000 MAV safety set to armed. Motors are enabled / running / can
                        # start. Ready to fly.
enums['MAV_MODE_FLAG'][128] = EnumEntry('MAV_MODE_FLAG_SAFETY_ARMED', '''0b10000000 MAV safety set to armed. Motors are enabled / running / can start. Ready to fly.''')
MAV_MODE_FLAG_ENUM_END = 129 #
enums['MAV_MODE_FLAG'][129] = EnumEntry('MAV_MODE_FLAG_ENUM_END', '''''')

# MAV_MODE_FLAG_DECODE_POSITION
enums['MAV_MODE_FLAG_DECODE_POSITION'] = {}
MAV_MODE_FLAG_DECODE_POSITION_CUSTOM_MODE = 1 # Eighth bit: 00000001
enums['MAV_MODE_FLAG_DECODE_POSITION'][1] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_CUSTOM_MODE', '''Eighth bit: 00000001''')
MAV_MODE_FLAG_DECODE_POSITION_TEST = 2 # Seventh bit: 00000010
enums['MAV_MODE_FLAG_DECODE_POSITION'][2] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_TEST', '''Seventh bit: 00000010''')
MAV_MODE_FLAG_DECODE_POSITION_AUTO = 4 # Sixt bit:   00000100
enums['MAV_MODE_FLAG_DECODE_POSITION'][4] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_AUTO', '''Sixt bit:   00000100''')
MAV_MODE_FLAG_DECODE_POSITION_GUIDED = 8 # Fifth bit:  00001000
enums['MAV_MODE_FLAG_DECODE_POSITION'][8] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_GUIDED', '''Fifth bit:  00001000''')
MAV_MODE_FLAG_DECODE_POSITION_STABILIZE = 16 # Fourth bit: 00010000
enums['MAV_MODE_FLAG_DECODE_POSITION'][16] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_STABILIZE', '''Fourth bit: 00010000''')
MAV_MODE_FLAG_DECODE_POSITION_HIL = 32 # Third bit:  00100000
enums['MAV_MODE_FLAG_DECODE_POSITION'][32] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_HIL', '''Third bit:  00100000''')
MAV_MODE_FLAG_DECODE_POSITION_MANUAL = 64 # Second bit: 01000000
enums['MAV_MODE_FLAG_DECODE_POSITION'][64] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_MANUAL', '''Second bit: 01000000''')
MAV_MODE_FLAG_DECODE_POSITION_SAFETY = 128 # First bit:  10000000
enums['MAV_MODE_FLAG_DECODE_POSITION'][128] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_SAFETY', '''First bit:  10000000''')
MAV_MODE_FLAG_DECODE_POSITION_ENUM_END = 129 #
enums['MAV_MODE_FLAG_DECODE_POSITION'][129] = EnumEntry('MAV_MODE_FLAG_DECODE_POSITION_ENUM_END', '''''')

# MAV_STATE
enums['MAV_STATE'] = {}
MAV_STATE_UNINIT = 0 # Uninitialized system, state is unknown.
enums['MAV_STATE'][0] = EnumEntry('MAV_STATE_UNINIT', '''Uninitialized system, state is unknown.''')
MAV_STATE_BOOT = 1 # System is booting up.
enums['MAV_STATE'][1] = EnumEntry('MAV_STATE_BOOT', '''System is booting up.''')
MAV_STATE_CALIBRATING = 2 # System is calibrating and not flight-ready.
enums['MAV_STATE'][2] = EnumEntry('MAV_STATE_CALIBRATING', '''System is calibrating and not flight-ready.''')
MAV_STATE_STANDBY = 3 # System is grounded and on standby. It can be launched any time.
enums['MAV_STATE'][3] = EnumEntry('MAV_STATE_STANDBY', '''System is grounded and on standby. It can be launched any time.''')
MAV_STATE_ACTIVE = 4 # System is active and might be already airborne. Motors are engaged.
enums['MAV_STATE'][4] = EnumEntry('MAV_STATE_ACTIVE', '''System is active and might be already airborne. Motors are engaged.''')
MAV_STATE_CRITICAL = 5 # System is in a non-normal flight mode. It can however still navigate.
enums['MAV_STATE'][5] = EnumEntry('MAV_STATE_CRITICAL', '''System is in a non-normal flight mode. It can however still navigate.''')
MAV_STATE_EMERGENCY = 6 # System is in a non-normal flight mode. It lost control over parts or
                        # over the whole airframe. It is in mayday and
                        # going down.
enums['MAV_STATE'][6] = EnumEntry('MAV_STATE_EMERGENCY', '''System is in a non-normal flight mode. It lost control over parts or over the whole airframe. It is in mayday and going down.''')
MAV_STATE_POWEROFF = 7 # System just initialized its power-down sequence, will shut down now.
enums['MAV_STATE'][7] = EnumEntry('MAV_STATE_POWEROFF', '''System just initialized its power-down sequence, will shut down now.''')
MAV_STATE_ENUM_END = 8 #
enums['MAV_STATE'][8] = EnumEntry('MAV_STATE_ENUM_END', '''''')

# message IDs
MAVLINK_MSG_ID_BAD_DATA = -1
MAVLINK_MSG_ID_HEARTBEAT = 0

class MAVLink_heartbeat_message(MAVLink_message):
        '''
        The heartbeat message shows that a system is present and
        responding. The type of the MAV and Autopilot hardware allow
        the receiving system to treat further messages from this
        system appropriate (e.g. by laying out the user interface
        based on the autopilot).
        '''
        id = MAVLINK_MSG_ID_HEARTBEAT
        name = 'HEARTBEAT'
        fieldnames = ['type', 'autopilot', 'base_mode', 'custom_mode', 'system_status', 'mavlink_version']
        ordered_fieldnames = [ 'custom_mode', 'type', 'autopilot', 'base_mode', 'system_status', 'mavlink_version' ]
        format = '<IBBBBB'
        native_format = bytearray('<IBBBBB', 'ascii')
        orders = [1, 2, 3, 0, 4, 5]
        lengths = [1, 1, 1, 1, 1, 1]
        array_lengths = [0, 0, 0, 0, 0, 0]
        crc_extra = 50

        def __init__(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version):
                MAVLink_message.__init__(self, MAVLink_heartbeat_message.id, MAVLink_heartbeat_message.name)
                self._fieldnames = MAVLink_heartbeat_message.fieldnames
                self.type = type
                self.autopilot = autopilot
                self.base_mode = base_mode
                self.custom_mode = custom_mode
                self.system_status = system_status
                self.mavlink_version = mavlink_version

        def pack(self, mav):
                return MAVLink_message.pack(self, mav, 50, struct.pack('<IBBBBB', self.custom_mode, self.type, self.autopilot, self.base_mode, self.system_status, self.mavlink_version))

mavlink_map = {
        MAVLINK_MSG_ID_HEARTBEAT : MAVLink_heartbeat_message,
}

class MAVError(Exception):
        '''MAVLink error class'''
        def __init__(self, msg):
            Exception.__init__(self, msg)
            self.message = msg

class MAVString(str):
        '''NUL terminated string'''
        def __init__(self, s):
                str.__init__(self)
        def __str__(self):
            i = self.find(chr(0))
            if i == -1:
                return self[:]
            return self[0:i]

class MAVLink_bad_data(MAVLink_message):
        '''
        a piece of bad data in a mavlink stream
        '''
        def __init__(self, data, reason):
                MAVLink_message.__init__(self, MAVLINK_MSG_ID_BAD_DATA, 'BAD_DATA')
                self._fieldnames = ['data', 'reason']
                self.data = data
                self.reason = reason
                self._msgbuf = data

        def __str__(self):
            '''Override the __str__ function from MAVLink_messages because non-printable characters are common in to be the reason for this message to exist.'''
            return '%s {%s, data:%s}' % (self._type, self.reason, [('%x' % ord(i) if isinstance(i, str) else '%x' % i) for i in self.data])

class MAVLink(object):
        '''MAVLink protocol handling class'''
        def __init__(self, file, srcSystem=0, srcComponent=0, use_native=False):
                self.seq = 0
                self.file = file
                self.srcSystem = srcSystem
                self.srcComponent = srcComponent
                self.callback = None
                self.callback_args = None
                self.callback_kwargs = None
                self.send_callback = None
                self.send_callback_args = None
                self.send_callback_kwargs = None
                self.buf = bytearray()
                self.expected_length = 8
                self.have_prefix_error = False
                self.robust_parsing = False
                self.protocol_marker = 254
                self.little_endian = True
                self.crc_extra = True
                self.sort_fields = True
                self.total_packets_sent = 0
                self.total_bytes_sent = 0
                self.total_packets_received = 0
                self.total_bytes_received = 0
                self.total_receive_errors = 0
                self.startup_time = time.time()
                if native_supported and (use_native or native_testing or native_force):
                    print("NOTE: mavnative is currently beta-test code")
                    self.native = mavnative.NativeConnection(MAVLink_message, mavlink_map)
                else:
                    self.native = None
                if native_testing:
                    self.test_buf = bytearray()

        def set_callback(self, callback, *args, **kwargs):
            self.callback = callback
            self.callback_args = args
            self.callback_kwargs = kwargs

        def set_send_callback(self, callback, *args, **kwargs):
            self.send_callback = callback
            self.send_callback_args = args
            self.send_callback_kwargs = kwargs

        def send(self, mavmsg):
                '''send a MAVLink message'''
                buf = mavmsg.pack(self)
                self.file.write(buf)
                self.seq = (self.seq + 1) % 256
                self.total_packets_sent += 1
                self.total_bytes_sent += len(buf)
                if self.send_callback:
                    self.send_callback(mavmsg, *self.send_callback_args, **self.send_callback_kwargs)

        def bytes_needed(self):
            '''return number of bytes needed for next parsing stage'''
            if self.native:
                ret = self.native.expected_length - len(self.buf)
            else:
                ret = self.expected_length - len(self.buf)

            if ret <= 0:
                return 1
            return ret

        def __parse_char_native(self, c):
            '''this method exists only to see in profiling results'''
            m = self.native.parse_chars(c)
            return m

        def __callbacks(self, msg):
            '''this method exists only to make profiling results easier to read'''
            if self.callback:
                self.callback(msg, *self.callback_args, **self.callback_kwargs)

        def parse_char(self, c):
            '''input some data bytes, possibly returning a new message'''
            self.buf.extend(c)

            self.total_bytes_received += len(c)

            if self.native:
                if native_testing:
                    self.test_buf.extend(c)
                    m = self.__parse_char_native(self.test_buf)
                    m2 = self.__parse_char_legacy()
                    if m2 != m:
                        print("Native: %s\nLegacy: %s\n" % (m, m2))
                        raise Exception('Native vs. Legacy mismatch')
                else:
                    m = self.__parse_char_native(self.buf)
            else:
                m = self.__parse_char_legacy()

            if m != None:
                self.total_packets_received += 1
                self.__callbacks(m)

            return m

        def __parse_char_legacy(self):
            '''input some data bytes, possibly returning a new message (uses no native code)'''
            if len(self.buf) >= 1 and self.buf[0] != 254:
                magic = self.buf[0]
                self.buf = self.buf[1:]
                if self.robust_parsing:
                    m = MAVLink_bad_data(chr(magic), "Bad prefix")
                    self.expected_length = 8
                    self.total_receive_errors += 1
                    return m
                if self.have_prefix_error:
                    return None
                self.have_prefix_error = True
                self.total_receive_errors += 1
                raise MAVError("invalid MAVLink prefix '%s'" % magic)
            self.have_prefix_error = False
            if len(self.buf) >= 2:
                if sys.version_info[0] < 3:
                    (magic, self.expected_length) = struct.unpack('BB', str(self.buf[0:2])) # bytearrays are not supported in py 2.7.3
                else:
                    (magic, self.expected_length) = struct.unpack('BB', self.buf[0:2])
                self.expected_length += 8
            if self.expected_length >= 8 and len(self.buf) >= self.expected_length:
                mbuf = array.array('B', self.buf[0:self.expected_length])
                self.buf = self.buf[self.expected_length:]
                self.expected_length = 8
                if self.robust_parsing:
                    try:
                        m = self.decode(mbuf)
                    except MAVError as reason:
                        m = MAVLink_bad_data(mbuf, reason.message)
                        self.total_receive_errors += 1
                else:
                    m = self.decode(mbuf)
                return m
            return None

        def parse_buffer(self, s):
            '''input some data bytes, possibly returning a list of new messages'''
            m = self.parse_char(s)
            if m is None:
                return None
            ret = [m]
            while True:
                m = self.parse_char("")
                if m is None:
                    return ret
                ret.append(m)
            return ret

        def decode(self, msgbuf):
                '''decode a buffer as a MAVLink message'''
                # decode the header
                try:
                    magic, mlen, seq, srcSystem, srcComponent, msgId = struct.unpack('cBBBBB', msgbuf[:6])
                except struct.error as emsg:
                    raise MAVError('Unable to unpack MAVLink header: %s' % emsg)
                if ord(magic) != 254:
                    raise MAVError("invalid MAVLink prefix '%s'" % magic)
                if mlen != len(msgbuf)-8:
                    raise MAVError('invalid MAVLink message length. Got %u expected %u, msgId=%u' % (len(msgbuf)-8, mlen, msgId))

                if not msgId in mavlink_map:
                    raise MAVError('unknown MAVLink message ID %u' % msgId)

                # decode the payload
                type = mavlink_map[msgId]
                fmt = type.format
                order_map = type.orders
                len_map = type.lengths
                crc_extra = type.crc_extra

                # decode the checksum
                try:
                    crc, = struct.unpack('<H', msgbuf[-2:])
                except struct.error as emsg:
                    raise MAVError('Unable to unpack MAVLink CRC: %s' % emsg)
                crcbuf = msgbuf[1:-2]
                if True: # using CRC extra
                    crcbuf.append(crc_extra)
                crc2 = x25crc(crcbuf)
                if crc != crc2.crc:
                    raise MAVError('invalid MAVLink CRC in msgID %u 0x%04x should be 0x%04x' % (msgId, crc, crc2.crc))

                try:
                    t = struct.unpack(fmt, msgbuf[6:-2])
                except struct.error as emsg:
                    raise MAVError('Unable to unpack MAVLink payload type=%s fmt=%s payloadLength=%u: %s' % (
                        type, fmt, len(msgbuf[6:-2]), emsg))

                tlist = list(t)
                # handle sorted fields
                if True:
                    t = tlist[:]
                    if sum(len_map) == len(len_map):
                        # message has no arrays in it
                        for i in range(0, len(tlist)):
                            tlist[i] = t[order_map[i]]
                    else:
                        # message has some arrays
                        tlist = []
                        for i in range(0, len(order_map)):
                            order = order_map[i]
                            L = len_map[order]
                            tip = sum(len_map[:order])
                            field = t[tip]
                            if L == 1 or isinstance(field, str):
                                tlist.append(field)
                            else:
                                tlist.append(t[tip:(tip + L)])

                # terminate any strings
                for i in range(0, len(tlist)):
                    if isinstance(tlist[i], str):
                        tlist[i] = str(MAVString(tlist[i]))
                t = tuple(tlist)
                # construct the message object
                try:
                    m = type(*t)
                except Exception as emsg:
                    raise MAVError('Unable to instantiate MAVLink message of type %s : %s' % (type, emsg))
                m._msgbuf = msgbuf
                m._payload = msgbuf[6:-2]
                m._crc = crc
                m._header = MAVLink_header(msgId, mlen, seq, srcSystem, srcComponent)
                return m
        def heartbeat_encode(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=2):
                '''
                The heartbeat message shows that a system is present and responding.
                The type of the MAV and Autopilot hardware allow the
                receiving system to treat further messages from this
                system appropriate (e.g. by laying out the user
                interface based on the autopilot).

                type                      : Type of the MAV (quadrotor, helicopter, etc., up to 15 types, defined in MAV_TYPE ENUM) (uint8_t)
                autopilot                 : Autopilot type / class. defined in MAV_AUTOPILOT ENUM (uint8_t)
                base_mode                 : System mode bitfield, see MAV_MODE_FLAGS ENUM in mavlink/include/mavlink_types.h (uint8_t)
                custom_mode               : A bitfield for use for autopilot-specific flags. (uint32_t)
                system_status             : System status flag, see MAV_STATE ENUM (uint8_t)
                mavlink_version           : MAVLink version (uint8_t)

                '''
                return MAVLink_heartbeat_message(type, autopilot, base_mode, custom_mode, system_status, mavlink_version)

        def heartbeat_send(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=2):
                '''
                The heartbeat message shows that a system is present and responding.
                The type of the MAV and Autopilot hardware allow the
                receiving system to treat further messages from this
                system appropriate (e.g. by laying out the user
                interface based on the autopilot).

                type                      : Type of the MAV (quadrotor, helicopter, etc., up to 15 types, defined in MAV_TYPE ENUM) (uint8_t)
                autopilot                 : Autopilot type / class. defined in MAV_AUTOPILOT ENUM (uint8_t)
                base_mode                 : System mode bitfield, see MAV_MODE_FLAGS ENUM in mavlink/include/mavlink_types.h (uint8_t)
                custom_mode               : A bitfield for use for autopilot-specific flags. (uint32_t)
                system_status             : System status flag, see MAV_STATE ENUM (uint8_t)
                mavlink_version           : MAVLink version (uint8_t)

                '''
                return self.send(self.heartbeat_encode(type, autopilot, base_mode, custom_mode, system_status, mavlink_version))


text:
package org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.tasks;

import org.eclipse.bpmn2.Task;
import org.kie.workbench.common.stunner.bpmn.backend.converters.NodeMatch;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.ActivityPropertyWriter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.BusinessRuleTaskPropertyWriter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.GenericServiceTaskPropertyWriter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.PropertyWriter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.PropertyWriterFactory;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.ScriptTaskPropertyWriter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.ServiceTaskPropertyWriter;
import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.UserTaskPropertyWriter;
import org.kie.workbench.common.stunner.bpmn.definition.BaseTask;
import org.kie.workbench.common.stunner.bpmn.definition.BaseUserTask;
import org.kie.workbench.common.stunner.bpmn.definition.BusinessRuleTask;
import org.kie.workbench.common.stunner.bpmn.definition.GenericServiceTask;
import org.kie.workbench.common.stunner.bpmn.definition.NoneTask;
import org.kie.workbench.common.stunner.bpmn.definition.ScriptTask;
import org.kie.workbench.common.stunner.bpmn.definition.property.general.TaskGeneralSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.service.GenericServiceTaskExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.task.BaseUserTaskExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.task.BusinessRuleTaskExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.task.RuleLanguage;
import org.kie.workbench.common.stunner.bpmn.definition.property.task.ScriptTaskExecutionSet;
import org.kie.workbench.common.stunner.bpmn.workitem.ServiceTask;
import org.kie.workbench.common.stunner.bpmn.workitem.ServiceTaskExecutionSet;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.view.View;

import static org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.Factories.bpmn2;

public class TaskConverter {

    private final PropertyWriterFactory propertyWriterFactory;

    public TaskConverter(PropertyWriterFactory propertyWriterFactory) {
        this.propertyWriterFactory = propertyWriterFactory;
    }

    public PropertyWriter toFlowElement(Node<View<BaseTask>, ?> node) {
        return NodeMatch.fromNode(BaseTask.class, PropertyWriter.class)
                .when(NoneTask.class, this::noneTask)
                .when(ScriptTask.class, this::scriptTask)
                .when(BusinessRuleTask.class, this::businessRuleTask)
                .when(BaseUserTask.class, this::userTask)
                .when(ServiceTask.class, this::serviceTask)
                .when(GenericServiceTask.class, this::genericServiceTask)
                .apply(node)
                .value();
    }

    private PropertyWriter genericServiceTask(Node<View<GenericServiceTask>, ?> n) {
        org.eclipse.bpmn2.ServiceTask task = bpmn2.createServiceTask();
        task.setId(n.getUUID());

        GenericServiceTask definition = n.getContent().getDefinition();
        GenericServiceTaskPropertyWriter p = propertyWriterFactory.of(task);

        TaskGeneralSet general = definition.getGeneral();
        GenericServiceTaskExecutionSet executionSet =
                definition.getExecutionSet();

        p.setName(general.getName().getValue());
        p.setDocumentation(general.getDocumentation().getValue());
        p.setAbsoluteBounds(n);
        p.setSimulationSet(definition.getSimulationSet());
        p.setValue(executionSet.getGenericServiceTaskInfo()
                                      .getValue());
        p.setAsync(executionSet.getIsAsync().getValue());
        p.setAdHocAutostart(executionSet.getAdHocAutostart().getValue());
        if (Boolean.TRUE.equals(executionSet.getIsMultipleInstance().getValue())) {
            p.setIsSequential(executionSet.getMultipleInstanceExecutionMode().isSequential());
            p.setCollectionInput(executionSet.getMultipleInstanceCollectionInput().getValue());
            p.setInput(executionSet.getMultipleInstanceDataInput().getValue());
            p.setCollectionOutput(executionSet.getMultipleInstanceCollectionOutput().getValue());
            p.setOutput(executionSet.getMultipleInstanceDataOutput().getValue());
            p.setCompletionCondition(executionSet.getMultipleInstanceCompletionCondition().getValue());
        }
        p.setOnEntryAction(executionSet.getOnEntryAction());
        p.setOnExitAction(executionSet.getOnExitAction());
        p.setSLADueDate(executionSet.getSlaDueDate().getValue());
        p.setAssignmentsInfo(executionSet.getAssignmentsinfo());
        return p;
    }

    private PropertyWriter serviceTask(Node<View<ServiceTask>, ?> n) {
        org.eclipse.bpmn2.Task task = bpmn2.createTask();
        task.setId(n.getUUID());

        ServiceTask definition = n.getContent().getDefinition();
        ServiceTaskPropertyWriter p = propertyWriterFactory.of(task);

        p.setServiceTaskName(definition.getName());

        TaskGeneralSet general = definition.getGeneral();
        p.setName(general.getName().getValue());
        p.setDocumentation(general.getDocumentation().getValue());

        p.setAssignmentsInfo(
                definition.getDataIOSet().getAssignmentsinfo());

        ServiceTaskExecutionSet executionSet =
                definition.getExecutionSet();

        p.setTaskName(executionSet.getTaskName().getValue());
        p.setAsync(executionSet.getIsAsync().getValue());
        p.setOnEntryAction(executionSet.getOnEntryAction());
        p.setOnExitAction(executionSet.getOnExitAction());
        p.setAdHocAutostart(executionSet.getAdHocAutostart().getValue());
        p.setSlaDueDate(executionSet.getSlaDueDate().getValue());

        p.setSimulationSet(definition.getSimulationSet());

        p.setAbsoluteBounds(n);
        return p;
    }

    private PropertyWriter userTask(Node<View<BaseUserTask>, ?> n) {
        org.eclipse.bpmn2.UserTask task = bpmn2.createUserTask();
        task.setId(n.getUUID());
        BaseUserTask definition = n.getContent().getDefinition();
        UserTaskPropertyWriter p = propertyWriterFactory.of(task);

        TaskGeneralSet general = definition.getGeneral();
        p.setName(general.getName().getValue());
        p.setDocumentation(general.getDocumentation().getValue());

        p.setSimulationSet(definition.getSimulationSet());

        BaseUserTaskExecutionSet executionSet = definition.getExecutionSet();

        p.setTaskName(executionSet.getTaskName().getValue());
        p.setActors(executionSet.getActors());
        p.setAssignmentsInfo(executionSet.getAssignmentsinfo());
        p.setReassignments(executionSet.getReassignmentsInfo());
        p.setNotifications(executionSet.getNotificationsInfo());
        p.setSkippable(executionSet.getSkippable().getValue());
        p.setGroupId(executionSet.getGroupid().getValue());
        p.setSubject(executionSet.getSubject().getValue());
        p.setDescription(executionSet.getDescription().getValue());
        p.setPriority(executionSet.getPriority().getValue());
        p.setAsync(executionSet.getIsAsync().getValue());
        p.setCreatedBy(executionSet.getCreatedBy().getValue());
        p.setAdHocAutostart(executionSet.getAdHocAutostart().getValue());
        if (Boolean.TRUE.equals(executionSet.getIsMultipleInstance().getValue())) {
            p.setIsSequential(executionSet.getMultipleInstanceExecutionMode().isSequential());
            p.setCollectionInput(executionSet.getMultipleInstanceCollectionInput().getValue());
            p.setInput(executionSet.getMultipleInstanceDataInput().getValue());
            p.setCollectionOutput(executionSet.getMultipleInstanceCollectionOutput().getValue());
            p.setOutput(executionSet.getMultipleInstanceDataOutput().getValue());
            p.setCompletionCondition(executionSet.getMultipleInstanceCompletionCondition().getValue());
        }
        p.setOnEntryAction(executionSet.getOnEntryAction());
        p.setOnExitAction(executionSet.getOnExitAction());
        p.setContent(executionSet.getContent().getValue());
        p.setSLADueDate(executionSet.getSlaDueDate().getValue());

        p.setAbsoluteBounds(n);

        return p;
    }

    private PropertyWriter businessRuleTask(Node<View<BusinessRuleTask>, ?> n) {
        org.eclipse.bpmn2.BusinessRuleTask task = bpmn2.createBusinessRuleTask();
        task.setId(n.getUUID());
        BusinessRuleTask definition = n.getContent().getDefinition();
        BusinessRuleTaskPropertyWriter p = propertyWriterFactory.of(task);

        TaskGeneralSet general = definition.getGeneral();
        p.setName(general.getName().getValue());
        p.setDocumentation(general.getDocumentation().getValue());

        BusinessRuleTaskExecutionSet executionSet =
                definition.getExecutionSet();

        p.setAsync(executionSet.getIsAsync().getValue());
        p.setOnEntryAction(executionSet.getOnEntryAction());
        p.setOnExitAction(executionSet.getOnExitAction());
        p.setAdHocAutostart(executionSet.getAdHocAutostart().getValue());
        p.setSlaDueDate(executionSet.getSlaDueDate().getValue());

        RuleLanguage ruleLanguage = executionSet.getRuleLanguage();
        p.setImplementation(ruleLanguage);

        if (ruleLanguage.getValue().equals(RuleLanguage.DRL)) {
            p.setRuleFlowGroup(executionSet.getRuleFlowGroup());
        } else if (ruleLanguage.getValue().equals(RuleLanguage.DMN)) {
            p.setNamespace(executionSet.getNamespace());
            p.setDecisionName(executionSet.getDecisionName());
            p.setDmnModelName(executionSet.getDmnModelName());
        }

        p.setAssignmentsInfo(definition.getDataIOSet().getAssignmentsinfo());

        p.setSimulationSet(definition.getSimulationSet());

        p.setAbsoluteBounds(n);
        return p;
    }

    private PropertyWriter scriptTask(Node<View<ScriptTask>, ?> n) {
        org.eclipse.bpmn2.ScriptTask task = bpmn2.createScriptTask();
        task.setId(n.getUUID());
        ScriptTask definition = n.getContent().getDefinition();
        ScriptTaskPropertyWriter p = propertyWriterFactory.of(task);

        TaskGeneralSet general = definition.getGeneral();
        p.setName(general.getName().getValue());
        p.setDocumentation(general.getDocumentation().getValue());

        ScriptTaskExecutionSet executionSet = definition.getExecutionSet();

        p.setScript(executionSet.getScript().getValue());
        p.setAsync(executionSet.getIsAsync().getValue());
        p.setAdHocAutostart(executionSet.getAdHocAutostart().getValue());

        p.setSimulationSet(definition.getSimulationSet());

        p.setAbsoluteBounds(n);
        return p;
    }

    private PropertyWriter noneTask(Node<View<NoneTask>, ?> n) {
        Task task = bpmn2.createTask();
        task.setId(n.getUUID());
        NoneTask definition = n.getContent().getDefinition();
        ActivityPropertyWriter p = propertyWriterFactory.of(task);

        TaskGeneralSet general = definition.getGeneral();
        p.setName(general.getName().getValue());
        p.setDocumentation(general.getDocumentation().getValue());

        p.setAbsoluteBounds(n);

        p.setSimulationSet(definition.getSimulationSet());
        return p;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.SearchScreenActivity">

    <!-- Search, should appear as action button -->
    <!--<item android:id="@+id/action_search"-->
    <!--android:icon="@drawable/ic_action_search"-->
    <!--android:title="@string/action_search"-->
    <!--android:showAsAction="ifRoom" />-->

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_about"
        android:title="@string/action_about"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>


text:
SpriteEffect
============

playing with the xna spriteeffect normal maps spritebatch thing


text:
<?php

namespace Sako\Passport\Exceptions;

class PermissionNotFound extends \Exception {

}


text:
from . Strategy import Strategy
from ai.STA.Tactic.Stop import Stop

class DoNothing(Strategy):
    def __init__(self, p_info_manager):
        tactics = [Stop(p_info_manager, 0),
                   Stop(p_info_manager, 1),
                   Stop(p_info_manager, 2),
                   Stop(p_info_manager, 3),
                   Stop(p_info_manager, 4),
                   Stop(p_info_manager, 5)]

        super().__init__(p_info_manager, tactics)


text:
from setuptools import setup, find_packages
from codecs import open
import os

here = os.path.abspath(os.path.dirname(__file__))

with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='nonogram-solver',
    version='0.1',
    description='A nonogram puzzle solver.',
    long_description=long_description,
    url='https://github.com/mprat/nonogram-solver',
    author='Michele Pratusevich',
    author_email='mprat@alum.mit.edu',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Other Audience',
        'Topic :: Games/Entertainment :: Puzzle Games',
        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5'
    ],
    keywords='puzzles nonogram solver puzzle',

    packages=find_packages(exclude=['tests', 'docs']),
    install_requires=['numpy>=1.10'],
    extras_require={
        'test': ['pytest', 'pytest-cov', 'coverage']
    }
)


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="48dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/umeng_common_progress_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:drawableTop="@android:drawable/stat_sys_download"
            android:singleLine="true"
            android:textColor="?android:attr/textColorPrimaryInverse"
            android:textSize="14sp" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingLeft="5dp"
        android:clickable="true"
        android:focusable="true" >

        <LinearLayout
            android:id="@+id/umeng_common_notification_controller"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="3dp"
            android:clickable="true"
            android:focusable="true"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/umeng_common_rich_notification_continue"
                android:layout_width="50dp"
                android:layout_height="25dp"
                android:background="@drawable/umeng_common_gradient_orange"
                android:singleLine="true"
                android:text="@string/umeng_common_action_pause"
                android:textSize="12sp" />

            <Button
                android:id="@+id/umeng_common_rich_notification_cancel"
                android:layout_width="50dp"
                android:layout_height="25dp"
                android:layout_marginLeft="2dp"
                android:layout_marginRight="2dp"
                android:background="@drawable/umeng_common_gradient_red"
                android:singleLine="true"
                android:text="@string/umeng_common_action_cancel"
                android:textSize="12sp" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/umeng_common_notification"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@id/umeng_common_notification_controller"
            android:clickable="true"
            android:focusable="true"
            android:orientation="horizontal"
            android:paddingTop="10dp" >

            <TextView
                android:id="@+id/umeng_common_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="2dp"
                android:singleLine="true"
                android:textColor="?android:attr/textColorPrimaryInverse"
                android:textSize="18sp"
                android:textStyle="bold" />
        </LinearLayout>

        <ProgressBar
            android:id="@+id/umeng_common_progress_bar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="12dp"
            android:layout_alignParentBottom="true"
            android:paddingBottom="8dp"
            android:paddingRight="25dp" />
    </RelativeLayout>

</LinearLayout>


text:
class MockFolder(dict, object):

    def __init__(self):
        self.name = 'Fake Folder'
        self.json = {'id': 'Fake Key', 'parent_id': 'cba321'}
        self['data'] = {'name': 'Fake Folder', 'key': 'Fake Key'}
        self['name'] = 'Fake Folder'
        self['id'] = 'Fake Key'


text:
function ConvertFrom-DsSchemaGuid {
<#
.SYNOPSIS

Converts an object schema GUID to a name

Author: Lee Christensen (@tifkin_)
License: BSD 3-Clause
Required Dependencies: None

Code heavily taken from https://www.pinvoke.net/default.aspx/ntdsapi/DsMapSchemaGuids.html

.DESCRIPTION

Converts an object schema GUID to a name.

.PARAMETER InputObject

Guid(s) to map to a name.

.EXAMPLE

ConvertFrom-DsSchemaGuid '3e10944d-c354-11d0-aff8-0000f80367c1'

.EXAMPLE

$Guids = (
    '{771727b1-31b8-4cdf-ae62-4fe39fadf89e}',
    'f6d6dd88-ccee-11d2-9993-0000f87a57d4',
    '3e10944d-c354-11d0-aff8-0000f80367c1'
)
ConvertFrom-DsSchemaGuid $Guids 'corp.local'

.EXAMPLE

'{771727b1-31b8-4cdf-ae62-4fe39fadf89e}', 'f6d6dd88-ccee-11d2-9993-0000f87a57d4' | ConvertFrom-DsSchemaGuid

#>
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [Guid[]]
        $InputObject,

        [Parameter(Mandatory=$false, Position=1)]
        [string]
        $Domain
    )

    Begin {
        # Load the PInvoked code if it hasn't been loaded yet
        try {
            $null = New-Object 'Interop+DS_SCHEMA_GUID_MAP'
        } catch {

            # Taken from https://www.pinvoke.net/default.aspx/ntdsapi/DsMapSchemaGuids.html
        Add-Type  -Verbose -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;

public static class Interop {
    [DllImport("Ntdsapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern uint DsMapSchemaGuids(
        IntPtr hDs,
        uint cGuids,
        Guid[] rGuids,
        out IntPtr ppGuidMap);

    [DllImport("Ntdsapi.dll", SetLastError = true)]
    public static extern void DsFreeSchemaGuidMap(IntPtr pGuidMap);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class GUID
    {
        public uint Data1;
        public int Data2;
        public int Data3;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public byte[] Data4 = new byte[8];
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct DS_SCHEMA_GUID_MAP
    {
        public GUID guid;
        public uint guidType;
        public string pName;
    }

    [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
    public static extern uint DsBind(
        IntPtr DomainControllerName,
        IntPtr DnsDomainName,
        ref IntPtr phDS);

    [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
    public static extern uint DsBind(
        IntPtr DomainControllerName,
        String DnsDomainName,
        ref IntPtr phDS);

    [DllImport("ntdsapi.dll", CharSet = CharSet.Auto)]
    public static extern uint DsUnBind(IntPtr phDS);

    public static List<string> parseGuids(IntPtr guidMap, int numGuids, bool freePointer)
    {
        int typeSize = Marshal.SizeOf(typeof(DS_SCHEMA_GUID_MAP));
        List<string> guids = new List<string>();
        DS_SCHEMA_GUID_MAP[] schemaMap = new DS_SCHEMA_GUID_MAP[numGuids];
        IntPtr guidPointer = guidMap;

        for (int i = 0; i < numGuids; i++)
        {
            schemaMap[i] = (DS_SCHEMA_GUID_MAP)Marshal.PtrToStructure(
            new IntPtr
            (
                (long)guidPointer + i * typeSize
            ),
                typeof(DS_SCHEMA_GUID_MAP)
            );

            if(String.IsNullOrEmpty(schemaMap[i].pName)) {
                guids.Add("");
            } else {
                guids.Add(String.Copy(schemaMap[i].pName));
            }
        }

        if (freePointer)
        {
            DsFreeSchemaGuidMap(guidPointer);
        }

        return guids;
    }
}
'@
        }

        $dsHandle = [System.IntPtr]::Zero

        if(([String]::IsNullOrEmpty($Domain))) {
            $status = [Interop]::DsBind([System.IntPtr]::Zero, [System.IntPtr]::Zero, [ref]$dsHandle)
        } else {
            $status = [Interop]::DsBind([System.IntPtr]::Zero, $Domain, [ref]$dsHandle)
        }
        if($status -ne 0) {
            throw "Unable to bind to AD: $status"
        }
    }

    Process {
        if($InputObject -isnot [array]) {
            $InputObject = [guid[]]@(,$InputObject)
        }

        $GuidMap = [System.IntPtr]::Zero
        $status = [Interop]::DsMapSchemaGuids($dsHandle, $InputObject.Length, $InputObject, [ref]$GuidMap);

        if($status -eq 0) {
            $GuidMapping = [interop]::parseGuids($GuidMap, $InputObject.Length, $true)

            for($i=0; $i -lt $InputObject.Count; $i++) {
                New-Object PSObject -Property @{
                    Guid = $InputObject[$i]
                    Name = $GuidMapping[$i]
                }
            }
        } else {
            Write-Error "Error mapping schema guids: $status"
        }
    }

    End {
        if($dsHandle -ne [System.IntPtr]::Zero) {
            $status = [Interop]::DsUnbind($dsHandle)
        }
    }
}


text:
require 'rubygems'

##
# The Version class processes string versions into comparable values
class Gem::Version

  include Comparable

  attr_reader :ints

  attr_reader :version

  ##
  # Checks if version string is valid format
  #
  # str:: [String] the version string
  # return:: [Boolean] true if the string format is correct, otherwise false
  #
  def self.correct?(version)
    case version
    when Integer, /\A\s*(\d+(\.\d+)*)*\s*\z/ then true
    else false
    end
  end

  ##
  # Factory method to create a Version object.  Input may be a Version or a
  # String.  Intended to simplify client code.
  #
  #   ver1 = Version.create('1.3.17')   # -> (Version object)
  #   ver2 = Version.create(ver1)       # -> (ver1)
  #   ver3 = Version.create(nil)        # -> nil
  #
  def self.create(input)
    if input.respond_to? :version then
      input
    elsif input.nil? then
      nil
    else
      new input
    end
  end

  ##
  # Constructs a version from the supplied string
  #
  # version:: [String] The version string.  Format is digit.digit...
  #
  def initialize(version)
    raise ArgumentError, "Malformed version number string #{version}" unless
      self.class.correct?(version)

    self.version = version
  end

  def inspect # :nodoc:
    "#<#{self.class} #{@version.inspect}>"
  end

  # Dump only the raw version string, not the complete object
  def marshal_dump
    [@version]
  end

  # Load custom marshal format
  def marshal_load(array)
    self.version = array[0]
  end

  # Strip ignored trailing zeros.
  def normalize
    @ints = build_array_from_version_string

    return if @ints.length == 1

    @ints.pop while @ints.last == 0

    @ints = [0] if @ints.empty?
  end

  ##
  # Returns the text representation of the version
  #
  # return:: [String] version as string
  #
  def to_s
    @version
  end

  ##
  # Convert version to integer array
  #
  # return:: [Array] list of integers
  #
  def to_ints
    normalize unless @ints
    @ints
  end

  def to_yaml_properties
    ['@version']
  end

  def version=(version)
    @version = version.to_s.strip
    normalize
  end

  def yaml_initialize(tag, values)
    self.version = values['version']
  end

  ##
  # Compares two versions
  #
  # other:: [Version or .ints] other version to compare to
  # return:: [Fixnum] -1, 0, 1
  #
  def <=>(other)
    return 1 unless other
    @ints <=> other.ints
  end

  alias eql? == # :nodoc:

  def hash # :nodoc:
    to_ints.inject { |hash_code, n| hash_code + n }
  end

  # Return a new version object where the next to the last revision
  # number is one greater. (e.g.  5.3.1 => 5.4)
  def bump
    ints = build_array_from_version_string
    ints.pop if ints.size > 1
    ints[-1] += 1
    self.class.new(ints.join("."))
  end

  def build_array_from_version_string
    @version.to_s.scan(/\d+/).map { |s| s.to_i }
  end
  private :build_array_from_version_string

  #:stopdoc:

  require 'rubygems/requirement'

  # Gem::Requirement's original definition is nested in Version.
  # Although an inappropriate place, current gems specs reference the nested
  # class name explicitly.  To remain compatible with old software loading
  # gemspecs, we leave a copy of original definition in Version, but define an
  # alias Gem::Requirement for use everywhere else.

  Requirement = ::Gem::Requirement

  # :startdoc:

end


text:
package com.gemstone.gemfire.management;

import com.gemstone.gemfire.cache.wan.GatewaySender;

/**
 * MBean that provides access to information and management functionality for a
 * {@link GatewaySender}.
 *
 * @author rishim
 * @since 7.0
 *
 */
public interface GatewaySenderMXBean {

  /**
   * Returns the ID of the GatewaySender.
   */
  public String getSenderId();

  /**
   * Returns the id of the remote GatewayReceiver's
   * DistributedSystem.
   */
  public int getRemoteDSId();

  /**
   * Returns the configured buffer size of the socket connection between this
   * GatewaySender and its receiving GatewayReceiver.
   */
  public int getSocketBufferSize();

  /**
   * Returns the amount of time (in milliseconds) that a socket read between a
   * sending GatewaySender and its receiving GatewayReceiver is
   * allowed to block.
   */
  public long getSocketReadTimeout();

  /**
   * Returns the name of the disk store that is used for persistence.
   */
  public String getOverflowDiskStoreName();

  /**
   * Returns the maximum memory after which the data needs to be overflowed to disk.
   */
  public int getMaximumQueueMemory();

  /**
   * Returns the size of a batch that gets delivered by the GatewaySender.
   */
  public int getBatchSize();

  /**
   * Returns the interval between transmissions by the GatewaySender.
   */
  public long getBatchTimeInterval();

  /**
   * Returns whether batch conflation for the GatewaySender's queue is enabled
   *
   * @return True if batch conflation is enabled, false otherwise.
   */
  public boolean isBatchConflationEnabled();

  /**
   * Returns whether the GatewaySender is configured to be persistent or
   * non-persistent.
   *
   * @return True if the sender is persistent, false otherwise.
   */

  public boolean isPersistenceEnabled();

  /**
   * Returns the alert threshold for entries in a GatewaySender's queue.The
   * default value is 0 milliseconds in which case no alert will be logged if
   * events are delayed in Queue.
   */
  public int getAlertThreshold();

  /**
   * Returns a list of GatewayEventFilters added to this
   * GatewaySender.
   */
  public String[] getGatewayEventFilters();

  /**
   * Returns a list of GatewayTransportFilters added to this
   * GatewaySender.
   */
  public String[] getGatewayTransportFilters();

  /**
   * Returns whether the GatewaySender is configured for manual start.
   *
   * @return True if the GatewaySender is configured for manual start, false otherwise.
   */
  public boolean isManualStart();

  /**
   * Returns whether or not this GatewaySender is running.
   *
   * @return True if the GatewaySender is running, false otherwise.
   */
  public boolean isRunning();

  /**
   * Returns whether or not this GatewaySender is paused.
   *
   * @return True of the GatewaySender is paused, false otherwise.
   */
  public boolean isPaused();

  /**
   * Returns the rate of events received per second by this Sender if it's a
   * serial-wan.
   */
  public float getEventsReceivedRate();

  /**
   * Returns the rate of events being queued.
   */
  public float getEventsQueuedRate();

  /**
   * Returns the current size of the event queue.
   */
  public int getEventQueueSize();

  /**
   * Returns the number of events received, but not added to the event queue, because
   * the queue already contains an event with the same key.
   */
  public int getTotalEventsConflated();

  /**
   * Returns the average number of batches sent per second.
   */
  public float getBatchesDispatchedRate();

  /**
   * Returns the average time taken to send a batch of events.
   */
  public long getAverageDistributionTimePerBatch();

  /**
   * Returns the total number of batches of events that were resent.
   */
  public int getTotalBatchesRedistributed();

  /**
   * Starts this GatewaySender. Once the GatewaySender is running its
   * configuration cannot be changed.
   *
   */
  public void start();

  /**
   * Stops this GatewaySender.
   */
  public void stop();

  /**
   * Pauses this GatewaySender.
   */
  public void pause();

  /**
   * Resumes this paused GatewaySender.
   */
  public void resume();

  /**
   * Rebalances this GatewaySender.
   */
  public void rebalance();

  /**
   * Returns whether this GatewaySender is primary or secondary.
   *
   * @return True if this is the primary, false otherwise.
   */
  public boolean isPrimary();

  /**
   * Returns the number of dispatcher threads working for this GatewaySender.
   */
  public int getDispatcherThreads();

  /**
   * Returns the order policy followed while dispatching the events to remote
   * distributed system. Order policy is only relevant when the number of dispatcher
   * threads is greater than one.
   */

  public String getOrderPolicy();

  /**
   * Returns whether the isDiskSynchronous property is set for this GatewaySender.
   *
   * @return True if the property is set, false otherwise.
   */
  public boolean isDiskSynchronous();

  /**
   * Returns whether the isParallel property is set for this GatewaySender.
   *
   * @return True if the property is set, false otherwise.
   */
  public boolean isParallel();

  /**
   * Returns the host and port information of GatewayReceiver to which this
   * gateway sender is connected.
   */
  public String getGatewayReceiver();

  /**
   * Returns whether this GatewaySender is connected and sending data to a
   * GatewayReceiver.
   */
  public boolean isConnected();

  /**
   * Returns number of events which have exceeded the configured alert threshold.
   */
  public int getEventsExceedingAlertThreshold();

}


text:
from django.contrib.gis.db import models

# generated by running ogrinspect against shapefiles
# ./manage.py ogrinspect ../state_tabblock_shapefiles/tl_2010_01_tabblock10/tl_2010_01_tabblock10.shp CensusBlock --srid=4326 --mapping --multi
# ./manage.py ogrinspect ../state_tract_shapefiles/tl_2010_01_tract10/tl_2010_01_tract10.shp CensusTract --srid=4326 --mapping --multi

class CensusBlock(models.Model):
    statefp10 = models.CharField(max_length=2)
    countyfp10 = models.CharField(max_length=3)
    tractce10 = models.CharField(max_length=6)
    blockce10 = models.CharField(max_length=4)
    geoid10 = models.CharField(max_length=15, primary_key=True)
    name10 = models.CharField(max_length=10)
    mtfcc10 = models.CharField(max_length=5)
    ur10 = models.CharField(max_length=1)
    uace10 = models.CharField(max_length=5)
    funcstat10 = models.CharField(max_length=1)
    aland10 = models.DecimalField(max_digits=14, decimal_places=0)
    awater10 = models.DecimalField(max_digits=14, decimal_places=0)
    intptlat10 = models.CharField(max_length=11)
    intptlon10 = models.CharField(max_length=12)
    the_geom = models.MultiPolygonField(srid=4326)
    objects = models.GeoManager()

    def __unicode__(self):
        return u'<'+self.__module__+' CensusBlock: '+unicode(self.geoid10)+')>'

    def __repr__(self):
        return unicode(self).encode('utf-8')

    def __str__(self):
        return "Block "+str(self.geoid10)

    class Meta:
        db_table = u'censusblocks'
        unique_together = ("statefp10", "countyfp10", "tractce10", "blockce10")
        verbose_name = u'Census Block'
        verbose_name_plural = u'Census Blocks'

class CensusTract(models.Model):
    statefp10 = models.CharField(max_length=2)
    countyfp10 = models.CharField(max_length=3)
    tractce10 = models.CharField(max_length=6)
    geoid10 = models.CharField(max_length=11, primary_key=True)
    name10 = models.CharField(max_length=7)
    namelsad10 = models.CharField(max_length=20)
    mtfcc10 = models.CharField(max_length=5)
    funcstat10 = models.CharField(max_length=1)
    aland10 = models.FloatField()
    awater10 = models.FloatField()
    intptlat10 = models.CharField(max_length=11)
    intptlon10 = models.CharField(max_length=12)
    the_geom = models.MultiPolygonField(srid=4326)
    objects = models.GeoManager()

    def __unicode__(self):
        return u'<'+self.__module__+' CensusTract: '+unicode(self.geoid10)+')>'

    def __repr__(self):
        return unicode(self).encode('utf-8')

    def __str__(self):
        return "Tract "+str(self.geoid10)

    class Meta:
        db_table = u'censustracts'
        unique_together = ("statefp10", "countyfp10", "tractce10")
        verbose_name = u'Census Tract'
        verbose_name_plural = u'Census Tracts'

class CensusCounty(models.Model):
    statefp10 = models.CharField(max_length=2)
    countyfp10 = models.CharField(max_length=3)
    countyns10 = models.CharField(max_length=8)
    geoid10 = models.CharField(max_length=5, primary_key=True)
    name10 = models.CharField(max_length=100)
    namelsad10 = models.CharField(max_length=100)
    lsad10 = models.CharField(max_length=2)
    classfp10 = models.CharField(max_length=2)
    mtfcc10 = models.CharField(max_length=5)
    csafp10 = models.CharField(max_length=3)
    cbsafp10 = models.CharField(max_length=5)
    metdivfp10 = models.CharField(max_length=5)
    funcstat10 = models.CharField(max_length=1)
    aland10 = models.FloatField()
    awater10 = models.FloatField()
    intptlat10 = models.CharField(max_length=11)
    intptlon10 = models.CharField(max_length=12)
    the_geom = models.MultiPolygonField(srid=4326)
    objects = models.GeoManager()

    def __unicode__(self):
        return u'<'+self.__module__+' CensusCounty: '+unicode(self.geoid10)+')>'

    def __repr__(self):
        return unicode(self).encode('utf-8')

    def __str__(self):
        return "Tract "+str(self.geoid10)

    class Meta:
        db_table = u'censuscounties'
        unique_together = ("statefp10", "countyfp10")
        verbose_name = u'Census County'
        verbose_name_plural = u'Census Counties'

class DataBlock(CensusBlock):
    #geoid10 = models.OneToOneField(CensusBlock, to_field='geoid10', parent_link=True) #0

    totpop = models.IntegerField(verbose_name="Total Population") #46
    totpop_wnh = models.IntegerField(verbose_name="Total Population, White Non-Hispanic") #77
    totpop_h = models.IntegerField(verbose_name="Total Population, Hispanic") #75
    totpop_black = models.IntegerField(verbose_name="Total Population, Black") #48
    totpop_na = models.IntegerField(verbose_name="Total Population, Native American") #49
    totpop_a = models.IntegerField(verbose_name="Total Population, Asian") #50
    totpop_hi = models.IntegerField(verbose_name="Total Population, Hawaiian/Pacific Islander") #51
    totpop_other = models.IntegerField(verbose_name="Total Population, Other") #82
    totpop_multiracial = models.IntegerField(verbose_name="Total Population, Other") #99

    vap = models.IntegerField(verbose_name="Voting Age Population") #112
    vap_wnh = models.IntegerField(verbose_name="Voting Age Population, White Non-Hispanic") #143
    vap_h = models.IntegerField(verbose_name="Voting Age Population, Hispanic") #141
    vap_black = models.IntegerField(verbose_name="Voting Age Population, Black") #114
    vap_na = models.IntegerField(verbose_name="Voting Age Population, Native American") #115
    vap_a = models.IntegerField(verbose_name="Voting Age Population, Asian") #116
    vap_hi = models.IntegerField(verbose_name="Voting Age Population, Hawaiian") #117
    vap_other = models.IntegerField(verbose_name="Voting Age Population, Other") #148
    vap_multiracial = models.IntegerField(verbose_name="Voting Age Population, Other") #165

    objects = models.GeoManager()

    def __unicode__(self):
        return u'<'+self.__module__+' DataBlock: '+unicode(self.geoid10)+')>'

    def __repr__(self):
        return unicode(self).encode('utf-8')

    def __str__(self):
        return "DataBlock "+str(self.geoid10)

    class Meta:
        db_table = u'datablocks'
        verbose_name = u'Block Data'
        verbose_name_plural = u'Blocks Data'


text:
from ajabsacco.core.facades import loans as loan_facades
from ajabsacco.core.facades import savings as savings_facades
from ajabsacco.core.models import *
from ajabsacco.core.forms import *

from ajabsacco.core.codes import loans as loan_codes
from ajabsacco.core.codes import savings as savings_codes

from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST, require_GET
from django.template.response import TemplateResponse
from django.shortcuts import redirect, get_object_or_404

from operator import itemgetter

from decimal import Decimal as D

from django.db.models import Q, Sum, F

import logging

logger = logging.getLogger('core.ajabsacco.loans')

@login_required
def chart_of_accounts(request):
    context = dict(
        loans=dict(
            portfolio_control_balance=loan_facades.loan_portfolio_control_balance(),
            write_off_expense_balance=loan_facades.write_off_expense_balance(),
            fund_source=loan_facades.loan_funding_balance(),
            interest_income=loan_facades.interest_income(),
            interest_income_receivable=loan_facades.interest_income_receivable(),
            fee_income=loan_facades.fee_income(),
            fee_income_receivable=loan_facades.fee_income_receivable(),
            penalty_income=loan_facades.penalty_income(),
            penalty_income_receivable=loan_facades.penalty_income_receivable(),
        ),
        savings=dict(
            overdraft_portfolio_control=savings_facades.overdraft_portfolio_control(),
            deposit_reference=savings_facades.deposit_reference(),
            member_deposits=savings_facades.member_deposits(),
            overdraft_interest_income=savings_facades.overdraft_interest_income(),
            overdraft_fee_income=savings_facades.overdraft_fee_income(),
            savings_fee_income=savings_facades.savings_fee_income(),
            savings_interest_expense=savings_facades.savings_interest_expense(),
            overdraft_write_off_expense=savings_facades.overdraft_write_off_expense(),
        ),
        account_types=["Asset", "Liability", "Equity", "Income", "Expense"],
        accounts=[
            dict(name="Loan Portfolio Control", type="Asset", code=loan_codes.LOAN_PORTFOLIO_CONTROL_ACCOUNT, amount=loan_facades.loan_portfolio_control_balance()),
            dict(name="Loan Write Off Expense",  type="Expense", code=loan_codes.LOAN_WRITE_OFF_EXPENSE_ACCOUNT, amount=loan_facades.write_off_expense_balance()),
            dict(name="Loan Funding Balance",  type="Asset", code=loan_codes.LOAN_FUND_SOURCE, amount=loan_facades.loan_funding_balance()),
            dict(name="Loan Interest Income",  type="Income", code=loan_codes.INTEREST_INCOME_ACCOUNT, amount=loan_facades.interest_income()),
            dict(name="Loan Interest Income Receivable",  type="Asset", code=loan_codes.INTEREST_INCOME_RECEIVABLE_ACCOUNT, amount=loan_facades.interest_income_receivable()),
            dict(name="Loan Fee Income",  type="Income", code=loan_codes.FEE_INCOME_ACCOUNT, amount=loan_facades.fee_income()),
            dict(name="Loan Fee Income Receivable",  type="Asset", code=loan_codes.FEE_INCOME_RECEIVABLE_ACCOUNT, amount=loan_facades.fee_income_receivable()),
            dict(name="Penalty Income",  type="Income", code=loan_codes.PENALTY_INCOME_ACCOUNT, amount=loan_facades.penalty_income()),
            dict(name="Penalty Income Receivable",  type="Asset", code=loan_codes.PENALTY_INCOME_RECEIVABLE_ACCOUNT, amount=loan_facades.penalty_income_receivable()),

            dict(name="Deposits Reference",  type="Asset", code=savings_codes.DEPOSITS_REFERENCE, amount=savings_facades.deposit_reference()),
            dict(name="Member Deposits",  type="Liability", code=savings_codes.DEPOSITS_CONTROL, amount=savings_facades.member_deposits()),
            dict(name="Savings Interest Expense", type="Expense", code=savings_codes.INTEREST_EXPENSE, amount=savings_facades.savings_interest_expense()),
            dict(name="Savings Fee Income", type="Income", code=savings_codes.SAVINGS_FEE_INCOME, amount=savings_facades.savings_fee_income()),
            dict(name="Overdraft Portfolio Control",  type="Asset", code=savings_codes.OVERDRAFT_PORTFOLIO_CONTROL, amount=savings_facades.overdraft_portfolio_control()),
            dict(name="Overdraft Interest Income", type="Income", code=savings_codes.OVERDRAFT_INTEREST_INCOME, amount=savings_facades.overdraft_interest_income()),
            dict(name="Overdraft Fee Income", type="Income", code=savings_codes.OVERDRAFT_FEE_INCOME, amount=savings_facades.overdraft_fee_income()),
            dict(name="Overdraft Write-off Expense", type="Expense", code=savings_codes.OVERDRAFT_WRITEOFF_EXPENSE, amount=savings_facades.overdraft_write_off_expense()),
        ]
    )

    context['accounts'] = sorted(context['accounts'], key=itemgetter('code'))

    return TemplateResponse(request, 'loans/loans_ledger.html', context)

@login_required
def journal_entries(request, gl_code=None):
    entries = GeneralLedgerEntry.objects.all()

    if gl_code is not None:
        entries.filter(account_gl_code=gl_code)

    return TemplateResponse(request, "accounting/journal_entries.html", {
        'entries': entries
    })


text:
#include <osapi.h>
#include <os_type.h>
#include <user_interface.h>
#include <espconn.h>
#include <gpio.h>
#include <mem.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define UREQ_ESP8266
#define UREQ_USE_FILESYSTEM

#include "../../../ureq.h"

// 6 works best
// this value was obtained experimentally
#define MAX_CONNS 6

struct HttpConnection {
    HttpRequest r;
    int id;
};

struct HttpConnection conns[MAX_CONNS];

//const char ssid[32] = "ssid";
//const char password[32] = "password";

bool gpioStatus = false;

// Data structure for the configuration of your wireless network.
// Will contain ssid and password for your network.
struct station_config stationConf;

/*
void ICACHE_FLASH_ATTR setGpio( int status ) {
    if (status == 0)
        gpio_output_set(BIT0, 0, BIT0, 0);
    else
        gpio_output_set(0, BIT0, BIT0, 0);
}

void ICACHE_FLASH_ATTR reverseGpio() {
  if (GPIO_REG_READ(GPIO_OUT_ADDRESS) & BIT0) {
        //Set GPIO2 to LOW
        gpio_output_set(0, BIT0, BIT0, 0);
    } else {
        //Set GPIO2 to HIGH
        gpio_output_set(BIT0, 0, BIT0, 0);
    }
}
*/

void ICACHE_FLASH_ATTR ssRecvCb(void *arg, char *data, unsigned short len) {
    char buf[64];
    int l;
    struct espconn *pespconn = (struct espconn *)arg;

    if (strlen(data) >= 1024) {
        // This is esp8266 specific, it just has too little memory
        // to answer all big requests with 413
        espconn_disconnect(pespconn);
        return;
    }

    HttpRequest r = ureq_init(data);

    ureq_run(&r);

    int i;
    for(i=0; i< MAX_CONNS-1; i++) {
        if (conns[i].id == 0)
            break;
        if (i == MAX_CONNS) {
            conns[0].id == 0;
            i = 0;
            break;
        }
    }

    conns[i].r = r;
    conns[i].id = pespconn->proto.tcp->remote_port;

    espconn_sent(pespconn, r.response.data, r.len);
    os_printf("Request %s from %d.%d.%d.%d. Status: %d. ID: %d.\n",
        r.url,
        pespconn->proto.tcp->remote_ip[0],
        pespconn->proto.tcp->remote_ip[1],
        pespconn->proto.tcp->remote_ip[2],
        pespconn->proto.tcp->remote_ip[3],
        r.response.code,
        conns[i].id);
}

struct HttpConnection *getHttpConnection(void *arg) {
    struct espconn *c = (struct espconn *)arg;
    int i;
    for(i=0; i<MAX_CONNS; i++) {
        if (conns[i].id == c->proto.tcp->remote_port)
            return &conns[i];
    }
    return NULL;
}

void ICACHE_FLASH_ATTR ssSentCb(void *arg) {
    struct espconn *pespconn = (struct espconn *)arg;
    struct HttpConnection *c = getHttpConnection(pespconn);

    if (c->r.complete == 1) {
        espconn_disconnect(pespconn);
        return;
    }

    ureq_run(&c->r);
    espconn_sent(pespconn, c->r.response.data, c->r.len);
    if (c->r.len < 1024) {
        espconn_disconnect(pespconn);
    }

}

void ICACHE_FLASH_ATTR ssDiscCb(void *arg) {
    struct espconn *pespconn = (struct espconn *)arg;
    struct HttpConnection *c = getHttpConnection(pespconn);
    if (!c) return;
    ureq_close(&c->r);
    c->id = 0;
}

void ICACHE_FLASH_ATTR ssConnCb(void *arg) {
    struct espconn *pespconn = (struct espconn *)arg;

    //printf("HEAP SIZE: %d\n", system_get_free_heap_size());

    if (pespconn->link_cnt > MAX_CONNS) {
        espconn_disconnect(pespconn);
        os_printf("Too many connections at once.\n");
        return;
    }

    espconn_regist_recvcb(pespconn, ssRecvCb);
    espconn_regist_sentcb(pespconn, ssSentCb);
    espconn_regist_disconcb(pespconn, ssDiscCb);
}

void ICACHE_FLASH_ATTR ssServerInit() {

    struct espconn * pSimpleServer;

    pSimpleServer = (struct espconn *)os_zalloc(sizeof(struct espconn));
    ets_memset( pSimpleServer, 0, sizeof( struct espconn ) );

    espconn_create( pSimpleServer );
    pSimpleServer->type = ESPCONN_TCP;
    pSimpleServer->state = ESPCONN_NONE;
    pSimpleServer->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp));
    pSimpleServer->proto.tcp->local_port = 80;

    //espconn_set_opt(pSimpleServer, ESPCONN_REUSEADDR);

    espconn_regist_connectcb(pSimpleServer, ssConnCb);
    espconn_accept(pSimpleServer);
    espconn_regist_time(pSimpleServer, 0, 0);
}

void ICACHE_FLASH_ATTR wifiInit() {
    // TODO: wifi configuration via http
    //os_memcpy(&stationConf.ssid, ssid, 32);
    //os_memcpy(&stationConf.password, password, 32);
    // STATION_MODE, SOFTAP_MODE or STATIONAP_MODE.
    wifi_set_opmode( STATION_MODE );
    //wifi_set_opmode( STATION_MODE );

    wifi_station_set_config(&stationConf);
}

char *s_home() {
    return "Hello World!";
}

char *s_get(HttpRequest *r) {
    /* This one shows how to handle GET parameters.
     * Please note, that ureq_get_param_value uses
     * common buffer for all operations, so store
     * copy data from it before calling it again */
    char *arg;

    strcpy(r->buffer, "data: ");
    arg = ureq_get_param_value(r, "data");
    strcat(r->buffer, arg);

    strcat(r->buffer, "
data2: ");
    arg = ureq_get_param_value(r, "data2");
    strcat(r->buffer, arg);

    return r->buffer;
}

char *s_post(HttpRequest *r) {
    if ( strcmp(UREQ_POST, r->type) != 0 )
        return  "Try requesting this page with POST method!
"
                "Feel free to use this form:
"
                "<form method='post'>"
                "Data: <input type='text' name='data'>
"
                "Data2: <input type='text' name='data2'>
"
                "<input type='submit' value='Submit'>"
                "</form>";

    char *arg;

    strcpy(r->buffer, "data: ");
    arg = ureq_post_param_value(r, "data");
    strcat(r->buffer, arg);

    strcat(r->buffer, "
data2: ");
    arg = ureq_post_param_value(r, "data2");
    strcat(r->buffer, arg);

    return r->buffer;
}

char *s_redirect(HttpRequest *r) {
    r->response.code = 302;
    r->response.header = "Location: /redirected";
    return "";
}

char *s_redirected() {
    return "Redirected from /redirect";
}

void user_init(void) {
    // Uart init
    uart_div_modify(0, UART_CLK_FREQ / 115200);
    os_printf("\nStarting...\n");

    int i;
    for(i=0; i<MAX_CONNS; i++) {
        // c field is used as indicator for free/used connection slots
        conns[i].id = 0;
    }

    // Add page to ureq
    //ureq_serve("/", s_home, "GET");
    ureq_serve("/get", s_get, "GET");
    ureq_serve("/post", s_post, "ALL");
    ureq_serve("/redirect", s_redirect, "GET");
    ureq_serve("/redirected", s_redirected, "GET");

    /*
    // Some gpio-related stuff
    gpio_init();
    //Set GPIO2 to output mode
    PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0);
    PIN_PULLUP_DIS(PERIPHS_IO_MUX_GPIO0_U);
    //Set GPIO2 high
    gpio_output_set(BIT0, 0, BIT0, 0);
    */

    // Wifi setup
    wifiInit();
    ssServerInit();

    // Print a message that we have completed user_init on debug uart
    os_printf("Ready.\n");
}


text:
package io.gravitee.am.management.handlers.management.api.provider;

import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

/**
 * @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com)
 * @author GraviteeSource Team
 */
@Provider
public class ClientErrorExceptionMapper extends AbstractExceptionMapper<ClientErrorException> {

    @Override
    public Response toResponse(final ClientErrorException e) {

        final Response.Status status = e.getResponse().getStatusInfo().toEnum();

        return Response
                .status(status)
                .type(MediaType.APPLICATION_JSON_TYPE)
                .entity(convert(e, status.getStatusCode()))
                .build();
    }
}