<commit_before>/**
 * @file   FunctionApproximatorGPR.cpp
 * @brief  FunctionApproximatorGPR class source file.
 * @author Freek Stulp
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo 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 DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/serialization/export.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include "functionapproximators/FunctionApproximatorGPR.hpp"

/** For boost::serialization. See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/special.html#export */
BOOST_CLASS_EXPORT_IMPLEMENT(DmpBbo::FunctionApproximatorGPR);

#include "functionapproximators/ModelParametersGPR.hpp"
#include "functionapproximators/MetaParametersGPR.hpp"
#include "functionapproximators/BasisFunction.hpp"

#include "dmpbbo_io/EigenBoostSerialization.hpp"

#include <iostream>
#include <eigen3/Eigen/SVD>
#include <eigen3/Eigen/LU>

using namespace std;
using namespace Eigen;

namespace DmpBbo {

FunctionApproximatorGPR::FunctionApproximatorGPR(const MetaParametersGPR *const meta_parameters, const ModelParametersGPR *const model_parameters)
:
  FunctionApproximator(meta_parameters,model_parameters)
{
  cerr << __FILE__ << ":" << __LINE__ << ":";
  cerr << "FunctionApproximatorGPR is still under development! No guarantees on functionality..." << endl;}

FunctionApproximatorGPR::FunctionApproximatorGPR(const ModelParametersGPR *const model_parameters)
:
  FunctionApproximator(model_parameters)
{
  cerr << __FILE__ << ":" << __LINE__ << ":";
  cerr << "FunctionApproximatorGPR is still under development! No guarantees on functionality..." << endl;
}

FunctionApproximator* FunctionApproximatorGPR::clone(void) const {
  // All error checking and cloning is left to the FunctionApproximator constructor.
  return new FunctionApproximatorGPR(
    dynamic_cast<const MetaParametersGPR*>(getMetaParameters()),
    dynamic_cast<const ModelParametersGPR*>(getModelParameters())
    );
};

void FunctionApproximatorGPR::train(const MatrixXd& inputs, const MatrixXd& targets)
{
  if (isTrained())
  {
    cerr << "WARNING: You may not call FunctionApproximatorGPR::train more than once. Doing nothing." << endl;
    cerr << "   (if you really want to retrain, call reTrain function instead)" << endl;
    return;
  }

  assert(inputs.rows() == targets.rows());
  assert(inputs.cols()==getExpectedInputDim());

  const MetaParametersGPR* meta_parameters_gpr =
    dynamic_cast<const MetaParametersGPR*>(getMetaParameters());

  double max_covar = meta_parameters_gpr->maximum_covariance();
  double length = meta_parameters_gpr->length();

  // Compute the gram matrix
  // In a gram matrix, every input point is itself a center
  MatrixXd centers = inputs;
  MatrixXd widths  = MatrixXd::Constant(centers.rows(),centers.cols(),length);

  MatrixXd gram(inputs.rows(),inputs.rows());
  bool normalize_activations = false;
  bool asymmetric_kernels = false;
  BasisFunction::Gaussian::activations(centers,widths,inputs,gram,normalize_activations,asymmetric_kernels);

  gram *= max_covar;

  setModelParameters(new ModelParametersGPR(inputs,targets,gram,max_covar,length));

}

void FunctionApproximatorGPR::predict(const MatrixXd& inputs, MatrixXd& outputs)
{
  if (!isTrained())
  {
    cerr << "WARNING: You may not call FunctionApproximatorLWPR::predict if you have not trained yet. Doing nothing." << endl;
    return;
  }

  const ModelParametersGPR* model_parameters_gpr = static_cast<const ModelParametersGPR*>(getModelParameters());

  assert(inputs.cols()==getExpectedInputDim());
  unsigned int n_samples = inputs.rows();

  outputs.resize(n_samples,1);

  MatrixXd ks;
  model_parameters_gpr->kernelActivations(inputs, ks);

  VectorXd weights = model_parameters_gpr->weights();
  for (unsigned int ii=0; ii<n_samples; ii++)
    outputs(ii) = ks.row(ii).dot(weights);

}

void FunctionApproximatorGPR::predictVariance(const MatrixXd& inputs, MatrixXd& variances)
{
  if (!isTrained())
  {
    cerr << "WARNING: You may not call FunctionApproximatorLWPR::predict if you have not trained yet. Doing nothing." << endl;
    return;
  }

  const ModelParametersGPR* model_parameters_gpr = static_cast<const ModelParametersGPR*>(getModelParameters());

  assert(inputs.cols()==getExpectedInputDim());

  unsigned int n_samples = inputs.rows();
  variances.resize(n_samples,1);

  MatrixXd ks;
  model_parameters_gpr->kernelActivations(inputs, ks);

  double maximum_covariance = model_parameters_gpr->maximum_covariance();
  MatrixXd gram_inv = model_parameters_gpr->gram_inv();

  VectorXd rest;
  for (unsigned int ii=0; ii<n_samples; ii++)
  {
    rest = ks.row(ii)*gram_inv*ks.row(ii).transpose();
    assert(rest.rows()==1);
    assert(rest.cols()==1);
    variances(ii) = maximum_covariance - rest(0);
  }

}

template<class Archive>
void FunctionApproximatorGPR::serialize(Archive & ar, const unsigned int version)
{
  // serialize base class information
  ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(FunctionApproximator);
}

}
<commit_msg>GPR stable now<commit_after>/**
 * @file   FunctionApproximatorGPR.cpp
 * @brief  FunctionApproximatorGPR class source file.
 * @author Freek Stulp
 *
 * This file is part of DmpBbo, a set of libraries and programs for the
 * black-box optimization of dynamical movement primitives.
 * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
 *
 * DmpBbo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * DmpBbo 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 DmpBbo.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/serialization/export.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include "functionapproximators/FunctionApproximatorGPR.hpp"

/** For boost::serialization. See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/special.html#export */
BOOST_CLASS_EXPORT_IMPLEMENT(DmpBbo::FunctionApproximatorGPR);

#include "functionapproximators/ModelParametersGPR.hpp"
#include "functionapproximators/MetaParametersGPR.hpp"
#include "functionapproximators/BasisFunction.hpp"

#include "dmpbbo_io/EigenBoostSerialization.hpp"

#include <iostream>
#include <eigen3/Eigen/SVD>
#include <eigen3/Eigen/LU>

using namespace std;
using namespace Eigen;

namespace DmpBbo {

FunctionApproximatorGPR::FunctionApproximatorGPR(const MetaParametersGPR *const meta_parameters, const ModelParametersGPR *const model_parameters)
:
  FunctionApproximator(meta_parameters,model_parameters)
{
}

FunctionApproximatorGPR::FunctionApproximatorGPR(const ModelParametersGPR *const model_parameters)
:
  FunctionApproximator(model_parameters)
{
}

FunctionApproximator* FunctionApproximatorGPR::clone(void) const {
  // All error checking and cloning is left to the FunctionApproximator constructor.
  return new FunctionApproximatorGPR(
    dynamic_cast<const MetaParametersGPR*>(getMetaParameters()),
    dynamic_cast<const ModelParametersGPR*>(getModelParameters())
    );
};

void FunctionApproximatorGPR::train(const MatrixXd& inputs, const MatrixXd& targets)
{
  if (isTrained())
  {
    cerr << "WARNING: You may not call FunctionApproximatorGPR::train more than once. Doing nothing." << endl;
    cerr << "   (if you really want to retrain, call reTrain function instead)" << endl;
    return;
  }

  assert(inputs.rows() == targets.rows());
  assert(inputs.cols()==getExpectedInputDim());

  const MetaParametersGPR* meta_parameters_gpr =
    dynamic_cast<const MetaParametersGPR*>(getMetaParameters());

  double max_covar = meta_parameters_gpr->maximum_covariance();
  double length = meta_parameters_gpr->length();

  // Compute the gram matrix
  // In a gram matrix, every input point is itself a center
  MatrixXd centers = inputs;
  MatrixXd widths  = MatrixXd::Constant(centers.rows(),centers.cols(),length);

  MatrixXd gram(inputs.rows(),inputs.rows());
  bool normalize_activations = false;
  bool asymmetric_kernels = false;
  BasisFunction::Gaussian::activations(centers,widths,inputs,gram,normalize_activations,asymmetric_kernels);

  gram *= max_covar;

  setModelParameters(new ModelParametersGPR(inputs,targets,gram,max_covar,length));

}

void FunctionApproximatorGPR::predict(const MatrixXd& inputs, MatrixXd& outputs)
{
  if (!isTrained())
  {
    cerr << "WARNING: You may not call FunctionApproximatorLWPR::predict if you have not trained yet. Doing nothing." << endl;
    return;
  }

  const ModelParametersGPR* model_parameters_gpr = static_cast<const ModelParametersGPR*>(getModelParameters());

  assert(inputs.cols()==getExpectedInputDim());
  unsigned int n_samples = inputs.rows();

  outputs.resize(n_samples,1);

  MatrixXd ks;
  model_parameters_gpr->kernelActivations(inputs, ks);

  VectorXd weights = model_parameters_gpr->weights();
  for (unsigned int ii=0; ii<n_samples; ii++)
    outputs(ii) = ks.row(ii).dot(weights);

}

void FunctionApproximatorGPR::predictVariance(const MatrixXd& inputs, MatrixXd& variances)
{
  if (!isTrained())
  {
    cerr << "WARNING: You may not call FunctionApproximatorLWPR::predict if you have not trained yet. Doing nothing." << endl;
    return;
  }

  const ModelParametersGPR* model_parameters_gpr = static_cast<const ModelParametersGPR*>(getModelParameters());

  assert(inputs.cols()==getExpectedInputDim());

  unsigned int n_samples = inputs.rows();
  variances.resize(n_samples,1);

  MatrixXd ks;
  model_parameters_gpr->kernelActivations(inputs, ks);

  double maximum_covariance = model_parameters_gpr->maximum_covariance();
  MatrixXd gram_inv = model_parameters_gpr->gram_inv();

  VectorXd rest;
  for (unsigned int ii=0; ii<n_samples; ii++)
  {
    rest = ks.row(ii)*gram_inv*ks.row(ii).transpose();
    assert(rest.rows()==1);
    assert(rest.cols()==1);
    variances(ii) = maximum_covariance - rest(0);
  }

}

template<class Archive>
void FunctionApproximatorGPR::serialize(Archive & ar, const unsigned int version)
{
  // serialize base class information
  ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(FunctionApproximator);
}

}
<|endoftext|>


