Computes the altitude from DF4 or DF20 message, bit 20-32.
    credit: @fbyrkjeland

    Args:
        msg (String): 28 bytes hexadecimal message string

    Returns:
        int: altitude in ft
353247
def altcode(msg):
    

    if df(msg) not in [0, 4, 16, 20]:
        raise RuntimeError("Message must be Downlink Format 0, 4, 16, or 20.")

    # Altitude code, bit 20-32
    mbin = hex2bin(msg)

    mbit = mbin[25]   # M bit: 26
    qbit = mbin[27]   # Q bit: 28


    if mbit == '0':         # unit in ft
        if qbit == '1':     # 25ft interval
            vbin = mbin[19:25] + mbin[26] + mbin[28:32]
            alt = bin2int(vbin) * 25 - 1000
        if qbit == '0':     # 100ft interval, above 50175ft
            C1 = mbin[19]
            A1 = mbin[20]
            C2 = mbin[21]
            A2 = mbin[22]
            C4 = mbin[23]
            A4 = mbin[24]
            # _ = mbin[25]
            B1 = mbin[26]
            # D1 = mbin[27]     # always zero
            B2 = mbin[28]
            D2 = mbin[29]
            B4 = mbin[30]
            D4 = mbin[31]

            graystr =  D2 + D4 + A1 + A2 + A4 + B1 + B2 + B4 + C1 + C2 + C4
            alt = gray2alt(graystr)

    if mbit == '1':         # unit in meter
        vbin = mbin[19:25] + mbin[26:31]
        alt = int(bin2int(vbin) * 3.28084)  # convert to ft

    return alt
1310227
public static int d(String msg) {
        // This is a quick check to avoid the expensive stack trace reflection.
        if (!activated) {
            return 0;
        }

        String caller = LogHelper.getCaller();
        if (caller != null) {
            return d(caller, msg);
        }
        return 0;
    }
1349350
def _checksum(self, msg):
        
        def carry_around_add(a, b):
            c = a + b
            return (c & 0xffff) + (c >> 16)

        s = 0
        for i in range(0, len(msg), 2):
            w = (msg[i] << 8) + msg[i + 1]
            s = carry_around_add(s, w)
        s = ~s & 0xffff

        return s
582256
def _read_message(self):
    
    size = int(self.buf.read_line().decode("utf-8"))
    return self.buf.read(size).decode("utf-8")
730041
def recv_msg(self):
        ''''''
        if self._index >= self._count:
            return None
        m = self._msgs[self._index]
        type = m.get_type()
        self._index += 1
        self.percent = (100.0 * self._index) / self._count
        self.messages[type] = m
        self._timestamp = m._timestamp

        if self._flightmode_index < len(self._flightmodes):
            (mode, tstamp, t2) = self._flightmodes[self._flightmode_index]
            if m._timestamp >= tstamp:
                self.flightmode = mode
                self._flightmode_index += 1

        self.check_param(m)
        return m
73820
def alt40mcp(msg):
    
    d = hex2bin(data(msg))

    if d[0] == '0':
        return None

    alt = bin2int(d[1:13]) * 16    # ft
    return alt
240771
def mavlink_packet(self, msg):
        ''''''
        type = msg.get_type()
        master = self.master
        # add some status fields
        if type == 'TERRAIN_REQUEST':
            self.current_request = msg
            self.sent_mask = 0
            self.requests_received += 1
        elif type == 'TERRAIN_REPORT':
            if (msg.lat == self.check_lat and
                msg.lon == self.check_lon and
                (self.check_lat != 0 or self.check_lon != 0)):
                print(msg)
                self.check_lat = 0
                self.check_lon = 0
147894
async def load_message(self, msg_type, msg=None):
        
        msg = msg_type() if msg is None else msg
        fields = msg_type.f_specs() if msg_type else msg.__class__.f_specs()
        for field in fields:
            await self.message_field(msg, field)

        return msg
354957
def category(msg):
    

    if common.typecode(msg) < 1 or common.typecode(msg) > 4:
        raise RuntimeError("%s: Not a identification message" % msg)

    msgbin = common.hex2bin(msg)
    return common.bin2int(msgbin[5:8])
