<commit_before>/*------------------------------------------------------------------------------

    Copyright (c) 2004 Media Development Loan Fund

    This file is part of the LiveSupport project.
    http://livesupport.campware.org/
    To report bugs, send an e-mail to bugs@campware.org

    LiveSupport is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    LiveSupport is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with LiveSupport; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Author   : $Author: fgerlits $
    Version  : $Revision: 1.5 $
    Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/core/src/AudioClip.cxx,v $

------------------------------------------------------------------------------*/

/* ============================================================ include files */

#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif

#include <sstream>

#include "LiveSupport/Core/AudioClip.h"

using namespace boost::posix_time;

using namespace LiveSupport::Core;

/* ===================================================  local data structures */

/* ================================================  local constants & macros */

/*------------------------------------------------------------------------------
 *  The name of the config element for this class
 *----------------------------------------------------------------------------*/
const std::string AudioClip::configElementNameStr = "audioClip";

/**
 *  The name of the attribute to get the id of the audio clip.
 */
static const std::string    idAttrName = "id";

/**
 *  The name of the attribute to get the URI of the audio clip.
 */
static const std::string    uriAttrName = "uri";

/**
 *  The name of the attribute to get the playlength of the audio clip.
 */
static const std::string    playlengthAttrName = "playlength";

/* ===============================================  local function prototypes */

/* =============================================================  module code */

/*------------------------------------------------------------------------------
 *  Create an audio clip object based on an XML element.
 *----------------------------------------------------------------------------*/
void
AudioClip :: configure(const xmlpp::Element  & element)
                                               throw (std::invalid_argument)
{
    if (element.get_name() != configElementNameStr) {
        std::string eMsg = "bad configuration element ";
        eMsg += element.get_name();
        throw std::invalid_argument(eMsg);
    }

    const xmlpp::Attribute    * attribute;
    std::stringstream           strStr;
    unsigned long int           idValue;

    if (!(attribute = element.get_attribute(idAttrName))) {
        std::string eMsg = "missing attribute ";
        eMsg += idAttrName;
        throw std::invalid_argument(eMsg);
    }
    strStr.str(attribute->get_value());
    strStr >> idValue;
    id.reset(new UniqueId(idValue));

    if (!(attribute = element.get_attribute(playlengthAttrName))) {
        std::string eMsg = "missing attribute ";
        eMsg += idAttrName;
        throw std::invalid_argument(eMsg);
    }
    playlength.reset(new time_duration(
                            duration_from_string(attribute->get_value())));

    if (attribute = element.get_attribute(uriAttrName)) {
        std::string  uriValue = attribute->get_value();
        uri.reset(new std::string(uriValue));
    }
}
<commit_msg>added parentheses to make gcc happy<commit_after>/*------------------------------------------------------------------------------

    Copyright (c) 2004 Media Development Loan Fund

    This file is part of the LiveSupport project.
    http://livesupport.campware.org/
    To report bugs, send an e-mail to bugs@campware.org

    LiveSupport is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    LiveSupport is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with LiveSupport; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Author   : $Author: fgerlits $
    Version  : $Revision: 1.6 $
    Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/core/src/AudioClip.cxx,v $

------------------------------------------------------------------------------*/

/* ============================================================ include files */

#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif

#include <sstream>

#include "LiveSupport/Core/AudioClip.h"

using namespace boost::posix_time;

using namespace LiveSupport::Core;

/* ===================================================  local data structures */

/* ================================================  local constants & macros */

/*------------------------------------------------------------------------------
 *  The name of the config element for this class
 *----------------------------------------------------------------------------*/
const std::string AudioClip::configElementNameStr = "audioClip";

/**
 *  The name of the attribute to get the id of the audio clip.
 */
static const std::string    idAttrName = "id";

/**
 *  The name of the attribute to get the URI of the audio clip.
 */
static const std::string    uriAttrName = "uri";

/**
 *  The name of the attribute to get the playlength of the audio clip.
 */
static const std::string    playlengthAttrName = "playlength";

/* ===============================================  local function prototypes */

/* =============================================================  module code */

/*------------------------------------------------------------------------------
 *  Create an audio clip object based on an XML element.
 *----------------------------------------------------------------------------*/
void
AudioClip :: configure(const xmlpp::Element  & element)
                                               throw (std::invalid_argument)
{
    if (element.get_name() != configElementNameStr) {
        std::string eMsg = "bad configuration element ";
        eMsg += element.get_name();
        throw std::invalid_argument(eMsg);
    }

    const xmlpp::Attribute    * attribute;
    std::stringstream           strStr;
    unsigned long int           idValue;

    if (!(attribute = element.get_attribute(idAttrName))) {
        std::string eMsg = "missing attribute ";
        eMsg += idAttrName;
        throw std::invalid_argument(eMsg);
    }
    strStr.str(attribute->get_value());
    strStr >> idValue;
    id.reset(new UniqueId(idValue));

    if (!(attribute = element.get_attribute(playlengthAttrName))) {
        std::string eMsg = "missing attribute ";
        eMsg += idAttrName;
        throw std::invalid_argument(eMsg);
    }
    playlength.reset(new time_duration(
                            duration_from_string(attribute->get_value())));

    if ((attribute = element.get_attribute(uriAttrName))) {
        std::string  uriValue = attribute->get_value();
        uri.reset(new std::string(uriValue));
    }
}
<|endoftext|>


<commit_before>// Time:  O(nlog(max_val - min_val))
// Space: O(1)

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        double left = *min_element(nums.begin(), nums.end());
        double right = *max_element(nums.begin(), nums.end());
        while (right - left > 0.00001) {
            double mid = left + (right - left) / 2;
            if (isMidLargerOrEqualToTarget(mid, nums, k)) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return left;
    }

private:
    bool isMidLargerOrEqualToTarget(double mid, const vector<int>& nums, int k) {
        double sum = 0, prev = 0, min_sum = 0;
        for (int i = 0; i < k; ++i) {
            sum += nums[i] - mid;
        }
        if (sum > 0) {
            return false;
        }
        for (int i = k; i < nums.size(); ++i) {
            sum += nums[i] - mid;
            prev += nums[i - k] - mid;
            min_sum = min(prev, min_sum);
            if (sum > min_sum) {
                return false;
            }
        }
        return true;
    }
};<commit_msg>update<commit_after>// Time:  O(n)
// Space: O(n)

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        double left = *min_element(nums.begin(), nums.end());
        double delta = numeric_limits<double>::max();
        while (delta > 1e-5) {
            delta = getDelta(nums, k, left);
            left += delta;
        }
        return left;
    }

private:
    double getDelta(const vector<int>& nums, int k, double avg) {
        vector<double> accu(nums.size() + 1);
        int minval_pos = -1;
        double delta = 0.0;
        for (int i = 0; i < nums.size(); ++i) {
            accu[i + 1] = nums[i] + accu[i] - avg;
            if (i >= k - 1) {
                if (minval_pos == -1 || accu[i - k + 1] < accu[minval_pos]) {
                    minval_pos = i - k + 1;
                }
                if (accu[i+1] - accu[minval_pos] >= 0) {
                    delta = max(delta, (accu[i + 1] - accu[minval_pos]) / (i + 1 - minval_pos));
                }
            }
        }
        return delta;
    }
};

// Time:  O(nlogm), m is (max_val - min_val)
// Space: O(1)
class Solution2 {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        double left = *min_element(nums.begin(), nums.end());
        double right = *max_element(nums.begin(), nums.end());
        while (right - left > 0.00001) {
            double mid = left + (right - left) / 2;
            if (isMidLargerOrEqualToTarget(mid, nums, k)) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return left;
    }

private:
    bool isMidLargerOrEqualToTarget(double mid, const vector<int>& nums, int k) {
        double sum = 0, prev = 0, min_sum = 0;
        for (int i = 0; i < k; ++i) {
            sum += nums[i] - mid;
        }
        if (sum > 0) {
            return false;
        }
        for (int i = k; i < nums.size(); ++i) {
            sum += nums[i] - mid;
            prev += nums[i - k] - mid;
            min_sum = min(prev, min_sum);
            if (sum > min_sum) {
                return false;
            }
        }
        return true;
    }
};<|endoftext|>


<commit_before>// Time:  O(log(min(m, n)))
// Space: O(1)

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if ((nums1.size() + nums2.size()) % 2 == 1) {
            return findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1);
        } else {
            return (findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2) +
                    findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
        }
    }

    int findKthInTwoSortedArrays(const vector<int>& A, const vector<int>& B,
                                 int k) {
        const int m = A.size();
        const int n = B.size();

        // Make sure m is the smaller one.
        if (m > n) {
            return findKthInTwoSortedArrays(B, A, k);
        }

        int left = 0;
        int right = m;
        // Find a partition of A and B
        // where min left s.t. A[left] >= B[k - 1 - left]. Thus left is the (k + 1)-th element.
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (0 <= k - 1 - mid && k - 1 - mid < n && A[mid] >= B[k - 1 - mid]) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        int Ai_minus_1 = left - 1 >= 0 ? A[left - 1] : numeric_limits<int>::min();
        int Bj = k - 1 - left >= 0 ? B[k - 1 - left] : numeric_limits<int>::min();

        // kth element would be A[left - 1] or B[k - 1 - left].
        return max(Ai_minus_1, Bj);
    }
};