<commit_before>// =============================================================================
// File Name: GraphHost.hpp
// Description: The host for the LiveGrapher real-time graphing application
// Author: FRC Team 3512, Spartatroniks
// =============================================================================

#ifndef GRAPHHOST_HPP
#define GRAPHHOST_HPP

/* Usage:
 *
 * The GraphHost interface is started upon object initialization.
 *
 * Call graphData() to send data over the network to a LiveGrapher client.
 *
 * The time value in each data pair is handled internally.
 *
 * Use the function hasIntervalPassed() to limit the frequency of data sending
 * in looping situations.
 *
 * Example:
 *     GraphHost pidGraph( 3513 );
 *
 *     if ( pidGraph.hasIntervalPassed() ) {
 *         pidGraph.graphData( frisbeeShooter.getRPM() , "PID0" );
 *         pidGraph.graphData( frisbeeShooter.getTargetRPM() , "PID1" );
 *
 *         pidGraph.resetInterval();
 *     }
 */

#include <vector>
#include <string>
#include <thread>
#include <mutex>
#include <chrono>
#include <atomic>
#include <memory>
#include <cstdint>

using namespace std::chrono;
using namespace std::chrono_literals;

#include "SocketConnection.hpp"

struct[[gnu::packed]] graph_payload_t{
    char type; // Set to 'd' to identify this as a graph payload packet
    char dataset[15];
    uint64_t x;
    float y;
};

struct[[gnu::packed]] graph_list_t{
    char type;
    char dataset[15];
    char end;
    char pad[11];
};

class GraphHost {
public:
    explicit GraphHost(int port);
    ~GraphHost();

    /* * Send data (y value) for a given dataset to remote client
     * * The current time is sent as the x value
     * * Return values:
     *       -1 = host not running
     *       0 = data sent successfully
     */
    int graphData(float value, std::string dataset);

    /* Sets time interval after which data is sent to graph (milliseconds per
     * sample)
     */
    template <typename Rep, typename Period>
    void setSendInterval(const std::chrono::duration<Rep, Period>& time);

    /* Returns true if the time between the last data transmission is greater
     * than the sending interval time
     */
    bool hasIntervalPassed();

    /* Resets time interval passed since last data transmission (makes
     * hasIntervalPassed() return false)
     */
    void resetInterval();

private:
    // Last time data was graphed
    uint64_t m_lastTime{0};

    // Time interval after which data is sent to graph (in milliseconds per sample)
    uint32_t m_sendInterval{5};

    // Used as a temp variables in graphData(2)
    uint64_t m_currentTime;

    // Mark the thread as not running, this will be set to 1 by the thread
    std::atomic<bool> m_running{false};
    std::unique_ptr<std::thread> m_thread;
    std::mutex m_mutex;
    int m_ipcfd_r;
    int m_ipcfd_w;
    int m_port;
    std::vector<std::string> m_graphList;
    std::vector<std::unique_ptr<SocketConnection>> m_connList;

    void socket_threadmain();

    static int socket_listen(int port, uint32_t s_addr);
    static int socket_accept(int listenfd);
    int addGraph(const std::string& dataset);
};

#include "GraphHost.inl"

#endif // GRAPHHOST_HPP

<commit_msg>LiveGrapherHost: updated documentation in comments<commit_after>// =============================================================================
// File Name: GraphHost.hpp
// Description: The host for the LiveGrapher real-time graphing application
// Author: FRC Team 3512, Spartatroniks
// =============================================================================

#ifndef GRAPHHOST_HPP
#define GRAPHHOST_HPP

/* Usage:
 *
 * The GraphHost interface is started upon object initialization.
 *
 * Call graphData() to send data over the network to a LiveGrapher client.
 *
 * The time value in each data pair is handled internally.
 *
 * Use the function hasIntervalPassed() to limit the frequency of data sending
 * in looping situations.
 *
 * Example:
 *     GraphHost pidGraph(3513);
 *     pidGraph.setSendInterval(5ms);
 *
 *     if (pidGraph.hasIntervalPassed()) {
 *         pidGraph.graphData(frisbeeShooter.getRPM(), "PID0");
 *         pidGraph.graphData(frisbeeShooter.getTargetRPM(), "PID1");
 *
 *         pidGraph.resetInterval();
 *     }
 */

#include <vector>
#include <string>
#include <thread>
#include <mutex>
#include <chrono>
#include <atomic>
#include <memory>
#include <cstdint>

using namespace std::chrono;
using namespace std::chrono_literals;

#include "SocketConnection.hpp"

struct[[gnu::packed]] graph_payload_t{
    char type; // Set to 'd' to identify this as a graph payload packet
    char dataset[15];
    uint64_t x;
    float y;
};

struct[[gnu::packed]] graph_list_t{
    char type;
    char dataset[15];
    char end;
    char pad[11];
};

class GraphHost {
public:
    explicit GraphHost(int port);
    ~GraphHost();

    /* * Send data (y value) for a given dataset to remote client
     * * The current time is sent as the x value
     * * Return values:
     *       -1 = host not running
     *       0 = data sent successfully
     */
    int graphData(float value, std::string dataset);

    /* Sets time interval after which data is sent to graph (milliseconds per
     * sample)
     */
    template <typename Rep, typename Period>
    void setSendInterval(const std::chrono::duration<Rep, Period>& time);

    /* Returns true if the time between the last data transmission is greater
     * than the sending interval time
     */
    bool hasIntervalPassed();

    /* Resets time interval passed since last data transmission (makes
     * hasIntervalPassed() return false)
     */
    void resetInterval();

private:
    // Last time data was graphed
    uint64_t m_lastTime{0};

    // Time interval after which data is sent to graph (in milliseconds per sample)
    uint32_t m_sendInterval{5};

    // Used as a temp variables in graphData(2)
    uint64_t m_currentTime;

    // Mark the thread as not running, this will be set to true by the thread
    std::atomic<bool> m_running{false};
    std::unique_ptr<std::thread> m_thread;
    std::mutex m_mutex;
    int m_ipcfd_r;
    int m_ipcfd_w;
    int m_port;
    std::vector<std::string> m_graphList;
    std::vector<std::unique_ptr<SocketConnection>> m_connList;

    void socket_threadmain();

    static int socket_listen(int port, uint32_t s_addr);
    static int socket_accept(int listenfd);
    int addGraph(const std::string& dataset);
};

#include "GraphHost.inl"

#endif // GRAPHHOST_HPP

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

