text:
#ifndef __BMA253_H__
#define __BMA253_H__

#include "os/mynewt.h"
#include "sensor/sensor.h"
#include "sensor/accel.h"
#include "sensor/temperature.h"

#ifdef __cplusplus
extern "C" {
#endif

#define BMA253_UNUSED_VAR(v)    ((void)v)

/* XXX use some better defaults.*/
#define BMA253_NO_MOTION_DURATION           5
#define BMA253_NO_MOTION_THRESH             0.3
#define BMA253_SLOPE_INT_DURATION           3
#define BMA253_SLOPE_INT_THRESH             0.3

#define BMA253_LOW_G_DELAY_MS_DEFAULT       20
#define BMA253_LOW_DUR                      142
#define BMA253_LOW_THRESHOLD                0.375
#define BMA253_LOW_HYS                      0.125

#define BMA253_LOW_AXIS_SUMMING             false

#define BMA253_HIGH_G_DELAY_MS_DEFAULT      40
#define BMA253_HIGH_DUR                     40
#define BMA253_HIGH_THRESHOLD_G             1.5
#define BMA253_HIGH_HYS                     0.25

#define BMA253_TAP_THRESHOLD_G              1.0

#define BMA253_BLOCKING_ANGLE               0x08
#define BMA253_ORIENT_HYSTER_G              0.125
#define BMA253_SIG_UP_DN                    false

/* define interrupt cofiguration type */
#define BMA253_SINGLE_TAP_INT               0
#define BMA253_DOUBLE_TAP_INT               1
#define BMA253_LOW_G_INT                    2
#define BMA253_ORIENT_INT                   3
#define BMA253_SLEEP_INT                    4
#define BMA253_WAKEUP_INT                   5
//#define BMA253_HIGH_G_INT                   6
#define BMA253_HIGH_G_P_X_INT               6
#define BMA253_HIGH_G_P_Y_INT               7
#define BMA253_HIGH_G_P_Z_INT               8
#define BMA253_HIGH_G_N_X_INT               9
#define BMA253_HIGH_G_N_Y_INT               10
#define BMA253_HIGH_G_N_Z_INT               11

#define BMA253_LOW_G_SRC                    0x01
#define BMA253_SLEEP_SRC                    0x08
#define BMA253_WAKEUP_SRC                   0x04
#define BMA253_HIGH_G_SRC                   0x02
#define BMA253_DOUBLE_TAP_SRC               0x10
#define BMA253_SINGLE_TAP_SRC               0x20
#define BMA253_ORIENT_SRC                   0x40

#define BMA253_POS_HIGH_G_X_SRC             0x01
#define BMA253_POS_HIGH_G_Y_SRC             0x02
#define BMA253_POS_HIGH_G_Z_SRC             0x04
#define BMA253_NEG_HIGH_G_X_SRC             0x01
#define BMA253_NEG_HIGH_G_Y_SRC             0x02
#define BMA253_NEG_HIGH_G_Z_SRC             0x04

/* Range of acceleration measurements */
enum bma253_g_range {
    BMA253_G_RANGE_2  = 0,
    BMA253_G_RANGE_4  = 1,
    BMA253_G_RANGE_8  = 2,
    BMA253_G_RANGE_16 = 3,
};

/* How often acceleration measurements are taken */
enum bma253_filter_bandwidth {
    BMA253_FILTER_BANDWIDTH_7_81_HZ  = 0,
    BMA253_FILTER_BANDWIDTH_15_63_HZ = 1,
    BMA253_FILTER_BANDWIDTH_31_25_HZ = 2,
    BMA253_FILTER_BANDWIDTH_62_5_HZ  = 3,
    BMA253_FILTER_BANDWIDTH_125_HZ   = 4,
    BMA253_FILTER_BANDWIDTH_250_HZ   = 5,
    BMA253_FILTER_BANDWIDTH_500_HZ   = 6,
    BMA253_FILTER_BANDWIDTH_1000_HZ  = 7,
};

/* Quiet time after a double/single tap */
enum bma253_tap_quiet {
    BMA253_TAP_QUIET_20_MS = 0,
    BMA253_TAP_QUIET_30_MS = 1,
};

/* Settling time after a double/single tap */
enum bma253_tap_shock {
    BMA253_TAP_SHOCK_50_MS = 0,
    BMA253_TAP_SHOCK_75_MS = 1,
};

/* How long to wait for the next tap in a double tap scenario */
enum bma253_d_tap_window {
    BMA253_D_TAP_WINDOW_50_MS  = 0,
    BMA253_D_TAP_WINDOW_100_MS = 1,
    BMA253_D_TAP_WINDOW_150_MS = 2,
    BMA253_D_TAP_WINDOW_200_MS = 3,
    BMA253_D_TAP_WINDOW_250_MS = 4,
    BMA253_D_TAP_WINDOW_375_MS = 5,
    BMA253_D_TAP_WINDOW_500_MS = 6,
    BMA253_D_TAP_WINDOW_700_MS = 7,
};

/* How many samples to use after a wake up from a low power mode to determine
 * whether a tap occurred */
enum bma253_tap_wake_samples {
    BMA253_TAP_WAKE_SAMPLES_2  = 0,
    BMA253_TAP_WAKE_SAMPLES_4  = 1,
    BMA253_TAP_WAKE_SAMPLES_8  = 2,
    BMA253_TAP_WAKE_SAMPLES_16 = 3,
};

/* Block generation of orientation events based on given criteria */
enum bma253_orient_blocking {
    BMA253_ORIENT_BLOCKING_NONE                       = 0,
    BMA253_ORIENT_BLOCKING_ACCEL_ONLY                 = 1,
    BMA253_ORIENT_BLOCKING_ACCEL_AND_SLOPE            = 2,
    BMA253_ORIENT_BLOCKING_ACCEL_AND_SLOPE_AND_STABLE = 3,
};

/* Orientation mode configuration, used to determine thresholds for
 * transitions between different orientations */
enum bma253_orient_mode {
    BMA253_ORIENT_MODE_SYMMETRICAL       = 0,
    BMA253_ORIENT_MODE_HIGH_ASYMMETRICAL = 1,
    BMA253_ORIENT_MODE_LOW_ASYMMETRICAL  = 2,
};

/* Power mode for the device */
enum bma253_power_mode {
    BMA253_POWER_MODE_NORMAL       = 0,
    BMA253_POWER_MODE_DEEP_SUSPEND = 1,
    BMA253_POWER_MODE_SUSPEND      = 2,
    BMA253_POWER_MODE_STANDBY      = 3,
    BMA253_POWER_MODE_LPM_1        = 4,
    BMA253_POWER_MODE_LPM_2        = 5,
};

/* Duration of sleep whenever the device is in a power mode that alternates
 * between wake and sleep (LPM 1 & 2) */
enum bma253_sleep_duration {
    BMA253_SLEEP_DURATION_0_5_MS = 0,
    BMA253_SLEEP_DURATION_1_MS   = 1,
    BMA253_SLEEP_DURATION_2_MS   = 2,
    BMA253_SLEEP_DURATION_4_MS   = 3,
    BMA253_SLEEP_DURATION_6_MS   = 4,
    BMA253_SLEEP_DURATION_10_MS  = 5,
    BMA253_SLEEP_DURATION_25_MS  = 6,
    BMA253_SLEEP_DURATION_50_MS  = 7,
    BMA253_SLEEP_DURATION_100_MS = 8,
    BMA253_SLEEP_DURATION_500_MS = 9,
    BMA253_SLEEP_DURATION_1_S    = 10,
};

/* Read moe for the sensor */
enum bma253_read_mode {
    BMA253_READ_M_POLL = 0,
    BMA253_READ_M_STREAM = 1,
};

struct bma253_notif_cfg {
    sensor_event_type_t event;
    uint8_t notif_src;
    uint8_t int_cfg;
};

/* Used to track interrupt state to wake any present waiters */
struct bma253_int {
    /* Synchronize access to this structure */
    os_sr_t lock;
    /* Sleep waiting for an interrupt to occur */
    struct os_sem wait;
    /* Is the interrupt currently active */
    bool active;
    /* Is there a waiter currently sleeping */
    bool asleep;
    /* Configured interrupts */
    struct sensor_int *ints;
};

/* Device private data */
struct bma253_private_driver_data {
    struct bma253_int * interrupt;
    struct sensor_notify_ev_ctx notify_ctx;
    struct sensor_read_ev_ctx read_ctx;
    uint8_t registered_mask;

    uint8_t int_num;
    uint8_t int_route;
    uint8_t int_ref_cnt;

    uint8_t fifo_buf[31 * 6];
};

typedef union bma253_feature_enable {
    struct {
        uint32_t any_motion :1;
        uint32_t double_tap :1;
        uint32_t single_tap :1;
        uint32_t orient     :1;
        uint32_t low_g      :1;
        uint32_t high_g     :1;
    } req;

    uint32_t bits;
} bma253_feature_enable_t;

/* Settings for the low-g interrupt */
struct low_g_int_cfg {
    uint16_t delay_ms;
    float thresh_g;
    float hyster_g;
    bool axis_summing;
};

struct high_g_int_cfg {
    float hyster_g;
    uint16_t delay_ms;
    float thresh_g;
};

/* Settings for the slow/no-motion interrupt */
struct slow_no_mot_int_cfg {
    uint16_t duration_p_or_s;
    float thresh_g;
};

/* Settings for the slope interrupt */
struct slope_int_cfg {
    uint8_t duration_p;
    float thresh_g;
};

/* Settings for the double/single tap interrupt */
struct tap_int_cfg {
    enum bma253_tap_quiet tap_quiet;
    enum bma253_tap_shock tap_shock;
    enum bma253_d_tap_window d_tap_window;
    enum bma253_tap_wake_samples tap_wake_samples;
    float thresh_g;
};

/* Settings for the orientation interrupt */
struct orient_int_cfg {
    float hyster_g;
    enum bma253_orient_blocking orient_blocking;
    enum bma253_orient_mode orient_mode;
    bool signal_up_dn;
    uint8_t blocking_angle;
};

/* Default configuration values to use with the device */
struct bma253_cfg {
    /* Accelerometer configuration */
    enum bma253_g_range g_range;
    enum bma253_filter_bandwidth filter_bandwidth;
    /* Whether to use data that has not been filtered at all */
    bool use_unfiltered_data;

    struct slope_int_cfg slope_int_cfg;
    struct slow_no_mot_int_cfg slow_no_mot_int_cfg;
    struct low_g_int_cfg low_g_int_cfg;
    struct high_g_int_cfg high_g_int_cfg;
    struct tap_int_cfg tap_int_cfg;
    struct orient_int_cfg orient_int_cfg;

    bool orient_signal_ud;
    /* Offsets for acceleration measurements, by axis */
    float offset_x_g;
    float offset_y_g;
    float offset_z_g;
    /* Power management configuration */
    enum bma253_power_mode power_mode;
    enum bma253_sleep_duration sleep_duration;
    /* Select read mode */
    enum bma253_read_mode read_mode;
    /* Applicable sensor types supported */
    sensor_type_t sensor_mask;
    /* Notif config */
    struct bma253_notif_cfg *notif_cfg;
    uint8_t max_num_notif;
};

#ifndef MAX
#define MAX(n, m) (((n) < (m)) ? (m) : (n))
#endif

/* The device itself */
struct bma253 {
#if MYNEWT_VAL(BUS_DRIVER_PRESENT)
    struct bus_i2c_node node;
#else
    /* Underlying OS device */
    struct os_dev dev;
#endif
    /* The sensor infrastructure */
    struct sensor sensor;
    /* Default configuration values */
    struct bma253_cfg cfg;
    /* Active interrupt state */
    struct bma253_int intr;
    /* Active power mode, could be different from default configured
     * power mode if a function that requires a higher power mode is
     * currently running. */
    enum bma253_power_mode power;

    /* Private driver data */
    struct bma253_private_driver_data pdd;

    /* all the features currently enabled */
    sensor_event_type_t     ev_enabled;

    uint32_t                daq_req_new: 1;
    /* the data acquisition is in progress */
    uint32_t                daq_in_proc: 1;

    /* this flag is to turn on or off bus read/write monitoring */
    uint32_t                bus_rw_mon      :1;

    /* currently configured bandwidth on hw, of type: enum bma253_filter_bandwidth */
    uint32_t                bandwidth_curr  :3;

    /* this flag tells that an important hw config change (like bandwidth, power mode) is pending */
    uint32_t                hw_cfg_pending  :1;

    /* pending power mode, of type enum bma253_power_mode */
    uint32_t                pending_hw_cfg_pm:3;

    /* pending bandwidth, of type enum bma253_filter_bandwidth */
    uint32_t                pending_hw_cfg_bw:3;

};

/* Offset compensation is performed to target this given value, by axis */
enum bma253_offset_comp_target {
    BMA253_OFFSET_COMP_TARGET_0_G     = 0,
    BMA253_OFFSET_COMP_TARGET_NEG_1_G = 1,
    BMA253_OFFSET_COMP_TARGET_POS_1_G = 2,
};

/* The device's X/Y orientation, in form of rotation */
enum bma253_orient_xy {
    BMA253_ORIENT_XY_PORTRAIT_UPRIGHT     = 0,
    BMA253_ORIENT_XY_PORTRAIT_UPSIDE_DOWN = 1,
    BMA253_ORIENT_XY_LANDSCAPE_LEFT       = 2,
    BMA253_ORIENT_XY_LANDSCAPE_RIGHT      = 3,
};

/* The device's full orientation */
struct bma253_orient_xyz {
    /* The X/Y orientation */
    enum bma253_orient_xy orient_xy;
    /* Is device facing upward or downward */
    bool downward_z;
};

/* Type of tap event to look for */
enum bma253_tap_type {
    BMA253_TAP_TYPE_DOUBLE = 0,
    BMA253_TAP_TYPE_SINGLE = 1,
};

/**
 * Perform a self test of the device and report on its health.
 *
 * @param The device object.
 * @param Multiplier on the high amplitude self test minimums; 1.0 for default.
 * @param Multiplier on the low amplitude self test minimums; 0.0 for default.
 * @param The result of the self-test: false if passed, true if failed.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_self_test(struct bma253 * bma253,
                 float delta_high_mult,
                 float delta_low_mult,
                 bool * self_test_fail);

/**
 * Perform an offset compensation and use the resulting offsets.
 *
 * @param The device object.
 * @param The correct target value for the X axis.
 * @param The correct target value for the Y axis.
 * @param The correct target value for the Z axis.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_offset_compensation(struct bma253 * bma253,
                           enum bma253_offset_comp_target target_x,
                           enum bma253_offset_comp_target target_y,
                           enum bma253_offset_comp_target target_z);

/**
 * Return the current compensation offsets in use.
 *
 * @param The device object.
 * @param The offset for the X axis, filled in by this function.
 * @param The offset for the Y axis, filled in by this function.
 * @param The offset for the Z axis, filled in by this function.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_query_offsets(struct bma253 * bma253,
                     float * offset_x_g,
                     float * offset_y_g,
                     float * offset_z_g);

/**
 * Store and use the provided compensation offsets.
 *
 * @param The device object.
 * @param The offset for the X axis.
 * @param The offset for the Y axis.
 * @param the offset for the Z axis.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_write_offsets(struct bma253 * bma253,
                     float offset_x_g,
                     float offset_y_g,
                     float offset_z_g);

/**
 * Provide a continuous stream of accelerometer readings.
 *
 * @param The sensor ptr
 * @param The sensor type
 * @param The function pointer to invoke for each accelerometer reading.
 * @param The opaque pointer that will be passed in to the function.
 * @param If non-zero, how long the stream should run in milliseconds.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_stream_read(struct sensor *sensor,
                   sensor_type_t sensor_type,
                   sensor_data_func_t read_func,
                   void *read_arg,
                   uint32_t time_ms);

/**
 * Do accelerometer polling reads
 *
 * @param The sensor ptr
 * @param The sensor type
 * @param The function pointer to invoke for each accelerometer reading.
 * @param The opaque pointer that will be passed in to the function.
 * @param If non-zero, how long the stream should run in milliseconds.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_poll_read(struct sensor * sensor,
                 sensor_type_t sensor_type,
                 sensor_data_func_t data_func,
                 void * data_arg,
                 uint32_t timeout);

/**
 * Get the current temperature at the device.
 *
 * @param The device object.
 * @param The current temperature in celsius, filled in by this function.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_current_temp(struct bma253 * bma253,
                    float * temp_c);

/**
 * Get the current device orientation.
 *
 * @param The device object.
 * @param The current orientation, filled in by this function.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_current_orient(struct bma253 * bma253,
                      struct bma253_orient_xyz * orient_xyz);

/**
 * Block until the device orientation changes.
 *
 * @param The device object.
 * @param The new orientation, filled in by this function.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_wait_for_orient(struct bma253 * bma253,
                       struct bma253_orient_xyz * orient_xyz);

/**
 * Block until a high-g event occurs.
 *
 * @param The device object.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_wait_for_high_g(struct bma253 * bma253);

/**
 * Block until a low-g event occurs.
 *
 * @param The device object.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_wait_for_low_g(struct bma253 * bma253);

/**
 * Block until a single or double tap event occurs.
 *
 * @param The device object.
 * @param The type of tap event to look for.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_wait_for_tap(struct bma253 * bma253,
                    enum bma253_tap_type tap_type);

/**
 * Change the default power settings.
 *
 * @param The device object.
 * @param The new power mode, which the device resides in unless a different
 *        and more aggressive power mode is required to satisfy a running API
 *        function.
 * @param The new sleep duration, used whenever device is in LPM_1/2 mode
 *        either due to default power mode or due to being in a temporarily
 *        overridden power mode.
 */
int
bma253_power_settings(struct bma253 * bma253,
                      enum bma253_power_mode power_mode,
                      enum bma253_sleep_duration sleep_duration);

/**
 * Configure the sensor.
 *
 * @param ptr to sensor driver
 * @param ptr to sensor driver config
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_config(struct bma253 * bma253, struct bma253_cfg * cfg);

/**
 * Expects to be called back through os_dev_create().
 *
 * @param ptr to the device object associated with this accelerometer
 * @param argument passed to OS device init
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_init(struct os_dev * dev, void * arg);

#if MYNEWT_VAL(BMA253_CLI)
/**
 * Initialize the BMA253 shell extensions.
 *
 * @return 0 on success, non-zero on failure.
 */
int
bma253_shell_init(void);
#endif

#if MYNEWT_VAL(BUS_DRIVER_PRESENT)
/**
 * Create I2C bus node for BMA253 sensor
 *
 * @param node        Bus node
 * @param name        Device name
 * @param i2c_cfg     I2C node configuration
 * @param sensor_itf  Sensors interface
 *
 * @return 0 on success, non-zero on failure
 */
int
bma253_create_i2c_sensor_dev(struct bus_i2c_node *node, const char *name,
                             const struct bus_i2c_node_cfg *i2c_cfg,
                             struct sensor_itf *sensor_itf);
#endif
#ifdef __cplusplus
}
#endif

