Encodes member percentile data to GRIB2 format.

        Returns:
            Series of GRIB2 messages
426444
def encode_grib2_percentile(self):
        
        lscale = 1e6
        grib_id_start = [7, 0, 14, 14, 2]
        gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32)
        lon_0 = self.proj_dict["lon_0"]
        sw_lon = self.grid_dict["sw_lon"]
        if lon_0 < 0:
            lon_0 += 360
        if sw_lon < 0:
            sw_lon += 360
        gdtmp1 = [1, 0, self.proj_dict['a'], 0, float(self.proj_dict['a']), 0, float(self.proj_dict['b']),
                  self.data.shape[-1], self.data.shape[-2], self.grid_dict["sw_lat"] * lscale,
                  sw_lon * lscale, 0, self.proj_dict["lat_0"] * lscale,
                  lon_0 * lscale,
                  self.grid_dict["dx"] * 1e3, self.grid_dict["dy"] * 1e3, 0b00000000, 0b01000000,
                  self.proj_dict["lat_1"] * lscale,
                  self.proj_dict["lat_2"] * lscale, -90 * lscale, 0]
        pdtmp1 = np.array([1,                # parameter category Moisture
                           31,               # parameter number Hail
                           4,                # Type of generating process Ensemble Forecast
                           0,                # Background generating process identifier
                           31,               # Generating process or model from NCEP
                           0,                # Hours after reference time data cutoff
                           0,                # Minutes after reference time data cutoff
                           1,                # Forecast time units Hours
                           0,                # Forecast time
                           1,                # Type of first fixed surface Ground
                           1,                # Scale value of first fixed surface
                           0,                # Value of first fixed surface
                           1,                # Type of second fixed surface
                           1,                # Scale value of 2nd fixed surface
                           0,                # Value of 2nd fixed surface
                           0,                # Derived forecast type
                           self.num_samples  # Number of ensemble members
                           ], dtype=np.int32)
        grib_objects = pd.Series(index=self.times, data=[None] * self.times.size, dtype=object)
        drtmp1 = np.array([0, 0, 4, 8, 0], dtype=np.int32)
        for t, time in enumerate(self.times):
            time_list = list(self.run_date.utctimetuple()[0:6])
            if grib_objects[time] is None:
                grib_objects[time] = Grib2Encode(0, np.array(grib_id_start + time_list + [2, 1], dtype=np.int32))
                grib_objects[time].addgrid(gdsinfo, gdtmp1)
            pdtmp1[8] = (time.to_pydatetime() - self.run_date).total_seconds() / 3600.0
            data = self.percentile_data[:, t] / 1000.0
            masked_data = np.ma.array(data, mask=data <= 0)
            for p, percentile in enumerate(self.percentiles):
                print("GRIB {3} Percentile {0}. Max: {1} Min: {2}".format(percentile, 
                                                                          masked_data[p].max(), 
                                                                          masked_data[p].min(),
                                                                          time))
                if percentile in range(1, 100):
                    pdtmp1[-2] = percentile
                    grib_objects[time].addfield(6, pdtmp1[:-1], 0, drtmp1, masked_data[p])
                else:
                    pdtmp1[-2] = 0
                    grib_objects[time].addfield(2, pdtmp1, 0, drtmp1, masked_data[p])
        return grib_objects
475210
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload):
		""""""

		timestamp = int(time())
		print("timestamp: " + str(timestamp))
		self.header = bytearray(HEADER_SIZE)
		#--------------
		# TO COMPLETE
		#--------------
		# Fill the header bytearray with RTP header fields

		#RTP-version filed(V), must set to 2
		#padding(P),extension(X),number of contributing sources(CC) and marker(M) fields all set to zero in this lab

		#Because we have no other contributing sources(field CC == 0),the CSRC-field does not exist
		#Thus the length of the packet header is therefore 12 bytes


			#Above all done in ServerWorker.py

		# ...
		#header[] =

		#header[0] = version + padding + extension + cc + seqnum + marker + pt + ssrc
		self.header[0] = version << 6
		self.header[0] = self.header[0] | padding << 5
		self.header[0] = self.header[0] | extension << 4
		self.header[0] = self.header[0] | cc
		self.header[1] = marker << 7
		self.header[1] = self.header[1] | pt

		self.header[2] = seqnum >> 8
		self.header[3] = seqnum

		self.header[4] = (timestamp >> 24) & 0xFF
		self.header[5] = (timestamp >> 16) & 0xFF
		self.header[6] = (timestamp >> 8) & 0xFF
		self.header[7] = timestamp & 0xFF

		self.header[8] = ssrc >> 24
		self.header[9] = ssrc >> 16
		self.header[10] = ssrc >> 8
		self.header[11] = ssrc


		# Get the payload from the argument
		# self.payload = ...
		self.payload = payload
