text:
package fakenet

import (
	"io/ioutil"
	"testing"
	"time"

	"golang.org/x/net/context"
)

func TestDuplex(t *testing.T) {
	defer time.AfterFunc(time.Second, func() { panic("too long") }).Stop()
	wantReq := "hello server!"
	wantResp := "hello client!"

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	client, server := newDuplex(ctx)

	go func() {

		req, err := ioutil.ReadAll(server)
		if err != nil {
			panic(err)
		}
		if want, got := wantReq, string(req); want != got {
			t.Errorf("want client request %q, got %q", want, got)
		}

		_, err = server.Write([]byte(wantResp))
		if err != nil {
			panic(err)
		}
		server.Close()
	}()

	_, err := client.Write([]byte(wantReq))
	if err != nil {
		panic(err)
	}
	client.Close()

	resp, err := ioutil.ReadAll(client)
	if err != nil {
		panic(err)
	}
	if want, got := wantResp, string(resp); want != got {
		t.Errorf("want server response %q, got %q", want, got)
	}
	t.Logf("want=%q", wantResp)
	t.Logf(" got=%q", string(resp))

}


text:
#ifndef CONTROL_ESTIMATOR_ESTIMATOR_TYPES_H_
#define CONTROL_ESTIMATOR_ESTIMATOR_TYPES_H_

#include <stdint.h>

#include "avionics/common/plc_messages.h"
#include "common/c_math/kalman.h"
#include "common/c_math/mat3.h"
#include "common/c_math/quaternion.h"
#include "common/c_math/vec2.h"
#include "common/c_math/vec3.h"
#include "control/experiments/experiment_types.h"
#include "control/sensor_types.h"
#include "control/system_types.h"

typedef enum {
  kEstimatorVelocitySolutionTypeGps,
  kEstimatorVelocitySolutionTypeGlas,
  kEstimatorVelocitySolutionTypeDeadReckoned
} EstimatorVelocitySolutionType;

typedef enum {
  kEstimatorPosMeasurementTypeForceSigned = -1,
  kEstimatorPosMeasurementBaro,
  kEstimatorPosMeasurementGps,
  kEstimatorPosMeasurementGlas,
  kNumEstimatorPosMeasurements
} EstimatorPosMeasType;

typedef enum {
  kEstimatorVelMeasurementTypeForceSigned = -1,
  kEstimatorVelMeasurementGps,
  kEstimatorVelMeasurementGlas,
  kNumEstimatorVelMeasurements
} EstimatorVelMeasType;

typedef enum {
  kAttitudeStateLabelForceSigned = -1,
  kAttitudeStateAttX,
  kAttitudeStateAttY,
  kAttitudeStateAttZ,
  kAttitudeStateBiasGX,
  kAttitudeStateBiasGY,
  kAttitudeStateBiasGZ,
  kNumAttitudeStates
} AttitudeStateLabel;

typedef enum {
  kAttitudeNoiseLabelForceSigned = -1,
  kAttitudeNoiseGyroX,
  kAttitudeNoiseGyroY,
  kAttitudeNoiseGyroZ,
  kAttitudeNoiseBiasGRwX,
  kAttitudeNoiseBiasGRwY,
  kAttitudeNoiseBiasGRwZ,
  kNumAttitudeNoises
} AttitudeNoiseLabel;

typedef enum {
  kPositionStateLabelForceSigned = -1,
  kPositionStateVelX,
  kPositionStateVelY,
  kPositionStateVelZ,
  kPositionStatePosX,
  kPositionStatePosY,
  kPositionStatePosZ,
  kNumPositionStates
} PositionStateLabel;

typedef enum {
  kPositionNoiseLabelForceSigned = -1,
  kPositionNoiseAccelX,
  kPositionNoiseAccelY,
  kPositionNoiseAccelZ,
  kNumPositionNoises
} PositionNoiseLabel;

typedef enum {
  kMahonyVecForceSigned = -1,
  kMahonyVecMag,
  kMahonyVecAppWind,
  kMahonyVecGravity,
  kNumMahonyVecs
} MahonyVecType;

typedef struct {
  Quat q;
  Vec3 bias;
  Vec3 ef[kNumMahonyVecs];
} MahonyState;

typedef enum {
  kApparentWindSolutionTypeForceSigned = -1,
  kApparentWindSolutionTypeInertialAndWind,
  kApparentWindSolutionTypeMixed,
  kApparentWindSolutionTypeFixedAngles,
  kApparentWindSolutionTypeLoadcell,
  kApparentWindSolutionTypePitot,
  kApparentWindSolutionTypeComplementary,
  kNumApparentWindSolutionTypes
} ApparentWindSolutionType;

typedef enum {
  kWindSolutionTypeForceSigned = -1,
  kWindSolutionTypeNone,
  kWindSolutionTypeGroundStationSensor,
  kWindSolutionTypeHardcoded,
  kWindSolutionTypePitotAndInertial,
  kNumWindSolutionTypes
} WindSolutionType;

typedef struct {
  // Last valid measurements for each GSG axis [rad].
  GsgData last_valid_gsg;
  // Last valid levelwind elevation measurement [rad].
  double last_valid_levelwind_ele;
  // Last valid perch azimuth measurement [rad].
  double last_valid_perch_azi;
} EstimatorEncodersState;

typedef struct {
  GsgData gsg;
  bool gsg_azi_valid;
  bool gsg_ele_valid;
  double levelwind_ele;
  bool levelwind_ele_valid;
  double perch_azi;
  bool perch_azi_valid;
} EncodersEstimate;

typedef struct {
  double pitot_upwash_alpha_bias;
  double pitot_upwash_alpha_scale;
  double v_low, v_high;
  double ang_est_low, ang_est_high;
  double ang_fly_low, ang_fly_high;
  double fc_v;
  double fc_alpha;
  double fc_beta;
  double fc_comp;
} EstimatorApparentWindParams;

typedef struct {
  // Apparent wind estimate with individually filtered airspeed [m/s],
  // angle-of-attach [rad] and side-slip-angle [rad].
  ApparentWindSph sph_f_z1;
  Vec3 apparent_wind_b_lpf_z1;
  Vec3 apparent_wind_b_hpf_z1;
} EstimatorApparentWindState;

typedef struct {
  Quat q_g2b_0;
  double coarse_init_kp;
  double coarse_init_kp_acc;
  double coarse_init_kp_mag;
  double sigma_attitude_0;
  double sigma_gyro_bias_0;
  double sigma_gyro_noise;
  double sigma_gyro_bias_instability;
  double gyro_bias_time_constant;
  double nominal_angle_of_attack;
  double nominal_angle_of_sideslip;
  double v_app_relative_err;
  double v_app_relative_err_min_airspeed;
  double mag_relative_err;
  double plumb_bob_relative_err;
  double plumb_bob_g_err_scale;
  double max_gyro_bias;
  double fc_acc;
  bool enable_apparent_wind_correction;
  bool enable_gps_vector_correction;
  double wing_port_to_star_sigma;
  double wing_wingtip_to_center_sigma;
  double wing_vector_sigma_ratio;
  double max_gps_position_sigma;
  double max_gps_vector_error;
  double gps_vector_relative_err;
  int32_t gps_vector_timeout_cycles;
  double max_gps_compass_sigma;
} EstimatorAttitudeParams;

typedef struct {
  // Kalman filter innovation.
  double dz;
  // Kalman filter innovation covariance.
  double pzz;
  // Kalman filter error state correction.
  double dx_plus[kNumAttitudeStates];
} EstimatorAttitudeCorrection;

typedef struct {
  EstimatorAttitudeCorrection x;
  EstimatorAttitudeCorrection y;
  EstimatorAttitudeCorrection z;
} EstimatorAttitudeCorrection3;