// Time:  O(log(max(m, n)) * log(max_val - min_val))
// Space: O(1)
// Generic solution.
class Solution_Generic {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<vector<int> *> arrays{&nums1, &nums2};
        if ((nums1.size() + nums2.size()) % 2 == 1) {
            return findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1);
        } else {
            return (findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2) +
                    findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
        }
    }

private:
    int findKthInSortedArrays(const vector<vector<int> *>& arrays, int k) {
        int left = numeric_limits<int>::max();
        int right = numeric_limits<int>::min();
        for (const auto array : arrays) {
            if (!array->empty()) {
                left = min(left, array->front());
                right = max(right, array->back());
            }
        }
        // left xxxxxxxooooooo right, find first xo or oo
        while (left + 1 < right) {
            const auto mid = left + (right - left) / 2;
            if (match(arrays, mid, k)) {
                right = mid;
            } else {
                left = mid;
            }
        }
        // case: xoo
        //        ^^
        if (match(arrays, left, k)) {
            return left;
        }
        // case: xo
        //       ^^
        return right;
    }

    bool match(const vector<vector<int> *>& arrays, int num, int target) {
        int res = 0;
        for (const auto array : arrays) {
            if (!array->empty()) {
                res += distance(upper_bound(array->cbegin(), array->cend(), num),
                                array->cend());
            }
        }
        return res < target;
    }
};
<commit_msg>Update median-of-two-sorted-arrays.cpp<commit_after>// Time:  O(log(min(m, n)))
// Space: O(1)

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if ((nums1.size() + nums2.size()) % 2 == 1) {
            return findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1);
        } else {
            return (findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2) +
                    findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
        }
    }

    int findKthInTwoSortedArrays(const vector<int>& A, const vector<int>& B,
                                 int k) {
        const int m = A.size();
        const int n = B.size();

        // Make sure m is the smaller one.
        if (m > n) {
            return findKthInTwoSortedArrays(B, A, k);
        }

        int left = 0;
        int right = m;
        // Find a partition of A and B
        // where min left s.t. A[left] >= B[k - 1 - left]. Thus left is the (k + 1)-th element.
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (0 <= k - 1 - mid && k - 1 - mid < n && A[mid] >= B[k - 1 - mid]) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        int Ai_minus_1 = left - 1 >= 0 ? A[left - 1] : numeric_limits<int>::min();
        int Bj = k - 1 - left >= 0 ? B[k - 1 - left] : numeric_limits<int>::min();

        // kth element would be A[left - 1] or B[k - 1 - left].
        return max(Ai_minus_1, Bj);
    }
};

// Time:  O(log(max(m, n)) * log(max_val - min_val))
// Space: O(1)
// Generic solution.
class Solution_Generic {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<vector<int> *> arrays{&nums1, &nums2};
        if ((nums1.size() + nums2.size()) % 2 == 1) {
            return findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1);
        } else {
            return (findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2) +
                    findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
        }
    }