1120074
def makeBulkAnglePacket(info):
	
	addr = le(xl320.XL320_GOAL_POSITION)
	data = []
	for pkt in info:
		data.append(pkt[0])  # ID
		data.append(addr[0])  # LSB
		data.append(addr[1])  # MSB
		data.append(2)  # 2 bytes
		data.append(0)
		angle = le(int(pkt[1]/300*1023))
		data.append(angle[0])  # LSB
		data.append(angle[1])  # MSB

	ID = xl320.XL320_BROADCAST_ADDR
	instr = xl320.XL320_BULK_WRITE
	pkt = makePacket(ID, instr, None, data)  # create packet

	return pkt
407941
def encode_timeseries_put(self, tsobj):
        
        req = riak.pb.riak_ts_pb2.TsPutReq()
        req.table = str_to_bytes(tsobj.table.name)

        if tsobj.columns:
            raise NotImplementedError("columns are not implemented yet")

        if tsobj.rows and isinstance(tsobj.rows, list):
            for row in tsobj.rows:
                tsr = req.rows.add()  # NB: type TsRow
                if not isinstance(row, list):
                    raise ValueError("TsObject row must be a list of values")
                for cell in row:
                    tsc = tsr.cells.add()  # NB: type TsCell
                    self.encode_to_ts_cell(cell, tsc)
        else:
            raise RiakError("TsObject requires a list of rows")

        mc = riak.pb.messages.MSG_CODE_TS_PUT_REQ
        rc = riak.pb.messages.MSG_CODE_TS_PUT_RESP
        return Msg(mc, req.SerializeToString(), rc)
1310841
def _encode_message_set(cls, messages):
        
        message_set = []
        for message in messages:
            encoded_message = KafkaProtocol._encode_message(message)
            message_set.append(struct.pack('>qi%ds' % len(encoded_message), 0,
                                           len(encoded_message),
                                           encoded_message))
        return b''.join(message_set)
280422
def store_text(x, y, dx, dy, grbit1, grbit2, rotation = 0x00)# :nodoc:
    record   = 0x1025            # Record identifier.
    length   = 0x0020            # Number of bytes to follow.
    at       = 0x02              # Horizontal alignment.
    vat      = 0x02              # Vertical alignment.
    wBkgMode = 0x0001            # Background display.
    rgbText  = 0x0000            # Text RGB colour.
    # x                          # Text x-pos.
    # y                          # Text y-pos.
    # dx                         # Width.
    # dy                         # Height.
    # grbit1                     # Option flags.
    icvText  = 0x004D            # Auto Colour.
    # grbit2                     # Show legend.
    # rotation                   # Show value.

    header = [record, length].pack('vv')
    data  = [at].pack('C')
    data += [vat].pack('C')
    data += [wBkgMode].pack('v')
    data += [rgbText].pack('V')
    data += [x].pack('V')
    data += [y].pack('V')
    data += [dx].pack('V')
    data += [dy].pack('V')
    data += [grbit1].pack('v')
    data += [icvText].pack('v')
    data += [grbit2].pack('v')
    data += [rotation].pack('v')

    append(header, data)
  end
722022
def encode(msg):
    
    msg = bytes(msg)
    return END + msg.replace(ESC, ESC + ESC_ESC).replace(END, ESC + ESC_END) + END
380785
def to_string(self):
        
        return "PartitionContext({}{}{}{})".format(self.eh_path,
                                                   self.consumer_group_name,
                                                   self.partition_id,
                                                   self.sequence_number)
386492
def encode(self):
        
        if self.mode == tables.modes['alphanumeric']:
            encoded = self.encode_alphanumeric()
        elif self.mode == tables.modes['numeric']:
            encoded = self.encode_numeric()
        elif self.mode == tables.modes['binary']:
            encoded = self.encode_bytes()
        elif self.mode == tables.modes['kanji']:
            encoded = self.encode_kanji()
        return encoded