#endif


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/corecache/p10_l2err_extract.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2020,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///----------------------------------------------------------------------------
///
/// @file p10_l2err_extract.H
///
/// @brief Parse and extract error information from L2 trace array (FAPI2)
///
/// *HWP HW Maintainer: Benjamin Gass <bgass@ibm.com>
/// *HWP FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com>
/// *HWP Consumed by : HB, PRDF
///----------------------------------------------------------------------------
#ifndef _P10_L2ERR_EXTRACT_H_
#define _P10_L2ERR_EXTRACT_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------

// enum used to denote what type of error occured or which we want to find
enum p10_l2err_extract_err_type
{
    L2ERR_CE,
    L2ERR_UE,
    L2ERR_CE_UE
};

// structure to document control/data registers for each supported trace array
struct p10_l2err_extract_err_data
{
    p10_l2err_extract_err_type      ce_ue;
    uint8_t                         member;  //3-bit
    uint8_t                         dw;      //3-bit
    uint8_t                         bank;    //1-bit
    bool                            back_of_2to1_nextcycle;
    uint8_t                         syndrome_col;
    uint16_t                        real_address_47_56;
};

// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p10_l2err_extract_FP_t)
(const fapi2::Target<fapi2::TARGET_TYPE_CORE>&,
 const fapi2::variable_buffer&,
 p10_l2err_extract_err_type,
 p10_l2err_extract_err_data&,
 bool&);

extern "C"
{

//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
///
/// @brief  FAPI2 p10_l2err_extract HWP entry point
///         Parse and extract L2 error information from provided
///         L2_T0 trace array that has been stopped on an L2 CE or UE.
///
/// @param[in]  i_target      => core chiplet target
/// @param[in]  i_ta_data     => Input trace data buffer
/// @param[in]  i_err_type    => Type of error that is to be extracted (CE,UE,both)
/// @param[out] o_err_data    => Failing location information for CE or UE
/// @param[out] o_error_found => Error is found
///
    fapi2::ReturnCode p10_l2err_extract(
        const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
        const fapi2::variable_buffer& i_ta_data,
        p10_l2err_extract_err_type i_err_type,
        p10_l2err_extract_err_data& o_err_data,
        bool& o_error_found);

} // extern "C"

#endif // _P10_L2ERR_EXTRACT_H_

redpajama_set_name: RedPajamaGithub


text:
AudioInputDevice::AudioInputDevice(size_t buffer_size,
                                   int channels,
                                   double sample_rate,
                                   CaptureCallback* callback,
                                   CaptureEventHandler* event_handler)
    : callback_(callback),
      event_handler_(event_handler),
      audio_delay_milliseconds_(0),
      volume_(1.0),
      stream_id_(0),
      session_id_(0),
      pending_device_ready_(false),
      shared_memory_handle_(base::SharedMemory::NULLHandle()),
      socket_handle_(base::SyncSocket::kInvalidHandle),
      memory_length_(0) {
  filter_ = RenderThreadImpl::current()->audio_input_message_filter();
  audio_data_.reserve(channels);
#if defined(OS_MACOSX)
  VLOG(1) << "Using AUDIO_PCM_LOW_LATENCY as input mode on Mac OS X.";
  audio_parameters_.format = AudioParameters::AUDIO_PCM_LOW_LATENCY;
#elif defined(OS_WIN)
  VLOG(1) << "Using AUDIO_PCM_LOW_LATENCY as input mode on Windows.";
  audio_parameters_.format = AudioParameters::AUDIO_PCM_LOW_LATENCY;
#else
  // TODO(henrika): add support for AUDIO_PCM_LOW_LATENCY on Linux as well.
  audio_parameters_.format = AudioParameters::AUDIO_PCM_LINEAR;
#endif
  audio_parameters_.channels = channels;
  audio_parameters_.sample_rate = static_cast<int>(sample_rate);
  audio_parameters_.bits_per_sample = 16;
  audio_parameters_.samples_per_packet = buffer_size;
  for (int i = 0; i < channels; ++i) {
    float* channel_data = new float[buffer_size];
    audio_data_.push_back(channel_data);
  }
}

AudioInputDevice::~AudioInputDevice() {
  // TODO(henrika): The current design requires that the user calls
  // Stop before deleting this class.
  CHECK_EQ(0, stream_id_);
  for (int i = 0; i < audio_parameters_.channels; ++i)
    delete [] audio_data_[i];
}

void AudioInputDevice::Start() {
  VLOG(1) << "Start()";
  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&AudioInputDevice::InitializeOnIOThread, this));
}

void AudioInputDevice::SetDevice(int session_id) {
  VLOG(1) << "SetDevice (session_id=" << session_id << ")";
  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&AudioInputDevice::SetSessionIdOnIOThread, this,
                 session_id));
}

void AudioInputDevice::Stop() {
  DCHECK(MessageLoop::current() != ChildProcess::current()->io_message_loop());
  VLOG(1) << "Stop()";
  // Max waiting time for Stop() to complete. If this time limit is passed,
  // we will stop waiting and return false. It ensures that Stop() can't block
  // the calling thread forever.
  const base::TimeDelta kMaxTimeOut = base::TimeDelta::FromMilliseconds(1000);

  base::WaitableEvent completion(false, false);

  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&AudioInputDevice::ShutDownOnIOThread, this,
                 &completion));

  // We wait here for the IO task to be completed to remove race conflicts
  // with OnLowLatencyCreated() and to ensure that Stop() acts as a synchronous
  // function call.
  if (!completion.TimedWait(kMaxTimeOut)) {
    LOG(ERROR) << "Failed to shut down audio input on IO thread";
  }

  if (audio_thread_.get()) {
    // Terminate the main thread function in the audio thread.
    {
      base::SyncSocket socket(socket_handle_);
    }
    // Wait for the audio thread to exit.
    audio_thread_->Join();
    // Ensures that we can call Stop() multiple times.
    audio_thread_.reset(NULL);
  }
}