private:
    int findKthInSortedArrays(const vector<vector<int> *>& arrays, int k) {
        int left = numeric_limits<int>::max();
        int right = numeric_limits<int>::min();
        for (const auto array : arrays) {
            if (!array->empty()) {
                left = min(left, array->front());
                right = max(right, array->back());
            }
        }
        // left xxxxxxxooooooo right, find first xo or oo
        while (left <= right) {
            const auto mid = left + (right - left) / 2;
            if (match(arrays, mid, k)) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    bool match(const vector<vector<int> *>& arrays, int num, int target) {
        int res = 0;
        for (const auto array : arrays) {
            if (!array->empty()) {
                res += distance(upper_bound(array->cbegin(), array->cend(), num),
                                array->cend());
            }
        }
        return res < target;
    }
};
<|endoftext|>


<commit_before>/*--------------------------------------------------*/
/* @Program name ; mbed_servo                       */
/* @Author : Kohei Izumi                            */
/* @Comment : Servo motor operation                 */
/*                                                  */
/* Copyright(c) 2014 Kohei Izumi                    */
/*--------------------------------------------------*/

#include "mbed.h"
Serial device(p9, p10);         // tx = P9, rx = P10
DigitalOut REDE(p11);           // RS485 Transmit Enable
/*--------------------------------------------------*/
/* Funcyion     : mbed initialize                   */
/* NAME         : Init                              */
/* Argument     : ---                               */
/* Return value : ---                               */
/*--------------------------------------------------*/
void Init(void){
    device.baud(115200);        // baud Rate = 115.2kbps [Futaba default]
    REDE = 0;                   // RS485 Transmit disable
}
/*--------------------------------------------------*/
/* Funcyion     : Servo torque enable               */
/* NAME         : Torque                            */
/* Argument     : ID (Servo ID)                     */
/*              : data (Torque enable)              */
/* Return value : ---                               */
/*--------------------------------------------------*/
void Torque (unsigned char ID, unsigned char data){

    unsigned char TxData[9];    // TransmitByteData [9byte]
    unsigned char CheckSum = 0; // CheckSum calculation

    TxData[0] = 0xFA;           // Header
    TxData[1] = 0xAF;           // Header
    TxData[2] = ID;             // ID
    TxData[3] = 0x00;           // Flags
    TxData[4] = 0x24;           // Address
    TxData[5] = 0x01;           // Length
    TxData[6] = 0x01;           // Count
    TxData[7] = data;           // Data

    // CheckSum calculation
    for(int i=2; i<=7; i++){
        CheckSum = CheckSum ^ TxData[i];                // XOR from ID to Data
    }

    TxData[8] = CheckSum;       // Sum

    // Send Packet
    REDE = 1;                   // RS485 Transmit Enable
    for(int i=0; i<=8; i++){
        device.putc(TxData[i]);
    }
    wait_us(250);               // Wait for transmission
    REDE = 0;                   // RS485 Transmitt disable
}
/*--------------------------------------------------*/
/* Function     : Servo goal position instruction   */
/*                (Not specify time)                */
/* NAME         : SetPosition                       */
/* Argument     : ID (Servo ID)                     */
/*              : data (Set position)              */
/* Return value : ---                               */
/*--------------------------------------------------*/
void SetPosition (unsigned char ID, short data){

    unsigned char TxData[10];   // TransmitByteData [10byte]
    unsigned char CheckSum = 0; // CheckSum calculation

    TxData[0] = 0xFA;           // Header
    TxData[1] = 0xAF;           // Header
    TxData[2] = ID;             // ID
    TxData[3] = 0x00;           // Flags
    TxData[4] = 0x1E;           // Address
    TxData[5] = 0x02;           // Length
    TxData[6] = 0x01;           // Count
                                // Data
    TxData[7] = (unsigned char)0x00FF & data;           // Low byte
    TxData[8] = (unsigned char)0x00FF & (data >> 8);    // Hi  byte

    // CheckSum calculation
    for(int i=3; i<=8; i++){
        CheckSum = CheckSum ^ TxData[i];                // XOR from ID to Data
    }
    TxData[9] = CheckSum;       // Sum
    // Send Packet
    REDE = 1;                   // RS485 Transmitt Enable
    for(int i=0; i<=9; i++){
        device.putc(TxData[i]);
    }
    wait_us(250);               // Wait for transmission
    REDE = 0;                   // RS485 Transmit disable
}

/*--------------------------------------------------*/
/* Function     : Set the time and position         */
/* NAME         : SetTimeAndPosition                */
/* Argument     : ID (servo ID)                     */
/*              : data (set position)               */
/*              : time (time to move)               */
/* Return value : ---                               */
/*--------------------------------------------------*/
void SetTimeAndPosition(unsigned char ID, short data, unsigned short stime){
    unsigned char TxData[12];   // TransmitByteData [10byte]
    unsigned char CheckSum = 0; // CheckSum calculation

    TxData[0] = 0xFA;           // Header
    TxData[1] = 0xAF;           // Header
    TxData[2] = ID;             // ID
    TxData[3] = 0x00;           // Flags
    TxData[4] = 0x1E;           // Address
    TxData[5] = 0x04;           // Length
    TxData[6] = 0x01;           // Count
                                // Data
    TxData[7] = (unsigned char)0x00FF & data;           // Low byte
    TxData[8] = (unsigned char)0x00FF & (data >> 8);    // Hi  byte
    TxData[9] = (unsigned char)0x00FF & stime;           // Low byte
    TxData[10] = (unsigned char)0x00FF * (stime >> 8);   // Hi  byte

    // CheckSum calculation
    for (int i=3; i<=10; i++) {
        CheckSum = CheckSum ^ TxData[i];
    }
    TxData[11] = CheckSum;      // Sum

    // Send Packet
    REDE = 1;                   // Transmit Enable
    for(int i=0; i<=11; i++){
        device.putc(data[i]);
    }
    wait_us(250);               // Wait for transmission
    REDE = 0;                   // Transmitt disable
}

/*--------------------------------------------------*/
/* Function     : main program                      */
/* NAME         : main                              */
/* Argument     : ---                               */
/* Return value : ---                               */
/*--------------------------------------------------*/
int main() {
    Init();                     // initialize
    Torque(0x01, 0x01);         // ID = 1(0x01) , torque = OFF (0x00)
                                // torque = OFF(0x00), ON(0x01), BRAKE(0x02)
    wait(1);                    // wait (1sec)
    while(1){
        SetPosition(0x01,300); // ID = 1(0x01) , GoalPosition = 30.0deg(300)
        wait(1);                // wait (1sec)
        SetPosition(0x01,-300);// ID = 1(0x01) , GoalPosition = -30.0deg(-300)
        wait(1);                // wait (1sec)

        SetTimeAndPosition(0x01, 500, 35);
	wait(1);
	SetTimeAndPosition(0x01, -500, 35);
	wait(1);
    }
}
<commit_msg>Bug fix of checksum.<commit_after>/*--------------------------------------------------*/
/* @Program name ; mbed_servo                       */
/* @Author : Kohei Izumi                            */
/* @Comment : Servo motor operation                 */
/*                                                  */
/* Copyright(c) 2014 Kohei Izumi                    */
/*--------------------------------------------------*/

#include "mbed.h"
Serial device(p9, p10);         // tx = P9, rx = P10
DigitalOut REDE(p11);           // RS485 Transmit Enable
/*--------------------------------------------------*/
/* Funcyion     : mbed initialize                   */
/* NAME         : Init                              */
/* Argument     : ---                               */
/* Return value : ---                               */
/*--------------------------------------------------*/
void Init(void){
    device.baud(115200);        // baud Rate = 115.2kbps [Futaba default]
    REDE = 0;                   // RS485 Transmit disable
}
/*--------------------------------------------------*/
/* Funcyion     : Servo torque enable               */
/* NAME         : Torque                            */
/* Argument     : ID (Servo ID)                     */
/*              : data (Torque enable)              */
/* Return value : ---                               */
/*--------------------------------------------------*/
void Torque (unsigned char ID, unsigned char data){

    unsigned char TxData[10];    // TransmitByteData [10byte]
    unsigned char CheckSum = 0; // CheckSum calculation

    TxData[0] = 0xFA;           // Header
    TxData[1] = 0xAF;           // Header
    TxData[2] = ID;             // ID
    TxData[3] = 0x00;           // Flags
    TxData[4] = 0x24;           // Address
    TxData[5] = 0x01;           // Length
    TxData[6] = 0x01;           // Count
    TxData[7] = data;           // Data

    // CheckSum calculation
    CheckSum = TxData[2];
    for(int i=3; i<8; i++){
        CheckSum = CheckSum ^ TxData[i];
    }

    TxData[8] = CheckSum;       // Sum

    // Send Packet
    REDE = 1;                   // RS485 Transmit Enable
    for(int i=0; i<9; i++){
        device.putc(TxData[i]);
    }
    wait_us(250);               // Wait for transmission
    REDE = 0;                   // RS485 Transmitt disable
}
/*--------------------------------------------------*/
/* Function     : Servo goal position instruction   */
/*                (Not specify time)                */
/* NAME         : SetPosition                       */
/* Argument     : ID (Servo ID)                     */
/*              : data (Set position)              */
/* Return value : ---                               */
/*--------------------------------------------------*/
void SetPosition (unsigned char ID, short data){

    unsigned char TxData[15];   // TransmitByteData [15byte]
    unsigned char CheckSum = 0; // CheckSum calculation

    TxData[0] = 0xFA;           // Header
    TxData[1] = 0xAF;           // Header
    TxData[2] = ID;             // ID
    TxData[3] = 0x00;           // Flags
    TxData[4] = 0x1E;           // Address
    TxData[5] = 0x02;           // Length
    TxData[6] = 0x01;           // Count
                                // Data
    TxData[7] = (unsigned char)0x00FF & data;           // Low byte
    TxData[8] = (unsigned char)0x00FF & (data >> 8);    // Hi  byte

    // CheckSum calculation
    CheckSum = TxData[2];
    for(int i=3; i<9; i++){
        CheckSum = CheckSum ^ TxData[i];
    }
    TxData[9] = CheckSum;       // Sum
    // Send Packet
    REDE = 1;                   // RS485 Transmitt Enable
    for(int i=0; i<10; i++){
        device.putc(TxData[i]);
    }
    wait_us(250);               // Wait for transmission
    REDE = 0;                   // RS485 Transmit disable
}

/*--------------------------------------------------*/
/* Function     : Set the time and position         */
/* NAME         : SetTimeAndPosition                */
/* Argument     : ID (servo ID)                     */
/*              : data (set position)               */
/*              : time (time to move)               */
/* Return value : ---                               */
/*--------------------------------------------------*/
void SetTimeAndPosition(unsigned char ID, short data, unsigned short stime){
    unsigned char TxData[15];   // TransmitByteData [15byte]
    unsigned char CheckSum = 0; // CheckSum calculation

    TxData[0] = 0xFA;           // Header
    TxData[1] = 0xAF;           // Header
    TxData[2] = ID;             // ID
    TxData[3] = 0x00;           // Flags
    TxData[4] = 0x1E;           // Address
    TxData[5] = 0x04;           // Length
    TxData[6] = 0x01;           // Count
                                // Data
    TxData[7] = (unsigned char)0x00FF & data;           // Low byte
    TxData[8] = (unsigned char)0x00FF & (data >> 8);    // Hi  byte
    TxData[9] = (unsigned char)0x00FF & stime;           // Low byte
    TxData[10] = (unsigned char)0x00FF * (stime >> 8);   // Hi  byte

    // CheckSum calculation
    CheckSum = TxData[2];
    for (int i=3; i<11; i++) {
        CheckSum = CheckSum ^ TxData[i];
    }
    TxData[11] = CheckSum;      // Sum

    // Send Packet
    REDE = 1;                   // Transmit Enable
    for(int i=0; i<12; i++){
        device.putc(data[i]);
    }
    wait_us(250);               // Wait for transmission
    REDE = 0;                   // Transmitt disable
}

/*--------------------------------------------------*/
/* Function     : main program                      */
/* NAME         : main                              */
/* Argument     : ---                               */
/* Return value : ---                               */
/*--------------------------------------------------*/
int main() {
    Init();                     // initialize
    Torque(0x01, 0x01);         // ID = 1(0x01) , torque = OFF (0x00)
                                // torque = OFF(0x00), ON(0x01), BRAKE(0x02)
    wait(1);                    // wait (1sec)
    while(1){
        SetPosition(0x01,300); // ID = 1(0x01) , GoalPosition = 30.0deg(300)
        wait(1);                // wait (1sec)
        SetPosition(0x01,-300);// ID = 1(0x01) , GoalPosition = -30.0deg(-300)
        wait(1);                // wait (1sec)

        SetTimeAndPosition(0x01, 500, 35);
	wait(1);
	SetTimeAndPosition(0x01, -500, 35);
	wait(1);
    }
}
<|endoftext|>


<commit_before>/* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robotiq, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Robotiq, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Copyright (c) 2014, Robotiq, Inc
*/

/**
 * \file rq_sensor.cpp
 * \date July 14, 2014
 *  \author Jonathan Savoie <jonathan.savoie@robotiq.com>
 *  \maintainer Nicolas Lauzier <nicolas@robotiq.com>
 */

#include <string.h>
#include <stdio.h>

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Bool.h"
#include "geometry_msgs/WrenchStamped.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"

static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret);
bool wait_for_other_connection(void);
bool try_connection(void);
static int max_retries_(100);

ros::Publisher sensor_pub_acc;

/**
 * \brief Decode the message received and do the associated action
 * \param buff message to decode
 * \param ret buffer containing the return value from a GET command
 */
static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret)
{
	INT_8 get_or_set[3];
	INT_8 nom_var[4];

	if(buff == NULL || strlen(buff) != 7)
	{
		return;
	}

	strncpy(get_or_set, &buff[0], 3);
	strncpy(nom_var, &buff[4], strlen(buff) -3);

	if(strstr(get_or_set, "GET"))
	{
		rq_state_get_command(nom_var, ret);
	}
	else if(strstr(get_or_set, "SET"))
	{
		if(strstr(nom_var, "ZRO"))
		{
			rq_state_do_zero_force_flag();
			strcpy(ret,"Done");
		}
	}
}

bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
	robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
	ROS_INFO("I heard: [%s]",req.command.c_str());
	INT_8 buffer[512];
	decode_message_and_do((char*)req.command.c_str(), buffer);
	res.res = buffer;
	ROS_INFO("I send: [%s]", res.res.c_str());
	return true;
}

/**
 * \fn bool wait_for_other_connection()
 * \brief Each second, checks for a sensor that has been connected
 */
bool wait_for_other_connection(void)
{
	INT_8 ret;
	INT_8 count = 0;

	while(ros::ok() && count < 6)
	{
	    if (count % 2 == 0)
	    {
		    ROS_INFO("Waiting for sensor connection...");
		}
		usleep(1000000); //Attend 1 seconde.

		ret = rq_sensor_state(max_retries_);
		if(ret == 0)
		{
			ROS_INFO("Sensor connected!");
			return true;
		}
        count++;
		ros::spinOnce();
	}
	return false;
}

/**
 * \fn bool try_connection()
 * \brief A helper function to avoid repeated code
 */
bool try_connection(void)
{
	INT_8 ret;
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		if (!wait_for_other_connection())
		{
		    return false;
		}
	}
	return true;
}

/**
 * \fn void get_data(void)
 * \brief Builds the message with the force/torque data
 * \return ft_sensor updated with the latest data
 */
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
	robotiq_force_torque_sensor::ft_sensor msgStream;

	msgStream.Fx = rq_state_get_received_data(0);
	msgStream.Fy = rq_state_get_received_data(1);
	msgStream.Fz = rq_state_get_received_data(2);
	msgStream.Mx = rq_state_get_received_data(3);
	msgStream.My = rq_state_get_received_data(4);
	msgStream.Mz = rq_state_get_received_data(5);

	return msgStream;
}

int main(int argc, char **argv)
{
	ros::init(argc, argv, "robotiq_force_torque_sensor");
	ROS_INFO("Trying to Start Sensor");
	ros::NodeHandle n;
	std_msgs::Bool connection_msg;
	ros::param::param<int>("~max_retries", max_retries_, 100);

	INT_8 bufStream[512];
	INT_32 publish_count = 0;
	robotiq_force_torque_sensor::ft_sensor msgStream;
    bool connected = false;

	//If we can't initialize, we return an error
	connected = try_connection();

	//Reads basic info on the sensor
	connected = try_connection();

	//Starts the stream
	connected = try_connection();

	ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
	ros::Publisher wrench_pub = n.advertise<geometry_msgs::WrenchStamped>("robotiq_force_torque_wrench", 512);
	ros::Publisher connection_pub = n.advertise<std_msgs::Bool>("robotiq_force_torque_sensor_connected", 1);
	ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);

	//std_msgs::String msg;
	geometry_msgs::WrenchStamped wrenchMsg;
	ros::param::param<std::string>("~frame_id", wrenchMsg.header.frame_id, "robotiq_force_torque_frame_id");

	// Publish the connection state
	connection_msg.data = connected;
	connection_pub.publish(connection_msg);
	ros::spinOnce();

	ROS_INFO("Starting Sensor");
	while(ros::ok() && connected)
	{
	    connected = try_connection();

		if(rq_sensor_get_current_state() == RQ_STATE_RUN)
		{
			strcpy(bufStream,"");
			msgStream = get_data();

			if(rq_state_got_new_message())
			{
				sensor_pub.publish(msgStream);

				//compose WrenchStamped Msg
				wrenchMsg.header.stamp = ros::Time::now();
				wrenchMsg.wrench.force.x = msgStream.Fx;
				wrenchMsg.wrench.force.y = msgStream.Fy;
				wrenchMsg.wrench.force.z = msgStream.Fz;
				wrenchMsg.wrench.torque.x = msgStream.Mx;
				wrenchMsg.wrench.torque.y = msgStream.My;
				wrenchMsg.wrench.torque.z = msgStream.Mz;
				wrench_pub.publish(wrenchMsg);
			}
		}

        // Publish the connection state every 1000 iterations
        if (publish_count == 1000)
        {
            connection_msg.data = connected;
	        connection_pub.publish(connection_msg);
	        publish_count = 0;
        }
        publish_count++;
		ros::spinOnce();
	}

	if (!connected)
	{
	    connection_msg.data = connected;
	    connection_pub.publish(connection_msg);
	}

	ROS_INFO("Sensor Stopped");
	return 0;
}
<commit_msg>last fix<commit_after>/* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robotiq, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Robotiq, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Copyright (c) 2014, Robotiq, Inc
*/

/**
 * \file rq_sensor.cpp
 * \date July 14, 2014
 *  \author Jonathan Savoie <jonathan.savoie@robotiq.com>
 *  \maintainer Nicolas Lauzier <nicolas@robotiq.com>
 */

#include <string.h>
#include <stdio.h>

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Bool.h"
#include "geometry_msgs/WrenchStamped.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"

static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret);
bool wait_for_other_connection(void);
bool try_connection(void);
static int max_retries_(100);

ros::Publisher sensor_pub_acc;

/**
 * \brief Decode the message received and do the associated action
 * \param buff message to decode
 * \param ret buffer containing the return value from a GET command
 */
static void decode_message_and_do(INT_8 const  * const buff, INT_8 * const ret)
{
	INT_8 get_or_set[3];
	INT_8 nom_var[4];

	if(buff == NULL || strlen(buff) != 7)
	{
		return;
	}

	strncpy(get_or_set, &buff[0], 3);
	strncpy(nom_var, &buff[4], strlen(buff) -3);

	if(strstr(get_or_set, "GET"))
	{
		rq_state_get_command(nom_var, ret);
	}
	else if(strstr(get_or_set, "SET"))
	{
		if(strstr(nom_var, "ZRO"))
		{
			rq_state_do_zero_force_flag();
			strcpy(ret,"Done");
		}
	}
}

bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
	robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
	ROS_INFO("I heard: [%s]",req.command.c_str());
	INT_8 buffer[512];
	decode_message_and_do((char*)req.command.c_str(), buffer);
	res.res = buffer;
	ROS_INFO("I send: [%s]", res.res.c_str());
	return true;
}

/**
 * \fn bool wait_for_other_connection()
 * \brief Each second, checks for a sensor that has been connected
 */
bool wait_for_other_connection(void)
{
	INT_8 ret;
	INT_8 count = 0;

	while(ros::ok() && count < 6)
	{
	    if (count % 2 == 0)
	    {
		    ROS_INFO("Waiting for sensor connection...");
		}
		usleep(1000000); //Attend 1 seconde.

		ret = rq_sensor_state(max_retries_);
		if(ret == 0)
		{
			ROS_INFO("Sensor connected!");
			return true;
		}
        count++;
		ros::spinOnce();
	}
	return false;
}

/**
 * \fn bool try_connection()
 * \brief A helper function to avoid repeated code
 */
bool try_connection(void)
{
	INT_8 ret;
	ret = rq_sensor_state(max_retries_);
	if(ret == -1)
	{
		if (!wait_for_other_connection())
		{
		    return false;
		}
	}
	return true;
}

/**
 * \fn void get_data(void)
 * \brief Builds the message with the force/torque data
 * \return ft_sensor updated with the latest data
 */
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
	robotiq_force_torque_sensor::ft_sensor msgStream;

	msgStream.Fx = rq_state_get_received_data(0);
	msgStream.Fy = rq_state_get_received_data(1);
	msgStream.Fz = rq_state_get_received_data(2);
	msgStream.Mx = rq_state_get_received_data(3);
	msgStream.My = rq_state_get_received_data(4);
	msgStream.Mz = rq_state_get_received_data(5);

	return msgStream;
}

int main(int argc, char **argv)
{
	ros::init(argc, argv, "robotiq_force_torque_sensor");
	ROS_INFO("Trying to Start Sensor");
	ros::NodeHandle n;
	std_msgs::Bool connection_msg;
	ros::param::param<int>("~max_retries", max_retries_, 100);

	INT_8 bufStream[512];
	INT_32 publish_count = 0;
	robotiq_force_torque_sensor::ft_sensor msgStream;
    bool connected = false;

	//If we can't initialize, we return an error
	connected = try_connection();

	//Reads basic info on the sensor
	connected = try_connection();

	//Starts the stream
	connected = try_connection();

	ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
	ros::Publisher wrench_pub = n.advertise<geometry_msgs::WrenchStamped>("robotiq_force_torque_wrench", 512);
	ros::Publisher connection_pub = n.advertise<std_msgs::Bool>("robotiq_force_torque_sensor_connected", 1);
	ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);

	//std_msgs::String msg;
	geometry_msgs::WrenchStamped wrenchMsg;
	ros::param::param<std::string>("~frame_id", wrenchMsg.header.frame_id, "robotiq_force_torque_frame_id");

	// Publish the connection state
	connection_msg.data = connected;
	connection_pub.publish(connection_msg);
	ros::spinOnce();

    if (connected)
    {
	    ROS_INFO("Starting Sensor");
	}

	while(ros::ok() && connected)
	{
	    connected = try_connection();

		if(rq_sensor_get_current_state() == RQ_STATE_RUN)
		{
			strcpy(bufStream,"");
			msgStream = get_data();

			if(rq_state_got_new_message())
			{
				sensor_pub.publish(msgStream);

				// compose WrenchStamped Msg
				wrenchMsg.header.stamp = ros::Time::now();
				wrenchMsg.wrench.force.x = msgStream.Fx;
				wrenchMsg.wrench.force.y = msgStream.Fy;
				wrenchMsg.wrench.force.z = msgStream.Fz;
				wrenchMsg.wrench.torque.x = msgStream.Mx;
				wrenchMsg.wrench.torque.y = msgStream.My;
				wrenchMsg.wrench.torque.z = msgStream.Mz;
				wrench_pub.publish(wrenchMsg);
			}
		}

        // Publish the connection state every 1000 iterations
        if (publish_count == 1000)
        {
            connection_msg.data = connected;
	        connection_pub.publish(connection_msg);
	        publish_count = 0;
        }
        publish_count++;
		ros::spinOnce();
	}

	if (!connected)
	{
	    connection_msg.data = connected;
	    connection_pub.publish(connection_msg);
	    ros::spinOnce();
	}

	ROS_INFO("Sensor Stopped");
	return 0;
}
<|endoftext|>