std::string correctUppers(const std::string& str) {
    // a single-character delimiters between sentences
    static const char delimiters[] = {'.', '?', '!'};
    int size = str.size();
    std::string result;
    bool new_sentence = false;
    result.push_back(toupper(str[0]));
    for (size_t pos = 1; pos < size; pos++) {
        for (int i = 0; i < 3; i++) {
            if (str[pos] == delimiters[i]) {
                new_sentence = true;
            }
        }
        if (islower(str[pos]) && new_sentence) {
            result.push_back(toupper(str[pos]));
            new_sentence = false;
        } else {
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string deleteBoundarySpaces(const std::string& str) {
    int size = str.size();
    std::string result;
    int begin = 0;
    while (isspace(str[begin])) {
        begin++;
    }
    int end = size - 1;
    while (isspace(str[end])) {
        end--;
    }
    for (size_t i = begin; i <= end; i++) {
        result.push_back(str[i]);
    }
    return result;
}

std::string deleteExtraSpaces(const std::string& str) {
    size_t size = str.size();
    std::string result;
    int spaces = 0;
    for (size_t pos = 0; pos < size; pos++) {
        if (isspace(str[pos])) {
            spaces++;
            if (spaces == 1) {
                result.push_back(str[pos]);
            }
        } else {
            spaces = 0;
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string correct(const std::string& str) {
    std::string value = deleteBoundarySpaces(str);
    return deleteExtraSpaces(value);
}

int main() {
    std::string str;
    std::getline(std::cin, str);
    std::cout << correct(str) << std::endl;
    return 0;
}
<commit_msg>Normalizer: expand clearBoundarySpaces()<commit_after>/*
 * Copyright (C) 2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

std::string correctUppers(const std::string& str) {
    // a single-character delimiters between sentences
    static const char delimiters[] = {'.', '?', '!'};
    int size = str.size();
    std::string result;
    bool new_sentence = false;
    result.push_back(toupper(str[0]));
    for (size_t pos = 1; pos < size; pos++) {
        for (int i = 0; i < 3; i++) {
            if (str[pos] == delimiters[i]) {
                new_sentence = true;
            }
        }
        if (islower(str[pos]) && new_sentence) {
            result.push_back(toupper(str[pos]));
            new_sentence = false;
        } else {
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string clearBorders(const std::string& str) {
    int size = str.size();
    std::string result;
    int begin = 0;
    while (!isalnum(str[begin])) {
        begin++;
    }
    int end = size - 1;
    while (isspace(str[end])) {
        end--;
    }
    for (size_t i = begin; i <= end; i++) {
        result.push_back(str[i]);
    }
    return result;
}

std::string deleteExtraSpaces(const std::string& str) {
    size_t size = str.size();
    std::string result;
    int spaces = 0;
    for (size_t pos = 0; pos < size; pos++) {
        if (isspace(str[pos])) {
            spaces++;
            if (spaces == 1) {
                result.push_back(str[pos]);
            }
        } else {
            spaces = 0;
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string correct(const std::string& str) {
    std::string value = clearBorders(str);
    return deleteExtraSpaces(value);
}

int main() {
    std::string str;
    std::getline(std::cin, str);
    std::cout << correct(str) << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#ifndef _TEST_FILESYSMTE_HPP_
#define _TEST_FILESYSMTE_HPP_

#include <map>

#include "nnet.hpp"

typedef std::map<double, nnetmodel> Level2Map;

void buildNnetMap(std::map<double, Level2Map> &nnetMap);

const nnetmodel &recallNnetMap(const std::map<double, Level2Map> &nnetMap, double bankCharge, double solarPower);

#endif
<commit_msg>updates selModel/testFilesystem.hpp<commit_after>#ifndef _TEST_FILESYSMTE_HPP_
#define _TEST_FILESYSMTE_HPP_

#include <map>

#include "../nnet/nnet.hpp"

typedef std::map<double, nnetmodel> Level2Map;

void buildNnetMap(std::map<double, Level2Map> &nnetMap);

const nnetmodel &recallNnetMap(const std::map<double, Level2Map> &nnetMap, double bankCharge, double solarPower);

#endif
<|endoftext|>


<commit_before>/*
 * This file is part of accounts-ui
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "service-selection-page.h"
#include "account-sync-handler.h"
#include "provider-plugin-process.h"
#include "service-settings-widget.h"
#include "accountsmanagersingleton.h"
#include "account-setup-finished-page.h"
#include "provider-plugin-process.h"
#include "basic-header-widget.h"
#include "last-page-actions.h"

//Qt
#include <QStringListModel>
#include <QItemSelection>
#include <QDebug>

//Meegotouch
#include <MLayout>
#include <MList>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MWidgetCreator>
#include <MContainer>
#include <MSeparator>
#include <MBasicListItem>
#include <MWidgetAction>
#include <MImageWidget>
#include <MLabel>
#include <MLocale>
#include <MPannableViewport>
#include <MPositionIndicator>

//libAccounts
#include <Accounts/Provider>
#include <Accounts/Manager>

namespace AccountsUI {

M_REGISTER_WIDGET_NO_CREATE(ServiceSelectionPage)

//TODO: write the service plugins
class ServiceSelectionPagePrivate
{
public:
    ServiceSelectionPagePrivate()
        : serviceList(0),
        saveAction(0),
        cancelAction(0),
        context(0),
        syncHandler(0),
        layoutServicePolicy(0)
        {}
    ~ServiceSelectionPagePrivate() {}

    MList *serviceList;
    MAction *saveAction;
    MAction *cancelAction;
    AbstractAccountSetupContext *context;
    QList<AbstractServiceSetupContext*> serviceContextList;
    QList<AbstractSetupContext*> abstractContexts;
    AccountSyncHandler *syncHandler;
    MLinearLayoutPolicy *layoutServicePolicy;
    QString serviceType;
    QMap<QString, bool> serviceStatusMap;
};

ServiceSelectionPage::ServiceSelectionPage(AbstractAccountSetupContext *context,
                                           QList<AbstractServiceSetupContext*>
                                           &serviceContextList,
                                           QGraphicsItem *parent)
        : MApplicationPage(parent),
        d_ptr(new ServiceSelectionPagePrivate())
{
    Q_D(ServiceSelectionPage);
    setStyleName("AccountsUiPage");
    d->context = context;
    d->serviceType = context->serviceType();
    d->context->account()->selectService(NULL);
    d->context->account()->setEnabled(true);
    d->serviceContextList = serviceContextList;
    d->abstractContexts.append(d->context);

    d->syncHandler = new AccountSyncHandler(this);
    connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
            this, SLOT(onSyncStateChanged(const SyncState&)));
    pannableViewport()->positionIndicator()->setStyleName("CommonPositionIndicatorInverted");
}

void ServiceSelectionPage::serviceSelected(QModelIndex index)
{
    Q_UNUSED(index);
}

ServiceSelectionPage::~ServiceSelectionPage()
{
    delete d_ptr;
}

void ServiceSelectionPage::createContent()
{
    Q_D(ServiceSelectionPage);

    setComponentsDisplayMode(EscapeButton, MApplicationPageModel::Hide);

    //we need a central widget to get the right layout size under the menubar
    MWidget *centralWidget = new MWidget();
    setCentralWidget(centralWidget);
    MLayout *layout = new MLayout(centralWidget);
    MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
    layoutPolicy->setSpacing(0);

    if (d->context) {
        MWidget *upperWidget = new MWidget(this);
        MLayout *upperLayout = new MLayout(upperWidget);
        MLinearLayoutPolicy *upperLayoutPolicy = new MLinearLayoutPolicy(upperLayout, Qt::Vertical);
        upperLayoutPolicy->setSpacing(0);

        MLayout *topLayout = new MLayout();
        MLinearLayoutPolicy *topLayoutPolicy = new MLinearLayoutPolicy(topLayout, Qt::Vertical);
        topLayoutPolicy->setSpacing(0);

        QString providerName(d->context->account()->providerName());
        // xml file that describes the ui elements for the provider
        Accounts::Provider *provider = AccountsManager::instance()->provider(providerName);
        if (provider) {
            // loading common catalog to show device name string
            MLocale locale;
            QString catalog = "common";
            if (!catalog.isEmpty() && !locale.isInstalledTrCatalog(catalog)) {
                locale.installTrCatalog(catalog);
                MLocale::setDefault(locale);
            }

            // provider info header
            QDomElement root = provider->domDocument().documentElement();
            QDomElement providerIcon = root.firstChildElement("icon");
            QString providerIconId = providerIcon.text();

            BasicHeaderWidget *providerInfoItem = new BasicHeaderWidget(IconWithTitleAndSubTitle, this);
            providerInfoItem->setImage(providerIconId);
            providerInfoItem->setTitle(qtTrId(provider->displayName().toLatin1()));
            providerInfoItem->setSubtitle(qtTrId(d->context->account()->displayName().toLatin1()));
            providerInfoItem->setObjectName("wgServiceSelectionPageBasicListItem");
            topLayoutPolicy->addItem(providerInfoItem, Qt::AlignLeft | Qt::AlignVCenter);

            // account connected message
            QString accountConnectedMessageId;
            QDomElement accountConnectedMessage= root.firstChildElement("account-connected-message");
            if (!accountConnectedMessage.isNull()) {
                // display a account connected message for provider
                accountConnectedMessageId =
                        qtTrId((accountConnectedMessage.text()).toLatin1()).arg(qtTrId("qtn_comm_product_n9"));
            }
            else {
                // default message for service selection.
                accountConnectedMessageId = qtTrId("qtn_acc_enable_services_in_apps");
            }
            MLabel *accountConnectedMessageLabel=
                    new MLabel(accountConnectedMessageId);
            accountConnectedMessageLabel->setWordWrap(1);
            accountConnectedMessageLabel->setStyleName("CommonBodyTextInverted");
            topLayoutPolicy->addItem(accountConnectedMessageLabel, Qt::AlignLeft | Qt::AlignVCenter);
        }

        MSeparator *separatorTop = new MSeparator(this);
        separatorTop->setStyleName("CommonItemDividerInverted");
        separatorTop->setOrientation(Qt::Horizontal);

        upperLayoutPolicy->addItem(topLayout);
        upperLayoutPolicy->addItem(separatorTop);

        layoutPolicy->addItem(upperWidget);
    }

    MWidget *serviceWidget = new MWidget();
    MLayout *serviceSettingLayout = new MLayout(serviceWidget);
    d->layoutServicePolicy = new MLinearLayoutPolicy(serviceSettingLayout, Qt::Vertical);
    d->layoutServicePolicy->setSpacing(0);

    for (int i = 0; i < d->serviceContextList.count(); i++) {
        //ServiceSettingsWidget sets the display widget of the changing settings
        ServiceSettingsWidget *settingsWidget =
            new ServiceSettingsWidget(d->serviceContextList.at(i), serviceWidget,
                                      ServiceSettingsWidget::MandatorySettings |
                                      ServiceSettingsWidget::EnableButton,
                                      true);
        const Accounts::Service *service = d->serviceContextList.at(i)->service();
        emit serviceEnabled(service->name(), true);
        d->serviceStatusMap.insert(service->name(), true);
        d->abstractContexts.append(d->serviceContextList.at(i));
        d->layoutServicePolicy->addItem(settingsWidget, Qt::AlignLeft);
        connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),
                 this, SIGNAL(serviceEnabled(const QString&, bool)));
        connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),
                 this, SLOT(setEnabledService(const QString&, bool)));
    }

    layoutPolicy->addItem(serviceWidget, Qt::AlignLeft);

    //% "DONE"
    d->saveAction = new MAction(qtTrId("qtn_comm_command_done"), centralWidget);
    d->saveAction->setLocation(MAction::ToolBarLocation);
    addAction(d->saveAction);

    //% "CANCEL"
    d->cancelAction = new MAction(qtTrId("qtn_comm_cancel"), centralWidget);
    d->cancelAction->setLocation(MAction::ToolBarLocation);
    addAction(d->cancelAction);
    layoutPolicy->addStretch();

    connect(d->saveAction, SIGNAL(triggered()),
            this, SLOT(onAccountInstallButton()));
    connect(d->cancelAction, SIGNAL(triggered()),
            this, SLOT(cancel()));
    connect(d->serviceList, SIGNAL(itemClicked(QModelIndex)),
            this,SLOT(serviceSelected(QModelIndex)));

    connect(this, SIGNAL(backButtonClicked()),
            this, SLOT(close()));
}

void ServiceSelectionPage::onAccountInstallButton()
{
    Q_D(ServiceSelectionPage);

    disconnect(d->saveAction, SIGNAL(triggered()),
               this, SLOT(onAccountInstallButton()));

    setProgressIndicatorVisible(true);
    for (int i = 0; i < d->serviceContextList.count(); i++) {
        const Accounts::Service *service = d->serviceContextList.at(i)->service();
        QMap<QString, bool>::iterator mapIterator =
                d->serviceStatusMap.find(service->name());
        if (mapIterator == d->serviceStatusMap.end())
            continue;
        d->serviceContextList.at(i)->enable(mapIterator.value());
        d->serviceStatusMap.remove(mapIterator.key());
    }
    d->syncHandler->validate(d->abstractContexts);
}

void ServiceSelectionPage::onSyncStateChanged(const SyncState &state)
{
    Q_D(ServiceSelectionPage);

    switch (state) {
        case Validated:
            d->syncHandler->store(d->abstractContexts);
            break;
        case Stored:
            if (ProviderPluginProcess::instance()->lastPageActions().
                serviceActions().isEmpty()) {
                connect(d->context->account(), SIGNAL(synced()),
                        ProviderPluginProcess::instance(), SLOT(quit()));
                d->context->account()->sync();
            } else {
                d->context->account()->sync();
                AccountSetupFinishedPage *page = new AccountSetupFinishedPage(d->context);
                page->appear();
            }
            break;
        default:
            connect(d->saveAction, SIGNAL(triggered()),
                    this, SLOT(onAccountInstallButton()));
            connect(d->cancelAction, SIGNAL(triggered()),
                    this, SLOT(cancel()));
            setProgressIndicatorVisible(false);
            return;
    }
}

void ServiceSelectionPage::setWidget(MWidget *widget)
{
    Q_D(ServiceSelectionPage);

    if (d->layoutServicePolicy && widget)
        d->layoutServicePolicy->addItem(widget);
}

void ServiceSelectionPage::setEnabledService(const QString &serviceName,
                                            bool enabled)
{
    Q_D(ServiceSelectionPage);
    d->serviceStatusMap[serviceName] = enabled;
}

void ServiceSelectionPage::cancel()
{
    ProviderPluginProcess::instance()->setReturnToAccountsList(true);
}

} //namespace
<commit_msg>Fixing: 261426 - Facebook chat option to be turned off by default<commit_after>/*
 * This file is part of accounts-ui
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "service-selection-page.h"
#include "account-sync-handler.h"
#include "provider-plugin-process.h"
#include "service-settings-widget.h"
#include "accountsmanagersingleton.h"
#include "account-setup-finished-page.h"
#include "provider-plugin-process.h"
#include "basic-header-widget.h"
#include "last-page-actions.h"

//Qt
#include <QStringListModel>
#include <QItemSelection>
#include <QDebug>

//Meegotouch
#include <MLayout>
#include <MList>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MWidgetCreator>
#include <MContainer>
#include <MSeparator>
#include <MBasicListItem>
#include <MWidgetAction>
#include <MImageWidget>
#include <MLabel>
#include <MLocale>
#include <MPannableViewport>
#include <MPositionIndicator>

//libAccounts
#include <Accounts/Provider>
#include <Accounts/Manager>

namespace AccountsUI {

M_REGISTER_WIDGET_NO_CREATE(ServiceSelectionPage)

//TODO: write the service plugins
class ServiceSelectionPagePrivate
{
public:
    ServiceSelectionPagePrivate()
        : serviceList(0),
        saveAction(0),
        cancelAction(0),
        context(0),
        syncHandler(0),
        layoutServicePolicy(0)
        {}
    ~ServiceSelectionPagePrivate() {}

    MList *serviceList;
    MAction *saveAction;
    MAction *cancelAction;
    AbstractAccountSetupContext *context;
    QList<AbstractServiceSetupContext*> serviceContextList;
    QList<AbstractSetupContext*> abstractContexts;
    AccountSyncHandler *syncHandler;
    MLinearLayoutPolicy *layoutServicePolicy;
    QString serviceType;
    QMap<QString, bool> serviceStatusMap;
};

ServiceSelectionPage::ServiceSelectionPage(AbstractAccountSetupContext *context,
                                           QList<AbstractServiceSetupContext*>
                                           &serviceContextList,
                                           QGraphicsItem *parent)
        : MApplicationPage(parent),
        d_ptr(new ServiceSelectionPagePrivate())
{
    Q_D(ServiceSelectionPage);
    setStyleName("AccountsUiPage");
    d->context = context;
    d->serviceType = context->serviceType();
    d->context->account()->selectService(NULL);
    d->context->account()->setEnabled(true);
    d->serviceContextList = serviceContextList;
    d->abstractContexts.append(d->context);

    d->syncHandler = new AccountSyncHandler(this);
    connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
            this, SLOT(onSyncStateChanged(const SyncState&)));
    pannableViewport()->positionIndicator()->setStyleName("CommonPositionIndicatorInverted");
}

void ServiceSelectionPage::serviceSelected(QModelIndex index)
{
    Q_UNUSED(index);
}

ServiceSelectionPage::~ServiceSelectionPage()
{
    delete d_ptr;
}

void ServiceSelectionPage::createContent()
{
    Q_D(ServiceSelectionPage);

    setComponentsDisplayMode(EscapeButton, MApplicationPageModel::Hide);

    //we need a central widget to get the right layout size under the menubar
    MWidget *centralWidget = new MWidget();
    setCentralWidget(centralWidget);
    MLayout *layout = new MLayout(centralWidget);
    MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);
    layoutPolicy->setSpacing(0);

    if (d->context) {
        MWidget *upperWidget = new MWidget(this);
        MLayout *upperLayout = new MLayout(upperWidget);
        MLinearLayoutPolicy *upperLayoutPolicy = new MLinearLayoutPolicy(upperLayout, Qt::Vertical);
        upperLayoutPolicy->setSpacing(0);

        MLayout *topLayout = new MLayout();
        MLinearLayoutPolicy *topLayoutPolicy = new MLinearLayoutPolicy(topLayout, Qt::Vertical);
        topLayoutPolicy->setSpacing(0);

        QString providerName(d->context->account()->providerName());
        // xml file that describes the ui elements for the provider
        Accounts::Provider *provider = AccountsManager::instance()->provider(providerName);
        if (provider) {
            // loading common catalog to show device name string
            MLocale locale;
            QString catalog = "common";
            if (!catalog.isEmpty() && !locale.isInstalledTrCatalog(catalog)) {
                locale.installTrCatalog(catalog);
                MLocale::setDefault(locale);
            }

            // provider info header
            QDomElement root = provider->domDocument().documentElement();
            QDomElement providerIcon = root.firstChildElement("icon");
            QString providerIconId = providerIcon.text();

            BasicHeaderWidget *providerInfoItem = new BasicHeaderWidget(IconWithTitleAndSubTitle, this);
            providerInfoItem->setImage(providerIconId);
            providerInfoItem->setTitle(qtTrId(provider->displayName().toLatin1()));
            providerInfoItem->setSubtitle(qtTrId(d->context->account()->displayName().toLatin1()));
            providerInfoItem->setObjectName("wgServiceSelectionPageBasicListItem");
            topLayoutPolicy->addItem(providerInfoItem, Qt::AlignLeft | Qt::AlignVCenter);

            // account connected message
            QString accountConnectedMessageId;
            QDomElement accountConnectedMessage= root.firstChildElement("account-connected-message");
            if (!accountConnectedMessage.isNull()) {
                // display a account connected message for provider
                accountConnectedMessageId =
                        qtTrId((accountConnectedMessage.text()).toLatin1()).arg(qtTrId("qtn_comm_product_n9"));
            }
            else {
                // default message for service selection.
                accountConnectedMessageId = qtTrId("qtn_acc_enable_services_in_apps");
            }
            MLabel *accountConnectedMessageLabel=
                    new MLabel(accountConnectedMessageId);
            accountConnectedMessageLabel->setWordWrap(1);
            accountConnectedMessageLabel->setStyleName("CommonBodyTextInverted");
            topLayoutPolicy->addItem(accountConnectedMessageLabel, Qt::AlignLeft | Qt::AlignVCenter);
        }

        MSeparator *separatorTop = new MSeparator(this);
        separatorTop->setStyleName("CommonItemDividerInverted");
        separatorTop->setOrientation(Qt::Horizontal);

        upperLayoutPolicy->addItem(topLayout);
        upperLayoutPolicy->addItem(separatorTop);

        layoutPolicy->addItem(upperWidget);
    }

    MWidget *serviceWidget = new MWidget();
    MLayout *serviceSettingLayout = new MLayout(serviceWidget);
    d->layoutServicePolicy = new MLinearLayoutPolicy(serviceSettingLayout, Qt::Vertical);
    d->layoutServicePolicy->setSpacing(0);

    for (int i = 0; i < d->serviceContextList.count(); i++) {
        bool serviceStatus = true;
        const Accounts::Service *service = d->serviceContextList.at(i)->service();
        QDomElement root = service->domDocument().documentElement();
        QDomElement serviceDefaultStatus = root.firstChildElement("default-status");
        if (serviceDefaultStatus.text() == "false")
            serviceStatus = false;
        //ServiceSettingsWidget sets the display widget of the changing settings
        ServiceSettingsWidget *settingsWidget =
            new ServiceSettingsWidget(d->serviceContextList.at(i), serviceWidget,
                                      ServiceSettingsWidget::MandatorySettings |
                                      ServiceSettingsWidget::EnableButton,
                                      serviceStatus);

        emit serviceEnabled(service->name(), true);
        d->serviceStatusMap.insert(service->name(), true);
        d->abstractContexts.append(d->serviceContextList.at(i));
        d->layoutServicePolicy->addItem(settingsWidget, Qt::AlignLeft);
        connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),
                 this, SIGNAL(serviceEnabled(const QString&, bool)));
        connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),
                 this, SLOT(setEnabledService(const QString&, bool)));
    }

    layoutPolicy->addItem(serviceWidget, Qt::AlignLeft);

    //% "DONE"
    d->saveAction = new MAction(qtTrId("qtn_comm_command_done"), centralWidget);
    d->saveAction->setLocation(MAction::ToolBarLocation);
    addAction(d->saveAction);

    //% "CANCEL"
    d->cancelAction = new MAction(qtTrId("qtn_comm_cancel"), centralWidget);
    d->cancelAction->setLocation(MAction::ToolBarLocation);
    addAction(d->cancelAction);
    layoutPolicy->addStretch();

    connect(d->saveAction, SIGNAL(triggered()),
            this, SLOT(onAccountInstallButton()));
    connect(d->cancelAction, SIGNAL(triggered()),
            this, SLOT(cancel()));
    connect(d->serviceList, SIGNAL(itemClicked(QModelIndex)),
            this,SLOT(serviceSelected(QModelIndex)));

    connect(this, SIGNAL(backButtonClicked()),
            this, SLOT(close()));
}

void ServiceSelectionPage::onAccountInstallButton()
{
    Q_D(ServiceSelectionPage);

    disconnect(d->saveAction, SIGNAL(triggered()),
               this, SLOT(onAccountInstallButton()));

    setProgressIndicatorVisible(true);
    for (int i = 0; i < d->serviceContextList.count(); i++) {
        const Accounts::Service *service = d->serviceContextList.at(i)->service();
        QMap<QString, bool>::iterator mapIterator =
                d->serviceStatusMap.find(service->name());
        if (mapIterator == d->serviceStatusMap.end())
            continue;
        d->serviceContextList.at(i)->enable(mapIterator.value());
        d->serviceStatusMap.remove(mapIterator.key());
    }
    d->syncHandler->validate(d->abstractContexts);
}

void ServiceSelectionPage::onSyncStateChanged(const SyncState &state)
{
    Q_D(ServiceSelectionPage);

    switch (state) {
        case Validated:
            d->syncHandler->store(d->abstractContexts);
            break;
        case Stored:
            if (ProviderPluginProcess::instance()->lastPageActions().
                serviceActions().isEmpty()) {
                connect(d->context->account(), SIGNAL(synced()),
                        ProviderPluginProcess::instance(), SLOT(quit()));
                d->context->account()->sync();
            } else {
                d->context->account()->sync();
                AccountSetupFinishedPage *page = new AccountSetupFinishedPage(d->context);
                page->appear();
            }
            break;
        default:
            connect(d->saveAction, SIGNAL(triggered()),
                    this, SLOT(onAccountInstallButton()));
            connect(d->cancelAction, SIGNAL(triggered()),
                    this, SLOT(cancel()));
            setProgressIndicatorVisible(false);
            return;
    }
}

void ServiceSelectionPage::setWidget(MWidget *widget)
{
    Q_D(ServiceSelectionPage);

    if (d->layoutServicePolicy && widget)
        d->layoutServicePolicy->addItem(widget);
}

void ServiceSelectionPage::setEnabledService(const QString &serviceName,
                                            bool enabled)
{
    Q_D(ServiceSelectionPage);
    d->serviceStatusMap[serviceName] = enabled;
}

void ServiceSelectionPage::cancel()
{
    ProviderPluginProcess::instance()->setReturnToAccountsList(true);
}

} //namespace
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_
#define _CONNECTIVITY_OSUBCOMPONENT_HXX_

#include <com/sun/star/lang/DisposedException.hpp>
#include <cppuhelper/interfacecontainer.h>
#include <cppuhelper/propshlp.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <cppuhelper/weak.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>

namespace cppu {
    class IPropertyArrayHelper;
}

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace lang
            {
                class XComponent;
            }
        }
    }
}

namespace connectivity
{
    namespace mysqlc
    {
        void release(oslInterlockedCount& _refCount,
                     ::cppu::OBroadcastHelper& rBHelper,
                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xInterface,
                     ::com::sun::star::lang::XComponent* _pObject);

        void checkDisposed(sal_Bool _bThrow) throw (::com::sun::star::lang::DisposedException);

        template <class SELF, class WEAK> class OSubComponent
        {
        protected:
            // the parent must support the tunnel implementation
            ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xParent;
            SELF*   m_pDerivedImplementation;

        public:
            OSubComponent(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xParent,
                    SELF* _pDerivedImplementation)
                :m_xParent(_xParent)
                ,m_pDerivedImplementation(_pDerivedImplementation)
            {
            }

        protected:
            void dispose_ChildImpl()
            {
                ::osl::MutexGuard aGuard(m_pDerivedImplementation->rBHelper.rMutex);
                m_xParent = NULL;
            }
            void relase_ChildImpl()
            {
                release(m_pDerivedImplementation->m_refCount,
                                        m_pDerivedImplementation->rBHelper,
                                        m_xParent,
                                        m_pDerivedImplementation);

                m_pDerivedImplementation->WEAK::release();
            }
        };

        template <class TYPE>
        class OPropertyArrayUsageHelper
        {
        protected:
            static sal_Int32                        s_nRefCount;
            static ::cppu::IPropertyArrayHelper*    s_pProps;
            static ::osl::Mutex                     s_aMutex;

        public:
            OPropertyArrayUsageHelper();
            virtual ~OPropertyArrayUsageHelper()
            {   // ARGHHHHHHH ..... would like to implement this in proparrhlp_impl.hxx (as we do with all other methods)
                // but SUNPRO 5 compiler (linker) doesn't like this
                ::osl::MutexGuard aGuard(s_aMutex);
                OSL_ENSURE(s_nRefCount > 0, "OPropertyArrayUsageHelper::~OPropertyArrayUsageHelper : suspicious call : have a refcount of 0 !");
                if (!--s_nRefCount)
                {
                    delete s_pProps;
                    s_pProps = NULL;
                }
            }

            /** call this in the getInfoHelper method of your derived class. The method returns the array helper of the
                class, which is created if necessary.
            */
            ::cppu::IPropertyArrayHelper*   getArrayHelper();

        protected:
            /** used to implement the creation of the array helper which is shared amongst all instances of the class.
                This method needs to be implemented in derived classes.

                The method gets called with s_aMutex acquired.

                as long as IPropertyArrayHelper has no virtual destructor, the implementation of ~OPropertyArrayUsageHelper
                assumes that you created an ::cppu::OPropertyArrayHelper when deleting s_pProps.
                @return                         an pointer to the newly created array helper. Must not be NULL.
            */
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const = 0;
        };

        template<class TYPE>
        sal_Int32                       OPropertyArrayUsageHelper< TYPE >::s_nRefCount  = 0;

        template<class TYPE>
        ::cppu::IPropertyArrayHelper*   OPropertyArrayUsageHelper< TYPE >::s_pProps = NULL;

        template<class TYPE>
        ::osl::Mutex                    OPropertyArrayUsageHelper< TYPE >::s_aMutex;

        template <class TYPE>
        OPropertyArrayUsageHelper<TYPE>::OPropertyArrayUsageHelper()
        {
            ::osl::MutexGuard aGuard(s_aMutex);
            ++s_nRefCount;
        }

        template <class TYPE>
        ::cppu::IPropertyArrayHelper* OPropertyArrayUsageHelper<TYPE>::getArrayHelper()
        {
            OSL_ENSURE(s_nRefCount, "OPropertyArrayUsageHelper::getArrayHelper : suspicious call : have a refcount of 0 !");
            if (!s_pProps) {
                ::osl::MutexGuard aGuard(s_aMutex);
                if (!s_pProps) {
                    s_pProps = createArrayHelper();
                    OSL_ENSURE(s_pProps, "OPropertyArrayUsageHelper::getArrayHelper : createArrayHelper returned nonsense !");
                }
            }
            return s_pProps;
        }

        class OBase_Mutex
        {
        public:
            ::osl::Mutex m_aMutex;
        };

        namespace internal
        {
            template <class T>
            void implCopySequence(const T* _pSource, T*& _pDest, sal_Int32 _nSourceLen)
            {
                for (sal_Int32 i=0; i<_nSourceLen; ++i, ++_pSource, ++_pDest)
                    *_pDest = *_pSource;
            }
        }

        /// concat two sequences
        template <class T>
        ::com::sun::star::uno::Sequence<T> concatSequences(const ::com::sun::star::uno::Sequence<T>& _rLeft, const ::com::sun::star::uno::Sequence<T>& _rRight)
        {
            sal_Int32 nLeft(_rLeft.getLength()), nRight(_rRight.getLength());
            const T* pLeft = _rLeft.getConstArray();
            const T* pRight = _rRight.getConstArray();

            sal_Int32 nReturnLen(nLeft + nRight);
            ::com::sun::star::uno::Sequence<T> aReturn(nReturnLen);
            T* pReturn = aReturn.getArray();

            internal::implCopySequence(pLeft, pReturn, nLeft);
            internal::implCopySequence(pRight, pReturn, nRight);

            return aReturn;
        }

#define DECLARE_SERVICE_INFO()                                                                                \
    virtual OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);                                       \
    virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException);                   \
    virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)   \

#define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname)                               \
    OUString SAL_CALL classname::getImplementationName() throw (::com::sun::star::uno::RuntimeException) \
    {                                                                                \
        return OUString::createFromAscii(implasciiname);                                                 \
    }                                                                                \
    ::com::sun::star::uno::Sequence< OUString > SAL_CALL classname::getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)    \
    {                                                                                \
        ::com::sun::star::uno::Sequence< OUString > aSupported(1);                                                                               \
        aSupported[0] = OUString::createFromAscii(serviceasciiname);                                                                             \
        return aSupported;                                                                                \
    }                                                                                \
    sal_Bool SAL_CALL classname::supportsService(const OUString& _rServiceName) throw(::com::sun::star::uno::RuntimeException)   \
    {                                                                                \
        return cppu::supportsService(this, ServiceName);                                                                         \
    }                                                                                \
    }
}
#endif // _CONNECTIVITY_OSUBCOMPONENT_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix typos<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef _CONNECTIVITY_OSUBCOMPONENT_HXX_
#define _CONNECTIVITY_OSUBCOMPONENT_HXX_