bool AudioInputDevice::SetVolume(double volume) {
  NOTIMPLEMENTED();
  return false;
}

bool AudioInputDevice::GetVolume(double* volume) {
  NOTIMPLEMENTED();
  return false;
}

void AudioInputDevice::InitializeOnIOThread() {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
  // Make sure we don't call Start() more than once.
  DCHECK_EQ(0, stream_id_);
  if (stream_id_)
    return;

  stream_id_ = filter_->AddDelegate(this);
  // If |session_id_| is not specified, it will directly create the stream;
  // otherwise it will send a AudioInputHostMsg_StartDevice msg to the browser
  // and create the stream when getting a OnDeviceReady() callback.
  if (!session_id_) {
    Send(new AudioInputHostMsg_CreateStream(
        stream_id_, audio_parameters_, true,
        AudioManagerBase::kDefaultDeviceId));
  } else {
    Send(new AudioInputHostMsg_StartDevice(stream_id_, session_id_));
    pending_device_ready_ = true;
  }
}

void AudioInputDevice::SetSessionIdOnIOThread(int session_id) {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
  session_id_ = session_id;
}

void AudioInputDevice::StartOnIOThread() {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
  if (stream_id_)
    Send(new AudioInputHostMsg_RecordStream(stream_id_));
}

void AudioInputDevice::ShutDownOnIOThread(base::WaitableEvent* completion) {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
  // Make sure we don't call shutdown more than once.
  if (!stream_id_) {
    completion->Signal();
    return;
  }

  filter_->RemoveDelegate(stream_id_);
  Send(new AudioInputHostMsg_CloseStream(stream_id_));

  stream_id_ = 0;
  session_id_ = 0;
  pending_device_ready_ = false;

  completion->Signal();
}

void AudioInputDevice::SetVolumeOnIOThread(double volume) {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
  if (stream_id_)
    Send(new AudioInputHostMsg_SetVolume(stream_id_, volume));
}

void AudioInputDevice::OnLowLatencyCreated(
    base::SharedMemoryHandle handle,
    base::SyncSocket::Handle socket_handle,
    uint32 length) {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
#if defined(OS_WIN)
  DCHECK(handle);
  DCHECK(socket_handle);
#else
  DCHECK_GE(handle.fd, 0);
  DCHECK_GE(socket_handle, 0);
#endif
  DCHECK(length);
  DCHECK(!audio_thread_.get());

  VLOG(1) << "OnLowLatencyCreated (stream_id=" << stream_id_ << ")";
  // Takes care of the case when Stop() is called before OnLowLatencyCreated().
  if (!stream_id_) {
    base::SharedMemory::CloseHandle(handle);
    // Close the socket handler.
    base::SyncSocket socket(socket_handle);
    return;
  }

  shared_memory_handle_ = handle;
  memory_length_ = length;

  socket_handle_ = socket_handle;

  audio_thread_.reset(
      new base::DelegateSimpleThread(this, "RendererAudioInputThread"));
  audio_thread_->Start();

  MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&AudioInputDevice::StartOnIOThread, this));
}

void AudioInputDevice::OnVolume(double volume) {
  NOTIMPLEMENTED();
}

void AudioInputDevice::OnStateChanged(AudioStreamState state) {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
  switch (state) {
    case kAudioStreamPaused:
      // Do nothing if the stream has been closed.
      if (!stream_id_)
        return;

      filter_->RemoveDelegate(stream_id_);

      // Joining the audio thread will be quite soon, since the stream has
      // been closed before.
      if (audio_thread_.get()) {
        {
          base::SyncSocket socket(socket_handle_);
        }
        audio_thread_->Join();
        audio_thread_.reset(NULL);
      }

      if (event_handler_)
        event_handler_->OnDeviceStopped();

      stream_id_ = 0;
      pending_device_ready_ = false;
      break;
    case kAudioStreamPlaying:
      NOTIMPLEMENTED();
      break;
    case kAudioStreamError:
      DLOG(WARNING) << "AudioInputDevice::OnStateChanged(kError)";
      break;
    default:
      NOTREACHED();
      break;
  }
}

void AudioInputDevice::OnDeviceReady(const std::string& device_id) {
  DCHECK(MessageLoop::current() == ChildProcess::current()->io_message_loop());
  VLOG(1) << "OnDeviceReady (device_id=" << device_id << ")";

  // Takes care of the case when Stop() is called before OnDeviceReady().
  if (!pending_device_ready_)
    return;

  // If AudioInputDeviceManager returns an empty string, it means no device
  // is ready for start.
  if (device_id.empty()) {
    filter_->RemoveDelegate(stream_id_);
    stream_id_ = 0;
  } else {
    Send(new AudioInputHostMsg_CreateStream(
        stream_id_, audio_parameters_, true, device_id));
  }

  pending_device_ready_ = false;
  // Notify the client that the device has been started.
  if (event_handler_)
    event_handler_->OnDeviceStarted(device_id);
}

void AudioInputDevice::Send(IPC::Message* message) {
  filter_->Send(message);
}

// Our audio thread runs here. We receive captured audio samples on
// this thread.
void AudioInputDevice::Run() {
  audio_thread_->SetThreadPriority(base::kThreadPriority_RealtimeAudio);

  base::SharedMemory shared_memory(shared_memory_handle_, false);
  shared_memory.Map(memory_length_);

  base::SyncSocket socket(socket_handle_);

  int pending_data;
  const int samples_per_ms =
      static_cast<int>(audio_parameters_.sample_rate) / 1000;
  const int bytes_per_ms = audio_parameters_.channels *
      (audio_parameters_.bits_per_sample / 8) * samples_per_ms;

  while ((sizeof(pending_data) == socket.Receive(&pending_data,
                                                sizeof(pending_data))) &&
         (pending_data >= 0)) {
    // TODO(henrika): investigate the provided |pending_data| value
    // and ensure that it is actually an accurate delay estimation.

    // Convert the number of pending bytes in the capture buffer
    // into milliseconds.
    audio_delay_milliseconds_ = pending_data / bytes_per_ms;

    FireCaptureCallback(reinterpret_cast<int16*>(shared_memory.memory()));
  }
}

void AudioInputDevice::FireCaptureCallback(int16* input_audio) {
  if (!callback_)
      return;

  const size_t number_of_frames = audio_parameters_.samples_per_packet;

  const int bytes_per_sample = sizeof(input_audio[0]);

  // Deinterleave each channel and convert to 32-bit floating-point
  // with nominal range -1.0 -> +1.0.
  for (int channel_index = 0; channel_index < audio_parameters_.channels;
       ++channel_index) {
    media::DeinterleaveAudioChannel(input_audio,
                                    audio_data_[channel_index],
                                    audio_parameters_.channels,
                                    channel_index,
                                    bytes_per_sample,
                                    number_of_frames);
  }

  // Deliver captured data to the client in floating point format
  // and update the audio-delay measurement.
  callback_->Capture(audio_data_,
                     number_of_frames,
                     audio_delay_milliseconds_);
}


text:
function BubbleInfo(id, color, magnitude ){
    this.id = id;
    this.color = color;
    this.magnitude = magnitude;
    this.margin;

    alert( id + " : " + color + " : " + magnitude );
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">WantyTemplate</string>
</resources>


text: angular.module('gestoFood', ['foodController', 'foodService']);


text:
/*
 * Copyright (c) 2011-2013 The original author or authors
 * ------------------------------------------------------
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Apache License v2.0 which accompanies this distribution.
 *
 *     The Eclipse Public License is available at
 *     http://www.eclipse.org/legal/epl-v10.html
 *
 *     The Apache License v2.0 is available at
 *     http://www.opensource.org/licenses/apache2.0.php
 *
 * You may elect to redistribute this code under either of these licenses.
 */
package org.vertx.java.core.http.impl;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultHttpContent;

/**
 *
 * This file was copied from the Vert.x code base. Unlike the original version it used a _patched_ {@link
 * HttpChunkContentCompressor} letting the HTTP handler disables the encoding per request.
 *
 * @author Norman Maurer
 */
final class HttpChunkContentCompressor extends WisdomHttpContentCompressor {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof ByteBuf) {
            // convert ByteBuf to HttpContent to make it work with compression. This is needed as we use the
            // ChunkedWriteHandler to send files when compression is enabled.
            msg =  new DefaultHttpContent((ByteBuf) msg);
        }
        super.write(ctx, msg, promise);
    }
}


text:
module MsgDiagram.Model where

type MsgDiagram = [MsgDiagramStep]

data MsgDiagramStep = MsgDiagramStep {
      num  :: Int,
      from :: String,
      to   :: String,
      ms   :: Messages
    } deriving (Show, Read)

type Messages = [Message]
type Message = String

-- --------------------------------------------------------------------- [ EOF ]


text:
from django import template

register = template.Library()

@register.inclusion_tag("people/researcher_item.html", takes_context=True)
def show_researcher(context, researcher):
    return {"researcher": researcher, 'request': context['request']}

@register.simple_tag
def clear_search_url(request):
    getvars = request.GET.copy()
    if "search" in getvars:
        del getvars["search"]
    if len(getvars.keys()) > 0:
        return "%s?%s" % (request.path, getvars.urlencode())
    else:
        return request.path


text:
package golog

type Facility int

const (
	// Facility.

	// From /usr/include/sys/syslog.h.
	// These are the same up to LOG_FTP on Linux, BSD, and OS X.
	SYSLOG_KERN Facility = iota << 3
	SYSLOG_USER
	SYSLOG_MAIL
	SYSLOG_DAEMON
	SYSLOG_AUTH
	SYSLOG_SYSLOG
	SYSLOG_LPR
	SYSLOG_NEWS
	SYSLOG_UUCP
	SYSLOG_CRON
	SYSLOG_AUTHPRIV
	SYSLOG_FTP
	_ // unused
	_ // unused
	_ // unused
	_ // unused
	SYSLOG_LOCAL0
	SYSLOG_LOCAL1
	SYSLOG_LOCAL2
	SYSLOG_LOCAL3
	SYSLOG_LOCAL4
	SYSLOG_LOCAL5
	SYSLOG_LOCAL6
	SYSLOG_LOCAL7
)


text:
"use strict";
var $___46__46__47_syntax_47_TokenType_46_js__,
    $__ModuleTransformer_46_js__,
    $__ParseTreeFactory_46_js__,
    $__globalThis_46_js__,
    $__scopeContainsThis_46_js__,
    $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__,
    $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__,
    $__PlaceholderParser_46_js__;
var $__0 = ($___46__46__47_syntax_47_TokenType_46_js__ = require("../syntax/TokenType.js"), $___46__46__47_syntax_47_TokenType_46_js__ && $___46__46__47_syntax_47_TokenType_46_js__.__esModule && $___46__46__47_syntax_47_TokenType_46_js__ || {default: $___46__46__47_syntax_47_TokenType_46_js__}),
    CONST = $__0.CONST,
    LET = $__0.LET;
var ModuleTransformer = ($__ModuleTransformer_46_js__ = require("./ModuleTransformer.js"), $__ModuleTransformer_46_js__ && $__ModuleTransformer_46_js__.__esModule && $__ModuleTransformer_46_js__ || {default: $__ModuleTransformer_46_js__}).ModuleTransformer;
var $__2 = ($__ParseTreeFactory_46_js__ = require("./ParseTreeFactory.js"), $__ParseTreeFactory_46_js__ && $__ParseTreeFactory_46_js__.__esModule && $__ParseTreeFactory_46_js__ || {default: $__ParseTreeFactory_46_js__}),
    createAssignmentStatement = $__2.createAssignmentStatement,
    createArgumentList = $__2.createArgumentList,
    createBindingIdentifier = $__2.createBindingIdentifier,
    createCallExpression = $__2.createCallExpression,
    createExpressionStatement = $__2.createExpressionStatement,
    createForInStatement = $__2.createForInStatement,
    createFunctionBody = $__2.createFunctionBody,
    createIfStatement = $__2.createIfStatement,
    createImmediatelyInvokedFunctionExpression = $__2.createImmediatelyInvokedFunctionExpression,
    createIdentifierExpression = $__2.createIdentifierExpression,
    createMemberLookupExpression = $__2.createMemberLookupExpression,
    createMemberExpression = $__2.createMemberExpression,
    createObjectLiteral = $__2.createObjectLiteral,
    createScopedExpression = $__2.createScopedExpression,
    createReturnStatement = $__2.createReturnStatement,
    createUseStrictDirective = $__2.createUseStrictDirective,
    createVariableDeclarationList = $__2.createVariableDeclarationList,
    createVariableStatement = $__2.createVariableStatement;