typedef struct {
  EstimatorAttitudeCorrection3 gps_port_to_star;
  EstimatorAttitudeCorrection3 gps_port_to_center;
  EstimatorAttitudeCorrection3 gps_star_to_center;
  EstimatorAttitudeCorrection3 apparent_wind;
  EstimatorAttitudeCorrection3 gravity_vector;
  EstimatorAttitudeCorrection3 magnetometer;
  EstimatorAttitudeCorrection3 gps_compass;
} EstimatorAttitudeCorrections;

typedef struct {
  // Cycles [#] since last GPS vector correction.
  int32_t gps_vector_timer_cycles;
  // Gyro biases [rad/s].
  Vec3 gyro_bias;
  // Quaternion encoding the rotation from g coordinates to b coordinates.
  Quat q_g2b;
  // UD factorization of the Kalman filter covariance.  The first
  // three error states are given by the attitude error encoded as an
  // Euler vector.  The remaining three states are for the gyro
  // biases.
  double ud[(kNumAttitudeStates + 1) * kNumAttitudeStates / 2];
} EstimatorAttitudeFilterState;

typedef struct {
  // Filter on the accelerometer vector before using it as a vector measurement.
  Vec3 acc_f_z1;
  EstimatorAttitudeFilterState filter;
} EstimatorAttitudeState;

typedef struct { int32_t num_debounce; } EstimatorGroundStationParams;

typedef struct {
  // Indicates that the fixed position has been detected.
  bool position_fixed;
  // Filtered ground station GPS position [m].
  Vec3 pos_ecef;
  // Rotatation matrix from ECEF to g.
  Mat3 dcm_ecef2g;

  int32_t mode_counts[kNumGroundStationModes];
  GroundStationMode last_confirmed_mode;
  uint8_t last_valid_transform_stage;
} EstimatorGroundStationState;

typedef struct {
  int32_t joystick_num_debounce;
  double fc_throttle;
  double fc_pitch;
} EstimatorJoystickParams;

typedef struct {
  // Most recent valid data.
  JoystickData last_valid_data;
  // State of the throttle filter.
  double throttle_f_z1;
  // State of the pitch filter.
  double pitch_f_z1;
  // Counter for debouncing the joystick release.
  int32_t debounce_joystick_release_count;
  // Joystick switch position at the previous time step.
  JoystickSwitchPositionLabel switch_position_z1;
  // Counters for debounching the joystick switch position.
  int32_t switch_up_count, switch_mid_count, switch_down_count;
} EstimatorJoystickState;

typedef struct {
  double max_angle_vel;
  double fc_angle_vel;
  double damping_ratio_angle_vel;
} EstimatorPerchAziParams;

typedef struct {
  // Last perch azimuth angle [rad] recorded without any faults.
  double last_valid_perch_azi_angle;
  // State of the second order derivative filter used to estimate the
  // perch azimuth angular rate.
  double angle_vel_filter_state[2];
} EstimatorPerchAziState;

typedef struct {
  double min_relative_sigma_pos_g;
  double sigma_per_weight_over_tension_ratio;
  double max_weight_over_tension_ratio;
  double gsg_bias_fc;
  double gsg_bias_tension_lim;
  GsgData bias_low, bias_high;
} EstimatorPositionGlasParams;

typedef struct {
  int32_t outage_hold_num;
  double min_disagreement_distance_hover;
  double min_disagreement_distance;
  double disagreement_hysteresis_ratio;
  double sigma_hysteresis;
  double relative_sigma_threshold;
} EstimatorPositionGpsParams;

typedef struct {
  BoundedKalman1dEstimatorParams kalman_est;
  double sigma_Xg_z_bias_0;
  double sigma_Xg_z;
} EstimatorPositionBaroParams;

typedef struct {
  double sigma_vel_g_0;
  double gps_sigma_multiplier;
  double min_gps_sigma_vel_g;
  double min_gps_sigma_pos_g;
  double sigma_wing_accel_hover;
  double sigma_wing_accel_dynamic;
  bool baro_enabled;
  bool glas_enabled;
  int32_t gps_position_timeout_cycles;
} EstimatorPositionFilterParams;

typedef struct {
  EstimatorPositionBaroParams baro;
  EstimatorPositionFilterParams filter;
  EstimatorPositionGlasParams glas;
  EstimatorPositionGpsParams gps;
} EstimatorPositionParams;

typedef struct {
  // Kalman filter innovation.
  double dz;
  // Kalman filter innovation covariance.
  double pzz;
  // Kalman filter error state correction.
  double dx_plus[kNumPositionStates];
} EstimatorPositionCorrection;

typedef struct {
  EstimatorPositionCorrection x;
  EstimatorPositionCorrection y;
  EstimatorPositionCorrection z;
} EstimatorPositionCorrection3;

typedef struct {
  // Use last_center_gps_receiver to determine the receiver identity of the
  // center channel.
  EstimatorPositionCorrection3 gps_center_position;
  EstimatorPositionCorrection3 gps_center_velocity;
  EstimatorPositionCorrection3 gps_port_position;
  EstimatorPositionCorrection3 gps_port_velocity;
  EstimatorPositionCorrection3 gps_star_position;
  EstimatorPositionCorrection3 gps_star_velocity;
  EstimatorPositionCorrection3 glas_position;
  EstimatorPositionCorrection baro;
} EstimatorPositionCorrections;

typedef struct {
  // Cycles [#] since last GPS position correction.
  int32_t gps_position_timer_cycles;
  // Position [m] estimate.
  Vec3 pos_g;
  // Velocity [m/s] estimate resolve in g coordinates.
  Vec3 vel_g;
  // UD factorization of the Kalman filter covariance.  The first
  // three error states are given by the velocity and the next three
  // are the position error both resolved in the g coordinate system.
  double ud[(kNumPositionStates + 1) * kNumPositionStates / 2];
} EstimatorPositionFilterState;

typedef struct {
  // Number [#] of control cycles to ignore GPS data.
  int32_t outage_timer;
  // Last time of week [ms], used to detect new data.
  int32_t time_of_week_z1;
} EstimatorPositionGpsState;

typedef struct {
  // Last valid wing g-frame z estimate [m].
  double last_valid_Xg_z;
  // Estimate of the bias [m].
  double Xg_z_bias;
  // Covariance for the bias [m^2].
  double cov_Xg_z_bias;
} EstimatorPositionBaroState;

typedef struct {
  // Last valid wing position [m] and velocity [m/s].
  Vec3 last_valid_wing_pos_g;
  // Biases [rad] for the GSG angles.
  GsgData gsg_bias;
} EstimatorPositionGlasState;

typedef struct {
  // Barometric altitude state.
  EstimatorPositionBaroState baro;
  // GLAS estimate state.
  EstimatorPositionGlasState glas;
  // Center GPS receiver chosen on the previous iteration.
  WingGpsReceiverLabel last_center_gps_receiver;
  // GPS estimate state.
  EstimatorPositionGpsState gps[kNumWingGpsReceivers];
  // Adaptive complementary filter state.
  EstimatorPositionFilterState filter;
} EstimatorPositionState;

typedef struct {
  // Only use the ground station pose estimate if this flag is true.
  bool valid;
  // Position [m] of the ground-station origin in ECEF.
  Vec3 pos_ecef;
  // Rotation matrix from ECEF to g.
  Mat3 dcm_ecef2g;
} GroundStationPoseEstimate;

typedef struct {
  // GPS estimate state.
  EstimatorPositionGpsState gps;
  // Adaptive complementary filter state.
  EstimatorPositionFilterState filter;
  // Ground frame with respect to ECEF.
  GroundStationPoseEstimate ground_frame;
} EstimatorPositionGroundState;