<commit_before>/* Begin CVS Header
  $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CEFMMethod.cpp,v $
  $Revision: 1.8 $
  $Name:  $
  $Author: shoops $
  $Date: 2009/09/16 16:15:35 $
  End CVS Header */

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001-2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

/**
 *  CEFMMethod class
 *  This class describes the interface to all optimization methods.
 *  The various method like RandomSearch or GA have to be derived from
 *  this class.
 *
 *  Created for Copasi by Stefan Hoops 2002
 */

#include "copasi.h"

#include "CEFMTask.h"
#include "CEFMMethod.h"

#include "CEFMAlgorithm.h"
#include "CBitPatternTreeMethod.h"

#ifdef COPASI_SSA
# include "CSSAMethod.h"
#endif

CEFMMethod * CEFMMethod::createMethod(CCopasiMethod::SubType subType)
{
  CEFMMethod * pMethod = NULL;

  switch (subType)
    {
      case EFMAlgorithm:
        pMethod = new CEFMAlgorithm();
        break;

      case EFMBitPatternTreeAlgorithm:
        pMethod = new CBitPatternTreeMethod();
        break;

#ifdef COPASI_SSA
      case stoichiometricStabilityAnalysis:
        pMethod = new CSSAMethod();
        break;
#endif

      default:
        pMethod = new CEFMAlgorithm();
        break;
    }

  return pMethod;
}

// Default constructor
CEFMMethod::CEFMMethod():
    CCopasiMethod(CCopasiTask::fluxMode, CCopasiMethod::unset),
    mReorderedReactions()
{CONSTRUCTOR_TRACE;}

CEFMMethod::CEFMMethod(const CCopasiTask::Type & taskType,
                       const CEFMMethod::SubType & subType,
                       const CCopasiContainer * pParent):
    CCopasiMethod(taskType, subType, pParent),
    mReorderedReactions()
{CONSTRUCTOR_TRACE;}

CEFMMethod::CEFMMethod(const CEFMMethod & src,
                       const CCopasiContainer * pParent):
    CCopasiMethod(src, pParent),
    mReorderedReactions(src.mReorderedReactions)
{CONSTRUCTOR_TRACE;}

CEFMMethod::~CEFMMethod()
{}

bool CEFMMethod::calculate(void)
{
  return false;
}

bool CEFMMethod::initialize()
{
  return true;
}

bool CEFMMethod::isValidProblem(const CCopasiProblem * pProblem)
{
  if (!CCopasiMethod::isValidProblem(pProblem)) return false;

  return true;
}

const std::vector< CFluxMode > & CEFMMethod::getFluxModes() const
{return mFluxModes;}

const std::vector< const CReaction * > & CEFMMethod::getReorderedReactions() const
{return mReorderedReactions;}
<commit_msg>Changed default method to be the new bit pattern tree algorithm.<commit_after>/* Begin CVS Header
  $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/elementaryFluxModes/CEFMMethod.cpp,v $
  $Revision: 1.9 $
  $Name:  $
  $Author: shoops $
  $Date: 2009/12/07 17:14:50 $
  End CVS Header */

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001-2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

/**
 *  CEFMMethod class
 *  This class describes the interface to all optimization methods.
 *  The various method like RandomSearch or GA have to be derived from
 *  this class.
 *
 *  Created for Copasi by Stefan Hoops 2002
 */

#include "copasi.h"

#include "CEFMTask.h"
#include "CEFMMethod.h"

#include "CEFMAlgorithm.h"
#include "CBitPatternTreeMethod.h"

#ifdef COPASI_SSA
# include "CSSAMethod.h"
#endif

CEFMMethod * CEFMMethod::createMethod(CCopasiMethod::SubType subType)
{
  CEFMMethod * pMethod = NULL;

  switch (subType)
    {
      case EFMAlgorithm:
        pMethod = new CEFMAlgorithm();
        break;

      case EFMBitPatternTreeAlgorithm:
        pMethod = new CBitPatternTreeMethod();
        break;

#ifdef COPASI_SSA
      case stoichiometricStabilityAnalysis:
        pMethod = new CSSAMethod();
        break;
#endif

      default:
        pMethod = new CBitPatternTreeMethod();
        break;
    }

  return pMethod;
}

// Default constructor
CEFMMethod::CEFMMethod():
    CCopasiMethod(CCopasiTask::fluxMode, CCopasiMethod::unset),
    mReorderedReactions()
{CONSTRUCTOR_TRACE;}

CEFMMethod::CEFMMethod(const CCopasiTask::Type & taskType,
                       const CEFMMethod::SubType & subType,
                       const CCopasiContainer * pParent):
    CCopasiMethod(taskType, subType, pParent),
    mReorderedReactions()
{CONSTRUCTOR_TRACE;}

CEFMMethod::CEFMMethod(const CEFMMethod & src,
                       const CCopasiContainer * pParent):
    CCopasiMethod(src, pParent),
    mReorderedReactions(src.mReorderedReactions)
{CONSTRUCTOR_TRACE;}

CEFMMethod::~CEFMMethod()
{}

bool CEFMMethod::calculate(void)
{
  return false;
}

bool CEFMMethod::initialize()
{
  return true;
}

bool CEFMMethod::isValidProblem(const CCopasiProblem * pProblem)
{
  if (!CCopasiMethod::isValidProblem(pProblem)) return false;

  return true;
}

const std::vector< CFluxMode > & CEFMMethod::getFluxModes() const
{return mFluxModes;}

const std::vector< const CReaction * > & CEFMMethod::getReorderedReactions() const
{return mReorderedReactions;}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MTypeConverter.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:30:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <MNSInclude.hxx>

#ifndef _CONNECTIVITY_MAB_TYPECONVERTER_HXX_
#include "MTypeConverter.hxx"
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif

using namespace connectivity::mozab;

// -------------------------------------------------------------------------
void MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)
{
    // Convert to ::rtl::OString (utf-8 encoding).
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);

    const char *cs = os.getStr();
    PRUint32 csLen = os.getLength();

    NS_ConvertUTF8toUCS2 mozString(cs, csLen);
    //const PRUnichar* uniMozString = (const PRUnichar*) mozString;
    nss = mozString; // temp.
}
// -------------------------------------------------------------------------
void MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)
{
    // Get clone of buffer.
    PRUnichar *uc = ToNewUnicode(nss);
    sal_Int32 nssLen = nss.Length();

    // TODO check if this is ok.
    ::rtl::OUString _ous(uc, nssLen);
    ous = _ous;

    nsMemory::Free(uc);
}
// -------------------------------------------------------------------------
void MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)
{
    // TODO, specify length.
    ::rtl::OUString _ous(pru);
    ous = _ous;
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)
{
    // Convert to ::rtl::OString,
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);

    const char *cs = os.getStr();

    return(strdup(cs));
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString,
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_ASCII_US);

    return(strdup(os.getStr()));
}
// -------------------------------------------------------------------------
char *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)
{
    char cs[1024];
    nss.ToCString(cs, 1024);

    return(strdup(cs));
}
// -------------------------------------------------------------------------
::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString.
    ::rtl::OString os(ous,ous.getLength(),RTL_TEXTENCODING_ASCII_US);
    return( ::std::string(os.getStr()));
}
#if 0
// -------------------------------------------------------------------------
::std::string MTypeConverter::nsStringToStlString(nsString const &nss)
{
    return( ::std::string(nss.GetBuffer()));
}
#endif
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.166); FILE MERGED 2006/09/01 17:22:30 kaib 1.5.166.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MTypeConverter.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:02:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#include <MNSInclude.hxx>