#include <com/sun/star/lang/DisposedException.hpp>
#include <cppuhelper/interfacecontainer.h>
#include <cppuhelper/propshlp.hxx>
#include <cppuhelper/supportsservice.hxx>
#include <cppuhelper/weak.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>

namespace cppu {
    class IPropertyArrayHelper;
}

namespace com
{
    namespace sun
    {
        namespace star
        {
            namespace lang
            {
                class XComponent;
            }
        }
    }
}

namespace connectivity
{
    namespace mysqlc
    {
        void release(oslInterlockedCount& _refCount,
                     ::cppu::OBroadcastHelper& rBHelper,
                     ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xInterface,
                     ::com::sun::star::lang::XComponent* _pObject);

        void checkDisposed(sal_Bool _bThrow) throw (::com::sun::star::lang::DisposedException);

        template <class SELF, class WEAK> class OSubComponent
        {
        protected:
            // the parent must support the tunnel implementation
            ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xParent;
            SELF*   m_pDerivedImplementation;

        public:
            OSubComponent(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xParent,
                    SELF* _pDerivedImplementation)
                :m_xParent(_xParent)
                ,m_pDerivedImplementation(_pDerivedImplementation)
            {
            }

        protected:
            void dispose_ChildImpl()
            {
                ::osl::MutexGuard aGuard(m_pDerivedImplementation->rBHelper.rMutex);
                m_xParent = NULL;
            }
            void relase_ChildImpl()
            {
                release(m_pDerivedImplementation->m_refCount,
                                        m_pDerivedImplementation->rBHelper,
                                        m_xParent,
                                        m_pDerivedImplementation);

                m_pDerivedImplementation->WEAK::release();
            }
        };