var globalThis = ($__globalThis_46_js__ = require("./globalThis.js"), $__globalThis_46_js__ && $__globalThis_46_js__.__esModule && $__globalThis_46_js__ || {default: $__globalThis_46_js__}).default;
var scopeContainsThis = ($__scopeContainsThis_46_js__ = require("./scopeContainsThis.js"), $__scopeContainsThis_46_js__ && $__scopeContainsThis_46_js__.__esModule && $__scopeContainsThis_46_js__ || {default: $__scopeContainsThis_46_js__}).default;
var IMPORT_SPECIFIER_SET = ($___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__ = require("../syntax/trees/ParseTreeType.js"), $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__ && $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__.__esModule && $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__ || {default: $___46__46__47_syntax_47_trees_47_ParseTreeType_46_js__}).IMPORT_SPECIFIER_SET;
var AnonBlock = ($___46__46__47_syntax_47_trees_47_ParseTrees_46_js__ = require("../syntax/trees/ParseTrees.js"), $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__ && $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__.__esModule && $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__ || {default: $___46__46__47_syntax_47_trees_47_ParseTrees_46_js__}).AnonBlock;
var parseStatement = ($__PlaceholderParser_46_js__ = require("./PlaceholderParser.js"), $__PlaceholderParser_46_js__ && $__PlaceholderParser_46_js__.__esModule && $__PlaceholderParser_46_js__ || {default: $__PlaceholderParser_46_js__}).parseStatement;
var anonInlineModules = 0;
var InlineES6ModuleTransformer = function($__super) {
  function InlineES6ModuleTransformer(identifierGenerator, reporter, options, metadata) {
    $traceurRuntime.superConstructor(InlineES6ModuleTransformer).call(this, identifierGenerator, reporter, options);
    this.metadata_ = metadata;
  }
  return ($traceurRuntime.createClass)(InlineES6ModuleTransformer, {
    moduleProlog: function() {
      return [createUseStrictDirective()];
    },
    wrapModule: function(statements) {
      var seed = this.moduleName || 'anon_' + ++anonInlineModules;
      var idName = this.getTempVarNameForModuleName(seed);
      if (this.isRootModule) {
        statements.pop();
        return statements;
      }
      var body = createFunctionBody(statements);
      var moduleExpression;
      if (statements.some(scopeContainsThis)) {
        moduleExpression = createScopedExpression(body, globalThis());
      } else {
        moduleExpression = createImmediatelyInvokedFunctionExpression(body);
      }
      return [createVariableStatement(CONST, idName, moduleExpression)];
    },
    transformExportDeclaration: function(tree) {
      if (this.isRootModule)
        return tree;
      this.exportVisitor_.visitAny(tree);
      return this.transformAny(tree.declaration);
    },
    transformImportDeclaration: function(tree) {
      if (!tree.importClause || (tree.importClause.type === IMPORT_SPECIFIER_SET && tree.importClause.specifiers.length === 0)) {
        return createExpressionStatement(this.transformAny(tree.moduleSpecifier));
      }
      var binding = this.transformAny(tree.importClause);
      var initializer = this.transformAny(tree.moduleSpecifier);
      return createVariableStatement(CONST, binding, initializer);
    },
    transformNamedExport: function(tree) {
      return new AnonBlock(null, []);
    },
    appendExportStatement: function(statements) {
      var $__11 = this;
      var exportProperties = this.getExportProperties();
      var exportObject = createObjectLiteral(exportProperties);
      if (this.exportVisitor_.starExports.length) {
        var starExports = this.exportVisitor_.starExports;
        var starIdents = starExports.map(function(moduleSpecifier) {
          return createIdentifierExpression($__11.getTempVarNameForModuleSpecifier(moduleSpecifier));
        });
        if (exportProperties.length)
          starIdents.push(exportObject);
        var exports = this.getTempIdentifier();
        statements.push(createVariableStatement(LET, exports, createObjectLiteral("")));
        var key = this.getTempIdentifier();
        starIdents.forEach(function(starIdent) {
          statements.push(createForInStatement(createVariableDeclarationList(LET, key, null), starIdent, createIfStatement(createCallExpression(createMemberExpression(starIdent, 'hasOwnProperty'), createArgumentList([createIdentifierExpression(key)])), createAssignmentStatement(createMemberLookupExpression(createIdentifierExpression(exports), createIdentifierExpression(key)), createMemberLookupExpression(starIdent, createIdentifierExpression(key))))));
        });
        statements.push(createReturnStatement(createIdentifierExpression(exports)));
        return statements;
      }
      statements.push(parseStatement($traceurRuntime.getTemplateObject(["return ", ""]), exportObject));
      return statements;
    },
    transformModuleSpecifier: function(tree) {
      return createBindingIdentifier(this.getTempVarNameForModuleSpecifier(tree));
    },
    get isRootModule() {
      return this.moduleName === (this.metadata_ && this.metadata_.rootModule);
    }
  }, {}, $__super);
}(ModuleTransformer);
Object.defineProperties(module.exports, {
  InlineES6ModuleTransformer: {get: function() {
      return InlineES6ModuleTransformer;
    }},
  __esModule: {value: true}
});


text:
package com.alibaba.nacos.config.server.utils;

import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ConfigExecutorTest {

    @Test
    public void testScheduleConfigTask() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.scheduleConfigTask(runnable, 0, 10, TimeUnit.MILLISECONDS);

        TimeUnit.MILLISECONDS.sleep(10);

        Assert.assertTrue(atomicInteger.get() >= 1);

    }

    @Test
    public void testExecuteEmbeddedDump() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.executeEmbeddedDump(runnable);

        TimeUnit.MILLISECONDS.sleep(20);

        Assert.assertEquals(1, atomicInteger.get());

    }

    @Test
    public void testScheduleCorrectUsageTask() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.scheduleCorrectUsageTask(runnable, 0, 10, TimeUnit.MILLISECONDS);

        TimeUnit.MILLISECONDS.sleep(10);

        Assert.assertTrue(atomicInteger.get() >= 1);

    }

    @Test
    public void testExecuteAsyncNotify() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.executeAsyncNotify(runnable);

        TimeUnit.MILLISECONDS.sleep(20);

        Assert.assertEquals(1, atomicInteger.get());

    }

    @Test
    public void testScheduleAsyncNotify() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.scheduleAsyncNotify(runnable, 20, TimeUnit.MILLISECONDS);

        Assert.assertEquals(0, atomicInteger.get());

        TimeUnit.MILLISECONDS.sleep(40);

        Assert.assertEquals(1, atomicInteger.get());
    }

    @Test
    public void testScheduleLongPollingV1() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.scheduleLongPolling(runnable, 0, 10, TimeUnit.MILLISECONDS);

        TimeUnit.MILLISECONDS.sleep(10);

        Assert.assertTrue(atomicInteger.get() >= 1);
    }

    @Test
    public void testScheduleLongPollingV2() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.scheduleLongPolling(runnable, 20, TimeUnit.MILLISECONDS);

        Assert.assertEquals(0, atomicInteger.get());

        TimeUnit.MILLISECONDS.sleep(40);

        Assert.assertEquals(1, atomicInteger.get());
    }

    @Test
    public void testExecuteLongPolling() throws InterruptedException {

        AtomicInteger atomicInteger = new AtomicInteger();

        Runnable runnable = atomicInteger::incrementAndGet;

        ConfigExecutor.executeLongPolling(runnable);

        TimeUnit.MILLISECONDS.sleep(20);

        Assert.assertEquals(1, atomicInteger.get());
    }
}


text:
package com.obsidian.compiler.Types;

import com.obsidian.compiler.AbstractSyntaxTree.IdentifierAstNode;
import com.obsidian.compiler.AbstractSyntaxTree.NullTypeAstNode;
import com.obsidian.compiler.AbstractSyntaxTree.TypeAstNode;
import com.obsidian.compiler.AbstractSyntaxTree.ValueTypeAstNode;
import com.obsidian.compiler.ControlFlowGraph.*;
import com.obsidian.compiler.Lava.*;
import com.obsidian.compiler.LvEvalEnvironment;
import com.obsidian.compiler.MemberInfo;
import com.obsidian.compiler.RawValues.RawValue;
import com.obsidian.compiler.StaticCodeAnalyzer.Errors.CannotFindTypeError;
import com.obsidian.compiler.TODO;

import javax.json.stream.JsonGenerator;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jonathon on 4/26/2017.
 */
public abstract class Type extends CfgNode {

	// The UNKNOWN type is a atom representing that the compiler could not deduce this type
	static Type UNKNOWN = new Type() {
		@Override
		public LvEvalResult eval(LvEvalEnvironment lv) {
			return null;
		}
		@Override
		public String getHumanName() {
			return "UNKNOWN";
		}
		@Override
		public MemberInfo getMemberInfo(LvEvalEnvironment lv, String memberId, RawValue value) {
			return null;
		}
		@Override
		public LvValue getAsString(RawValue value) {
			new PANIC();
			return null;
		}
	};

	public static Type fromAst(LvEvalEnvironment lv, TypeAstNode typeAstNode) {
		Type ret = null;

		if (typeAstNode instanceof ValueTypeAstNode) {
			ValueTypeAstNode valueTypeAstNode = (ValueTypeAstNode) typeAstNode;
			if (valueTypeAstNode.isArray) {
//				ret = new ArrayType(false, Type.fromAst(lv, typeAstNode));
//				new TODO("Array types");
			}
			if (valueTypeAstNode.generic != null) {
				new TODO("Generic types");
			}

			IdentifierAstNode identifier = valueTypeAstNode.type;
			String id = identifier.getText();
			if (id.equals("boolean")) {
				ret = new BooleanType();
			}
			else if (id.equals("string")) {
				ret = new StringType(false);
			}
			else if (id.equals("int")) {
				ret = new IntegerType(IntegerType.SubType.INT);
			}
			else if (id.equals("float")) {
				ret = new FloatType(FloatType.SubType.FLOAT);
			}
			else {
				LvValue global = lv.globalScope.getValue(id);
				if (global != null) {
					if (global.isClassConstructor()) {
						ret = Type.forClassInstance(((ClassConstructorType) global.type).classNode);
					}
					if (global.isEnumDeclaration()) {
						ret = Type.forEnumEntry((EnumDeclarationType) global.type);
//						ret = Type.forEnum(((EnumDeclarationType) global.type).enumeration);
					}
				}
				if (ret == null) {
					lv.sca.emitMessage(new CannotFindTypeError(id, new LvRangeInFile(identifier.sourceFilePath, identifier.charOffset, identifier.charLength)));
				}
			}

			if (valueTypeAstNode.isArray) {
				ret = new ArrayType(false, ret);
			}
		}
		else if (typeAstNode instanceof NullTypeAstNode) {
			ret = Type.forNull();
		}
		else {
			ret = UnionType.fromAst(lv, typeAstNode);
		}

		if (ret != null) {
			ret.setSource(typeAstNode.sourceFilePath, typeAstNode.charOffset, typeAstNode.charLength);
		}

		if (ret == null) {
			ret = Type.unknown();
		}

		return ret;
	}

	private void setSource(String currentFile, int charOffset, int charLength) {
		this.source = new LvRangeInFile(currentFile, charOffset, charLength);
	}

	public static Type fromAst(LvEvalEnvironment lv, ValueTypeAstNode typeAstNode) {
		String id = typeAstNode.type.getText();
		Type ret = null;
		if (id.equals("true")) {
			ret = new BooleanTypeCfgNode(true);
		}
		if (id.equals("false")) {
			ret = new BooleanTypeCfgNode(false);
		}
		if (id.equals("int")) {
			ret = new IntegerType(IntegerType.SubType.INT);
		}
		if (ret != null) {
			ret.setSource(lv.sca.currentFile.filepath, typeAstNode.charOffset, typeAstNode.charLength);
		}
		return ret;
	}