712482
def parse(self, msg):
        
        #init
        dictValues = HL7Dict(self.tersersep)
        msg_ = msg.strip('\r\n ')

        # extracts separator defined in the message itself
        self.extractSeparators(dictValues, msg_)
        msg_ = msg_.replace('\r', '\n')
        lines = msg_.split('\n')
        lineNumber = 1

        # build the map of segments
        segmentNameCount, lineMap = self.buildSegmentMap(lines)
        dictValues.setSegmentsMap(segmentNameCount, lineMap)

        # Parse each line of the message : 1 line = 1 segment
        for line in lines:
            dictValues.currentLineNumber = lineNumber
            self.extractValues(dictValues, line)
            lineNumber += 1

        return dictValues
432161
def next_message(self):
        ''''''

        msg = self.msg
        if msg is None:
            self.paused = True

        if self.paused:
            self.root.after(100, self.next_message)
            return

        try:
            speed = float(self.playback.get())
        except:
            speed = 0.0
        timestamp = getattr(msg, '_timestamp')

        now = time.strftime("%H:%M:%S", time.localtime(timestamp))
        self.clock.configure(text=now)

        if speed == 0.0:
            self.root.after(200, self.next_message)
        else:
            self.root.after(int(1000*(timestamp - self.last_timestamp) / speed), self.next_message)
        self.last_timestamp = timestamp

        while True:
            self.msg = self.mlog.recv_match(condition=args.condition)
            if self.msg is None and self.mlog.f.tell() > self.filesize - 10:
                self.paused = True
                return
            if self.msg is not None and self.msg.get_type() != "BAD_DATA":
                break

        pos = float(self.mlog.f.tell()) / self.filesize
        self.slider.set(pos)
        self.filepos = self.slider.get()

        if msg.get_type() != "BAD_DATA":
            for m in self.mout:
                m.write(msg.get_msgbuf())

        if msg.get_type() == "GPS_RAW":
            self.fdm.set('latitude', msg.lat, units='degrees')
            self.fdm.set('longitude', msg.lon, units='degrees')
            if args.gpsalt:
                self.fdm.set('altitude', msg.alt, units='meters')

        if msg.get_type() == "GPS_RAW_INT":
            self.fdm.set('latitude', msg.lat/1.0e7, units='degrees')
            self.fdm.set('longitude', msg.lon/1.0e7, units='degrees')
            if args.gpsalt:
                self.fdm.set('altitude', msg.alt/1.0e3, units='meters')

        if msg.get_type() == "VFR_HUD":
            if not args.gpsalt:
                self.fdm.set('altitude', msg.alt, units='meters')
            self.fdm.set('num_engines', 1)
            self.fdm.set('vcas', msg.airspeed, units='mps')

        if msg.get_type() == "ATTITUDE":
            self.fdm.set('phi', msg.roll, units='radians')
            self.fdm.set('theta', msg.pitch, units='radians')
            self.fdm.set('psi', msg.yaw, units='radians')
            self.fdm.set('phidot', msg.rollspeed, units='rps')
            self.fdm.set('thetadot', msg.pitchspeed, units='rps')
            self.fdm.set('psidot', msg.yawspeed, units='rps')

        if msg.get_type() == "RC_CHANNELS_SCALED":
            self.fdm.set("right_aileron", msg.chan1_scaled*0.0001)
            self.fdm.set("left_aileron", -msg.chan1_scaled*0.0001)
            self.fdm.set("rudder",        msg.chan4_scaled*0.0001)
            self.fdm.set("elevator",      msg.chan2_scaled*0.0001)
            self.fdm.set('rpm',           msg.chan3_scaled*0.01)

        if msg.get_type() == 'STATUSTEXT':
            print("APM: %s" % msg.text)

        if msg.get_type() == 'SYS_STATUS':
            self.flightmode.configure(text=self.mlog.flightmode)

        if msg.get_type() == "BAD_DATA":
            if mavutil.all_printable(msg.data):
                sys.stdout.write(msg.data)
                sys.stdout.flush()

        if self.fdm.get('latitude') != 0:
            for f in self.fgout:
                f.write(self.fdm.pack())