typedef struct {
  // If false, do not use Xg.
  bool wing_pos_valid;
  // Position estimate [m].
  Vec3 Xg;
  // Position standard devation [m].
  Vec3 sigma_Xg;
} EstimatorPositionGlasEstimate;

typedef struct {
  // If false, do not use Xg_z.
  bool valid;
  // Position estimate [m].
  double Xg_z;
  // Standard deviation [m] on the estimate based on
  // the quality of initial biasing.
  double sigma_Xg_z;
} EstimatorPositionBaroEstimate;

typedef struct {
  // If false, do not apply a measurement correction.
  bool new_data;
  // If false do not use Xg.
  bool wing_pos_valid;
  // If false, do not use Vg.
  bool wing_vel_valid;
  // Wing position estimate in g-coordinates [m].
  Vec3 Xg;
  // Standard deviations [m] for the wing position estimate.
  Vec3 sigma_Xg;
  // Wing velocity [m/s] estimate in g coordinates.
  Vec3 Vg;
  // Standard deviations [m/s] for the wing velocity in ground coordinates.
  Vec3 sigma_Vg;
} EstimatorPositionGpsEstimate;

#define ESTIMATOR_VIBRATION_FILTER_ORDER 2
#define ESTIMATOR_VB_FILTER_ORDER 2

typedef struct {
  // Velocity solution type from previous control sample.
  EstimatorVelocitySolutionType vel_type_z1;
  // States of the third-order low-pass filter on the body angular
  // rates and accelerations.
  double p_filter[ESTIMATOR_VIBRATION_FILTER_ORDER];
  double q_filter[ESTIMATOR_VIBRATION_FILTER_ORDER];
  double r_filter[ESTIMATOR_VIBRATION_FILTER_ORDER];
  double acc_b_x_filter[ESTIMATOR_VIBRATION_FILTER_ORDER];
  double acc_b_y_filter[ESTIMATOR_VIBRATION_FILTER_ORDER];
  double acc_b_z_filter[ESTIMATOR_VIBRATION_FILTER_ORDER];
  // State of the acceleration norm low-pass filter.
  Vec3 acc_norm_f_z1;
  // State for the anti-vibration velocity filter.
  double Vb_x_filter_state[ESTIMATOR_VB_FILTER_ORDER];
  double Vb_y_filter_state[ESTIMATOR_VB_FILTER_ORDER];
  double Vb_z_filter_state[ESTIMATOR_VB_FILTER_ORDER];
  // Expected magnetometer measurement [Gauss] in g-coordinates.
  Vec3 mag_g;
} EstimatorNavState;

typedef struct {
  EstimatorNavState estimator_nav_state;
  // Label of the IMU to trust if all IMUs are currently faulted.
  WingImuLabel last_used_imu;
  // Attitude estimator state.
  EstimatorAttitudeState attitude[kNumWingImus];
  // Position estimator state.
  EstimatorPositionState position;
  // Filtered kite velocity [m/s] for attitude determination in crosswind.
  Vec3 Vg_f_z1;
} EstimatorNavKiteState;

typedef struct {
  EstimatorNavState estimator_nav_state;
  // Attitude estimator state.
  EstimatorAttitudeState attitude;
  // Ground estimator state.
  EstimatorPositionGroundState position;
} EstimatorNavGroundState;

typedef struct {
  EstimatorAttitudeParams attitude;
  EstimatorPositionParams position;
  double fc_Vg;
  double fc_acc_norm;
  double vibration_filter_a[ESTIMATOR_VIBRATION_FILTER_ORDER + 1];
  double vibration_filter_b[ESTIMATOR_VIBRATION_FILTER_ORDER + 1];
  double Vb_filter_a[ESTIMATOR_VB_FILTER_ORDER + 1];
  double Vb_filter_b[ESTIMATOR_VB_FILTER_ORDER + 1];
  double max_valid_position_sigma_norm;
} EstimatorNavParams;

#undef ESTIMATOR_VIBRATION_FILTER_ORDER
#undef ESTIMATOR_VB_FILTER_ORDER

typedef struct {
  Vec3 last_valid;
  Vec3 pos_zs[2];
  double z_z1;
} EstimatorTetherAnchorState;

typedef struct {
  double fc_near_perch;
  double fc_far_from_perch;
  double payout_near_perch;
  double payout_far_from_perch;
  double fc_lateral;
  double zeta_lateral;
} EstimatorTetherAnchorParams;

typedef struct {
  double last_valid_elevation_g;
  double last_valid_elevation_p;
  double last_valid_detwist_angle;
  double last_detwist_angle;
  double last_valid_accumulated_detwist_angle;
} EstimatorTetherGroundAnglesState;

typedef struct {
  double hold_cone_half_angle;
  double detwist_axis_offset;
} EstimatorTetherGroundAnglesParams;

typedef struct {
  // Most recent loadcell measurement when no fault was reported.
  double last_valid_loadcells[kNumLoadcellSensors];
  // Tension filter state [N].
  Vec3 vector_f_z1;
} EstimatorTetherForceState;

typedef struct { double fc_tension; } EstimatorTetherForceParams;

typedef struct {
  double fc_rho;
  double zeta_rho;
} EstimatorWeatherParams;

typedef struct {
  double last_valid_rho;
  double rho_zs[2];
} EstimatorWeatherState;

typedef struct {
  // Value of winch_pos [m] recorded from the last time flight_mode was
  // kFlightModePerched.
  double position_perched;
  // Last valid recorded winch_pos [m].
  double last_valid_position;
  // Last valid proximity sensor value.
  bool last_valid_proximity;
} EstimatorWinchState;

typedef struct {
  Vec3 hard_coded_wind_g;
  double fc_initialize;
  double fc_vector;
  double fc_vector_slow;
  double fc_speed;
  double fc_speed_playbook;
  double zeta_speed_playbook;
  double fc_dir;
  double zeta_dir;
  double fc_dir_playbook;
  double zeta_dir_playbook;
  double playbook_aloft_azi_offset_max;
} EstimatorWindParams;

typedef struct {
  // Last wind vector [m/s] in the ground coordinates for which there
  // were no sensor faults.
  Vec3 last_valid_wind_g;
  // State of the wind low-pass filter [m/s] used to generate vector_f.
  Vec3 vector_f_z1;
  // State of the wind low-pass filter [m/s] used to generate vector_f_slow.
  Vec3 vector_f_slow_z1;
  // State of the speed low-pass filter [m/s].
  double speed_f_z1;
  double speed_f_pb_zs[2];
  // State of the wind low-pass filter [m/s] used to generate dir_f.
  Vec3 wind_direction_vector_f_zs[2];
  // State of the wind low-pass filter [m/s] used to generate dir_f_playbook.
  Vec3 wind_direction_vector_f_zs_playbook[2];
} EstimatorWindState;

typedef struct {
  double t_initialize;
  double hard_coded_initial_payout;
  EstimatorApparentWindParams apparent_wind;
  EstimatorGroundStationParams ground_station;
  EstimatorJoystickParams joystick;
  EstimatorNavParams nav;
  EstimatorPerchAziParams perch_azi;
  EstimatorTetherAnchorParams tether_anchor;
  EstimatorTetherForceParams tether_force;
  EstimatorTetherGroundAnglesParams tether_ground_angles;
  EstimatorWeatherParams weather;
  EstimatorWindParams wind;
} EstimatorParams;