263489
def to_message(base):
    
    ctype, ctparams = base.get_content_type()

    if not ctype:
        if base.parts:
            ctype = 'multipart/mixed'
        else:
            ctype = 'text/plain'

    maintype, subtype = ctype.split('/')
    is_text = maintype == 'text'
    is_multipart = maintype == 'multipart'

    if base.parts and not is_multipart:
        raise RuntimeError(
            'Content type should be multipart, not %r' % ctype
            )

    body = base.get_body()
    ctenc = base.get_transfer_encoding()
    charset = ctparams.get('charset')

    if is_multipart:
        out = MIMEMultipart(subtype, **ctparams)
    else:
        out = MIMENonMultipart(maintype, subtype, **ctparams)
        if ctenc:
            out['Content-Transfer-Encoding'] = ctenc
        if isinstance(body, text_type):
            if not charset:
                if is_text:
                    charset, _ = best_charset(body)
                else:
                    charset = 'utf-8'
            if PY2:
                body = body.encode(charset)
            else: # pragma: no cover
                body = body.encode(charset, 'surrogateescape')
        if body is not None:
            if ctenc:
                body = transfer_encode(ctenc, body)
            if not PY2: # pragma: no cover
                body = body.decode(charset or 'ascii', 'replace')
        out.set_payload(body, charset) 

    for k in base.keys(): # returned sorted
        value = base[k]
        if not value:
            continue
        out[k] = value

    cdisp, cdisp_params = base.get_content_disposition()

    if cdisp:
        out.add_header('Content-Disposition', cdisp, **cdisp_params)

    # go through the children
    for part in base.parts:
        sub = to_message(part)
        out.attach(sub)

    return out
806810
def encodeUcs2(text):
    
    result = bytearray()
    for b in map(ord, text):
        result.append(b >> 8)
        result.append(b & 0xFF)
    return result
192788
def encode_x(self, data):
        
        encoded = OrderedDict()
        if self.multiprocessing:
            pool = multiprocessing.Pool(self.workers)
            results = []
            for encoder in self.encoders:
                results.append((encoder, pool.apply_async(self.transform, (encoder, data))))

            for encoder, result in results:
                self.merged_transformed(encoded, encoder, result.get())

        else:
            for encoder in self.encoders:
                self.merged_transformed(encoded, encoder, self.transform(encoder, data), append_twin=False)
                if encoder.twin:
                    self.merged_transformed(encoded, encoder, self.transform(encoder, data, append_twin = True), append_twin=True)

        for column in self.index:
            encoded[column] = self.read_column(data, column)

        # Using a DataFrame as a container temporarily requires double the memory,
        # as pandas copies all data on __init__. This is justified by having a
        # type supported by all dependent libraries (heterogeneous dict is not)
        dataframe = pandas.DataFrame(encoded)
        if self.index:
            dataframe.set_index(self.index)
        return dataframe
410087
def encode(binary_data):
	'''
	
	'''
	framed_data = frame(binary_data)

	# set volume to 1/2, preceed packet with 1/20 s silence to allow for startup glitches
	for sample in itertools.chain(
		audiogen.silence(1.05), 
		multiply(modulate(framed_data), constant(0.5)), 
		audiogen.silence(1.05), 
	):
		yield sample
594415
def percent_encode_non_ascii_headers(self, encoding='UTF-8'):
        
        def do_encode(m):
            return "*={0}''".format(encoding) + quote(to_native_str(m.group(1)))

        for index in range(len(self.headers) - 1, -1, -1):
            curr_name, curr_value = self.headers[index]
            try:
                # test if header is ascii encodable, no action needed
                curr_value.encode('ascii')
            except:
                new_value = self.ENCODE_HEADER_RX.sub(do_encode, curr_value)
                if new_value == curr_value:
                    new_value = quote(curr_value)

                self.headers[index] = (curr_name, new_value)
494494
def encode(self):
		

		buff = _GNTPBuffer()

		buff.writeln(self._format_info())

		#Headers
		for k, v in self.headers.items():
			buff.writeheader(k, v)
		buff.writeln()

		#Notifications
		if len(self.notifications) > 0:
			for notice in self.notifications:
				for k, v in notice.items():
					buff.writeheader(k, v)
				buff.writeln()

		#Resources
		for resource, data in self.resources.items():
			buff.writeheader('Identifier', resource)
			buff.writeheader('Length', len(data))
			buff.writeln()
			buff.write(data)
			buff.writeln()
			buff.writeln()

		return buff.getvalue()
1048672
def _format_info(data):
    '''
    
    '''
    # Put GECOS info into a list
    gecos_field = salt.utils.stringutils.to_unicode(data.pw_gecos).split(',', 4)
    # Make sure our list has at least five elements
    while len(gecos_field) < 5:
        gecos_field.append('')

    return {'gid': data.pw_gid,
            'groups': list_groups(data.pw_name),
            'home': data.pw_dir,
            'name': data.pw_name,
            'passwd': data.pw_passwd,
            'shell': data.pw_shell,
            'uid': data.pw_uid,
            'fullname': gecos_field[0],
            'roomnumber': gecos_field[1],
            'workphone': gecos_field[2],
            'homephone': gecos_field[3],
            'other': gecos_field[4]}
1274942
def ias60(msg):
    
    d = hex2bin(data(msg))

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

    ias = bin2int(d[13:23])    # kts
    return ias