#ifndef _CONNECTIVITY_MAB_TYPECONVERTER_HXX_
#include "MTypeConverter.hxx"
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif

using namespace connectivity::mozab;

// -------------------------------------------------------------------------
void MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)
{
    // Convert to ::rtl::OString (utf-8 encoding).
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);

    const char *cs = os.getStr();
    PRUint32 csLen = os.getLength();

    NS_ConvertUTF8toUCS2 mozString(cs, csLen);
    //const PRUnichar* uniMozString = (const PRUnichar*) mozString;
    nss = mozString; // temp.
}
// -------------------------------------------------------------------------
void MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)
{
    // Get clone of buffer.
    PRUnichar *uc = ToNewUnicode(nss);
    sal_Int32 nssLen = nss.Length();

    // TODO check if this is ok.
    ::rtl::OUString _ous(uc, nssLen);
    ous = _ous;

    nsMemory::Free(uc);
}
// -------------------------------------------------------------------------
void MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)
{
    // TODO, specify length.
    ::rtl::OUString _ous(pru);
    ous = _ous;
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)
{
    // Convert to ::rtl::OString,
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);

    const char *cs = os.getStr();

    return(strdup(cs));
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString,
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_ASCII_US);

    return(strdup(os.getStr()));
}
// -------------------------------------------------------------------------
char *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)
{
    char cs[1024];
    nss.ToCString(cs, 1024);

    return(strdup(cs));
}
// -------------------------------------------------------------------------
::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString.
    ::rtl::OString os(ous,ous.getLength(),RTL_TEXTENCODING_ASCII_US);
    return( ::std::string(os.getStr()));
}
#if 0
// -------------------------------------------------------------------------
::std::string MTypeConverter::nsStringToStlString(nsString const &nss)
{
    return( ::std::string(nss.GetBuffer()));
}
#endif
// -------------------------------------------------------------------------
<|endoftext|>


<commit_before>/***************************************************************************
                          filter_mbox.cxx  -  mbox mail import
                             -------------------
    begin                : Sat Apr 5 2003
    copyright            : (C) 2003 by Laurence Anderson
    email                : l.d.anderson@warwick.ac.uk
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <config.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <ktemporaryfile.h>
#include <kdebug.h>

#include "filter_mbox.hxx"

FilterMBox::FilterMBox() :
        Filter( i18n("Import mbox Files (UNIX, Evolution)"),
                "Laurence Anderson
( Filter accelerated by Danny Kukawka )
",
                i18n("
mbox import filter
"
                     "
This filter will import mbox files into KMail. Use this filter "
                     "if you want to import mails from Ximian Evolution or other mailers "
                     "that use this traditional UNIX format.
"
                     "
Note: Emails will be imported into folders named after the "
                     "file they came from, prefixed with MBOX-
" ))
{}

FilterMBox::~FilterMBox()
{
    endImport();
}

void FilterMBox::import(FilterInfo *info)
{
    int currentFile = 1;
    int overall_status = 0;
    bool first_msg = true;

    QStringList filenames = KFileDialog::getOpenFileNames( QDir::homePath(), "*|" + i18n("mbox Files (*)"), info->parent() );
    info->setOverall(0);

    for ( QStringList::Iterator filename = filenames.begin(); filename != filenames.end(); ++filename, ++currentFile) {
        QFile mbox( *filename );
        if (! mbox.open( QIODevice::ReadOnly ) ) {
            info->alert( i18n("Unable to open %1, skipping", *filename ) );
        } else {
            QFileInfo filenameInfo( *filename );
            QString folderName( "MBOX-" + filenameInfo.completeBaseName() );

            info->setCurrent(0);
            info->addLog( i18n("Importing emails from %1...", *filename ) );

            info->setFrom( *filename );
            info->setTo( folderName );

            QByteArray input(MAX_LINE,'\0');
            long l = 0;

            while ( ! mbox.atEnd() ) {
                KTemporaryFile tmp;
                tmp.open();
                QIODevice::Offset filepos = 0;
                /* comment by Danny:
                * Don't use QTextStream to read from mbox, better use QDataStream. QTextStream only
                * support Unicode/Latin1/Locale. So you lost information from emails with
                * charset!=Unicode/Latin1/Locale (e.g. KOI8-R) and Content-Transfer-Encoding != base64
                * (e.g. 8Bit). It also not help to convert the QTextStream to Unicode. By this you
                * get Unicode/UTF-email but KMail can't detect the correct charset.
                */
                QByteArray seperate;

                /* check if the first line start with "From " (and not "From: ") and discard the line
                 * in this case because some IMAP servers (e.g. Cyrus) don't accept this header line */
                if(!first_msg && ((seperate = input.data()).left(5) != "From "))
                    tmp.write( input, l );

                l = mbox.readLine( input.data(),MAX_LINE); // read the first line, prevent "From "

                if ((seperate = input.data()).left(5) != "From ")
                    tmp.write( input, l );

                while ( ! mbox.atEnd() &&  (l = mbox.readLine(input.data(),MAX_LINE)) && ((seperate = input.data()).left(5) != "From ")) {
                       tmp.write( input, l );

                       // workaround to fix hang if a corrupted mbox contains some
                       // binary data, for more see bug #106796
                       if (mbox.pos() == filepos)
                           mbox.seek(mbox.size());
                       else
                           filepos = mbox.pos();
                }
                tmp.flush();
                first_msg = false;

                /* comment by Danny Kukawka:
                * addMessage() == old function, need more time and check for duplicates
                * addMessage_fastImport == new function, faster and no check for duplicates
                */
                if(info->removeDupMsg)
                    addMessage( info, folderName, tmp.fileName() );
                else
                    addMessage_fastImport( info, folderName, tmp.fileName() );

                int currentPercentage = (int) ( ( (float) mbox.pos() / filenameInfo.size() ) * 100 );
                info->setCurrent( currentPercentage );
                if (currentFile == 1)
                    overall_status = (int)( currentPercentage*((float)currentFile/filenames.count()));
                else
                    overall_status = (int)(((currentFile-1)*(100.0/(float)filenames.count()))+(currentPercentage*(1.0/(float)filenames.count())));
                info->setOverall( overall_status );

                if ( info->shouldTerminate() ) break;
            }

            info->addLog( i18n("Finished importing emails from %1", *filename ));
            if (count_duplicates > 0) {
                info->addLog( i18np("1 duplicate message not imported to folder %1 in KMail",
                                   "%n duplicate messages not imported to folder %1 in KMail",
                                   count_duplicates, folderName));
            }
            if (info->shouldTerminate()) info->addLog( i18n("Finished import, canceled by user."));
            count_duplicates = 0;
            // don't forget to close the file !!!
            mbox.close();
        }
    }
}
<commit_msg>forward port SVN commit 578568 by dkukawka:<commit_after>/***************************************************************************
                          filter_mbox.cxx  -  mbox mail import
                             -------------------
    begin                : Sat Apr 5 2003
    copyright            : (C) 2003 by Laurence Anderson
    email                : l.d.anderson@warwick.ac.uk
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <config.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <ktemporaryfile.h>
#include <kdebug.h>

#include "filter_mbox.hxx"

FilterMBox::FilterMBox() :
        Filter( i18n("Import mbox Files (UNIX, Evolution)"),
                "Laurence Anderson
( Filter accelerated by Danny Kukawka )
",
                i18n("
mbox import filter
"
                     "
This filter will import mbox files into KMail. Use this filter "
                     "if you want to import mails from Ximian Evolution or other mailers "
                     "that use this traditional UNIX format.
"
                     "
Note: Emails will be imported into folders named after the "
                     "file they came from, prefixed with MBOX-
" ))
{}

FilterMBox::~FilterMBox()
{
    endImport();
}

void FilterMBox::import(FilterInfo *info)
{
    int currentFile = 1;
    int overall_status = 0;
    bool first_msg = true;

    QStringList filenames = KFileDialog::getOpenFileNames( QDir::homePath(), "*|" + i18n("mbox Files (*)"), info->parent() );
    info->setOverall(0);

    for ( QStringList::Iterator filename = filenames.begin(); filename != filenames.end(); ++filename, ++currentFile) {
        QFile mbox( *filename );
        if (! mbox.open( QIODevice::ReadOnly ) ) {
            info->alert( i18n("Unable to open %1, skipping", *filename ) );
        } else {
            QFileInfo filenameInfo( *filename );
            QString folderName( "MBOX-" + filenameInfo.completeBaseName() );

            info->setCurrent(0);
            info->addLog( i18n("Importing emails from %1...", *filename ) );

            info->setFrom( *filename );
            info->setTo( folderName );

            QByteArray input(MAX_LINE,'\0');
            long l = 0;

            while ( ! mbox.atEnd() ) {
                KTemporaryFile tmp;
                tmp.open();
                QIODevice::Offset filepos = 0;
                /* comment by Danny:
                * Don't use QTextStream to read from mbox, better use QDataStream. QTextStream only
                * support Unicode/Latin1/Locale. So you lost information from emails with
                * charset!=Unicode/Latin1/Locale (e.g. KOI8-R) and Content-Transfer-Encoding != base64
                * (e.g. 8Bit). It also not help to convert the QTextStream to Unicode. By this you
                * get Unicode/UTF-email but KMail can't detect the correct charset.
                */
                QByteArray seperate;
                QString x_status_flag = "";

                /* check if the first line start with "From " (and not "From: ") and discard the line
                 * in this case because some IMAP servers (e.g. Cyrus) don't accept this header line */
                if(!first_msg && ((seperate = input.data()).left(5) != "From "))
                    tmp.write( input, l );

                l = mbox.readLine( input.data(),MAX_LINE); // read the first line, prevent "From "

                if ((seperate = input.data()).left(5) != "From ")
                    tmp.write( input, l );

                while ( ! mbox.atEnd() &&  (l = mbox.readLine(input.data(),MAX_LINE)) && ((seperate = input.data()).left(5) != "From ")) {
                    tmp.write( input, l );

                    if ((seperate = input.data()).left(10) == "X-Status: ") {
                        x_status_flag = seperate;
                        x_status_flag.remove("X-Status: ");
                        x_status_flag = x_status_flag.trimmed();
                        // qDebug("x_status_flag: %s", x_status_flag.latin1() );
                    }

                    // workaround to fix hang if a corrupted mbox contains some
                    // binary data, for more see bug #106796
                    if (mbox.pos() == filepos)
                        mbox.seek(mbox.size());
                    else
                      filepos = mbox.pos();
                }
                tmp.flush();
                first_msg = false;

                /* comment by Danny Kukawka:
                * addMessage() == old function, need more time and check for duplicates
                * addMessage_fastImport == new function, faster and no check for duplicates
                */
                if(info->removeDupMsg)
                    addMessage( info, folderName, tmp.fileName(), x_status_flag );
                else
                    addMessage_fastImport( info, folderName, tmp.fileName(), x_status_flag );

                int currentPercentage = (int) ( ( (float) mbox.pos() / filenameInfo.size() ) * 100 );
                info->setCurrent( currentPercentage );
                if (currentFile == 1)
                    overall_status = (int)( currentPercentage*((float)currentFile/filenames.count()));
                else
                    overall_status = (int)(((currentFile-1)*(100.0/(float)filenames.count()))+(currentPercentage*(1.0/(float)filenames.count())));
                info->setOverall( overall_status );

                if ( info->shouldTerminate() ) break;
            }

            info->addLog( i18n("Finished importing emails from %1", *filename ));
            if (count_duplicates > 0) {
                info->addLog( i18np("1 duplicate message not imported to folder %1 in KMail",
                                   "%n duplicate messages not imported to folder %1 in KMail",
                                   count_duplicates, folderName));
            }
            if (info->shouldTerminate()) info->addLog( i18n("Finished import, canceled by user."));
            count_duplicates = 0;
            // don't forget to close the file !!!
            mbox.close();
        }
    }
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