typedef struct {
  // Indicates the sensors used in solving for apparent wind
  // when flying-like-an-airplane.
  int32_t solution_type;  // See ApparentWindSolutionType.
  // Apparent wind estimate in Cartesian coordinates.
  Vec3 vector;
  // Apparent wind estimate in spherical coordinates.
  ApparentWindSph sph;
  // Apparent wind estimate in spherical coordinates with individually
  // low-pass filtered components.
  ApparentWindSph sph_f;
} ApparentWindEstimate;

typedef struct {
  GroundStationPoseEstimate pose;
  GroundStationMode mode;
  uint8_t transform_stage;
  double detwist_angle;
  bool detwist_angle_valid;
} GroundStationEstimate;

typedef struct {
  // Whether to trust this estimate.
  bool valid;
  // Most recent valid joystick data.
  JoystickData data;
  // Low-pass filtered throttle.
  double throttle_f;
  // Low-pass filtered pitch stick.
  double pitch_f;
} JoystickEstimate;

typedef struct {
  // Whether to trust this estimate.
  bool valid;
  // Most recent valid perch azimuth angle [rad].
  double angle;
  // Estimate of the perch azimuth angular rate [rad/s].
  double angle_vel_f;
} PerchAziEstimate;

typedef struct {
  // Whether to trust this estimate.
  bool valid;
  // Tether force estimate in Cartesian coordinates [N].
  Vec3 vector;
  // Tether force estimate in spherical coordinates.
  TetherForceSph sph;
  // Low-pass filtered tension [N].
  double tension_f;
  Vec3 vector_f;
  // Port bridle force estimate in Cartesian coordinates [N].
  Vec3 bridle_port_vector;
  // Starboard bridle force estimate in Cartesian coordinates [N].
  Vec3 bridle_star_vector;
} TetherForceEstimate;

typedef struct {
  bool valid;
  // Negative one times the nominal tether length [m] that must be
  // payed out to reach the crosswind orientation (defined to be zero
  // in the crosswind orientation).
  //
  // This value is negative when reeled-in, increases during pay-out
  // and must be non-negative before the ground station experiences
  // crosswind loads.
  double position;
  // Nominal tether length [m] that has been payed-out since last
  // being on the perch (defined to be zero when perched).
  double payout;
  // Whether or not the proximity flag is valid.
  // TODO: Use payout as a backup proximity sensor.
  bool proximity_valid;
  // Whether or not the proximity sensor is active.
  bool proximity;
} WinchEstimate;

typedef struct {
  bool elevation_valid;
  double elevation_g, elevation_p;
  double departure_detwist_angle;
  double accumulated_detwist_angle;
} TetherGroundAnglesEstimate;

typedef struct {
  bool valid;
  Vec3 pos_g;
  Vec3 pos_g_f;
} TetherAnchorEstimate;

typedef struct {
  // Whether to trust this estimate.
  bool valid;
  // Where this estimate came from.
  int32_t solution_type;  // See WindSolutionType.
  // Wind speed estimate [m/s].
  Vec3 vector;
  // Low-pass filtered wind speed estimate [m/s].
  Vec3 vector_f;
  // More heavily low-pass filtered wind speed estimate [m/s].
  Vec3 vector_f_slow;
  // Low-pass filtered angle [rad] indicating the direction the wind
  // is coming from (i.e. defined to be 0 when the wind vector is
  // aligned with the negative x-axis, and increasing according to the
  // right-hand rule around the down axis).  This value is filtered in
  // a wind speed dependent way so as to vary more slowly in
  // low-winds.
  double dir_f;
  double dir_f_playbook;
  // Filtered wind speed estimate [m/s].
  double speed_f;
  double speed_f_playbook;
} WindEstimate;

// TODO: Rename this to PlatformEstimate, and move dcm_g2v to a
// separate structure?
typedef struct {
  // Platform estimate.
  Vec3 pos_g;    // Origin of the vessel and platform frames.
  Vec3 vel_g;    // Velocity of the vessel and platform with respect to ground.
  Mat3 dcm_g2p;  // Attitude of the platform. Differs from g2v only
                 // by a rotation of vessel_heading about the -z
                 // axis.
  Vec3 pqr;      // Body rates of the platform frame w.r.t ground.
  bool position_valid;
  bool attitude_valid;

  // Vessel estimate.
  bool dcm_g2v_valid;
  Mat3 dcm_g2v;  // Attitude of the vessel with respect to ground.
} VesselEstimate;

typedef struct { VesselEstimate last_valid; } EstimatorVesselState;

// Structure of the internal state of the estimator.
typedef struct {
  bool tether_release_latched;
  double time;
  EstimatorApparentWindState apparent_wind;
  EstimatorEncodersState encoders;
  ExperimentState experiment;
  EstimatorGroundStationState ground_station;
  EstimatorJoystickState joystick;
  EstimatorNavKiteState nav;
  EstimatorPerchAziState perch_azi;
  EstimatorTetherAnchorState tether_anchor;
  EstimatorTetherGroundAnglesState tether_ground_angles;
  EstimatorTetherForceState tether_force;
  EstimatorVesselState vessel;
  EstimatorWeatherState weather;
  EstimatorWinchState winch;
  EstimatorWindState wind;
  EstimatorWindState wind_aloft;
  int32_t gs_unpause_transform_count;
} EstimatorState;

typedef struct {
  int32_t stacking_state;  // See StackingState.

  // Attitude and angular rate estimates.
  Mat3 dcm_g2b;
  Vec3 pqr;

  // Filtered values.
  double acc_norm_f;
  Vec3 pqr_f;

  // Position, velocity, and acceleration estimates.
  Vec3 Xg, Vg, Vg_f, Vb, Vb_f, Ag, Ab_f;
  bool gps_active;

  // Whether the tether has been released. This field latches and is only set to
  // true when an unfaulted loadcell indicates that release has occurred.
  bool tether_released;

  // Whether the gs mode has been forced to high tension or reel by the
  // operator.
  bool force_high_tension;
  bool force_reel;

  // Whether the operator has commanded a GS unpause using flight_command.
  bool gs_unpause_transform;

  // Whether the operator has commanded detwist to perform an extra turn.
  bool force_detwist_turn_once;

  // Air density at weather station (on ground station) [kg/m^3].
  // This value is not used by the controller, but is provided for
  // convenience of flight data analysis.
  // TODO: It would be more useful to estimate the density at
  // the wing; however, the wing currently does not have a good
  // outside air temperature sensor. Another approach would be to
  // apply an atmospheric model (i.e. adiabatic lapse rate) to
  // extrapolate the density to the wing altitude. Care should be
  // taken to not introduce unintentional feedback from position to
  // density to motor thrust.
  double rho;

  // Apparent wind estimate resolved in body coordinates.
  ApparentWindEstimate apparent_wind;

  // Joystick estimate.
  JoystickEstimate joystick;

  // Perch azimuth estimate.
  PerchAziEstimate perch_azi;

  // Tether tension information resolved in body coordinates.
  TetherForceEstimate tether_force_b;

  // Winch position / payout estimate.
  WinchEstimate winch;

  // Tether elevation and anchor point.
  TetherGroundAnglesEstimate tether_ground_angles;
  TetherAnchorEstimate tether_anchor;

  // Wind estimates resolved in ground coordinates.
  WindEstimate wind_g;

  // Estimate of the wind at the kite.
  WindEstimate wind_aloft_g;

  // Ground station mode.
  GroundStationMode gs_mode;
  uint8_t gs_transform_stage;

  VesselEstimate vessel;

  // Experiment configs.
  ExperimentState experiment;
} StateEstimate;