	public static Type forStaticString() {
		return forImmutableString();    // Use immutable for now, later on use special handling to avoid reference counting, etc
	}

	public static String getParameterSignature(Type[] parameterTypes) {
		StringBuilder ret = new StringBuilder();
		ret.append("(");
		for (int i = 0; i < parameterTypes.length; i++) {
			ret.append(parameterTypes[i].getHumanName());
			if (i < parameterTypes.length - 1) {
				ret.append(", ");
			}
		}
		ret.append(")");
		return ret.toString();
	}

	public static Type forUndefined() {
		return new UndefinedTypeCfgNode();
	}

	public static Type forBoolean() {
		return new BooleanType();
	}

	public static Type forImmutableString() {
		return new StringType(false);
	}

	public static Type forMutableString() {
		return new StringType(true);
	}

	public void writeJson(JsonGenerator generator) {
//		this.type.writeJson(generator);
	}

	public static Type forInt() {
		return new IntegerType(IntegerType.SubType.INT);
	}

	public static Type forFloat() {
		return new FloatType(FloatType.SubType.FLOAT);
	}

	public static Type forAsciiChar() {
		return new AsciiCharType();
	}

	private static Type forClassInstance(ClassCfgNode classNode) {
		return new ClassInstanceType(classNode);
	}

	public static boolean compare(Type t1, Type t2) {
		// TODO: Compare sub-types
		if (t1 instanceof StringType && t2 instanceof StringType) {
			return ((StringType) t1).mutable == ((StringType) t2).mutable;
		}
		if (t1 instanceof IntegerType && t2 instanceof IntegerType) {
			return true;
		}
		if (t1 instanceof FloatType && t2 instanceof FloatType) {
			return true;
		}
		if (t1 instanceof BooleanType && t2 instanceof BooleanType) {
			return true;
		}
		if (t1 instanceof EnumEntryType && t2 instanceof EnumEntryType) {
			return ((EnumEntryType) t1).getBase() == ((EnumEntryType) t2).getBase();
		}
		if (t1 instanceof ArrayType && t2 instanceof ArrayType) {
			return ((ArrayType) t1).mutable == ((ArrayType) t2).mutable && Type.compare(((ArrayType) t1).type, ((ArrayType) t2).type);
		}
		return false;
	}

	public static Type forEnum(EnumCfgNode enumeration) {
		return new EnumDeclarationType(enumeration);
	}

	public static Type forEnumEntry(EnumDeclarationType base) {
		return new EnumEntryType(base.enumeration);
	}

	public static Type forNamespace(NamespaceCfgNode namespace) {
		return new NamespaceType(namespace.id, namespace);
	}

	public static Type coalesce(List<Type> types) {
		int size = types.size();
		if (size == 0) {
			return Type.forUndefined();
		}
		if (size == 1) {
			return types.get(0);
		}
		List<Type> combined = new ArrayList<>();
		for (int i = 0; i < types.size(); i++) {
			if (!Type.contains(combined, types.get(i))) {
				combined.add(types.get(i));
			}
		}
		if (combined.size() == 1) {
			return types.get(0);
		}
		return UnionType.fromTypes(combined);
	}

	private static boolean contains(List<Type> list, Type type) {
		for (Type typeInList : list) {
			if (Type.canCoalesce(typeInList, type)) {
				return true;
			}
		}
		return false;
	}

	private static boolean canCoalesce(Type t1, Type t2) {
		return Type.compare(t1, t2);
	}

	public String getHumanName(boolean delimit) {
		if (delimit) {
			return "\"" + this.getHumanName() + "\"";
		}
		return this.getHumanName();
	}

	public static Type unknown() {
		return UNKNOWN;
	}

	public static boolean isKnown(Type type) {
		return type != UNKNOWN;
	}

	public boolean isKnown() {
		return Type.isKnown(this);
	}

	public boolean isUnknown() {
		return !Type.isKnown(this);
	}

	public static Type forNull() {
		return new NullType();
	}

	public static Type forImmutableArrayOfType(Type type) {
		return new ArrayType(false, type);
	}

	public static Type forArray(boolean mutable, Type type) {
		return new ArrayType(mutable, type);
	}

	public static List<Type> valueListToTypeList(List<LvValue> args) {
		List<Type> types = new ArrayList<>(args.size());
		for (LvValue value : args) {
			types.add(value.type);
		}
		return types;
	}

	public static List<LvValue> typeListToValueList(List<Type> types) {
		List<LvValue> values = new ArrayList<>(types.size());
		for (Type type : types) {
			values.add(new LvValue(type, null));
		}
		return values;
	}

	//
	//  Abstract Methods
	//____________________//

	public abstract String getHumanName();

	public abstract MemberInfo getMemberInfo(LvEvalEnvironment lv, String memberId, RawValue value);

	public abstract LvValue getAsString(RawValue value);

}


text:
"""Add a column

Revision ID: 212ab906cad8
Revises: 63bb5f350f3
Create Date: 2015-09-17 20:22:53.100000

"""

# revision identifiers, used by Alembic.
revision = '212ab906cad8'
down_revision = '63bb5f350f3'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('account', sa.Column('last_transaction_date', sa.DateTime))

def downgrade():
    op.drop_column('account', 'last_transaction_date')


text:
package org.apache.shindig.gadgets.variables;

import org.apache.shindig.gadgets.variables.BidiSubstituter;
import org.apache.shindig.gadgets.variables.Substitutions;

import junit.framework.TestCase;

public class BidiSubstituterTest extends TestCase {

  public void testBidiWithRtl() {
    assertRightToLeft(BidiSubstituter.RTL);
  }

  public void testBidiWithLtr() {
    assertLeftToRight(BidiSubstituter.LTR);
  }

  public void testBidiWithEmpty() {
    assertLeftToRight("");
  }

  public void testBidiWithNull() {
    assertLeftToRight(null);
  }

  private void assertRightToLeft(String direction) {
    assertSubstitutions(direction, BidiSubstituter.RIGHT,
        BidiSubstituter.LEFT, BidiSubstituter.RTL, BidiSubstituter.LTR);
  }

  private void assertLeftToRight(String direction) {
    assertSubstitutions(direction, BidiSubstituter.LEFT,
        BidiSubstituter.RIGHT, BidiSubstituter.LTR, BidiSubstituter.RTL);
  }

  private void assertSubstitutions(String direction,
      String startEdge, String endEdge, String dir, String reverseDir) {
    Substitutions substitutions = new Substitutions();
    BidiSubstituter.addSubstitutions(substitutions, direction);

    assertEquals(startEdge, substitutions.getSubstitution(
        Substitutions.Type.BIDI, BidiSubstituter.START_EDGE));
    assertEquals(endEdge, substitutions.getSubstitution(
        Substitutions.Type.BIDI, BidiSubstituter.END_EDGE));
    assertEquals(dir, substitutions.getSubstitution(
        Substitutions.Type.BIDI, BidiSubstituter.DIR));
    assertEquals(reverseDir, substitutions.getSubstitution(
        Substitutions.Type.BIDI, BidiSubstituter.REVERSE_DIR));
  }
}


text:
using System.Management.Automation;

namespace Zyborg.Vault.POSH
{
	/// <summary>
	/// <para type="synopsis">
	/// Disable an already-enabled auth provider.
	/// </para><para type="synopsis">
	/// Comparable to the vault CLI <c>auth-disable</c> command.
	/// </para>
	/// </summary>
	/// <remarks>
	/// <para type="description">
	/// Once the auth provider is disabled its path can no longer be used
	/// to authenticate.
	/// </para><para type="description">
	/// All access tokens generated via the disabled auth provider
	/// will be revoked.This command will block until all tokens are revoked.
	/// If the command is exited early the tokens will still be revoked.
	/// </para>
	/// </remarks>
	[Cmdlet(VerbsData.Dismount, "SecretProvider")]
	public class DismountSecretProvider : VaultBaseCmdlet
	{
		/// <summary>
		/// <para type="description">
		/// One or more paths at which auth providers are mounted.
		/// If an auth provider is mounted at multiple paths, each representing
		/// a different instance (with different configuration), this identifies
		/// the specific instance to disable.
		/// </para>
		/// </summary>
		[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
		public string[] MountName
		{ get; set; }

#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

		protected override void BeginProcessing()
		{
			ResolveVaultClient();
		}

		protected override void ProcessRecord()
		{
			foreach (var mn in MountName)
			{
				AsyncWait(_client.UnmountSecretBackendAsync(mn));
			}
		}

#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
	}
}


text:
all:
	cp ../app_builder_py3.py resources/opt/pythonlibs
	cp ../tarball_applet_builder_py3.py .


text:
export { getStorage } from './getStorage';
export { getWindow } from './getWindow';
export { isStorage } from './isStorage';

import * as storage from './storage';
export { storage };


text:
module PGCrypto::Extensions
  module SqlScrubber
    # SqlScrubber prevents sensitive data embedded in SQL statements from
    # being logged (which would only occur for debug loggers).
    # Example:
    #   `pgp_sym_encrypt('a-secure-field', 'my-encryption-key')`
    #    is changed to `pgp_sym_encrypt([FILTERED])`

    SCRUBBED_TEXT = '[FILTERED]'
    PGP_RE = /(?<=pgp_sym_(decrypt|encrypt)\()[^\)]*/

    def sql(event)
      return unless logger.debug?