#include "LinearTransferFunction.h"
#include "LinearTransferFunction_ispc.h"

namespace ospray {

  LinearTransferFunction::LinearTransferFunction()
  {
    ispcEquivalent = ispc::LinearTransferFunction_create();
  }

  void LinearTransferFunction::commit()
  {
    TransferFunction::commit();

    colorValues = getParamDataT<vec3f>("color");
    opacityValues = getParamDataT<float>("opacity");

    ispc::LinearTransferFunction_set(
        ispcEquivalent, ispc(colorValues), ispc(opacityValues));
  }

  std::string LinearTransferFunction::toString() const
  {
    return "ospray::LinearTransferFunction";
  }

  std::vector<range1i> LinearTransferFunction::getPositiveOpacityIndexRanges() const
  {
    std::vector<range1i> intervals;

    range1i interval;
    bool rangeActive = false;

    const DataT<float> &opacities = *opacityValues;

    for (int i = 0; i < opacities.size(); i++) {
      if (opacities[i] > 0.f && !rangeActive) {
        rangeActive    = true;
        interval.lower = i;
      } else if (opacities[i] <= 0.f && rangeActive) {
        rangeActive    = false;
        interval.upper = i;
        intervals.push_back(interval);
      }
    }

    // special case for final value
    if (opacities[opacities.size()-1] > 0.f) {
      if (rangeActive) {
        rangeActive    = false;
        interval.upper = opacities.size();
        intervals.push_back(interval);
      } else {
        throw std::runtime_error("getPositiveOpacityIndexRanges() error");
      }
    }

    return intervals;
  }

  std::vector<range1f> LinearTransferFunction::getPositiveOpacityValueRanges() const
  {
    std::vector<range1f> valueRanges;

    // determine index ranges for positive opacities
    std::vector<range1i> indexRanges = getPositiveOpacityIndexRanges();

    const DataT<float> &opacities = *opacityValues;

    // convert index ranges to value ranges
    // note that a positive opacity value has a span of +/-1 due to the linear
    // interpolation, and returned index ranges are [min, max) intervals
    for (int i = 0; i < indexRanges.size(); i++) {
      int minValueIndex = indexRanges[i].lower - 1;
      int maxValueIndex = indexRanges[i].upper;

      range1f range(neg_inf, inf);

      if (minValueIndex >= 0) {
        range.lower = valueRange.lower
                 + minValueIndex * valueRange.size() / (opacities.size() - 1.f);
      }

      if (maxValueIndex < opacities.size()) {
        range.upper = valueRange.lower
                    + maxValueIndex * valueRange.size() / (opacities.size() - 1.f);
      }

      valueRanges.push_back(range);
    }

    return valueRanges;
  }

  OSP_REGISTER_TRANSFER_FUNCTION(LinearTransferFunction, piecewise_linear);

} // namespace ospray
<commit_msg>warning fixes<commit_after>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

#include "LinearTransferFunction.h"
#include "LinearTransferFunction_ispc.h"

namespace ospray {

  LinearTransferFunction::LinearTransferFunction()
  {
    ispcEquivalent = ispc::LinearTransferFunction_create();
  }

  void LinearTransferFunction::commit()
  {
    TransferFunction::commit();

    colorValues = getParamDataT<vec3f>("color");
    opacityValues = getParamDataT<float>("opacity");

    ispc::LinearTransferFunction_set(
        ispcEquivalent, ispc(colorValues), ispc(opacityValues));
  }

  std::string LinearTransferFunction::toString() const
  {
    return "ospray::LinearTransferFunction";
  }

  std::vector<range1i> LinearTransferFunction::getPositiveOpacityIndexRanges() const
  {
    std::vector<range1i> intervals;

    range1i interval;
    bool rangeActive = false;

    const DataT<float> &opacities = *opacityValues;

    for (int i = 0; i < int(opacities.size()); i++) {
      if (opacities[i] > 0.f && !rangeActive) {
        rangeActive    = true;
        interval.lower = i;
      } else if (opacities[i] <= 0.f && rangeActive) {
        rangeActive    = false;
        interval.upper = i;
        intervals.push_back(interval);
      }
    }

    // special case for final value
    if (opacities[opacities.size()-1] > 0.f) {
      if (rangeActive) {
        rangeActive    = false;
        interval.upper = opacities.size();
        intervals.push_back(interval);
      } else {
        throw std::runtime_error("getPositiveOpacityIndexRanges() error");
      }
    }

    return intervals;
  }

  std::vector<range1f> LinearTransferFunction::getPositiveOpacityValueRanges() const
  {
    std::vector<range1f> valueRanges;

    // determine index ranges for positive opacities
    std::vector<range1i> indexRanges = getPositiveOpacityIndexRanges();

    const DataT<float> &opacities = *opacityValues;

    // convert index ranges to value ranges
    // note that a positive opacity value has a span of +/-1 due to the linear
    // interpolation, and returned index ranges are [min, max) intervals
    for (int i = 0; i < int(indexRanges.size()); i++) {
      int minValueIndex = indexRanges[i].lower - 1;
      int maxValueIndex = indexRanges[i].upper;

      range1f range(neg_inf, inf);

      if (minValueIndex >= 0) {
        range.lower = valueRange.lower
                 + minValueIndex * valueRange.size() / (opacities.size() - 1.f);
      }

      if (maxValueIndex < int(opacities.size())) {
        range.upper = valueRange.lower
                    + maxValueIndex * valueRange.size() / (opacities.size() - 1.f);
      }

      valueRanges.push_back(range);
    }

    return valueRanges;
  }

  OSP_REGISTER_TRANSFER_FUNCTION(LinearTransferFunction, piecewise_linear);

} // namespace ospray
<|endoftext|>


<commit_before>#include "../Include/CGridNode.h"

using namespace cocos2d;

namespace LM
{