        template <class TYPE>
        class OPropertyArrayUsageHelper
        {
        protected:
            static sal_Int32                        s_nRefCount;
            static ::cppu::IPropertyArrayHelper*    s_pProps;
            static ::osl::Mutex                     s_aMutex;

        public:
            OPropertyArrayUsageHelper();
            virtual ~OPropertyArrayUsageHelper()
            {   // ARGHHHHHHH ..... would like to implement this in proparrhlp_impl.hxx (as we do with all other methods)
                // but SUNPRO 5 compiler (linker) doesn't like this
                ::osl::MutexGuard aGuard(s_aMutex);
                OSL_ENSURE(s_nRefCount > 0, "OPropertyArrayUsageHelper::~OPropertyArrayUsageHelper : suspicious call : have a refcount of 0 !");
                if (!--s_nRefCount)
                {
                    delete s_pProps;
                    s_pProps = NULL;
                }
            }

            /** call this in the getInfoHelper method of your derived class. The method returns the array helper of the
                class, which is created if necessary.
            */
            ::cppu::IPropertyArrayHelper*   getArrayHelper();

        protected:
            /** used to implement the creation of the array helper which is shared amongst all instances of the class.
                This method needs to be implemented in derived classes.

                The method gets called with s_aMutex acquired.

                as long as IPropertyArrayHelper has no virtual destructor, the implementation of ~OPropertyArrayUsageHelper
                assumes that you created an ::cppu::OPropertyArrayHelper when deleting s_pProps.
                @return                         an pointer to the newly created array helper. Must not be NULL.
            */
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const = 0;
        };