1335295
def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'):
        
        latitude = "%s %s" % (
            format_degrees(abs(self.latitude), symbols={
                'deg': deg_char, 'arcmin': min_char, 'arcsec': sec_char
            }),
            self.latitude >= 0 and 'N' or 'S'
        )
        longitude = "%s %s" % (
            format_degrees(abs(self.longitude), symbols={
                'deg': deg_char, 'arcmin': min_char, 'arcsec': sec_char
            }),
            self.longitude >= 0 and 'E' or 'W'
        )
        coordinates = [latitude, longitude]

        if altitude is None:
            altitude = bool(self.altitude)
        if altitude:
            if not isinstance(altitude, string_compare):
                altitude = 'km'
            coordinates.append(self.format_altitude(altitude))

        return ", ".join(coordinates)
377588
def dmstodd(self, dms):
        
        size = len(dms)
        letters = 'WENS'
        is_annotated = False

        try:
            float(dms)
        except ValueError:
            for letter in letters:
                if letter in dms.upper():
                    is_annotated = True
                    break
            if not is_annotated:
                raise core.RTreeError("unable to parse '%s' to decimal degrees" % dms)
        is_negative = False
        if is_annotated:
            dms_upper = dms.upper()
            if 'W' in dms_upper or 'S' in dms_upper:
                is_negative = True
        else:
            if dms < 0:
                is_negative = True

        if is_annotated:
            bletters = letters.encode(encoding='utf-8')
            bdms = dms.encode(encoding = 'utf-8')
            dms = bdms.translate(None, bletters).decode('ascii')

            # bletters = bytes(letters, encoding='utf-8')
            # bdms = bytes(dms, encoding='utf-8')
            # dms = bdms.translate(None, bletters).decode('ascii')

            # dms = dms.translate(None, letters) # Python 2.x version

        pieces = dms.split(".")
        D = 0.0
        M = 0.0
        S = 0.0
        divisor = 3600.0
        if len(pieces) == 1:
            S = dms[-2:]
            M = dms[-4:-2]
            D = dms[:-4]
        else:
            S = '{0:s}.{1:s}'.format (pieces[0][-2:], pieces[1])
            M = pieces[0][-4:-2]
            D = pieces[0][:-4]

        DD = float(D) + float(M)/60.0 + float(S)/divisor
        if is_negative:
            DD = DD * -1.0
        return DD
309021
def prep_message(msg):
    
    if six.PY3:
        msg_out = msg.as_string().encode("utf-8")
    else:
        msg_out = msg.as_string()

    our_len = len(msg_out) + 4
    size = struct.pack('>L', our_len)
    # why the hell is this "bytes" on python3?

    return size + msg_out
91322
def extract_altitude(self):
        '''
        
        '''
        altitude_ref = {
            0: 1,
            1: -1}
        fields = ['GPS GPSAltitude', 'EXIF GPS GPSAltitude']
        refs = ['GPS GPSAltitudeRef', 'EXIF GPS GPSAltitudeRef']
        altitude, _ = self._extract_alternative_fields(fields, 0, float)
        ref = 0 if not any([True for x in refs if x in self.tags]) else [
            self.tags[x].values for x in refs if x in self.tags][0][0]
        return altitude * altitude_ref[ref]
1261539
def getMessage(self):
        
        msg = str(self.msg)
        if self.args:
            msg = msg % self.args

        if platform.system().lower() == 'windows' or self.levelno < 10:
            return msg
        elif self.levelno >= 50:
            return utils.return_colorized(msg, 'critical')
        elif self.levelno >= 40:
            return utils.return_colorized(msg, 'error')
        elif self.levelno >= 30:
            return utils.return_colorized(msg, 'warn')
        elif self.levelno >= 20:
            return utils.return_colorized(msg, 'info')
        else:
            return utils.return_colorized(msg, 'debug')
478928
def messageReceived(self, message):
        
        i = message.index(b'')
        assert i > 0
        (routingInfo, msgId, payload) = (
            message[:i - 1], message[i - 1], message[i + 1:])
        msgParts = payload[0:]
        self._routingInfo[msgId] = routingInfo
        self.gotMessage(msgId, *msgParts)