#ifdef __cplusplus
extern "C" {
#endif

const char *ApparentWindSolutionTypeToString(ApparentWindSolutionType type);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // CONTROL_ESTIMATOR_ESTIMATOR_TYPES_H_

redpajama_set_name: RedPajamaGithub


text:
async function foo() {
  var _iteratorAbruptCompletion = false;
  var _didIteratorError = false;

  var _iteratorError;

  try {
    for (var _iterator = babelHelpers.asyncIterator(y), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
      const x = _step.value;
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (_iteratorAbruptCompletion && _iterator.return != null) {
        await _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }
}


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide an attribute class to describe socket linger options.
//
//@CLASSES:
//  btlso::LingerOptions: attributes describing socket linger options
//
//@SEE_ALSO: btlso_socketoptions
//
//@DESCRIPTION: This component provides a single, simply constrained
// (value-semantic) attribute class, 'btlso::LingerOptions', that is used to
// describe the linger options of a stream-based socket.  Linger options
// describe how a stream-based socket behaves when it is being closed.  Note
// that linger options is designed to be used in conjunction with the
// 'btlso_socketoptions' component to configure a stream-based socket.
//
///Attributes
///----------
//..
//  Name        Type         Default  Simple Constraints
//  ----------  -----------  -------  ------------------
//  lingerFlag  bool         false    none
//  timeout     int          0        >= 0
//..
//: o lingerFlag: 'true' if the process should block when trying to 'close' a
//:   socket if there is untransmitted data.
//:
//: o timeout: maximum time (in seconds) that a process should block when
//:   trying to 'close' a socket if there is untransmitted data.
//
///Usage
///-----
// In this section we show intended usage of this component.
//
///Example 1: Creating functions to set linger option
/// - - - - - - - - - - - - - - - - - - - - - - - - -
// This component is designed to be used at a higher level to set the linger
// options for a stream-based socket.  This example shows how to create a
// function that takes 'btlso::LingerOptions' as an argument and sets the
// linger options of a socket.  We will assume Berkeley socket API is available
// to configure the socket.
//
// First, we define a cross-platform compatible typedef for a socket handle:
//..
//  #ifdef BSLS_PLATFORM_OS_WINDOWS
//      typedef SOCKET Handle;
//  #else
//      typedef int Handle;
//  #endif
//..
// Then, we declare the function, 'setLingerOptions', that takes a 'Handle' and
// a 'btlso::LingerOptions' object, and sets the linger options for 'Handle':
//..
//  int setLingerOptions(Handle                      handle,
//                       const btlso::LingerOptions& lingerOptions)
//  {
//..
// Next, we define a 'typedef' for the 'struct' needed to set the linger
// options:
//..
//  #if defined(BSLS_PLATFORM_OS_WINDOWS)
//      typedef LINGER LingerData;
//  #else
//      typedef linger LingerData;
//  #endif
//..
// Then, we initialize a 'LingerData' object with data from 'lingerOptions',
// which will be supplied to the 'setsockopt' system call:
//..
//      LingerData linger;
//      linger.l_onoff  = lingerOptions.lingerFlag();
//      linger.l_linger = lingerOptions.timeout();
//..
// Next, we configure the linger options for the socket:
//..
//  #if defined(BSLS_PLATFORM_OS_WINDOWS)
//      return ::setsockopt(handle,
//                          SOL_SOCKET,
//                          SO_LINGER,
//                          reinterpret_cast<char *>(&linger),
//                          sizeof linger);
//  #else
//      return ::setsockopt(handle,
//                          SOL_SOCKET,
//                          SO_LINGER,
//                          reinterpret_cast<void *>(&linger),
//                          sizeof linger);
//  #endif
//  }
//..
// Then, we create a new socket using the 'socket' function from Berkeley API:
//..
//  Handle socketHandle = ::socket(AF_INET, SOCK_STREAM, 0);
//..
// Now, we create a 'btlso::LingerOptions' object, 'option', indicating an
// associated socket should block for 2 seconds when closing a stream with
// untransmitted data (i.e., lingering):
//..
//  btlso::LingerOptions option(true, 2);
//..
// Finally, we call 'setLingerOptions' (defined above), to configure the
// options for the socket:
//..
//  setLingerOptions(socketHandle, option);
//..

#ifndef INCLUDED_BTLSCM_VERSION
#include <btlscm_version.h>
#endif

#ifndef INCLUDED_BSLMF_ISBITWISEMOVEABLE
#include <bslmf_isbitwisemoveable.h>
#endif

#ifndef INCLUDED_BSLMF_NESTEDTRAITDECLARATION
#include <bslmf_nestedtraitdeclaration.h>
#endif

#ifndef INCLUDED_BSLS_ASSERT
#include <bsls_assert.h>
#endif

#ifndef INCLUDED_BSL_IOSFWD
#include <bsl_iosfwd.h>
#endif

namespace BloombergLP {

namespace btlso {

                       // ===================
                       // class LingerOptions
                       // ===================

class LingerOptions {
    // This simply constrained (value-semantic) attribute class describes
    // linger options on a stream-based socket.  See the Attributes section
    // under @DESCRIPTION in the component-level documentation.  Note that the
    // class invariants are identically the constraints on the individual
    // attributes.
    //
    // This class:
    //: o supports a complete set of *value-semantic* operations
    //: o is *exception-safe*
    //: o is *alias-safe*
    //: o is 'const' *thread-safe*
    // For terminology see 'bsldoc_glossary'.

    // DATA
    int  d_timeout;     // maximum time-out value (in seconds) that a process
                        // should block when trying to 'close' a socket if
                        // there is untransmitted data

    bool d_lingerFlag;  // flag specifying if the process should block when
                        // trying to 'close' a socket if there is
                        // untransmitted data

  public:
    // TRAITS
    BSLMF_NESTED_TRAIT_DECLARATION(LingerOptions, bslmf::IsBitwiseMoveable)

    // CREATORS
    LingerOptions();
        // Create a 'LingerOptions' object having the (default) attribute
        // values:
        //..
        //  timeout    == 0
        //  lingerFlag == false
        //..

    LingerOptions(int timeout, bool lingerFlag);
        // Create a 'LingerOptions' object having the specified 'timeout', and
        // 'lingerFlag' attribute values.  The behavior is undefined unless
        // '0 <= timeout'.

    //! LingerOptions(const LingerOptions& original) = default;
        // Create a 'LingerOptions' object having the same value as the
        // specified 'original' object.

    //! ~LingerOptions() = default;
        // Destroy this object.

    // MANIPULATORS
    //! LingerOptions& operator=(const LingerOptions& rhs) = default;
        // Assign to this object the value of the specified 'rhs' object, and
        // return a reference providing modifiable access to this object.

    void setTimeout(int value);
        // Set the 'timeout' attribute of this object to the specified 'value'.
        // The behavior is undefined unless '0 <= value'.

    void setLingerFlag(bool value);
        // Set the 'lingerFlag' attribute of this object to the specified
        // 'value'.

    // ACCESSORS
    bool lingerFlag() const;
        // Return the value of the 'lingerFlag' attribute of this object.

    int timeout() const;
        // Return the value of the 'timeout' attribute of this object.  Note
        // that '0 <= timeout()'.

                                  // Aspects

    bsl::ostream& print(bsl::ostream& stream,
                        int           level = 0,
                        int           spacesPerLevel = 4) const;
        // Write the value of this object to the specified output 'stream' in
        // a human-readable format, and return a reference to 'stream'.
        // Optionally specify an initial indentation 'level', whose absolute
        // value is incremented recursively for nested objects.  If 'level' is
        // specified, optionally specify 'spacesPerLevel', whose absolute
        // value indicates the number of spaces per indentation level for this
        // and all of its nested objects.  If 'level' is negative, suppress
        // indentation of the first line.  If 'spacesPerLevel' is negative,
        // format the entire output on one line, suppressing all but the
        // initial indentation (as governed by 'level').  Note that the
        // format is not fully specified, and can change without notice.
};

// FREE OPERATORS
inline
bool operator==(const LingerOptions& lhs, const LingerOptions& rhs);
    // Return 'true' if the specified 'lhs' and 'rhs' objects have the same
    // value, and 'false' otherwise.  Two 'LingerOptions' objects have the same
    // value if all of the corresponding values of their 'timeout', and
    // 'lingerFlag' attributes are the same.

inline
bool operator!=(const LingerOptions& lhs, const LingerOptions& rhs);
    // Return 'true' if the specified 'lhs' and 'rhs' objects do not have the
    // same value, and 'false' otherwise.  Two 'LingerOptions' objects do not
    // have the same value if any of the corresponding values of their
    // 'timeout', and 'lingerFlag' attributes are not the same.

bsl::ostream& operator<<(bsl::ostream& stream, const LingerOptions& object);
    // Write the value of the specified 'object' to the specified output
    // 'stream' in a single-line format, and return a reference providing
    // modifiable access to 'stream'.  If 'stream' is not valid on entry, this
    // operation has no effect.  Note that this human-readable format is not
    // fully specified and can change without notice.  Also note that this
    // method has the same behavior as 'object.print(stream, 0, -1)', but with
    // the attribute names elided.

// ============================================================================
//                         INLINE FUNCTION DEFINITIONS
// ============================================================================

                       // -------------------
                       // class LingerOptions
                       // -------------------

// CREATORS
inline
LingerOptions::LingerOptions()
: d_timeout(0)
, d_lingerFlag(false)
{
}

inline
LingerOptions::LingerOptions(int timeout, bool lingerFlag)
: d_timeout(timeout)
, d_lingerFlag(lingerFlag)
{
    BSLS_ASSERT_SAFE(0 <= timeout);
}

inline
void LingerOptions::setTimeout(int value)
{
    BSLS_ASSERT_SAFE(0 <= value);

    d_timeout = value;
}

inline
void LingerOptions::setLingerFlag(bool value)
{
    d_lingerFlag = value;
}

// ACCESSORS
inline
int LingerOptions::timeout() const
{
    return d_timeout;
}

inline
bool LingerOptions::lingerFlag() const
{
    return d_lingerFlag;
}

}  // close package namespace

// FREE OPERATORS
inline
bool btlso::operator==(const LingerOptions& lhs, const LingerOptions& rhs)
{
    return  lhs.lingerFlag() == rhs.lingerFlag()
         && lhs.timeout()    == rhs.timeout();
}

inline
bool btlso::operator!=(const LingerOptions& lhs, const LingerOptions& rhs)
{
    return  lhs.lingerFlag() != rhs.lingerFlag()
         || lhs.timeout()    != rhs.timeout();
}

}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
Converts this  [OfficeDevPnP.Core.Pages.ClientSideText](OfficeDevPnP.Core.Pages.ClientSideText.md)  control to it's html representation

**Namespace:** [OfficeDevPnP.Core.Pages](OfficeDevPnP.Core.Pages.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public override string ToHtml(Single controlIndex)
```
### Parameters
#### controlIndex
  Type: System.Single
  The sequence of the control inside the section

### Return Value
Type: string
Html representation of this  [OfficeDevPnP.Core.Pages.ClientSideText](OfficeDevPnP.Core.Pages.ClientSideText.md)  control

## See also
- [ClientSideText](OfficeDevPnP.Core.Pages.ClientSideText.md)
- [OfficeDevPnP.Core.Pages.ClientSideText](OfficeDevPnP.Core.Pages.ClientSideText.md)
- [OfficeDevPnP.Core.Pages](OfficeDevPnP.Core.Pages.md)


text:
package lua

type Metatable struct {
    IndexFunc Function
    NewindexFunc Function
    TostringFunc Function
    GCFunc Function
}

func (this *Metatable) Index() Function {
    return this.IndexFunc
}

func (this *Metatable) Newindex() Function {
    return this.NewindexFunc
}

func (this *Metatable) Tostring() Function {
    return this.TostringFunc
}

func (this *Metatable) GC() Function {
    return this.GCFunc
}


text:
namespace AgileObjects.ReadableExpressions.Translations
{
    using System;
#if NET35
    using Microsoft.Scripting.Ast;
#else
    using System.Linq.Expressions;
#endif
    using Extensions;

    internal class LambdaTranslation : ITranslation, IPotentialMultiStatementTranslatable
    {
        private const string _fatArrow = " => ";

        private readonly ParameterSetTranslation _parameters;
        private readonly CodeBlockTranslation _bodyTranslation;

        public LambdaTranslation(LambdaExpression lambda, ITranslationContext context)
        {
            Type = lambda.Type;
            _parameters = ParameterSetTranslation.For(lambda, context);
            _bodyTranslation = context.GetCodeBlockTranslationFor(lambda.Body);

            TranslationSize =
                _parameters.TranslationSize +
                _fatArrow.Length +
                _bodyTranslation.TranslationSize;

            FormattingSize = _parameters.FormattingSize + _bodyTranslation.FormattingSize;

            if (_bodyTranslation.IsMultiStatement == false)
            {
                _bodyTranslation.WithoutTermination();
            }
        }

        public ExpressionType NodeType => ExpressionType.Lambda;

        public Type Type { get; }

        public int TranslationSize { get; }

        public int FormattingSize { get; }

        public bool IsMultiStatement => _bodyTranslation.IsMultiStatement;

        public int GetIndentSize()
        {
            return _parameters.GetIndentSize() +
                   _bodyTranslation.GetIndentSize();
        }

        public int GetLineCount()
        {
            var parametersLineCount = _parameters.GetLineCount();
            var bodyLineCount = _bodyTranslation.GetLineCount();

            if (parametersLineCount == 1)
            {
                return bodyLineCount > 1 ? bodyLineCount : 1;
            }

            return bodyLineCount > 1
                ? parametersLineCount + bodyLineCount - 1
                : parametersLineCount;
        }

        public void WriteTo(TranslationWriter writer)
        {
            _parameters.WriteTo(writer);

            writer.WriteToTranslation(_bodyTranslation.HasBraces ? " =>" : _fatArrow);

            _bodyTranslation.WriteTo(writer);
        }
    }
}


text:
using LifxMvc.Domain;
using LifxMvc.Services.UdpHelper;
using LifxNet;
using LifxNet.Domain;
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Threading;

namespace LifxMvc.Services
{

    public class BulbLock
    {
        const int LOCK_TIMEOUT_7_SECOND = 7000;

        public bool Lock(Bulb b)
        {
            return Monitor.TryEnter(b, LOCK_TIMEOUT_7_SECOND);
        }

        public void Unlock(Bulb b)
        {
            Monitor.Exit(b);
        }
    }

	public class BulbService : IBulbService
	{
        const int BULB_OFFLINE_RETRY_TIME = 10000;
        const int BULB_LAST_READ_RETRY_TIME = 1000;

        private BulbLock _BulbLock = new BulbLock();

		R Send<R>(IBulb bulb, LifxPacketBase<R> packet) where R : LifxResponseBase
		{
            var response = (R)null;

            // If the bulb is Offline and we haven't waited BULB_OFFLINE_RETRY_TIME seconds yet, then
            // skip any communication with the bulb and send back a NULL response
            if (BulbOfflineCheck(bulb))
            {
                var udp = UdpHelperManager.Instance[packet.IPEndPoint];
                response = udp.Send(packet);

                if (null != response)
                {
                    bulb.isOffline = false;

                    // Don't update the bulb info if we sent a SET message because the response
                    // has the previous settings. For example, if we change brightness from 25%
                    // to 75%, the response will show brightness as 25%.
                    if (!IsSetPacket(packet.MessageType))
                        BulbExtensions.Set(bulb, (dynamic)response);
                }
                else
                {
                    //bulb.IsOn = false;
                    bulb.isOffline = true;
                    bulb.LastOfflineCheck = DateTime.UtcNow;
                }
            }

			return response;
		}
        //--------------------------------------------------------------------

        private bool IsSetPacket(PacketType pt)
        {
            bool isSetPacket = false;

            if(pt == PacketType.LightSetColor || pt == PacketType.LightSetPower || pt == PacketType.LightSetWaveform)
            {
                isSetPacket = true;
            }

            return isSetPacket;
        }
        //--------------------------------------------------------------------

        private bool BulbOfflineCheck(IBulb bulb)
        {
            bool okToSendRequestToBulb = true;

            // If the bulb is offline, then wait BULB_OFFLINE_RETRY_TIME seconds before checking if it's back online.
            if (bulb.isOffline)
            {
                double deltaTime = DateTime.UtcNow.Subtract(bulb.LastOfflineCheck).TotalMilliseconds;
                if (deltaTime >= 0 && deltaTime <= BULB_OFFLINE_RETRY_TIME)
                {
                    okToSendRequestToBulb = false;
                }
            }

            return okToSendRequestToBulb;
        }
        //--------------------------------------------------------------------

        private bool IsOkToReadFromBulb(DateTime lastReadTime)
        {
            bool okToRead = false;

            double deltaTime = DateTime.UtcNow.Subtract(lastReadTime).TotalMilliseconds;

            // If the time difference since the last time we read data from the light is negative, or
            // greater than BULB_LAST_READ_RETRY_TIME, then get the data from the light again.
            // Else, just use the old data
            if (deltaTime < 0 || deltaTime > BULB_LAST_READ_RETRY_TIME)
            {
                okToRead = true;
            }

            return okToRead;
        }
        //--------------------------------------------------------------------

		bool SendAsync(IBulb bulb, LifxPacketBase packet)
		{
            bool success = false;

            //if (!bulb.isOffline)
            //{
            //    var udp = UdpHelperManager.Instance[packet.IPEndPoint];
            //    udp.SendAsync(packet);
            //    success = true;
            //}
            //else
            //{
            //    //return false;
            //}

            return success;
		}
        //--------------------------------------------------------------------

		public bool Initialize(IBulb bulb)
		{
            bool isSuccess = false;

            // Get Version returns the Version and Product number of the bulb. The Product number
            // is used to determine of we are using a Color bulb or not.
            isSuccess = this.DeviceGetVersion(bulb);

            if (isSuccess)
            {
                // LightGet get the light status; which has all the color properties (hue, saturation, brightness)
                isSuccess = this.LightGet(bulb, true);
            }

			//this.DeviceGetGroup(bulb);
			//this.DeviceGetLocation(bulb);

            return isSuccess;
		}
        //--------------------------------------------------------------------

		public bool LightGet(IBulb bulb, bool forceUpdate = false)
		{
            bool gotResponse = false;

            if (IsOkToReadFromBulb(bulb.LastStateRequest) || forceUpdate)
            {
                // update the Last Request time first so other threads that coming in
                // immediatly don't try reading as well
                bulb.LastStateRequest = DateTime.UtcNow;

                var packet = new LightGetPacket(bulb);
                var response = this.Send(bulb, packet);

                if (response != null)
                {
                    gotResponse = true;
                }
                else
                {
                    // If there was an issue reading, then set date time Min Value so
                    // we try reading with the next request instead of waiting for the timeout.
                    bulb.LastStateRequest = DateTime.MinValue;
                }
            }

            return gotResponse;
		}
        //--------------------------------------------------------------------

        public bool DeviceGetVersion(IBulb bulb)
		{
            bool isSuccess = false;

			var packet = new DeviceGetVersionPacket(bulb);
			var response = this.Send(bulb, packet);

            if (response != null)
            {
                isSuccess = true;
            }

            return isSuccess;
		}
        //--------------------------------------------------------------------

        public bool? LightGetPower(IBulb bulb)
        {
            // Only read from the bulb every 15 seconds. This helps eliminate
            // every property asking the bulb for the same info.
            if (IsOkToReadFromBulb(bulb.LastPowerRequest))
            {
                // update the Last Request time first so other threads that coming in
                // immediatly don't try reading as well
                bulb.LastPowerRequest = DateTime.UtcNow;

                var packet = new LightGetPowerPacket(bulb);
                var response = this.Send(bulb, packet);
                if (response == null)
                {
                    // If there was an issue reading, then set date time Min Value so
                    // we try reading with the next request instead of waiting for the timeout.
                    bulb.LastPowerRequest = DateTime.MinValue;
                }
            }

            return bulb.isOffline ? null : (bool?)bulb.IsOn;
        }
        //--------------------------------------------------------------------

		public bool LightSetPower(IBulb bulb, bool power)
		{
			bool isSuccess = false;

            if (_BulbLock.Lock((Bulb)bulb))
            {
                var packet = new LightSetPowerPacket(bulb, power);
                var response = this.Send(bulb, packet);

                if (response != null)
                {
                    isSuccess = true;
                    bulb.IsOn = power;
                }

                _BulbLock.Unlock((Bulb)bulb);
            }

            return isSuccess;
		}
        //--------------------------------------------------------------------

        public string LightGetColor(IBulb bulb)
        {
            // Get the latest Bulb HSBK settings
            this.LightGet(bulb);

            string colorString = String.Format("{0:X2}{1:X2}{2:X2}{3:X2}", bulb.Color.A, bulb.Color.R, bulb.Color.G, bulb.Color.B);

            return bulb.isOffline ? null : colorString;
        }
        //--------------------------------------------------------------------

		public bool LightSetColor(IBulb bulb, Color color)
		{
            bool isSuccess = false;

            if (_BulbLock.Lock((Bulb)bulb))
            {
                // Get the latest Bulb HSBK settings (could have change from another source)
                if (this.LightGet(bulb, true))
                {
                    // create new HSBK from color
                    var hsbk = color.ToHSBK(bulb.IsKelvin);
                    if (null == hsbk)
                        throw new ArgumentNullException();

                    // Update the HSBK settings
                    bulb.SetHSBK(hsbk);

                    // Create the Packet and send request
                    isSuccess = LightSetHSBK(bulb);
                }
                _BulbLock.Unlock((Bulb)bulb);
            }

            return isSuccess;
		}
        //--------------------------------------------------------------------

        public ushort? LightGetBrightness(IBulb bulb)
        {
            // Get the latest Bulb HSBK settings (could have change from another source)
            this.LightGet(bulb);
            return bulb.isOffline ? null : (ushort?)bulb.Brightness;
        }
        //--------------------------------------------------------------------

        public bool LightSetBrightness(IBulb bulb, ushort brightness)
        {
            bool isSuccess = false;

            if (_BulbLock.Lock((Bulb)bulb))
            {
                // Get the latest Bulb HSBK settings (could have change from another source)
                if (this.LightGet(bulb, true))
                {
                    // Update the brightness setting
                    bulb.Brightness = brightness;

                    // Create the Packet and send request
                    isSuccess = LightSetHSBK(bulb);
                }
                _BulbLock.Unlock((Bulb)bulb);
            }

            return isSuccess;
        }
        //--------------------------------------------------------------------

        public ushort? LightGetSaturation(IBulb bulb)
        {
            // Get the latest Bulb HSBK settings (could have change from another source)
            this.LightGet(bulb);
            return bulb.isOffline ? null : (ushort?)bulb.Saturation;
        }
        //--------------------------------------------------------------------

        public bool LightSetSaturation(IBulb bulb, ushort saturation)
        {
            bool isSuccess = false;

            if (_BulbLock.Lock((Bulb)bulb))
            {
                // Get the latest Bulb HSBK settings (could have change from another source)
                if (this.LightGet(bulb, true))
                {
                    // Update the brightness setting
                    bulb.Saturation = saturation;

                    // Create the Packet and send request
                    isSuccess = LightSetHSBK(bulb);
                }
                _BulbLock.Unlock((Bulb)bulb);
            }

            return isSuccess;
        }
        //--------------------------------------------------------------------

        public ushort? LightGetKelvin(IBulb bulb)
        {
            // Get the latest Bulb HSBK settings (could have change from another source)
            this.LightGet(bulb);
            return bulb.isOffline ? null : (ushort?)bulb.Kelvin;
        }
        //--------------------------------------------------------------------

        public bool LightSetKelvin(IBulb bulb, ushort kelvin)
        {
            bool isSuccess = false;

            if (_BulbLock.Lock((Bulb)bulb))
            {
                // Get the latest Bulb HSBK settings (could have change from another source)
                if (this.LightGet(bulb, true))
                {
                    // Update the brightness setting
                    bulb.Kelvin = kelvin;

                    // Create the Packet and send request
                    isSuccess = LightSetHSBK(bulb);
                }
                _BulbLock.Unlock((Bulb)bulb);
            }

            return isSuccess;
        }
        //--------------------------------------------------------------------

        public void LightSetWaveform(IBulb bulb, LightSetWaveformCreationContext ctx)
        {
            //var packet = new LightSetWaveformPacket(bulb, ctx);
            //this.SendAsync(bulb, packet);
        }
        //--------------------------------------------------------------------

        bool LightSetHSBK(IBulb bulb)
        {
            bool isSuccess = false;

            var packet = new LightSetHSBKPacket(bulb);
            packet.Duration = 100;

            var response = this.Send(bulb, packet);

            if (response != null)
            {
                isSuccess = true;
            }

            return isSuccess;
        }
        //--------------------------------------------------------------------

        public void DeviceGetGroup(IBulb bulb)
        {
            var packet = new DeviceGetGroupPacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void DeviceGetLocation(IBulb bulb)
        {
            var packet = new DeviceGetLocationPacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public bool DeviceGetPower(IBulb bulb)
        {
            var packet = new DeviceGetPowerPacket(bulb);
            var response = this.Send(bulb, packet);

            var result = response.IsOn;
            return result;
        }
        //--------------------------------------------------------------------

        public void DeviceSetPower(IBulb bulb, bool isOn)
        {
            var packet = new DeviceSetPowerPacket(bulb, isOn);
            this.Send(bulb, packet);

            bulb.IsOn = isOn;
        }
        //--------------------------------------------------------------------

        public void GetHostInfo(IBulb bulb)
        {
            var packet = new DeviceGetHostInfoPacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void GetHostFirmware(IBulb bulb)
        {
            var packet = new DeviceGetHostFirmwarePacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void GetWifiInfo(IBulb bulb)
        {
            var packet = new DeviceGetWifiInfoPacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void GetWifiFirmware(IBulb bulb)
        {
            var packet = new DeviceGetWifiFirmwarePacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void GetLabel(IBulb bulb)
        {
            var packet = new DeviceGetLabelPacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void SetLabel(IBulb bulb, string label)
        {
            var packet = new DeviceSetLabelPacket(bulb, label);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void GetInfo(IBulb bulb)
        {
            var packet = new DeviceGetInfoPacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

        public void EchoRequest(IBulb bulb)
        {
            var packet = new DeviceEchoRequestPacket(bulb);
            this.Send(bulb, packet);
        }
        //--------------------------------------------------------------------

	}//class

	public static class BulbExtensions
	{
		public static void SetColor(this IBulb bulb, IHSBK hsbk)
		{
            bulb.Color = hsbk.ToColor(bulb.IsKelvin);

			bulb.Hue = hsbk.Hue;
			bulb.Saturation = hsbk.Saturation;
			bulb.Brightness = hsbk.Brightness;
			bulb.Kelvin = hsbk.Kelvin;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceAcknowledgementResponse r)
		{
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceEchoResponse r)
		{
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateGroupResponse r)
		{
			bulb.Group = r.Label;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateHostFirmwareResponse r)
		{
			bulb.HostFirmwareBuild = r.Build;
			bulb.HostFirmwareVersion = r.Version;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateHostInfoResponse r)
		{
			bulb.Signal = r.Signal;
			bulb.TxCount = r.TxCount;
			bulb.RxCount = r.RxCount;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateInfoResponse r)
		{
			bulb.Time = r.Time;
			bulb.Uptime = r.Uptime;
			bulb.Downtime = r.Downtime;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateLabelResponse r)
		{
			bulb.Label = r.Label;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateLocationResponse r)
		{
			bulb.Location = r.Label;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStatePowerResponse r)
		{
			bulb.IsOn = r.IsOn;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateServiceResponse r)
		{
			bulb.Service = r.Service;
			bulb.Port = r.Port;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateVersionResponse r)
		{
			bulb.Vendor = r.Vendor;
			bulb.Product = (LifxProductEnum)r.Product;
			bulb.Version = r.Version;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateWifiFirmwareResponse r)
		{
			bulb.WifiFirmwareBuild = r.Build;
			bulb.WifiFirmwareVersion = r.Version;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, DeviceStateWifiInfoResponse r)
		{
			bulb.WifiInfoSignal = r.Signal;
			bulb.WifiInfoTxCount = r.TxCount;
			bulb.WifiInfoRxCount = r.RxCount;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, LightStatePowerResponse r)
		{
			bulb.IsOn = r.IsOn;
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, LightStateResponse r)
		{
			bulb.IsOn = r.IsOn;
			bulb.Label = r.Label;

			bulb.Hue = r.Hue;
			bulb.Saturation = r.Saturation;
			bulb.Brightness = r.Brightness;
			bulb.Kelvin = r.Kelvin;

			IHSBK hsbk = null;
			if (bulb.Product.IsColor())
				hsbk = new HSBK(r.Hue, r.Saturation, r.Brightness);
			else
				hsbk = new HSBK(r.Kelvin, r.Brightness);

			bulb.SetHSBK(hsbk);
		}
        //--------------------------------------------------------------------

		public static void Set(this IBulb bulb, UnknownResponse r)
		{
			throw new ArgumentOutOfRangeException();
		}
        //--------------------------------------------------------------------

	}//class

}//ns


text:
/* This file is generated automatically by generatejs.con. Do not edit. */

'use strict';

if (!con.coding)
	con.coding = { };
con.coding.mime_encode = this.__cjs_mime_encode;
con.coding.mime_decode = this.__cjs_mime_decode;


text:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'order'
})
export class OrderPipe implements PipeTransform {

  transform(value: any, prop: any): any {
    return value.sort((a: Object, b: Object) => {
      a = typeof a[prop] === 'string' ? a[prop].toLowerCase() : a[prop];
      b = typeof b[prop] === 'string' ? b[prop].toLowerCase() : b[prop];
      return a > b;
    });
  }

}


text:
package org.dean.example.nettychat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by Dean on 2014/6/25.
 */
public class ChatClient {

    public static void main(String[] args) throws Exception{
        new ChatClient("localhost", 8000).run();
    }

    private final String host;
    private final int port;

    public ChatClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap  = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChatClientInitializer());
            Channel channel = bootstrap.connect(host, port).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while(true){
                channel.write(in.readLine() + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }

}