        template<class TYPE>
        sal_Int32                       OPropertyArrayUsageHelper< TYPE >::s_nRefCount  = 0;

        template<class TYPE>
        ::cppu::IPropertyArrayHelper*   OPropertyArrayUsageHelper< TYPE >::s_pProps = NULL;

        template<class TYPE>
        ::osl::Mutex                    OPropertyArrayUsageHelper< TYPE >::s_aMutex;

        template <class TYPE>
        OPropertyArrayUsageHelper<TYPE>::OPropertyArrayUsageHelper()
        {
            ::osl::MutexGuard aGuard(s_aMutex);
            ++s_nRefCount;
        }

        template <class TYPE>
        ::cppu::IPropertyArrayHelper* OPropertyArrayUsageHelper<TYPE>::getArrayHelper()
        {
            OSL_ENSURE(s_nRefCount, "OPropertyArrayUsageHelper::getArrayHelper : suspicious call : have a refcount of 0 !");
            if (!s_pProps) {
                ::osl::MutexGuard aGuard(s_aMutex);
                if (!s_pProps) {
                    s_pProps = createArrayHelper();
                    OSL_ENSURE(s_pProps, "OPropertyArrayUsageHelper::getArrayHelper : createArrayHelper returned nonsense !");
                }
            }
            return s_pProps;
        }

        class OBase_Mutex
        {
        public:
            ::osl::Mutex m_aMutex;
        };

        namespace internal
        {
            template <class T>
            void implCopySequence(const T* _pSource, T*& _pDest, sal_Int32 _nSourceLen)
            {
                for (sal_Int32 i=0; i<_nSourceLen; ++i, ++_pSource, ++_pDest)
                    *_pDest = *_pSource;
            }
        }

        /// concat two sequences
        template <class T>
        ::com::sun::star::uno::Sequence<T> concatSequences(const ::com::sun::star::uno::Sequence<T>& _rLeft, const ::com::sun::star::uno::Sequence<T>& _rRight)
        {
            sal_Int32 nLeft(_rLeft.getLength()), nRight(_rRight.getLength());
            const T* pLeft = _rLeft.getConstArray();
            const T* pRight = _rRight.getConstArray();

            sal_Int32 nReturnLen(nLeft + nRight);
            ::com::sun::star::uno::Sequence<T> aReturn(nReturnLen);
            T* pReturn = aReturn.getArray();

            internal::implCopySequence(pLeft, pReturn, nLeft);
            internal::implCopySequence(pRight, pReturn, nRight);

            return aReturn;
        }
    }

#define DECLARE_SERVICE_INFO()                                                                                \
    virtual OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);                                       \
    virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException);                   \
    virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)

#define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname)                               \
    OUString SAL_CALL classname::getImplementationName() throw (::com::sun::star::uno::RuntimeException) \
    {                                                                                \
        return OUString::createFromAscii(implasciiname);                                                 \
    }                                                                                \
    ::com::sun::star::uno::Sequence< OUString > SAL_CALL classname::getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)    \
    {                                                                                \
        ::com::sun::star::uno::Sequence< OUString > aSupported(1);                                                                               \
        aSupported[0] = OUString::createFromAscii(serviceasciiname);                                                                             \
        return aSupported;                                                                                \
    }                                                                                \
    sal_Bool SAL_CALL classname::supportsService(const OUString& _rServiceName) throw(::com::sun::star::uno::RuntimeException)   \
    {                                                                                \
        return cppu::supportsService(this, _rServiceName);                                                                       \
    }

}
#endif // _CONNECTIVITY_OSUBCOMPONENT_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before><?hh // strict

namespace h4cc\HHVMProgressBundle\Services;

use h4cc\HHVMProgressBundle\Entity\PackageVersion;
use h4cc\HHVMProgressBundle\Exception\GithubAuthErrorException;
use h4cc\HHVMProgressBundle\Exception\GithubRateLimitException;
use Packagist\Api\Result\Package\Source;
use Psr\Log\LoggerInterface;
use Github\Client as GithubClient;

class TravisFetcher
{
    private LoggerInterface $logger;
    private GithubClient $github;
    private array $githubTokens;

    public function __construct(LoggerInterface $logger, GithubClient $github, array $githubTokens) {
        $this->logger = $logger;
        $this->github = $github;
        $this->githubTokens = $githubTokens;
    }

    public function fetchTravisContentFromSource(Source $source)
    {
        if('git' != $source->getType()) {
            $this->logger->info('Not a Git source');

            return false;
        }

        $url = $source->getUrl();

        // Try to fetch from github
        if(false !== stripos($url, 'github.com')) {
            if(preg_match('@github.com/(.+)/(.+)@', $url, $matches)) {
                $user = $matches[1];
                $repo = basename($matches[2], '.git');
                $this->logger->debug("Fetching travis file from github for $user/$repo.");

                return $this->fetchGithub($user, $repo, $source->getReference());
            }
        }

        $this->logger->info('Not a GitHub source');

        return false;
    }

    public function fetchGithub($user, $repo, $branch) {
        try {
            return $this->fetchGithubWithoutRetry($user, $repo, $branch);
        }
        catch(GithubAuthErrorException $e) {
            $this->logger->info('Using next github token because of GithubAuthErrorException.');
            $this->logger->debug($e);
            if(!$this->useNextGithubToken()) {
                throw $e;
            }
        }
        catch(GithubRateLimitException $e) {
            $this->logger->info('Using next github token because of GithubRateLimitException.');
            $this->logger->debug($e);
            if(!$this->useNextGithubToken()) {
                throw $e;
            }
        }

        // Retry with new github token.
        return $this->fetchGithub($user, $repo, $branch);
    }

    private function useNextGithubToken() {
        if(!$this->githubTokens) {
            return false;
        }

        // Using a random token and remove it from array.
        $randomKey = array_rand($this->githubTokens, 1);
        $nextToken = $this->githubTokens[$randomKey];
        unset($this->githubTokens[$randomKey]);

        $this->logger->debug('Using GithubToken: '. $nextToken);

        $this->github->authenticate($nextToken, "http_token");

        return true;
    }

    private function fetchGithubWithoutRetry($user, $repo, $branch) {

        // Fetch content
        $api = $this->github->api('repos')->contents();
        try {
            $travisConfig = $api->show($user, $repo, '.travis.yml', $branch);
        }catch(\Github\Exception\RuntimeException $e) {

            // Auth error
            if('Bad credentials' == $e->getMessage()) {
                throw new GithubAuthErrorException("Github Auth failed", 0, $e);
            }

            // Reaching limit is a hard error.
            if(false !== stripos($e->getMessage(), 'You have reached GitHub hour limit')) {
                throw new GithubRateLimitException("Reached Github Limit", 0, $e);
            }

            if('Not Found' == $e->getMessage() || 0 === stripos($e->getMessage(), 'No commit found' || 0 === stripos($e->getMessage(), 'This repository is empty')) {
                $this->logger->info($e->getMessage());
            }else{
                $this->logger->warning($e->getMessage());
                $this->logger->debug($e);
            }

            return false;
        }

        // Convert content
        $content = $travisConfig['content'];
        if('base64' == $travisConfig['encoding']) {
            $content = base64_decode($content);
        }

        return [
            'content' => $content,
            'ref' => $travisConfig['sha'],
        ];
    }
}
<commit_msg>Added missing )<commit_after><?hh // strict

namespace h4cc\HHVMProgressBundle\Services;

use h4cc\HHVMProgressBundle\Entity\PackageVersion;
use h4cc\HHVMProgressBundle\Exception\GithubAuthErrorException;
use h4cc\HHVMProgressBundle\Exception\GithubRateLimitException;
use Packagist\Api\Result\Package\Source;
use Psr\Log\LoggerInterface;
use Github\Client as GithubClient;

class TravisFetcher
{
    private LoggerInterface $logger;
    private GithubClient $github;
    private array $githubTokens;

    public function __construct(LoggerInterface $logger, GithubClient $github, array $githubTokens) {
        $this->logger = $logger;
        $this->github = $github;
        $this->githubTokens = $githubTokens;
    }

    public function fetchTravisContentFromSource(Source $source)
    {
        if('git' != $source->getType()) {
            $this->logger->info('Not a Git source');

            return false;
        }

        $url = $source->getUrl();

        // Try to fetch from github
        if(false !== stripos($url, 'github.com')) {
            if(preg_match('@github.com/(.+)/(.+)@', $url, $matches)) {
                $user = $matches[1];
                $repo = basename($matches[2], '.git');
                $this->logger->debug("Fetching travis file from github for $user/$repo.");

                return $this->fetchGithub($user, $repo, $source->getReference());
            }
        }

        $this->logger->info('Not a GitHub source');

        return false;
    }

    public function fetchGithub($user, $repo, $branch) {
        try {
            return $this->fetchGithubWithoutRetry($user, $repo, $branch);
        }
        catch(GithubAuthErrorException $e) {
            $this->logger->info('Using next github token because of GithubAuthErrorException.');
            $this->logger->debug($e);
            if(!$this->useNextGithubToken()) {
                throw $e;
            }
        }
        catch(GithubRateLimitException $e) {
            $this->logger->info('Using next github token because of GithubRateLimitException.');
            $this->logger->debug($e);
            if(!$this->useNextGithubToken()) {
                throw $e;
            }
        }

        // Retry with new github token.
        return $this->fetchGithub($user, $repo, $branch);
    }

    private function useNextGithubToken() {
        if(!$this->githubTokens) {
            return false;
        }

        // Using a random token and remove it from array.
        $randomKey = array_rand($this->githubTokens, 1);
        $nextToken = $this->githubTokens[$randomKey];
        unset($this->githubTokens[$randomKey]);

        $this->logger->debug('Using GithubToken: '. $nextToken);

        $this->github->authenticate($nextToken, "http_token");

        return true;
    }