      event.payload[:sql] = event.payload[:sql].gsub(PGP_RE, SCRUBBED_TEXT)
      super
    end
  end
end

if defined? ActiveRecord::LogSubscriber
  ActiveRecord::LogSubscriber.prepend PGCrypto::Extensions::SqlScrubber
else
  ActiveSupport.on_load(:active_record) do
    ActiveRecord::LogSubscriber.prepend PGCrypto::Extensions::SqlScrubber
  end
end


text:
/**
 * DVC Plugin API: See the original MS DVC Client API:
 * http://msdn.microsoft.com/en-us/library/bb540880%28v=VS.85%29.aspx
 *
 * The FreeRDP DVC Plugin API is a simulation of the MS DVC Client API in C.
 * The main difference is that every interface method must take an instance
 * pointer as the first parameter.
 */

/**
 * Implemented by DRDYNVC:
 * o IWTSVirtualChannelManager
 * o IWTSListener
 * o IWTSVirtualChannel
 *
 * Implemented by DVC plugin:
 * o IWTSPlugin
 * o IWTSListenerCallback
 * o IWTSVirtualChannelCallback
 *
 * A basic DVC plugin implementation:
 * 1. DVCPluginEntry:
 *    The plugin entry point, which creates and initializes a new IWTSPlugin
 *    instance
 * 2. IWTSPlugin.Initialize:
 *    Call IWTSVirtualChannelManager.CreateListener with a newly created
 *    IWTSListenerCallback instance
 * 3. IWTSListenerCallback.OnNewChannelConnection:
 *    Create IWTSVirtualChannelCallback instance if the new channel is accepted
 */

#ifndef __FREERDP_DVC_H
#define __FREERDP_DVC_H

#include <freerdp/types.h>

typedef struct _IWTSVirtualChannelManager IWTSVirtualChannelManager;
typedef struct _IWTSListener IWTSListener;
typedef struct _IWTSVirtualChannel IWTSVirtualChannel;

typedef struct _IWTSPlugin IWTSPlugin;
typedef struct _IWTSListenerCallback IWTSListenerCallback;
typedef struct _IWTSVirtualChannelCallback IWTSVirtualChannelCallback;

struct _IWTSListener
{
	/* Retrieves the listener-specific configuration. */
	int (*GetConfiguration) (IWTSListener* pListener,
		void** ppPropertyBag);
};

struct _IWTSVirtualChannel
{
	/* Starts a write request on the channel. */
	int (*Write) (IWTSVirtualChannel* pChannel,
		uint32 cbSize,
		uint8* pBuffer,
		void* pReserved);
	/* Closes the channel. */
	int (*Close) (IWTSVirtualChannel* pChannel);
};

struct _IWTSVirtualChannelManager
{
	/* Returns an instance of a listener object that listens on a specific
	   endpoint, or creates a static channel. */
	int (*CreateListener) (IWTSVirtualChannelManager* pChannelMgr,
		const char* pszChannelName,
		uint32 ulFlags,
		IWTSListenerCallback* pListenerCallback,
		IWTSListener** ppListener);
	/* Push a virtual channel event.
	   This is a FreeRDP extension to standard MS API. */
	int (*PushEvent) (IWTSVirtualChannelManager* pChannelMgr,
		RDP_EVENT* pEvent);
};

struct _IWTSPlugin
{
	/* Used for the first call that is made from the client to the plug-in. */
	int (*Initialize) (IWTSPlugin* pPlugin,
		IWTSVirtualChannelManager* pChannelMgr);
	/* Notifies the plug-in that the Remote Desktop Connection (RDC) client
	   has successfully connected to the Remote Desktop Session Host (RD
	   Session Host) server. */
	int (*Connected) (IWTSPlugin* pPlugin);
	/* Notifies the plug-in that the Remote Desktop Connection (RDC) client
	   has disconnected from the RD Session Host server. */
	int (*Disconnected) (IWTSPlugin* pPlugin,
		uint32 dwDisconnectCode);
	/* Notifies the plug-in that the Remote Desktop Connection (RDC) client
	   has terminated. */
	int (*Terminated) (IWTSPlugin* pPlugin);
};

struct _IWTSListenerCallback
{
	/* Accepts or denies a connection request for an incoming connection to
	   the associated listener. */
	int (*OnNewChannelConnection) (IWTSListenerCallback* pListenerCallback,
		IWTSVirtualChannel* pChannel,
		uint8* Data,
		int* pbAccept,
		IWTSVirtualChannelCallback** ppCallback);
};

struct _IWTSVirtualChannelCallback
{
	/* Notifies the user about data that is being received. */
	int (*OnDataReceived) (IWTSVirtualChannelCallback* pChannelCallback,
		uint32 cbSize,
		uint8* pBuffer);
	/* Notifies the user that the channel has been closed. */
	int (*OnClose) (IWTSVirtualChannelCallback* pChannelCallback);
};

/* The DVC Plugin entry points */
typedef struct _IDRDYNVC_ENTRY_POINTS IDRDYNVC_ENTRY_POINTS;
struct _IDRDYNVC_ENTRY_POINTS
{
	int (*RegisterPlugin) (IDRDYNVC_ENTRY_POINTS* pEntryPoints,
		const char* name, IWTSPlugin* pPlugin);
	IWTSPlugin* (*GetPlugin) (IDRDYNVC_ENTRY_POINTS* pEntryPoints,
		const char* name);
	RDP_PLUGIN_DATA* (*GetPluginData) (IDRDYNVC_ENTRY_POINTS* pEntryPoints);
};

typedef int (*PDVC_PLUGIN_ENTRY) (IDRDYNVC_ENTRY_POINTS*);

#endif


text:
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("extensions.ui.lastCategory", "addons://list/extension");
user_pref("browser.rights.3.shown", true);
user_pref("shumway.ignoreCTP", true);
user_pref("shumway.environment", "test");
user_pref("xpinstall.signatures.required", false);
user_pref("browser.displayedE10SPrompt", 5);
user_pref("browser.displayedE10SPrompt.1", 5);
user_pref("browser.displayedE10SNotice", 2);
user_pref("browser.tabs.remote.autostart", false);
user_pref("browser.tabs.remote.autostart.1", false);
user_pref('canvas.filters.enabled', true);
user_pref('extensions.autoDisableScopes', 14);
user_pref('security.turn_off_all_security_so_that_viruses_can_take_over_this_computer', true);
user_pref('gfx.hidpi.enabled', 0);


text:
class CacheFxCommand : public QObject {
  Q_OBJECT

public:
  CacheFxCommand();
  ~CacheFxCommand();

  static CacheFxCommand *instance();

  void onNewScene();
  void onSceneLoaded();

  void onLevelChanged(const std::string &levelName);

public slots:

  void onFxChanged();
  void onXsheetChanged();
  void onObjectChanged();
};

//=============================================================================
//    Misc Stuff
//-----------------------------------------------------------------------------

void buildTreeDescription(std::string &desc, const TFxP &root);

#endif


text:
 /**
 * @file BigPuppy.cpp
 * @brief Implementing a quadruped based off the Flemons BigPuppy model.
 * @author Dawn Hustig-Schultz
 * @date July 2015
 * @version 1.1.0
 * $Id$
 */

//This application
#include "BigPuppy.h"

// This library
#include "core/tgModel.h"
#include "core/tgSimView.h"
#include "core/tgSimViewGraphics.h"
#include "core/tgSimulation.h"
#include "core/tgWorld.h"
#include "core/tgBasicActuator.h"
#include "tgcreator/tgKinematicActuatorInfo.h"
#include "tgcreator/tgKinematicContactCableInfo.h"
#include "core/tgRod.h"
#include "core/tgSpringCableActuator.h"
#include "core/tgString.h"
#include "tgcreator/tgBuildSpec.h"
#include "tgcreator/tgBasicActuatorInfo.h"
#include "tgcreator/tgRodInfo.h"
#include "tgcreator/tgStructure.h"
#include "tgcreator/tgStructureInfo.h"
// The Bullet Physics library
#include "LinearMath/btVector3.h"
// The C++ Standard Library
#include <iostream>
#include <stdexcept>

#define USE_KINEMATIC
#define PASSIVE_STRUCTURE

BigPuppy::BigPuppy() :
tgModel()
{
}

BigPuppy::~BigPuppy()
{
}

void BigPuppy::addNodesFoot(tgStructure& s, double r1, double r2){
    s.addNode(r2,0,r2);//0
    s.addNode(r2,0,-r2);//1
    s.addNode(-r2,0,-r2);//2
    s.addNode(-r2,0,r2);//3
    s.addNode(r2/2,r1/2,0);//4
    s.addNode(0,r1/2,-r2/2);//5
    s.addNode(-r2/2,r1/2,0);//6
    s.addNode(0,r1/2,r2/2);//7
}

void BigPuppy::addRodsFoot(tgStructure& s){
    s.addPair(0,6,"rod");
    s.addPair(1,7,"rod");
    s.addPair(2,4,"rod");
    s.addPair(3,5,"rod");
}

void BigPuppy::addNodesLeg(tgStructure& s, double r){
    s.addNode(0,0,0); //0: Bottom Center of lower leg segment
    s.addNode(0,r,0);  //1: Center of lower leg segment
    s.addNode(r,r,0); //2: Right of lower leg segment
    s.addNode(-r,r,0);  //3: Left of lower leg segment
    s.addNode(0,2*r,0);  //4: Top of lower leg segment
    s.addNode(0,-r/2,0);  //5: Leg segment extension for connections to foot.
}

void BigPuppy::addRodsLeg(tgStructure& s){
    s.addPair(0,1,"rod");
    s.addPair(1,2,"rod");
    s.addPair(1,3,"rod");
    s.addPair(1,4,"rod");
    s.addPair(0,5,"rod");
}

void BigPuppy::addNodesHip(tgStructure& s, double r){
    s.addNode(0,0,0); //Node 0
    s.addNode(0,r,r); //Node 1
    s.addNode(0,-r,-r); //Node 2
    s.addNode(0,-r,r); //Node 3
}

void BigPuppy::addRodsHip(tgStructure& s){
    s.addPair(0,1,"rod");
    s.addPair(0,2,"rod");
    s.addPair(0,3,"rod");
}

void BigPuppy::addNodesVertebra(tgStructure& s, double r){
    s.addNode(0,0,0); //Node 0
    s.addNode(r,0,r); //Node 1
    s.addNode(r,0,-r); //Node 2
    s.addNode(-r,0,-r); //Node 3
    s.addNode(-r,0,r); //Node 4
}

void BigPuppy::addRodsVertebra(tgStructure& s){
    s.addPair(0,1,"rod");
    s.addPair(0,2,"rod");
    s.addPair(0,3,"rod");
    s.addPair(0,4,"rod");
}

void BigPuppy::addSegments(tgStructure& puppy, tgStructure& vertebra, tgStructure& hip, tgStructure& leg, tgStructure& foot,
                 double r, std::size_t segments, std::size_t hips, std::size_t legs, std::size_t feet){
    const double offsetDist = r+1;
    const double offsetDist2 = r*5+8;
    const double offsetDist3 = r*6;
    const double yOffset_leg = -(2*r+1);
    const double yOffset_foot = -(2*r+6);

    //Vertebrae
    btVector3 offset(offsetDist,0.0,0);
    //Hips
    btVector3 offset1(offsetDist*2,0.0,offsetDist);
    btVector3 offset2(offsetDist2,0.0,offsetDist);
    btVector3 offset3(offsetDist*2,0.0,-offsetDist);
    btVector3 offset4(offsetDist2,0.0,-offsetDist);
    //Lower legs
    btVector3 offset5(offsetDist3,yOffset_leg,offsetDist);
    btVector3 offset6(offsetDist3,yOffset_leg,-offsetDist);
    btVector3 offset7(r*2,yOffset_leg,offsetDist);
    btVector3 offset8(r*2,yOffset_leg,-offsetDist);
    //Feet
    btVector3 offset9(offsetDist3+1,yOffset_foot,offsetDist);
    btVector3 offset10(offsetDist3+1,yOffset_foot,-offsetDist);
    btVector3 offset11(r*2+1,yOffset_foot,offsetDist);
    btVector3 offset12(r*2+1,yOffset_foot,-offsetDist);

    for(std::size_t i = 0; i < segments; i++) { //Connect segments for spine of puppy
        tgStructure* t = new tgStructure (vertebra);
        t->addTags(tgString("segment num", i + 1));
        t->move((i + 1)*offset);

        if (i % 2 == 1){

            t->addRotation(btVector3((i + 1) * offsetDist, 0.0, 0.0), btVector3(1, 0, 0), 0.0);

        }
        else{

            t->addRotation(btVector3((i + 1) * offsetDist, 0.0, 0.0), btVector3(1, 0, 0), M_PI/2.0);

        }

        puppy.addChild(t); //Add a segment to the puppy
    }

     for(std::size_t i = segments; i < (segments + 2); i++) {//deal with right hip and shoulder first
        tgStructure* t = new tgStructure (hip);
        t->addTags(tgString("segment num", i + 1));

        if(i % 2 == 0){
            t->move(offset1);
            t->addRotation(btVector3(offsetDist*2, 0.0, offsetDist), btVector3(0, 1, 0), M_PI);
        }
        else{
            t->move(offset2);
            t->addRotation(btVector3(offsetDist2, 0.0, offsetDist), btVector3(0, 1, 0), M_PI);
        }

        puppy.addChild(t); //Add a segment to the puppy
    }

    for(std::size_t i = (segments + 2); i < (segments + hips); i++) {//deal with left hip and shoulder now
        tgStructure* t = new tgStructure (hip);
        t->addTags(tgString("segment num", i + 1));

        if(i % 2 == 0){
            t->move(offset3);
        }
        else{
            t->move(offset4);
        }

        puppy.addChild(t); //Add a segment to the puppy

    }

     for(std::size_t i = (segments + hips); i < (segments + hips + 2); i++) {//right front and back legs
        tgStructure* t = new tgStructure (leg);
        t->addTags(tgString("segment num", i + 1));

        if(i % 2 == 0){
            t->move(offset7);
            t->addRotation(btVector3(r*2, yOffset_leg, offsetDist), btVector3(0, 1, 0), M_PI);
            //the rotations for the legs are a remnant of the earlier design. Removing them now
            //would mean changing all my muscle attachments. I will do this someday.
        }
        else{
            t->move(offset5);
            t->addRotation(btVector3(offsetDist3, yOffset_leg, offsetDist), btVector3(0, 1, 0), M_PI);
        }

        puppy.addChild(t); //Add a segment to the puppy
    }

    for(std::size_t i = (segments + hips + 2); i < (segments + hips + legs); i++) {//left front and back legs
        tgStructure* t = new tgStructure (leg);
        t->addTags(tgString("segment num", i + 1));

        if(i % 2 == 0){
            t->move(offset8);
            t->addRotation(btVector3(r*2, yOffset_leg, -offsetDist), btVector3(0, 1, 0), M_PI);
        }
        else{
            t->move(offset6);
            t->addRotation(btVector3(offsetDist3, yOffset_leg, -offsetDist), btVector3(0, 1, 0), M_PI);
        }

        puppy.addChild(t); //Add a segment to the puppy
    }

    for(std::size_t i = (segments + hips + legs); i < (segments + hips + legs + 2); i++) {//right front and back feet
        tgStructure* t = new tgStructure (foot);
        t->addTags(tgString("segment num", i + 1));

        if(i % 2 == 0){
            t->move(offset11);
            t->addRotation(btVector3(r*2+1, yOffset_foot, offsetDist), btVector3(0, 1, 0), 0.0);
        }
        else{
            t->move(offset9);
            t->addRotation(btVector3(offsetDist3+1, yOffset_foot, offsetDist), btVector3(0, 1, 0), 0.0);
        }

        puppy.addChild(t); //Add a segment to the puppy
    }

    for(std::size_t i = (segments + hips + legs + 2); i < (segments + hips + legs + feet); i++) {//left front and back feet
        tgStructure* t = new tgStructure (foot);
        t->addTags(tgString("segment num", i + 1));

        if(i % 2 == 0){
            t->move(offset12);
            t->addRotation(btVector3(r*2+1, yOffset_foot, -offsetDist), btVector3(0, 1, 0), 0.0);
        }
        else{
            t->move(offset10);
            t->addRotation(btVector3(offsetDist3+1, yOffset_foot, -offsetDist), btVector3(0, 1, 0), 0.0);
        }

        puppy.addChild(t); //Add a segment to the puppy
    }
}

void BigPuppy::addMuscles(tgStructure& puppy, std::size_t segments, std::size_t hips, std::size_t legs, std::size_t feet){
        //Time to add the muscles to the structure. Todo: try to clean this up some more.
    std::vector<tgStructure*> children = puppy.getChildren();
    for(std::size_t i = 2; i < (children.size() - (hips + legs + feet)); i++) {

        tgNodes n0 = children[i-2]->getNodes();
        tgNodes n1 = children[i-1]->getNodes();
        tgNodes n2 = children[i]->getNodes();

        if(i==2){
            //Extra muscles, to keep front vertebra from swinging.
            puppy.addPair(n0[3], n1[3], tgString("puppy front upper right muscle seg", i-2) + tgString(" seg", i-1));
            puppy.addPair(n0[3], n1[4], tgString("puppy front upper left muscle seg", i-2) + tgString(" seg", i-1));

        }

        //Add muscles to the puppy
        if(i < 3){
            if(i % 2 == 0){ //front
                puppy.addPair(n0[1], n1[3], tgString("puppy front lower right muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[1], n1[4], tgString("puppy front lower left muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[2], n1[3], tgString("puppy front upper right muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[2], n1[4], tgString("puppy front upper left muscle seg", i-2) + tgString(" seg", i-1));
            }
            else{ //rear
                puppy.addPair(n0[1], n1[3], tgString("puppy rear upper left muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[1], n1[4], tgString("puppy rear lower left muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[2], n1[3], tgString("puppy rear upper right muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[2], n1[4], tgString("puppy rear lower right muscle seg", i-2) + tgString(" seg", i-1));
            }
        }
        if(i < 6){
            if(i % 2 == 0){
                puppy.addPair(n0[1], n2[4], tgString("puppy bottom muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[2], n2[3], tgString("puppy top muscle seg", i-2) + tgString(" seg", i-1));
            }
            else{
                puppy.addPair(n0[1], n2[4], tgString("puppy lateral left muscle seg", i-2) + tgString(" seg", i-1));
                puppy.addPair(n0[2], n2[3], tgString("puppy lateral right muscle seg", i-2) + tgString(" seg", i-1));

            }
        }
        if(i > 0 && i < 5){
            if(i % 2 == 0){//rear
                puppy.addPair(n1[1], n2[3], tgString("puppy rear upper left muscle seg", i-1) + tgString(" seg", i));
                puppy.addPair(n1[1], n2[4], tgString("puppy rear lower left muscle seg", i-1) + tgString(" seg", i));
                puppy.addPair(n1[2], n2[3], tgString("puppy rear upper right muscle seg", i-1) + tgString(" seg", i));
                puppy.addPair(n1[2], n2[4], tgString("puppy rear lower right muscle seg", i-1) + tgString(" seg", i));
            }
            else{//front

                puppy.addPair(n1[1], n2[3], tgString("puppy front lower right muscle seg", i-1) + tgString(" seg", i));
                puppy.addPair(n1[1], n2[4], tgString("puppy front lower left muscle seg", i-1) + tgString(" seg", i));
                puppy.addPair(n1[2], n2[3], tgString("puppy front upper right muscle seg", i-1) + tgString(" seg", i));
                puppy.addPair(n1[2], n2[4], tgString("puppy front upper left muscle seg", i-1) + tgString(" seg", i));
            }
        }
        if(i == 5){
            //rear
            puppy.addPair(n1[1], n2[1], tgString("puppy rear lower left muscle seg", i-1) + tgString(" seg", i));
            puppy.addPair(n1[1], n2[2], tgString("puppy rear lower right muscle seg", i-1) + tgString(" seg", i));
            puppy.addPair(n1[2], n2[1], tgString("puppy rear upper left muscle seg", i-1) + tgString(" seg", i));
            puppy.addPair(n1[2], n2[2], tgString("puppy rear upper right muscle seg", i-1) + tgString(" seg", i));
            //front
            puppy.addPair(n1[1], n2[3], tgString("puppy front lower right muscle seg", i-1) + tgString(" seg", i));
            puppy.addPair(n1[1], n2[4], tgString("puppy front lower left muscle seg", i-1) + tgString(" seg", i));
            puppy.addPair(n1[2], n2[3], tgString("puppy front upper right muscle seg", i-1) + tgString(" seg", i));
            puppy.addPair(n1[2], n2[4], tgString("puppy front upper left muscle seg", i-1) + tgString(" seg", i));

        }

    }

    //Now add muscles to hips....
    tgNodes n0 = children[0]->getNodes();
    tgNodes n1 = children[1]->getNodes();
    tgNodes n2 = children[2]->getNodes();
    tgNodes n3 = children[3]->getNodes();
    tgNodes n4 = children[4]->getNodes();
    tgNodes n5 = children[5]->getNodes();
    tgNodes n6 = children[6]->getNodes();
    tgNodes n7 = children[7]->getNodes();
    tgNodes n8 = children[8]->getNodes();
    tgNodes n9 = children[9]->getNodes();
    tgNodes n10 = children[10]->getNodes();
    tgNodes n11 = children[11]->getNodes();
    tgNodes n12 = children[12]->getNodes();
    tgNodes n13 = children[13]->getNodes();

    //Left shoulder muscles
    puppy.addPair(n6[1], n1[1], tgString("left shoulder rear upper muscle seg", 6) + tgString(" seg", 1));
    puppy.addPair(n6[1], n1[4], tgString("left shoulder front upper muscle seg", 6) + tgString(" seg", 1));
    puppy.addPair(n6[1], n0[2], tgString("left shoulder front top muscle seg", 6) + tgString(" seg", 0));
    puppy.addPair(n6[1], n2[3], tgString("left shoulder rear top muscle seg", 6) + tgString(" seg", 2));

    puppy.addPair(n6[3], n1[1], tgString("left shoulder rear lower muscle seg", 6) + tgString(" seg", 1));
    puppy.addPair(n6[3], n1[4], tgString("left shoulder front lower muscle seg", 6) + tgString(" seg", 1));
    puppy.addPair(n6[3], n0[1], tgString("left shoulder front bottom muscle seg", 6) + tgString(" seg", 0));
    puppy.addPair(n6[3], n2[4], tgString("left shoulder rear bottom muscle seg", 6) + tgString(" seg", 2));

    //Extra muscles, to move left shoulder forward and back:
    puppy.addPair(n6[0], n1[1], tgString("left shoulder rear mid muscle seg", 6) + tgString(" seg", 1));
    puppy.addPair(n6[0], n1[4], tgString("left shoulder front mid muscle seg", 6) + tgString(" seg", 1));

    //Left hip muscles
    puppy.addPair(n7[1], n5[1], tgString("left hip rear upper muscle seg", 7) + tgString(" seg", 5));
    puppy.addPair(n7[1], n5[4], tgString("left hip front upper muscle seg", 7) + tgString(" seg", 5));
    puppy.addPair(n7[1], n4[2], tgString("left hip rear top muscle seg", 7) + tgString(" seg", 4));
    puppy.addPair(n7[1], n4[3], tgString("left hip front top muscle seg", 7) + tgString(" seg", 4));

    puppy.addPair(n7[3], n5[1], tgString("left hip rear lower muscle seg", 7) + tgString(" seg", 5));
    puppy.addPair(n7[3], n5[4], tgString("left hip front lower muscle seg", 7) + tgString(" seg", 5));
    puppy.addPair(n7[3], n4[1], tgString("left hip bottom muscle seg", 7) + tgString(" seg", 4));

    //Extra muscles, to move left hip forward and back:
    puppy.addPair(n7[0], n3[1], tgString("left hip rear mid muscle seg", 7) + tgString(" seg", 3)); //could also be n3[3]
    puppy.addPair(n7[0], n5[4], tgString("left hip front mid muscle seg", 7) + tgString(" seg", 5));

    //Inter-hip connector muscle
    puppy.addPair(n7[3], n9[3], tgString("inter-hip bottom muscle seg", 7) + tgString(" seg", 9)); //inter-hip bottom muscle

    //Right shoulder muscles
    puppy.addPair(n8[1], n1[2], tgString("right shoulder rear upper muscle seg", 8) + tgString(" seg", 1));
    puppy.addPair(n8[1], n1[3], tgString("right shoulder front upper muscle seg", 8) + tgString(" seg", 1));
    puppy.addPair(n8[1], n0[2], tgString("right shoulder front top muscle seg", 8) + tgString(" seg", 0));
    puppy.addPair(n8[1], n2[3], tgString("right shoulder rear top muscle seg", 8) + tgString(" seg", 2));

    puppy.addPair(n8[3], n1[2], tgString("right shoulder rear lower muscle seg", 8) + tgString(" seg", 1));
    puppy.addPair(n8[3], n1[3], tgString("right shoulder front lower muscle seg", 8) + tgString(" seg", 1));
    puppy.addPair(n8[3], n0[1], tgString("right shoulder front bottom muscle seg", 8) + tgString(" seg", 0));
    puppy.addPair(n8[3], n2[4], tgString("right shoulder rear bottom muscle seg", 8) + tgString(" seg", 2));

    //Extra muscles, to move right shoulder forward and back:
    puppy.addPair(n8[0], n1[2], tgString("right shoulder rear mid muscle seg", 8) + tgString(" seg", 1));
    puppy.addPair(n8[0], n1[3], tgString("right shoulder front mid muscle seg", 8) + tgString(" seg", 1));

    //Right hip muscles
    puppy.addPair(n9[1], n5[2], tgString("right hip rear upper muscle seg", 9) + tgString(" seg", 5));
    puppy.addPair(n9[1], n5[3], tgString("right hip front upper muscle seg", 9) + tgString(" seg", 5));
    puppy.addPair(n9[1], n4[2], tgString("right hip rear top muscle seg", 9) + tgString(" seg", 4));
    puppy.addPair(n9[1], n4[3], tgString("right hip front top muscle seg", 9) + tgString(" seg", 4));

    puppy.addPair(n9[3], n5[2], tgString("right hip rear lower muscle seg", 9) + tgString(" seg", 5));
    puppy.addPair(n9[3], n5[3], tgString("right hip front lower muscle seg", 9) + tgString(" seg", 5));
    puppy.addPair(n9[3], n4[1], tgString("right hip bottom muscle seg", 9) + tgString(" seg", 4));

    //Extra muscles, to move right hip forward and back:
    puppy.addPair(n9[0], n3[2], tgString("right hip rear mid muscle seg", 9) + tgString(" seg", 3)); //could also be n3[3]
    puppy.addPair(n9[0], n5[3], tgString("right hip front mid muscle seg", 9) + tgString(" seg", 5));

    //Leg/hip connections:

    //Left front leg/shoulder
    puppy.addPair(n10[4], n6[3], tgString("right outer bicep muscle seg", 10) + tgString(" seg", 6));
    puppy.addPair(n10[4], n6[2], tgString("right inner bicep muscle seg", 10) + tgString(" seg", 6));
    puppy.addPair(n10[4], n1[4], tgString("right front abdomen connection muscle seg", 10) + tgString(" seg", 1));

    puppy.addPair(n10[3], n6[3], tgString("right outer tricep muscle seg", 10) + tgString(" seg", 6));
    puppy.addPair(n10[3], n6[2], tgString("right inner tricep muscle seg", 10) + tgString(" seg", 6));

    puppy.addPair(n10[2], n6[3], tgString("right outer front tricep muscle seg", 10) + tgString(" seg", 6));
    puppy.addPair(n10[2], n6[2], tgString("right inner front tricep muscle seg", 10) + tgString(" seg", 6));

    //Adding muscle to pull up on right front leg:
    puppy.addPair(n10[4], n6[1], tgString("right mid bicep muscle seg", 10) + tgString(" seg", 6));

    //Right front leg/shoulder
    puppy.addPair(n12[4], n8[2], tgString("left inner bicep muscle seg", 12) + tgString(" seg", 8));
    puppy.addPair(n12[4], n8[3], tgString("left outer bicep muscle seg", 12) + tgString(" seg", 8));
    puppy.addPair(n12[4], n1[3], tgString("left front abdomen connection muscle seg", 12) + tgString(" seg", 1)); //Was n1[2]

    puppy.addPair(n12[3], n8[2], tgString("left inner tricep muscle seg", 12) + tgString(" seg", 8));
    puppy.addPair(n12[3], n8[3], tgString("left outer tricep muscle seg", 12) + tgString(" seg", 8));

    puppy.addPair(n12[2], n8[2], tgString("left inner front tricep muscle seg", 12) + tgString(" seg", 8));
    puppy.addPair(n12[2], n8[3], tgString("left outer front tricep muscle seg", 12) + tgString(" seg", 8));

    //Adding muscle to pull up on left front leg:
    puppy.addPair(n12[4], n8[1], tgString("left mid bicep muscle seg", 12) + tgString(" seg", 8));

    //Left rear leg/hip
    puppy.addPair(n11[4], n7[3], tgString("right outer thigh muscle seg", 11) + tgString(" seg", 7));
    puppy.addPair(n11[4], n7[2], tgString("right inner thigh muscle seg", 11) + tgString(" seg", 7));

    puppy.addPair(n11[4], n3[4],tgString("right rear abdomen connection muscle seg", 11) + tgString(" seg", 3));
    puppy.addPair(n11[3], n5[1],tgString("right rear abdomen connection muscle seg", 11) + tgString(" seg", 5));

    puppy.addPair(n11[3], n7[3], tgString("right outer calf muscle seg", 11) + tgString(" seg", 7));
    puppy.addPair(n11[3], n7[2], tgString("right inner calf muscle seg", 11) + tgString(" seg", 7));

    puppy.addPair(n11[2], n7[3], tgString("right outer front calf muscle seg", 11) + tgString(" seg", 7));
    puppy.addPair(n11[2], n7[2], tgString("right inner front calf muscle seg", 11) + tgString(" seg", 7));

    //Adding muscle to pull rear right leg up:
    puppy.addPair(n11[4], n7[1], tgString("right central thigh muscle seg", 11) + tgString(" seg", 7));

    //Right rear leg/hip
    puppy.addPair(n13[4], n9[2], tgString("left inner thigh muscle seg", 13) + tgString(" seg", 9));
    puppy.addPair(n13[4], n9[3], tgString("left outer thigh muscle seg", 13) + tgString(" seg", 9));

    puppy.addPair(n13[4], n3[3], tgString("left rear abdomen connection muscle seg", 13) + tgString(" seg", 3));
    puppy.addPair(n13[3], n5[2], tgString("left rear abdomen connection muscle seg", 13) + tgString(" seg", 5));

    puppy.addPair(n13[3], n9[2], tgString("left inner calf muscle seg", 13) + tgString(" seg", 9));
    puppy.addPair(n13[3], n9[3], tgString("left outer calf muscle seg", 13) + tgString(" seg", 9));

    puppy.addPair(n13[2], n9[2], tgString("left inner front calf muscle seg", 13) + tgString(" seg", 9));
    puppy.addPair(n13[2], n9[3], tgString("left outer front calf muscle seg", 13) + tgString(" seg", 9));

    //Adding muscle to pull rear left leg up:
    puppy.addPair(n13[4], n9[1], tgString("left central thigh muscle seg", 13) + tgString(" seg", 9));

    //Populate feet with muscles. Todo: think up names to differentiate each!
    for(std::size_t i = (segments + hips + legs); i < children.size(); i++) {
        tgNodes ni = children[i]->getNodes();
        tgNodes ni4 = children[i-4]->getNodes(); //Think of a nicer name for this!

        puppy.addPair(ni[0],ni[1],tgString("foot muscle seg", i));
        puppy.addPair(ni[0],ni[3],tgString("foot muscle seg", i));
        puppy.addPair(ni[1],ni[2],tgString("foot muscle seg", i));
        puppy.addPair(ni[2],ni[3],tgString("foot muscle seg", i));
        puppy.addPair(ni[0],ni[7],tgString("foot muscle seg", i));
        puppy.addPair(ni[1],ni[4],tgString("foot muscle seg", i));
        puppy.addPair(ni[2],ni[5],tgString("foot muscle seg", i));
        puppy.addPair(ni[3],ni[6],tgString("foot muscle seg", i));
        puppy.addPair(ni[4],ni[5],tgString("foot muscle seg", i));
        puppy.addPair(ni[4],ni[7],tgString("foot muscle seg", i));
        puppy.addPair(ni[5],ni[6],tgString("foot muscle seg", i));
        puppy.addPair(ni[6],ni[7],tgString("foot muscle seg", i));

        //Connect feet to legs:
        puppy.addPair(ni4[5],ni[0],tgString("foot muscle seg", i) + tgString(" seg", i-4));
        puppy.addPair(ni4[5],ni[1],tgString("foot muscle seg", i) + tgString(" seg", i-4));
        puppy.addPair(ni4[5],ni[2],tgString("foot muscle seg", i) + tgString(" seg", i-4));
        puppy.addPair(ni4[5],ni[3],tgString("foot muscle seg", i) + tgString(" seg", i-4));

        puppy.addPair(ni4[0],ni[4],tgString("foot muscle seg", i) + tgString(" seg", i-4));
        puppy.addPair(ni4[0],ni[5],tgString("foot muscle seg", i) + tgString(" seg", i-4));
        puppy.addPair(ni4[0],ni[6],tgString("foot muscle seg", i) + tgString(" seg", i-4));
        puppy.addPair(ni4[0],ni[7],tgString("foot muscle seg", i) + tgString(" seg", i-4));

    }

}

void BigPuppy::setup(tgWorld& world)
{
    //Rod and Muscle configuration.
    const double density = 4.2/300.0; //Note: this needs to be high enough or things fly apart...
    const double radius = 0.5;
    const double rod_space = 10.0;
    const double rod_space2 = 8.0;
    const double friction = 0.5;
    const double rollFriction = 0.0;
    const double restitution = 0.0;

    const tgRod::Config rodConfig(radius, density, friction, rollFriction, restitution);

    const double stiffness = 1000.0;
    const double damping = .01*stiffness;
    const double pretension = 0.0;
    const bool   history = false;
    const double maxTens = 7000.0;
    const double maxSpeed = 12.0;

    const double passivePretension = 700; // 5 N. Todo: make this a #ifdef

#ifdef USE_KINEMATIC

    const double mRad = 1.0;
    const double motorFriction = 10.0;
    const double motorInertia = 1.0;
    const bool backDrivable = false;
    #ifdef PASSIVE_STRUCTURE
        tgKinematicActuator::Config motorConfig(2000, 20, passivePretension,
                                            mRad, motorFriction, motorInertia, backDrivable,
                                            history, maxTens, maxSpeed);
    #else
        tgKinematicActuator::Config motorConfig(stiffness, damping, pretension,
                                            mRad, motorFriction, motorInertia, backDrivable,
                                            history, maxTens, maxSpeed);
    #endif

#else

    #ifdef PASSIVE_STRUCTURE
        tgSpringCableActuator::Config muscleConfig(2000, 20, passivePretension);
    #else
        tgSpringCableActuator::Config stringConfig(stiffness, damping, pretension, history, maxTens, 2*maxSpeed);
    #endif

#endif
    // Calculations for the flemons puppy model

    //Todo: make separate functions for node, rod, and muscle placement! Do for each type of segment.

    //Foot:
    tgStructure foot;
    addNodesFoot(foot,rod_space,rod_space2);
    addRodsFoot(foot);

    //Leg:
    tgStructure leg;
    addNodesLeg(leg,rod_space);
    addRodsLeg(leg);

    //Create the basic unit of the puppy
    tgStructure vertebra;
    addNodesVertebra(vertebra,rod_space);
    addRodsVertebra(vertebra);

    //Create the basic unit for the hips/shoulders.
    tgStructure hip;
    addNodesHip(hip,rod_space);
    addRodsHip(hip);

    //Build the puppy
    tgStructure puppy;

    std::size_t m_segments = 6;
    std::size_t m_hips = 4;
    std::size_t m_legs = 4;
    std::size_t m_feet = 4;
    const double yOffset_foot = -(2*rod_space+6);

    addSegments(puppy,vertebra,hip,leg,foot,rod_space,m_segments,m_hips,m_legs,m_feet);

    puppy.move(btVector3(0.0,-yOffset_foot,0.0));

    addMuscles(puppy,m_segments,m_hips,m_legs,m_feet);

    //Time to add the muscles to the structure. Todo: make this a function; also try to clean this up.
    std::vector<tgStructure*> children = puppy.getChildren();

    // Create the build spec that uses tags to turn the structure into a real model
    tgBuildSpec spec;
    spec.addBuilder("rod", new tgRodInfo(rodConfig));

#ifdef USE_KINEMATIC
    spec.addBuilder("muscle", new tgKinematicContactCableInfo(motorConfig));
#else
    spec.addBuilder("muscle", new tgBasicActuatorInfo(muscleConfig));
#endif

    // Create your structureInfo
    tgStructureInfo structureInfo(puppy, spec);

    // Use the structureInfo to build ourselves
    structureInfo.buildInto(*this, world);

    // We could now use tgCast::filter or similar to pull out the
    // models (e.g. muscles) that we want to control.
    allActuators = tgCast::filter<tgModel, tgSpringCableActuator> (getDescendants());

    // Notify controllers that setup has finished.
    notifySetup();

    // Actually setup the children
    tgModel::setup(world);

    children.clear();
}

void BigPuppy::step(double dt)
{
    // Precondition
    if (dt <= 0.0)
    {
        throw std::invalid_argument("dt is not positive");
    }
    else
    {
        // Notify observers (controllers) of the step so that they can take action
        notifyStep(dt);
        tgModel::step(dt);  // Step any children
    }
}

const std::vector<tgSpringCableActuator*>& BigPuppy::getAllActuators() const
{
    return allActuators;
}

void BigPuppy::teardown()
{
    notifyTeardown();
    tgModel::teardown();
}


text:
var foo = require('./foo');

var obj1 = foo();
console.log('obj1: ', obj1.something);

var obj2 = foo();
console.log('obj2: ', obj2.something);
console.log('Changing obj2...');
obj2.something = 'ciao';

console.log('obj1:', obj1.something);
console.log('obj2:', obj2.something);


text:
package org.drools.compiler.integrationtests;

import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.Order;
import org.drools.compiler.OrderItem;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.junit.Test;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;

public class QueryTest2 extends CommonTestMethodBase {

    @Test
    public void testEvalRewrite() throws Exception {
        String str = "" +
        "package org.drools.compiler;\n" +
        "global java.util.List results;\n" +
        "rule \"eval rewrite\"\n" +
        "    when\n" +
        "        $o1 : OrderItem( order.number == 11, $seq : seq == 1 )\n" +
        //"        $o2 : OrderItem( order.number == $o1.order.number, seq != $seq )\n" +
        "        $o2 : Order( items[(Integer) 1] == $o1 ) \n" +
        "    then\n" +
        "        System.out.println( $o1 + \":\" + $o2 );\n" +
        "end        \n";

        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL );

        if ( kbuilder.hasErrors() ) {
            fail( kbuilder.getErrors().toString() );
        }

        final Order order1 = new Order( 11,
                                        "Bob" );
        final OrderItem item11 = new OrderItem( order1,
                                                1 );
        final OrderItem item12 = new OrderItem( order1,
                                                2 );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( kbuilder.getKnowledgePackages() );
        KieSession ksession = createKnowledgeSession(kbase);
        ksession.insert( order1 );
        ksession.insert( item11 );
        ksession.insert( item12 );

        ksession.fireAllRules();

    }
}