	CGridNode::CGridNode(int a_iRows, int a_iCols, EAnchor a_eAnchor, int a_iWidth, int a_iHeight, int a_iXPosition, int a_iYPosition) :
		CGroupNode(a_eAnchor, a_iWidth, a_iHeight, a_iXPosition, a_iYPosition),
		m_iRows(a_iRows),
		m_iCols(a_iCols),
		m_iColIndex(0),
		m_iRowIndex(0)
{

}

	void CGridNode::Init()
	{
        m_iColIndex = 0;
        m_iRowIndex = 0;
		// populate empty slots in the grid with placeholder groups
		for (int iNbPlaceholders = m_iRows * m_iCols - m_vChildren.size();
			iNbPlaceholders > 0;
			--iNbPlaceholders)
		{
			CGroupNode* pPlaceHolder = new CGroupNode();
			AddChildNode(pPlaceHolder);
		}

		CGroupNode::Init();
	}

    void CGridNode::SetGrid(int a_iRows, int a_iCols)
    {
        m_iRows = a_iRows;
        m_iCols = a_iCols;
        ON_CC_THREAD(LM::CGridNode::Update, this);
    }

    int CGridNode::GetRowCount()
    {
        return m_iRows;
    }

    int CGridNode::GetColCount()
    {
        return m_iCols;
    }

Size CGridNode::GetVisibleSize()
{
	Size oGridSize = CEntityNode::GetVisibleSize();
    if (m_iRowIndex < m_iRows && m_iColIndex < m_iCols)
    {
        return cocos2d::Size(oGridSize.width / m_iCols, oGridSize.height / m_iRows);
    }
    return cocos2d::Size(0, 0);
}

Vec2 CGridNode::GetOrigin()
{
	Vec2 oGridOrigin = CEntityNode::GetOrigin();

	// return the origin of the cell of the grid for the item
    Vec2 oNodeOrigin = Vec2(oGridOrigin.x + m_iColIndex * GetVisibleSize().width,
        oGridOrigin.y + (m_iRows - m_iRowIndex - 1) * GetVisibleSize().height);

    if (m_iRowIndex < m_iRows && m_iColIndex < m_iCols - 1)
	{
		m_iColIndex++;
	}
	else
	{
		m_iRowIndex++;
		m_iColIndex = 0;
	}

	return oNodeOrigin;
}

} // namespace LM
<commit_msg>[MODIF] reverted some modifications in grid management to avoid breaking previous games logic<commit_after>#include "../Include/CGridNode.h"

using namespace cocos2d;

namespace LM
{

	CGridNode::CGridNode(int a_iRows, int a_iCols, EAnchor a_eAnchor, int a_iWidth, int a_iHeight, int a_iXPosition, int a_iYPosition) :
		CGroupNode(a_eAnchor, a_iWidth, a_iHeight, a_iXPosition, a_iYPosition),
		m_iRows(a_iRows),
		m_iCols(a_iCols),
		m_iColIndex(0),
		m_iRowIndex(0)
{

}

	void CGridNode::Init()
	{
        m_iColIndex = 0;
        m_iRowIndex = 0;
		// populate empty slots in the grid with placeholder groups
		for (int iNbPlaceholders = m_iRows * m_iCols - m_vChildren.size();
			iNbPlaceholders > 0;
			--iNbPlaceholders)
		{
			CGroupNode* pPlaceHolder = new CGroupNode();
			AddChildNode(pPlaceHolder);
		}

		CGroupNode::Init();
	}

    void CGridNode::SetGrid(int a_iRows, int a_iCols)
    {
        m_iRows = a_iRows;
        m_iCols = a_iCols;
        // ON_CC_THREAD(LM::CGridNode::Update, this); // editor only
    }

    int CGridNode::GetRowCount()
    {
        return m_iRows;
    }

    int CGridNode::GetColCount()
    {
        return m_iCols;
    }

Size CGridNode::GetVisibleSize()
{
	Size oGridSize = CEntityNode::GetVisibleSize();
    //if (m_iRowIndex < m_iRows && m_iColIndex < m_iCols)
    //{
        return cocos2d::Size(oGridSize.width / m_iCols, oGridSize.height / m_iRows);
    //}
    //return cocos2d::Size(0, 0);
}

Vec2 CGridNode::GetOrigin()
{
	Vec2 oGridOrigin = CEntityNode::GetOrigin();

	// return the origin of the cell of the grid for the item
    Vec2 oNodeOrigin = Vec2(oGridOrigin.x + m_iColIndex * GetVisibleSize().width,
        oGridOrigin.y + m_iRowIndex * GetVisibleSize().height);

    if (m_iRowIndex < m_iRows && m_iColIndex < m_iCols - 1)
	{
		m_iColIndex++;
	}
	else
	{
		m_iRowIndex++;
		m_iColIndex = 0;
	}

	return oNodeOrigin;
}

} // namespace LM
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/shared_resources_data_source.h"

#include <string>

#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/shared_resources.h"
#include "grit/shared_resources_map.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

int PathToIDR(const std::string& path) {
  int idr = -1;
  if (path == "app/resources/folder_closed.png") {
    idr = IDR_FOLDER_CLOSED;
  } else if (path == "app/resources/folder_closed_rtl.png") {
    idr = IDR_FOLDER_CLOSED_RTL;
  } else if (path == "app/resources/folder_open.png") {
    idr = IDR_FOLDER_OPEN;
  } else if (path == "app/resources/folder_open_rtl.png") {
    idr = IDR_FOLDER_OPEN_RTL;
  } else if (path == "app/resources/throbber.png") {
    idr = IDR_THROBBER;
  } else {
    // The name of the files in the grd list are prefixed with the following
    // directory:
    std::string key("shared/");
    key += path;

    for (size_t i = 0; i < kSharedResourcesSize; ++i) {
      if (kSharedResources[i].name == key) {
        idr = kSharedResources[i].value;
        break;
      }
    }
  }

  return idr;
}

}  // namespace

SharedResourcesDataSource::SharedResourcesDataSource()
    : DataSource(chrome::kChromeUIResourcesHost, NULL) {
}

SharedResourcesDataSource::~SharedResourcesDataSource() {
}

void SharedResourcesDataSource::StartDataRequest(const std::string& path,
                                                 bool is_incognito,
                                                 int request_id) {
  int idr = PathToIDR(path);
  DCHECK_NE(-1, idr);
  const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  scoped_refptr<RefCountedStaticMemory> bytes(rb.LoadDataResourceBytes(idr));
  SendResponse(request_id, bytes);
}

std::string SharedResourcesDataSource::GetMimeType(
    const std::string& path) const {
  // Requests should not block on the disk!  On Windows this goes to the
  // registry.
  //   http://code.google.com/p/chromium/issues/detail?id=59849
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  std::string mime_type;
  net::GetMimeTypeFromFile(FilePath().AppendASCII(path), &mime_type);
  return mime_type;
}
<commit_msg>shared_resources_data_source.cc: add path name to dcheck<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/shared_resources_data_source.h"

#include <string>

#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/shared_resources.h"
#include "grit/shared_resources_map.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

int PathToIDR(const std::string& path) {
  int idr = -1;
  if (path == "app/resources/folder_closed.png") {
    idr = IDR_FOLDER_CLOSED;
  } else if (path == "app/resources/folder_closed_rtl.png") {
    idr = IDR_FOLDER_CLOSED_RTL;
  } else if (path == "app/resources/folder_open.png") {
    idr = IDR_FOLDER_OPEN;
  } else if (path == "app/resources/folder_open_rtl.png") {
    idr = IDR_FOLDER_OPEN_RTL;
  } else if (path == "app/resources/throbber.png") {
    idr = IDR_THROBBER;
  } else {
    // The name of the files in the grd list are prefixed with the following
    // directory:
    std::string key("shared/");
    key += path;

    for (size_t i = 0; i < kSharedResourcesSize; ++i) {
      if (kSharedResources[i].name == key) {
        idr = kSharedResources[i].value;
        break;
      }
    }
  }

  return idr;
}

}  // namespace

SharedResourcesDataSource::SharedResourcesDataSource()
    : DataSource(chrome::kChromeUIResourcesHost, NULL) {
}

SharedResourcesDataSource::~SharedResourcesDataSource() {
}

void SharedResourcesDataSource::StartDataRequest(const std::string& path,
                                                 bool is_incognito,
                                                 int request_id) {
  int idr = PathToIDR(path);
  DCHECK_NE(-1, idr) << " path: " << path;
  const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  scoped_refptr<RefCountedStaticMemory> bytes(rb.LoadDataResourceBytes(idr));
  SendResponse(request_id, bytes);
}

std::string SharedResourcesDataSource::GetMimeType(
    const std::string& path) const {
  // Requests should not block on the disk!  On Windows this goes to the
  // registry.
  //   http://code.google.com/p/chromium/issues/detail?id=59849
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  std::string mime_type;
  net::GetMimeTypeFromFile(FilePath().AppendASCII(path), &mime_type);
  return mime_type;
}
<|endoftext|>