    private function fetchGithubWithoutRetry($user, $repo, $branch) {

        // Fetch content
        $api = $this->github->api('repos')->contents();
        try {
            $travisConfig = $api->show($user, $repo, '.travis.yml', $branch);
        }catch(\Github\Exception\RuntimeException $e) {

            // Auth error
            if('Bad credentials' == $e->getMessage()) {
                throw new GithubAuthErrorException("Github Auth failed", 0, $e);
            }

            // Reaching limit is a hard error.
            if(false !== stripos($e->getMessage(), 'You have reached GitHub hour limit')) {
                throw new GithubRateLimitException("Reached Github Limit", 0, $e);
            }

            if('Not Found' == $e->getMessage() || 0 === stripos($e->getMessage(), 'No commit found') || 0 === stripos($e->getMessage(), 'This repository is empty')) {
                $this->logger->info($e->getMessage());
            }else{
                $this->logger->warning($e->getMessage());
                $this->logger->debug($e);
            }

            return false;
        }

        // Convert content
        $content = $travisConfig['content'];
        if('base64' == $travisConfig['encoding']) {
            $content = base64_decode($content);
        }

        return [
            'content' => $content,
            'ref' => $travisConfig['sha'],
        ];
    }
}
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#ifndef __STOUT_OS_POSIX_SU_HPP__
#define __STOUT_OS_POSIX_SU_HPP__

#include <string>

#include <grp.h>
#include <pwd.h>

#include <stout/error.hpp>
#include <stout/nothing.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>

namespace os {

inline Result<uid_t> getuid(const Option<std::string>& user = None())
{
  if (user.isNone()) {
    return ::getuid();
  }

  struct passwd passwd;
  struct passwd* result = nullptr;

  int size = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (size == -1) {
    // Initial value for buffer size.
    size = 1024;
  }

  while (true) {
    char* buffer = new char[size];

    if (getpwnam_r(user.get().c_str(), &passwd, buffer, size, &result) == 0) {
      // The usual interpretation of POSIX is that getpwnam_r will
      // return 0 but set result == nullptr if the user is not found.
      if (result == nullptr) {
        delete[] buffer;
        return None();
      }

      uid_t uid = passwd.pw_uid;
      delete[] buffer;
      return uid;
    } else {
      // RHEL7 (and possibly other systems) will return non-zero and
      // set one of the following errors for "The given name or uid
      // was not found." See 'man getpwnam_r'. We only check for the
      // errors explicitly listed, and do not consider the ellipsis.
      if (errno == ENOENT ||
          errno == ESRCH ||
          errno == EBADF ||
          errno == EPERM) {
        delete[] buffer;
        return None();
      }

      if (errno != ERANGE) {
        delete[] buffer;
        return ErrnoError("Failed to get username information");
      }
      // getpwnam_r set ERANGE so try again with a larger buffer.
      size *= 2;
      delete[] buffer;
    }
  }

  UNREACHABLE();
}

inline Result<gid_t> getgid(const Option<std::string>& user = None())
{
  if (user.isNone()) {
    return ::getgid();
  }

  struct passwd passwd;
  struct passwd* result = nullptr;

  int size = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (size == -1) {
    // Initial value for buffer size.
    size = 1024;
  }

  while (true) {
    char* buffer = new char[size];

    if (getpwnam_r(user.get().c_str(), &passwd, buffer, size, &result) == 0) {
      // The usual interpretation of POSIX is that getpwnam_r will
      // return 0 but set result == nullptr if the group is not found.
      if (result == nullptr) {
        delete[] buffer;
        return None();
      }

      gid_t gid = passwd.pw_gid;
      delete[] buffer;
      return gid;
    } else {
      // RHEL7 (and possibly other systems) will return non-zero and
      // set one of the following errors for "The given name or uid
      // was not found." See 'man getpwnam_r'. We only check for the
      // errors explicitly listed, and do not consider the ellipsis.
      if (errno == ENOENT ||
          errno == ESRCH ||
          errno == EBADF ||
          errno == EPERM) {
        delete[] buffer;
        return None();
      }

      if (errno != ERANGE) {
        delete[] buffer;
        return ErrnoError("Failed to get username information");
      }
      // getpwnam_r set ERANGE so try again with a larger buffer.
      size *= 2;
      delete[] buffer;
    }
  }

  UNREACHABLE();
}

inline Result<std::string> user(Option<uid_t> uid = None())
{
  if (uid.isNone()) {
    uid = ::getuid();
  }

  int size = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (size == -1) {
    // Initial value for buffer size.
    size = 1024;
  }

  struct passwd passwd;
  struct passwd* result = nullptr;

  while (true) {
    char* buffer = new char[size];

    if (getpwuid_r(uid.get(), &passwd, buffer, size, &result) == 0) {
      // getpwuid_r will return 0 but set result == nullptr if the uid is
      // not found.
      if (result == nullptr) {
        delete[] buffer;
        return None();
      }

      std::string user(passwd.pw_name);
      delete[] buffer;
      return user;
    } else {
      if (errno != ERANGE) {
        delete[] buffer;
        return ErrnoError();
      }

      // getpwuid_r set ERANGE so try again with a larger buffer.
      size *= 2;
      delete[] buffer;
    }
  }
}

inline Try<Nothing> su(const std::string& user)
{
  Result<gid_t> gid = os::getgid(user);
  if (gid.isError() || gid.isNone()) {
    return Error("Failed to getgid: " +
        (gid.isError() ? gid.error() : "unknown user"));
  } else if (::setgid(gid.get())) {
    return ErrnoError("Failed to set gid");
  }

  // Set the supplementary group list. We ignore EPERM because
  // performing a no-op call (switching to same group) still
  // requires being privileged, unlike 'setgid' and 'setuid'.
  if (::initgroups(user.c_str(), gid.get()) == -1 && errno != EPERM) {
    return ErrnoError("Failed to set supplementary groups");
  }

  Result<uid_t> uid = os::getuid(user);
  if (uid.isError() || uid.isNone()) {
    return Error("Failed to getuid: " +
        (uid.isError() ? uid.error() : "unknown user"));
  } else if (::setuid(uid.get())) {
    return ErrnoError("Failed to setuid");
  }

  return Nothing();
}

} // namespace os {

#endif // __STOUT_OS_POSIX_SU_HPP__
<commit_msg>Added stout functions to set uid and gid.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#ifndef __STOUT_OS_POSIX_SU_HPP__
#define __STOUT_OS_POSIX_SU_HPP__

#include <string>

#include <grp.h>
#include <pwd.h>

#include <stout/error.hpp>
#include <stout/nothing.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>

namespace os {

inline Result<uid_t> getuid(const Option<std::string>& user = None())
{
  if (user.isNone()) {
    return ::getuid();
  }

  struct passwd passwd;
  struct passwd* result = nullptr;

  int size = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (size == -1) {
    // Initial value for buffer size.
    size = 1024;
  }

  while (true) {
    char* buffer = new char[size];

    if (getpwnam_r(user.get().c_str(), &passwd, buffer, size, &result) == 0) {
      // The usual interpretation of POSIX is that getpwnam_r will
      // return 0 but set result == nullptr if the user is not found.
      if (result == nullptr) {
        delete[] buffer;
        return None();
      }

      uid_t uid = passwd.pw_uid;
      delete[] buffer;
      return uid;
    } else {
      // RHEL7 (and possibly other systems) will return non-zero and
      // set one of the following errors for "The given name or uid
      // was not found." See 'man getpwnam_r'. We only check for the
      // errors explicitly listed, and do not consider the ellipsis.
      if (errno == ENOENT ||
          errno == ESRCH ||
          errno == EBADF ||
          errno == EPERM) {
        delete[] buffer;
        return None();
      }

      if (errno != ERANGE) {
        delete[] buffer;
        return ErrnoError("Failed to get username information");
      }
      // getpwnam_r set ERANGE so try again with a larger buffer.
      size *= 2;
      delete[] buffer;
    }
  }

  UNREACHABLE();
}

inline Try<Nothing> setuid(uid_t uid)
{
  if (::setuid(uid) == -1) {
    return ErrnoError();
  }

  return Nothing();
}

inline Result<gid_t> getgid(const Option<std::string>& user = None())
{
  if (user.isNone()) {
    return ::getgid();
  }

  struct passwd passwd;
  struct passwd* result = nullptr;

  int size = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (size == -1) {
    // Initial value for buffer size.
    size = 1024;
  }

  while (true) {
    char* buffer = new char[size];

    if (getpwnam_r(user.get().c_str(), &passwd, buffer, size, &result) == 0) {
      // The usual interpretation of POSIX is that getpwnam_r will
      // return 0 but set result == nullptr if the group is not found.
      if (result == nullptr) {
        delete[] buffer;
        return None();
      }

      gid_t gid = passwd.pw_gid;
      delete[] buffer;
      return gid;
    } else {
      // RHEL7 (and possibly other systems) will return non-zero and
      // set one of the following errors for "The given name or uid
      // was not found." See 'man getpwnam_r'. We only check for the
      // errors explicitly listed, and do not consider the ellipsis.
      if (errno == ENOENT ||
          errno == ESRCH ||
          errno == EBADF ||
          errno == EPERM) {
        delete[] buffer;
        return None();
      }

      if (errno != ERANGE) {
        delete[] buffer;
        return ErrnoError("Failed to get username information");
      }
      // getpwnam_r set ERANGE so try again with a larger buffer.
      size *= 2;
      delete[] buffer;
    }
  }

  UNREACHABLE();
}

inline Try<Nothing> setgid(gid_t gid)
{
  if (::setgid(gid) == -1) {
    return ErrnoError();
  }

  return Nothing();
}

inline Result<std::string> user(Option<uid_t> uid = None())
{
  if (uid.isNone()) {
    uid = ::getuid();
  }

  int size = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (size == -1) {
    // Initial value for buffer size.
    size = 1024;
  }

  struct passwd passwd;
  struct passwd* result = nullptr;

  while (true) {
    char* buffer = new char[size];

    if (getpwuid_r(uid.get(), &passwd, buffer, size, &result) == 0) {
      // getpwuid_r will return 0 but set result == nullptr if the uid is
      // not found.
      if (result == nullptr) {
        delete[] buffer;
        return None();
      }

      std::string user(passwd.pw_name);
      delete[] buffer;
      return user;
    } else {
      if (errno != ERANGE) {
        delete[] buffer;
        return ErrnoError();
      }

      // getpwuid_r set ERANGE so try again with a larger buffer.
      size *= 2;
      delete[] buffer;
    }
  }
}

inline Try<Nothing> su(const std::string& user)
{
  Result<gid_t> gid = os::getgid(user);
  if (gid.isError() || gid.isNone()) {
    return Error("Failed to getgid: " +
        (gid.isError() ? gid.error() : "unknown user"));
  } else if (::setgid(gid.get())) {
    return ErrnoError("Failed to set gid");
  }

  // Set the supplementary group list. We ignore EPERM because
  // performing a no-op call (switching to same group) still
  // requires being privileged, unlike 'setgid' and 'setuid'.
  if (::initgroups(user.c_str(), gid.get()) == -1 && errno != EPERM) {
    return ErrnoError("Failed to set supplementary groups");
  }

  Result<uid_t> uid = os::getuid(user);
  if (uid.isError() || uid.isNone()) {
    return Error("Failed to getuid: " +
        (uid.isError() ? uid.error() : "unknown user"));
  } else if (::setuid(uid.get())) {
    return ErrnoError("Failed to setuid");
  }

  return Nothing();
}

} // namespace os {

#endif // __STOUT_OS_POSIX_SU_HPP__
<|endoftext|>


<commit_before>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <limits.h>

// Serial includes
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif

// include class definition
#include "wifly_serial.h"

// TODO: Investigate this parameter... what exactly does it do?
#define WD 1000

using std::string;
using namespace std;

WiflySerial::WiflySerial() : SerialPort() {
	printf("simple wifly constructor\n");
}

WiflySerial::WiflySerial(bool verbose) : SerialPort(verbose) {
	// nothing specific to do in this constructor
	printf("verbose wifly constructor\n");
}

WiflySerial::WiflySerial(bool verbose, char* &uart_name) : SerialPort(verbose, uart_name) {
	printf("complex wifly constructor\n");
}

WiflySerial::~WiflySerial() {
	// nothing to do in the destructor
}

void WiflySerial::enter_commandmode() {

	if (_verbose) printf("entering command mode...\n");

	// First, we must make sure we are in command mode
	// For now, let's assume we just booted up
	/*
	write(fd, "exit\r", 5);
	usleep(WD);
	write(fd, "exit\r", 5);
	usleep(WD);
	*/

	/* Give it the turn on command */
	/* Must wait 250 ms before and after giving $$$ command */
	/* To be safe, I wait 300 ms */
	write(fd, "$$$", 3);
	usleep(300000);
}

/**
 * Scans the channels and returns the rssi of the specified SSID
 */
int WiflySerial::scanrssi(char *ssid) {
	if (_verbose) printf("scanning...\n");
	char buf[2048];
	write(fd, "scan 10\r", 8);
	usleep(250000);
	if (_verbose) printf("reading from wifly...\n");

	read(fd, buf, sizeof(buf));
	if (_verbose) printf("%s\n", buf);

	return parserssi(buf, ssid);
}

// private functions

/*
 * New function for parsing message, ideally prevents seg faults
 */
int WiflySerial::parserssi(char* buf, char* ssid) {
	if (_verbose) printf("parsing rssi from message...\n");

	char *delim = (char *) "\n";
	char *comma_delim = (char *)  ",";
	char *jam_token;
	char *pEnd;
	int i = 0;
	int rssi_value = INT_MAX;

	char *token = strtok(buf, delim);

	// get to the starting point of the message
	while (token != NULL && strstr(token, (char*) "SCAN:Found") == NULL) {
		token = strtok(NULL, delim);
	}

	// can get the information of how many entries found
	//jam_token = strtok(token, " ");
	//jam_token = strtok(NULL, " ");
	//if (_verbose) printf("found %s results\n", jam_token);

	// get to the first actual line of the scan results
	token = strtok(NULL, delim);

	// now loop through to the end of the message
	while (token != NULL && strstr(token, (char*) "END:") == NULL) {

		if (_verbose) printf("%s\n", token);

		// check to see if this row contains the desired SSID
		if (strstr(token, ssid) != NULL) {
			jam_token = strtok(token, comma_delim);

			while (jam_token != NULL && i < 2) {
				jam_token = strtok(NULL, comma_delim);
				i++;
			}
			i = 0;

			// jam_token should now contain the rssi value
			// need to make sure it's not null and is an int
			if (jam_token != NULL) {
				rssi_value = (int) strtol(jam_token, &pEnd, 10);

				printf("rssi value parsed: %i\n", rssi_value);

				// check to make sure this was indeed the rssi value
				if (strstr(pEnd, "\0") == NULL) {
					printf("rssi not correct value\n");
					rssi_value = INT_MAX;
				}
			}

			// set token to null to end search
			token = NULL;
		} else {
			// get the next line
			token = strtok(NULL, delim);
		}
	}

	// return the rssi value
	return rssi_value;
}

<commit_msg>add flow control on wifly read<commit_after>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <limits.h>

// Serial includes
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif

// include class definition
#include "wifly_serial.h"

// TODO: Investigate this parameter... what exactly does it do?
#define WD 1000

using std::string;
using namespace std;

WiflySerial::WiflySerial() : SerialPort() {
	printf("simple wifly constructor\n");
}

WiflySerial::WiflySerial(bool verbose) : SerialPort(verbose) {
	// nothing specific to do in this constructor
	printf("verbose wifly constructor\n");
}

WiflySerial::WiflySerial(bool verbose, char* &uart_name) : SerialPort(verbose, uart_name) {
	printf("complex wifly constructor\n");
}

WiflySerial::~WiflySerial() {
	// nothing to do in the destructor
}

void WiflySerial::enter_commandmode() {

	if (_verbose) printf("entering command mode...\n");

	// First, we must make sure we are in command mode
	// For now, let's assume we just booted up
	/*
	write(fd, "exit\r", 5);
	usleep(WD);
	write(fd, "exit\r", 5);
	usleep(WD);
	*/

	/* Give it the turn on command */
	/* Must wait 250 ms before and after giving $$$ command */
	/* To be safe, I wait 300 ms */
	write(fd, "$$$", 3);
	usleep(300000);
}

/**
 * Scans the channels and returns the rssi of the specified SSID
 */
int WiflySerial::scanrssi(char *ssid) {
	if (_verbose) printf("scanning...\n");
	char buf[2048];
	write(fd, "scan 10\r", 8);
	usleep(250000);
	if (_verbose) printf("reading from wifly...\n");

	int iMode = 0;
	ioctl(fd, FIONBIO, &iMode);
	read(fd, buf, sizeof(buf));
	if (_verbose) printf("%s\n", buf);

	return parserssi(buf, ssid);
}

// private functions

/*
 * New function for parsing message, ideally prevents seg faults
 */
int WiflySerial::parserssi(char* buf, char* ssid) {
	if (_verbose) printf("parsing rssi from message...\n");

	char *delim = (char *) "\n";
	char *comma_delim = (char *)  ",";
	char *jam_token;
	char *pEnd;
	int i = 0;
	int rssi_value = INT_MAX;

	char *token = strtok(buf, delim);

	// get to the starting point of the message
	while (token != NULL && strstr(token, (char*) "SCAN:Found") == NULL) {
		token = strtok(NULL, delim);
	}

	// can get the information of how many entries found
	//jam_token = strtok(token, " ");
	//jam_token = strtok(NULL, " ");
	//if (_verbose) printf("found %s results\n", jam_token);

	// get to the first actual line of the scan results
	token = strtok(NULL, delim);

	// now loop through to the end of the message
	while (token != NULL && strstr(token, (char*) "END:") == NULL) {

		if (_verbose) printf("%s\n", token);

		// check to see if this row contains the desired SSID
		if (strstr(token, ssid) != NULL) {
			jam_token = strtok(token, comma_delim);

			while (jam_token != NULL && i < 2) {
				jam_token = strtok(NULL, comma_delim);
				i++;
			}
			i = 0;

			// jam_token should now contain the rssi value
			// need to make sure it's not null and is an int
			if (jam_token != NULL) {
				rssi_value = (int) strtol(jam_token, &pEnd, 10);

				printf("rssi value parsed: %i\n", rssi_value);

				// check to make sure this was indeed the rssi value
				if (strstr(pEnd, "\0") == NULL) {
					printf("rssi not correct value\n");
					rssi_value = INT_MAX;
				}
			}

			// set token to null to end search
			token = NULL;
		} else {
			// get the next line
			token = strtok(NULL, delim);
		}
	}

	// return the rssi value
	return rssi_value;
}

<|endoftext|>


<commit_before><commit_msg>PAL10471 - incorrect 3D popup for erased objects<commit_after><|endoftext|>


<commit_before>#include "XmlItemBookmarksDatabaseManager.h"

#include <QDebug>
#include <QDir>

const QString XmlItemBookmarksDatabaseManager::_databaseName = "somafm.sqlite";

QSqlDatabase XmlItemBookmarksDatabaseManager::db = QSqlDatabase::addDatabase("QSQLITE");

XmlItemBookmarksDatabaseManager::XmlItemBookmarksDatabaseManager(QObject *parent) :
    QObject(parent)
{
    if (!db.isOpen()) {
        openDatabase();

        // "Relink" queries to the opened database
        insertBookmarkPreparedQuery.clear();
        deleteBookmarkPreparedQuery.clear();
    }
}

XmlItemBookmarksDatabaseManager::~XmlItemBookmarksDatabaseManager()
{
    QSqlDatabase::removeDatabase(_databaseName);
}

bool XmlItemBookmarksDatabaseManager::openDatabase()
{
    QString dbPath(QDir::homePath());
    dbPath.append(QDir::separator()).append(_databaseName);
    db.setDatabaseName(dbPath);

    return db.open();
}

void XmlItemBookmarksDatabaseManager::init()
{
    checkStructure();
    prepareQueries();
}

<commit_msg>store database in Qt standard paths for applications<commit_after>#include "XmlItemBookmarksDatabaseManager.h"

#include <QDebug>
#include <QStandardPaths>

const QString XmlItemBookmarksDatabaseManager::_databaseName = "somafm.sqlite";

QSqlDatabase XmlItemBookmarksDatabaseManager::db = QSqlDatabase::addDatabase("QSQLITE");

XmlItemBookmarksDatabaseManager::XmlItemBookmarksDatabaseManager(QObject *parent) :
    QObject(parent)
{
    if (!db.isOpen()) {
        openDatabase();

        // "Relink" queries to the opened database
        insertBookmarkPreparedQuery.clear();
        deleteBookmarkPreparedQuery.clear();
    }
}

XmlItemBookmarksDatabaseManager::~XmlItemBookmarksDatabaseManager()
{
    QSqlDatabase::removeDatabase(_databaseName);
}

bool XmlItemBookmarksDatabaseManager::openDatabase()
{
    QString dbPath = QStandardPaths::locate(QStandardPaths::DataLocation, _databaseName);
    db.setDatabaseName(dbPath);

    return db.open();
}

void XmlItemBookmarksDatabaseManager::init()
{
    checkStructure();
    prepareQueries();
}

<|endoftext|>