<commit_before>/*
  Copyright (c) DataStax, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include "auth.hpp"
#include "external.hpp"
#include "string.hpp"

#include "cassandra.h"

#include <algorithm>

using namespace datastax;
using namespace datastax::internal::core;
using namespace datastax::internal::enterprise;

#define DSE_AUTHENTICATOR "com.datastax.bdp.cassandra.auth.DseAuthenticator"

#define DSE_PLAINTEXT_AUTH_MECHANISM "PLAIN"
#define DSE_PLAINTEXT_AUTH_SERVER_INITIAL_CHALLENGE "PLAIN-START"

extern "C" {

void cass_authenticator_address(const CassAuthenticator* auth, CassInet* address) {
  address->address_length = auth->address().to_inet(address->address);
}

const char* cass_authenticator_hostname(const CassAuthenticator* auth, size_t* length) {
  if (length != NULL) *length = auth->hostname().length();
  return auth->hostname().c_str();
}

const char* cass_authenticator_class_name(const CassAuthenticator* auth, size_t* length) {
  if (length != NULL) *length = auth->class_name().length();
  return auth->class_name().c_str();
}

void* cass_authenticator_exchange_data(CassAuthenticator* auth) { return auth->exchange_data(); }

void cass_authenticator_set_exchange_data(CassAuthenticator* auth, void* exchange_data) {
  auth->set_exchange_data(exchange_data);
}

char* cass_authenticator_response(CassAuthenticator* auth, size_t size) {
  String* response = auth->response();

  if (response != NULL) {
    response->resize(size, 0);
    return &(*response)[0];
  }

  return NULL;
}

void cass_authenticator_set_response(CassAuthenticator* auth, const char* response,
                                     size_t response_size) {
  if (auth->response() != NULL) {
    auth->response()->assign(response, response_size);
  }
}

void cass_authenticator_set_error(CassAuthenticator* auth, const char* message) {
  cass_authenticator_set_error_n(auth, message, SAFE_STRLEN(message));
}

void cass_authenticator_set_error_n(CassAuthenticator* auth, const char* message,
                                    size_t message_length) {
  auth->set_error(String(message, message_length));
}

} // extern "C"

bool PlainTextAuthenticator::initial_response(String* response) {
  response->reserve(username_.size() + password_.size() + 2);
  response->push_back(0);
  response->append(username_);
  response->push_back(0);
  response->append(password_);
  return true;
}

bool PlainTextAuthenticator::evaluate_challenge(const String& token, String* response) {
  // no-op
  return true;
}

bool PlainTextAuthenticator::success(const String& token) {
  // no-op
  return true;
}

bool DsePlainTextAuthenticator::initial_response(String* response) {
  if (class_name_ == "com.datastax.bdp.cassandra.auth.DseAuthenticator") {
    response->assign(DSE_PLAINTEXT_AUTH_MECHANISM);
    return true;
  } else {
    return evaluate_challenge(DSE_PLAINTEXT_AUTH_SERVER_INITIAL_CHALLENGE, response);
  }
}

bool DsePlainTextAuthenticator::evaluate_challenge(const String& token, String* response) {
  if (token != DSE_PLAINTEXT_AUTH_SERVER_INITIAL_CHALLENGE) {
    LOG_ERROR("Invalid start token for DSE plaintext authenticator during challenge: '%s'",
              token.c_str());
    return false;
  }

  // Credentials are of the form "<authid>\0<username>\0<password>"
  response->append(authorization_id_);
  response->push_back('\0');
  response->append(username_);
  response->push_back('\0');
  response->append(password_);

  return true;
}

bool DsePlainTextAuthenticator::success(const String& token) {
  // no-op
  return true;
}

ExternalAuthenticator::ExternalAuthenticator(const Address& address, const String& hostname,
                                             const String& class_name,
                                             const CassAuthenticatorCallbacks* callbacks,
                                             void* data)
    : address_(address)
    , hostname_(hostname)
    , class_name_(class_name)
    , response_(NULL)
    , callbacks_(callbacks)
    , data_(data)
    , exchange_data_(NULL) {}

ExternalAuthenticator::~ExternalAuthenticator() {
  response_ = NULL;
  if (callbacks_->cleanup_callback != NULL) {
    callbacks_->cleanup_callback(CassAuthenticator::to(this), data_);
  }
}

bool ExternalAuthenticator::initial_response(String* response) {
  if (callbacks_->initial_callback == NULL) {
    return true;
  }
  response_ = response;
  error_.clear();
  callbacks_->initial_callback(CassAuthenticator::to(this), data_);
  return error_.empty();
}

bool ExternalAuthenticator::evaluate_challenge(const String& token, String* response) {
  if (callbacks_->challenge_callback == NULL) {
    return true;
  }
  response_ = response;
  error_.clear();
  callbacks_->challenge_callback(CassAuthenticator::to(this), data_, token.data(), token.size());
  return error_.empty();
}

bool ExternalAuthenticator::success(const String& token) {
  if (callbacks_->success_callback == NULL) {
    return true;
  }
  response_ = NULL;
  error_.clear();
  callbacks_->success_callback(CassAuthenticator::to(this), data_, token.data(), token.size());
  return error_.empty();
}
<commit_msg>Use constant for DSE authenticator<commit_after>/*
  Copyright (c) DataStax, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include "auth.hpp"
#include "external.hpp"
#include "string.hpp"

#include "cassandra.h"

#include <algorithm>

using namespace datastax;
using namespace datastax::internal::core;
using namespace datastax::internal::enterprise;

#define DSE_AUTHENTICATOR "com.datastax.bdp.cassandra.auth.DseAuthenticator"

#define DSE_PLAINTEXT_AUTH_MECHANISM "PLAIN"
#define DSE_PLAINTEXT_AUTH_SERVER_INITIAL_CHALLENGE "PLAIN-START"

extern "C" {

void cass_authenticator_address(const CassAuthenticator* auth, CassInet* address) {
  address->address_length = auth->address().to_inet(address->address);
}

const char* cass_authenticator_hostname(const CassAuthenticator* auth, size_t* length) {
  if (length != NULL) *length = auth->hostname().length();
  return auth->hostname().c_str();
}

const char* cass_authenticator_class_name(const CassAuthenticator* auth, size_t* length) {
  if (length != NULL) *length = auth->class_name().length();
  return auth->class_name().c_str();
}

void* cass_authenticator_exchange_data(CassAuthenticator* auth) { return auth->exchange_data(); }

void cass_authenticator_set_exchange_data(CassAuthenticator* auth, void* exchange_data) {
  auth->set_exchange_data(exchange_data);
}

char* cass_authenticator_response(CassAuthenticator* auth, size_t size) {
  String* response = auth->response();

  if (response != NULL) {
    response->resize(size, 0);
    return &(*response)[0];
  }

  return NULL;
}

void cass_authenticator_set_response(CassAuthenticator* auth, const char* response,
                                     size_t response_size) {
  if (auth->response() != NULL) {
    auth->response()->assign(response, response_size);
  }
}

void cass_authenticator_set_error(CassAuthenticator* auth, const char* message) {
  cass_authenticator_set_error_n(auth, message, SAFE_STRLEN(message));
}

void cass_authenticator_set_error_n(CassAuthenticator* auth, const char* message,
                                    size_t message_length) {
  auth->set_error(String(message, message_length));
}

} // extern "C"

bool PlainTextAuthenticator::initial_response(String* response) {
  response->reserve(username_.size() + password_.size() + 2);
  response->push_back(0);
  response->append(username_);
  response->push_back(0);
  response->append(password_);
  return true;
}

bool PlainTextAuthenticator::evaluate_challenge(const String& token, String* response) {
  // no-op
  return true;
}

bool PlainTextAuthenticator::success(const String& token) {
  // no-op
  return true;
}

bool DsePlainTextAuthenticator::initial_response(String* response) {
  if (class_name_ == DSE_AUTHENTICATOR) {
    response->assign(DSE_PLAINTEXT_AUTH_MECHANISM);
    return true;
  } else {
    return evaluate_challenge(DSE_PLAINTEXT_AUTH_SERVER_INITIAL_CHALLENGE, response);
  }
}

bool DsePlainTextAuthenticator::evaluate_challenge(const String& token, String* response) {
  if (token != DSE_PLAINTEXT_AUTH_SERVER_INITIAL_CHALLENGE) {
    LOG_ERROR("Invalid start token for DSE plaintext authenticator during challenge: '%s'",
              token.c_str());
    return false;
  }

  // Credentials are of the form "<authid>\0<username>\0<password>"
  response->append(authorization_id_);
  response->push_back('\0');
  response->append(username_);
  response->push_back('\0');
  response->append(password_);

  return true;
}

bool DsePlainTextAuthenticator::success(const String& token) {
  // no-op
  return true;
}

ExternalAuthenticator::ExternalAuthenticator(const Address& address, const String& hostname,
                                             const String& class_name,
                                             const CassAuthenticatorCallbacks* callbacks,
                                             void* data)
    : address_(address)
    , hostname_(hostname)
    , class_name_(class_name)
    , response_(NULL)
    , callbacks_(callbacks)
    , data_(data)
    , exchange_data_(NULL) {}

ExternalAuthenticator::~ExternalAuthenticator() {
  response_ = NULL;
  if (callbacks_->cleanup_callback != NULL) {
    callbacks_->cleanup_callback(CassAuthenticator::to(this), data_);
  }
}

bool ExternalAuthenticator::initial_response(String* response) {
  if (callbacks_->initial_callback == NULL) {
    return true;
  }
  response_ = response;
  error_.clear();
  callbacks_->initial_callback(CassAuthenticator::to(this), data_);
  return error_.empty();
}

bool ExternalAuthenticator::evaluate_challenge(const String& token, String* response) {
  if (callbacks_->challenge_callback == NULL) {
    return true;
  }
  response_ = response;
  error_.clear();
  callbacks_->challenge_callback(CassAuthenticator::to(this), data_, token.data(), token.size());
  return error_.empty();
}

bool ExternalAuthenticator::success(const String& token) {
  if (callbacks_->success_callback == NULL) {
    return true;
  }
  response_ = NULL;
  error_.clear();
  callbacks_->success_callback(CassAuthenticator::to(this), data_, token.data(), token.size());
  return error_.empty();
}
<|endoftext|>


<commit_before><commit_msg>gtk: Implement AutomationProvider::GetBrowserForWindow.<commit_after><|endoftext|>


<commit_before><commit_msg>Change KeyboardAccessTests from DISABLED to FLAKY to see if they pass now. BUG=39213 TEST=interactive_ui_tests pass for me locally on Linux, Vista, and XP. TBR=maruel<commit_after><|endoftext|>


<commit_before>//utils.cpp
#include <cmath>
#include <iostream>

#include "utils.hpp"

namespace utils{

    DataPoint::DataPoint(std::vector<double> x, double y = 0.0){

        if (x.size()==0){
            this->x.push_back(0.0);
        }
        else {
            for(int i=0; i<x.size(); i++){
                this->x.push_back(x.at(i));
            }
        }

        this->y = y;
    }

    //=========================FUNÇÕES BINÁRIAS===========================//

    //Função Soma
    double uAdd(double v1, double v2) {

        return (v1 + v2);
    }

    //Função Subtração
    double uSub(double v1, double v2) {

        return (v1 - v2);
    }

    //Função Multiplicação
    double uMult(double v1, double v2) {

        return (v1 * v2);
    }

    //Função Divisão
    double uDiv(double v1, double v2) {

        if (v2 == 0)
            return 0;   //Padrão
        else
            return (v1 / v2);
    }

    //Função Potência
    double uPow(double v1, double v2) {

        if ((v1 == 0)&&(v2 == 0))
            return 0;   //Padrão - Equivalente matemático a 0/0
        else
            return pow(v1, v2);
    }

    //==========================FUNÇÕES UNÁRIAS===========================//

    //Função Exponencial (e^v)
    double uExp(double v) {

        return (exp(v));
    }

    //Função Raiz Quadrada
    double uSqrt(double v) {

        if (v < 0)
            return 0;
        else
            return (sqrt(v));
    }

    //Função Logaritmo Neperiano
    double uLn(double v) {

        if (v > 0)
            return (log(v));
        else
            return 0;
    }

    //Converter radianos em graus para poder utilizar as funções trigonométricas
    double rad_to_degrees(double v) {

        double V = ((v*180)/(M_PI));    //Transforma o valor de entrada para graus
        if ((V >= 360) || (V <= -360)) V = V%360;
        if (V < 0) V = 360+V;
        return V;

    }

    //Função Seno
    double uSin(double v) {

        return (sin(rad_to_degrees(v)));
    }

    //Função Cosseno
    double uCos(double v) {

        return (cos(rad_to_degrees(v)));
    }

    //Função Tangente
    double uTan(double v) {

        double V = rad_to_degrees(v);

        if ((V == 90)||(V == 270))
            return 0;
        else
            return (tan(V));
    }

    //=====================SOLUCIONADOR DE EQUAÇÕES=======================//

    //Solucionador de equações de aridade 1
    double func1_solver(int F_id, double v) {

        switch (F_id) {
            case LN:
                return uLn(v);
            case EXP:
                return uExp(v);
            case SQRT:
                return uSqrt(v);
            case SIN:
                return uSin(v);
            case COS:
                return uCos(v);
            case TAN:
                return tan(v);
            default:
                std::cout << "ERRO FUNC1 SOLVER" << std::endl;
                return -1.0;
        }
    }

    //Solucionador de equações de aridaade 2
    double func2_solver(int F_id, double v1, double v2) {

        switch (F_id) {
            case ADD:
                return uAdd(v1, v2);
            case SUB:
                return uSub(v1, v2);
            case MULT:
                return uMult(v1, v2);
            case DIV:
                return uDiv(v1, v2);
            case POW:
                return uPow(v1, v2);
            default:
                std::cout << "ERRO FUNC2 SOLVER" << std::endl;
                return -1.0;
        }
    }
}
<commit_msg>1.2.3 Casting para funcionar o % em rad_to_deg<commit_after>//utils.cpp
#include <cmath>
#include <iostream>

#include "utils.hpp"

namespace utils{

    DataPoint::DataPoint(std::vector<double> x, double y = 0.0){

        if (x.size()==0){
            this->x.push_back(0.0);
        }
        else {
            for(int i=0; i<x.size(); i++){
                this->x.push_back(x.at(i));
            }
        }

        this->y = y;
    }

    //=========================FUNÇÕES BINÁRIAS===========================//

    //Função Soma
    double uAdd(double v1, double v2) {

        return (v1 + v2);
    }

    //Função Subtração
    double uSub(double v1, double v2) {

        return (v1 - v2);
    }

    //Função Multiplicação
    double uMult(double v1, double v2) {

        return (v1 * v2);
    }

    //Função Divisão
    double uDiv(double v1, double v2) {

        if (v2 == 0)
            return 0;   //Padrão
        else
            return (v1 / v2);
    }

    //Função Potência
    double uPow(double v1, double v2) {

        if ((v1 == 0)&&(v2 == 0))
            return 0;   //Padrão - Equivalente matemático a 0/0
        else
            return pow(v1, v2);
    }

    //==========================FUNÇÕES UNÁRIAS===========================//

    //Função Exponencial (e^v)
    double uExp(double v) {

        return (exp(v));
    }

    //Função Raiz Quadrada
    double uSqrt(double v) {

        if (v < 0)
            return 0;
        else
            return (sqrt(v));
    }

    //Função Logaritmo Neperiano
    double uLn(double v) {

        if (v > 0)
            return (log(v));
        else
            return 0;
    }

    //Converter radianos em graus para poder utilizar as funções trigonométricas
    double rad_to_degrees(double v) {

        double V = ((v*180)/(M_PI));    //Transforma o valor de entrada para graus
        if ((V >= 360) || (V <= -360)) V = (int)V%360;
        if (V < 0) V = 360+V;
        return V;

    }

    //Função Seno
    double uSin(double v) {

        return (sin(rad_to_degrees(v)));
    }

    //Função Cosseno
    double uCos(double v) {

        return (cos(rad_to_degrees(v)));
    }

    //Função Tangente
    double uTan(double v) {

        double V = rad_to_degrees(v);

        if ((V == 90)||(V == 270))
            return 0;
        else
            return (tan(V));
    }

    //=====================SOLUCIONADOR DE EQUAÇÕES=======================//

    //Solucionador de equações de aridade 1
    double func1_solver(int F_id, double v) {

        switch (F_id) {
            case LN:
                return uLn(v);
            case EXP:
                return uExp(v);
            case SQRT:
                return uSqrt(v);
            case SIN:
                return uSin(v);
            case COS:
                return uCos(v);
            case TAN:
                return tan(v);
            default:
                std::cout << "ERRO FUNC1 SOLVER" << std::endl;
                return -1.0;
        }
    }

    //Solucionador de equações de aridaade 2
    double func2_solver(int F_id, double v1, double v2) {

        switch (F_id) {
            case ADD:
                return uAdd(v1, v2);
            case SUB:
                return uSub(v1, v2);
            case MULT:
                return uMult(v1, v2);
            case DIV:
                return uDiv(v1, v2);
            case POW:
                return uPow(v1, v2);
            default:
                std::cout << "ERRO FUNC2 SOLVER" << std::endl;
                return -1.0;
        }
    }
}
<|endoftext|>


<commit_before>#ifndef __NODE_MAPNIK_UTILS_H__
#define __NODE_MAPNIK_UTILS_H__

// v8
#include <v8.h>

// node
#include <node.h>

// stl
#include <string>

// core types
#include <mapnik/unicode.hpp>
#include <mapnik/value.hpp>

// boost
#include <boost/variant/static_visitor.hpp>

#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))

#define FUNCTION_ARG(I, VAR)                                            \
  if (args.Length() <= (I) || !args[I]->IsFunction())                   \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be a function")));  \
  Local<Function> VAR = Local<Function>::Cast(args[I]);

#define ATTR(t, name, get, set) \
  t->InstanceTemplate()->SetAccessor(String::NewSymbol(name), get, set);

using namespace v8;
using namespace node;

namespace node_mapnik {

// adapted to work for both mapnik features and mapnik parameters
struct params_to_object : public boost::static_visitor<>
{
public:
    params_to_object( Local<Object>& ds, std::string key):
        ds_(ds),
        key_(key) {}

    void operator () ( int val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Integer::New(val) );
    }

    void operator () ( bool val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Boolean::New(val) );
    }

    void operator () ( double val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Number::New(val) );
    }

    void operator () ( std::string const& val )
    {

        ds_->Set(String::NewSymbol(key_.c_str()), String::New(val.c_str()) );
    }

    void operator () ( UnicodeString const& val)
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        ds_->Set(String::NewSymbol(key_.c_str()), String::New(buffer.c_str()) );
    }

    void operator () ( mapnik::value_null const& val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Undefined() );
    }

private:
    Local<Object>& ds_;
    std::string key_;
};

struct value_converter: public boost::static_visitor<Local<Value> >
{
    Local<Value> operator () ( int val ) const
    {
        return Integer::New(val);
    }

    Local<Value> operator () ( double val ) const
    {
        return Number::New(val);
    }

    Local<Value> operator () ( std::string const& val ) const
    {

        return String::New(val.c_str());
    }

    Local<Value> operator () ( UnicodeString const& val) const
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        return String::New(buffer.c_str());
    }

    Local<Value> operator () ( mapnik::value_null const& val ) const
    {
        return String::New("");//Undefined();
    }
};

}
#endif
<commit_msg>fixup visitor for mapnik::value<commit_after>#ifndef __NODE_MAPNIK_UTILS_H__
#define __NODE_MAPNIK_UTILS_H__

// v8
#include <v8.h>

// node
#include <node.h>

// stl
#include <string>

// core types
#include <mapnik/unicode.hpp>
#include <mapnik/value.hpp>

// boost
#include <boost/variant/static_visitor.hpp>

#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))

#define FUNCTION_ARG(I, VAR)                                            \
  if (args.Length() <= (I) || !args[I]->IsFunction())                   \
    return ThrowException(Exception::TypeError(                         \
                  String::New("Argument " #I " must be a function")));  \
  Local<Function> VAR = Local<Function>::Cast(args[I]);

#define ATTR(t, name, get, set) \
  t->InstanceTemplate()->SetAccessor(String::NewSymbol(name), get, set);

using namespace v8;
using namespace node;

namespace node_mapnik {

// adapted to work for both mapnik features and mapnik parameters
struct params_to_object : public boost::static_visitor<>
{
public:
    params_to_object( Local<Object>& ds, std::string key):
        ds_(ds),
        key_(key) {}

    void operator () ( int val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Integer::New(val) );
    }

    void operator () ( bool val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Boolean::New(val) );
    }

    void operator () ( double val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Number::New(val) );
    }

    void operator () ( std::string const& val )
    {

        ds_->Set(String::NewSymbol(key_.c_str()), String::New(val.c_str()) );
    }

    void operator () ( UnicodeString const& val)
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        ds_->Set(String::NewSymbol(key_.c_str()), String::New(buffer.c_str()) );
    }

    void operator () ( mapnik::value_null const& val )
    {
        ds_->Set(String::NewSymbol(key_.c_str()), Undefined() );
    }

private:
    Local<Object>& ds_;
    std::string key_;
};

struct value_converter: public boost::static_visitor<Handle<Value> >
{
    Handle<Value> operator () ( int val ) const
    {
        return Integer::New(val);
    }

    Handle<Value> operator () ( bool val ) const
    {
        return Boolean::New(val);
    }

    Handle<Value> operator () ( double val ) const
    {
        return Number::New(val);
    }

    Handle<Value> operator () ( std::string const& val ) const
    {
        return String::New(val.c_str());
    }

    Handle<Value> operator () ( UnicodeString const& val) const
    {
        std::string buffer;
        mapnik::to_utf8(val,buffer);
        return String::New(buffer.c_str());
    }

    Handle<Value> operator () ( mapnik::value_null const& val ) const
    {
        return Undefined();
    }
};

}
#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <sys/time.h>
using namespace std;

// Quicksort
void quickSort(int a[], int p, int r);
int partition(int a[], int p, int r);

// BubbleSort
void bubbleSort(int array[]);

// InsertionSort
void insertionSort(int arr[], int length);

// Get unsorted lists of integers
void getList(int array[], int sizeInt, char sizeChar[], int listNum);

// Print array contents
void printList(int array[]);

int main(int argc, char** argv)
{
	int sizes[6] = {10,50,100,500,1000,5000}; // the sizes of lists
	int sizeInt = sizes[4];
	char sizeChar[50];
    	int array[sizeInt + 1]; // creates array to hold names
	sprintf (sizeChar, "%d", sizeInt);
	int listNum = 1; // 1-1000
	ofstream outFile;
  	outFile.open ("output.txt");
  	outFile << "n, BubbleSort, QuickSort, InsertionSort, MergeSort\n";
    /*
       cout << "unsorted list:\n{";
       printList(array);
       cout << "}\n";
     */

    timeval t1;
    timeval t2;

while (listNum <= 1000)
{
 	getList(array, sizeInt, sizeChar, listNum);
	// Bubble Sort
	gettimeofday(&t1, NULL);
 	bubbleSort(array);
	gettimeofday(&t2, NULL);

    /*
       cout << "bubbleSorted list:\n{";
       printList(array);
       cout << "}\n";

     */
    	//cout << "t1: " << t1.tv_usec << ", t2: " << t2.tv_usec << endl;
//	cout << "bubbleSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
 	outFile << sizeInt << "," << t2.tv_usec - t1.tv_usec << ",";
	getList(array, sizeInt, sizeChar, listNum);
    /*
 	cout << "unsorted list:\n{";
	printList(array);
 	cout << "}\n";
     */

    // Quick Sort
 	gettimeofday(&t1, NULL);
 	quickSort(array, 0, 1000);
	gettimeofday(&t2, NULL);

    /*
       cout << "quickSorted list:\n{";
       printList(array);
       cout << "}\n";

       cout << "t1: " << t1 << ", t2: " << t2 << endl;
     */
//	cout << "quickSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
	outFile << t2.tv_usec - t1.tv_usec << ",";

	getList(array, sizeInt, sizeChar, listNum);
	/*
	cout << "unSorted list:\n{";
    	printList(array);
    	cout << "}\n";
	*/

	gettimeofday(&t1, NULL);
	insertionSort(array, sizeInt);
	gettimeofday(&t2, NULL);

	/*
    cout << "insertionSorted list:\n{";
    printList(array);
    cout << "}\n";
	*/

//	cout << "insertionSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
	outFile << t2.tv_usec - t1.tv_usec << "\n";
	++listNum;
}

    outFile.close();
    return 0;
}

void bubbleSort(int array[])
{
    int swap;
    do{
        swap = 0;
        int n = 1;
        while (array[n] != '\0')
        {
            if (array[n-1] > array[n])
            {
                swap = 1;
                int temp = array[n-1];
                array[n-1] = array[n];
                array[n] = temp;
            }
            ++n;
        }
    }while(swap == 1);
}

int partition(int a[], int p, int r) {
    int x = a[r];
    int j = p - 1;
    for (int i = p; i < r; i++) {

        if (x <= a[i]) {
            j = j + 1;
            int temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
    }
    a[r] = a[j + 1];
    a[j + 1] = x;

    return (j + 1);
}

void quickSort(int a[], int p, int r) {
    if (p < r) {
        int q = partition(a, p, r);
        quickSort(a, p, q - 1);
        quickSort(a, q + 1, r);
    }
}

void getList(int array[], int sizeInt, char sizeChar[], int listNum)
{
    	int n = 0;
	char listChar[50];
	char pathName[50];
	strcpy (pathName, "../../size");
	strcat(pathName, sizeChar);
	strcat(pathName, "/");
	strcat(pathName, "list");
        sprintf (listChar, "%d", listNum);
	strcat(pathName, listChar);
    ifstream myfile (pathName); //opening the file.
    if(myfile.is_open()) //if the file is open
    {
        while (!myfile.eof() && (n < sizeInt)) //while the end of file is NOT reached
        {
            myfile >> array[n];
            n++;
        }
        array[n] = '\0';
        myfile.close(); //closing the file

    }
    else {
      cerr << "Unable to open file\n"; //if the file is not open output
      exit(0);
    }
}

void printList(int array[])
{
    int n = 0;
    while (array[n] != '\0')
    {
        cout << array[n] << ", ";
        ++n;
    }
}

void insertionSort(int arr[], int length)
{

    int i, j, tmp;
    for (i = 1; i < length; i++)
    {
        j = i;
        while (j > 0 && arr[j - 1] > arr[j])
        {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            j--;

        }

    }

}
<commit_msg>cleaned up some inconsistent indentation<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <sys/time.h>
using namespace std;

// Quicksort
void quickSort(int a[], int p, int r);
int partition(int a[], int p, int r);

// BubbleSort
void bubbleSort(int array[]);

// InsertionSort
void insertionSort(int arr[], int length);

// Get unsorted lists of integers
void getList(int array[], int sizeInt, char sizeChar[], int listNum);

// Print array contents
void printList(int array[]);

int main(int argc, char** argv)
{
    int sizes[6] = {10,50,100,500,1000,5000}; // the sizes of lists
    int sizeInt = sizes[4];
    char sizeChar[50];
        int array[sizeInt + 1]; // creates array to hold names
    sprintf (sizeChar, "%d", sizeInt);
    int listNum = 1; // 1-1000
    ofstream outFile;
      outFile.open ("output.txt");
      outFile << "n, BubbleSort, QuickSort, InsertionSort, MergeSort\n";
    /*
       cout << "unsorted list:\n{";
       printList(array);
       cout << "}\n";
     */

    timeval t1;
    timeval t2;

    while (listNum <= 1000)
    {
        getList(array, sizeInt, sizeChar, listNum);
        // Bubble Sort
        gettimeofday(&t1, NULL);
        bubbleSort(array);
        gettimeofday(&t2, NULL);

    /*
       cout << "bubbleSorted list:\n{";
       printList(array);
       cout << "}\n";

     */
        //cout << "t1: " << t1.tv_usec << ", t2: " << t2.tv_usec << endl;
//    cout << "bubbleSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << sizeInt << "," << t2.tv_usec - t1.tv_usec << ",";
        getList(array, sizeInt, sizeChar, listNum);
    /*
     cout << "unsorted list:\n{";
    printList(array);
     cout << "}\n";
     */

    // Quick Sort
        gettimeofday(&t1, NULL);
        quickSort(array, 0, 1000);
        gettimeofday(&t2, NULL);

    /*
       cout << "quickSorted list:\n{";
       printList(array);
       cout << "}\n";

       cout << "t1: " << t1 << ", t2: " << t2 << endl;
     */
//    cout << "quickSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << t2.tv_usec - t1.tv_usec << ",";

        getList(array, sizeInt, sizeChar, listNum);
    /*
    cout << "unSorted list:\n{";
        printList(array);
        cout << "}\n";
    */

        gettimeofday(&t1, NULL);
        insertionSort(array, sizeInt);
        gettimeofday(&t2, NULL);

    /*
    cout << "insertionSorted list:\n{";
    printList(array);
    cout << "}\n";
    */

//    cout << "insertionSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << t2.tv_usec - t1.tv_usec << "\n";
        ++listNum;
    }
    outFile.close();
    return 0;
}

void bubbleSort(int array[])
{
    int swap;
    do{
        swap = 0;
        int n = 1;
        while (array[n] != '\0')
        {
            if (array[n-1] > array[n])
            {
                swap = 1;
                int temp = array[n-1];
                array[n-1] = array[n];
                array[n] = temp;
            }
            ++n;
        }
    }while(swap == 1);
}

int partition(int a[], int p, int r) {
    int x = a[r];
    int j = p - 1;
    for (int i = p; i < r; i++) {

        if (x <= a[i]) {
            j = j + 1;
            int temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
    }
    a[r] = a[j + 1];
    a[j + 1] = x;

    return (j + 1);
}

void quickSort(int a[], int p, int r) {
    if (p < r) {
        int q = partition(a, p, r);
        quickSort(a, p, q - 1);
        quickSort(a, q + 1, r);
    }
}

void getList(int array[], int sizeInt, char sizeChar[], int listNum)
{
    int n = 0;
    char listChar[50];
    char pathName[50];
    strcpy (pathName, "../../size");
    strcat(pathName, sizeChar);
    strcat(pathName, "/");
    strcat(pathName, "list");
    sprintf (listChar, "%d", listNum);
    strcat(pathName, listChar);
    ifstream myfile (pathName); //opening the file.
    if(myfile.is_open()) //if the file is open
    {
        while (!myfile.eof() && (n < sizeInt)) //while the end of file is NOT reached
        {
            myfile >> array[n];
            n++;
        }
        array[n] = '\0';
        myfile.close(); //closing the file

    }
    else {
        cerr << "Unable to open file\n"; //if the file is not open output
        exit(0);
    }
}

void printList(int array[])
{
    int n = 0;
    while (array[n] != '\0')
    {
        cout << array[n] << ", ";
        ++n;
    }
}

void insertionSort(int arr[], int length)
{
    int i, j, tmp;
    for (i = 1; i < length; i++)
    {
        j = i;
        while (j > 0 && arr[j - 1] > arr[j])
        {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            j--;
        }
    }
}
<|endoftext|>


<commit_before>/* $Id$ */
# ifndef CPPAD_REVERSE_INCLUDED
# define CPPAD_REVERSE_INCLUDED

/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*
$begin Reverse$$
$spell
	typename
	xk
	xp
	dw
	Ind
	uj
	std
	arg
	const
	taylor_
$$

$section Reverse Mode$$

$childtable%
	omh/reverse.omh
%$$

$end
-----------------------------------------------------------------------------
*/
# include <algorithm>
# include <cppad/local/pod_vector.hpp>

CPPAD_BEGIN_NAMESPACE
/*!
\file reverse.hpp
Compute derivatives using reverse mode.
*/

/*!
Use reverse mode to compute derivative of forward mode Taylor coefficients.

The function
\f$ X : {\rm R} \times {\rm R}^{n \times p} \rightarrow {\rm R} \f$
is defined by
\f[
X(t , u) = \sum_{k=0}^{p-1} u^{(k)} t^k
\f]
The function
\f$ Y : {\rm R} \times {\rm R}^{n \times p} \rightarrow {\rm R} \f$
is defined by
\f[
Y(t , u) = F[ X(t, u) ]
\f]
The function
\f$ W : {\rm R}^{n \times p} \rightarrow {\rm R} \f$ is defined by
\f[
W(u) = \sum_{k=0}^{p-1} ( w^{(k)} )^{\rm T}
\frac{1}{k !} \frac{ \partial^k } { t^k } Y(0, u)
\f]

\tparam Base
base type for the operator; i.e., this operation sequence was recorded
using AD< \a Base > and computations by this routine are done using type
\a Base.

\tparam VectorBase
is a Simple Vector class with elements of type \a Base.

\param p
is the number of the number of Taylor coefficients that are being
differentiated (per variable).

\param w
is the weighting for each of the Taylor coefficients corresponding
to dependent variables.
If the argument \a w has size <tt>m * p </tt>,
for \f$ k = 0 , \ldots , p-1 \f$ and \f$ i = 0, \ldots , m-1 \f$,
\f[
	w_i^{(k)} = w [ i * p + k ]
\f]
If the argument \a w has size \c m ,
for \f$ k = 0 , \ldots , p-1 \f$ and \f$ i = 0, \ldots , m-1 \f$,
\f[
w_i^{(k)} = \left\{ \begin{array}{ll}
	w [ i ] & {\rm if} \; k = p-1
	\\
	0       & {\rm otherwise}
\end{array} \right.
\f]

\return
Is a vector \f$ dw \f$ such that
for \f$ j = 0 , \ldots , n-1 \f$ and
\f$ k = 0 , \ldots , p-1 \f$
\f[
	dw[ j * p + k ] = W^{(1)} ( x )_{j,k}
\f]
where the matrix \f$ x \f$ is the value for \f$ u \f$
that corresponding to the forward mode Taylor coefficients
for the independent variables as specified by previous calls to Forward.

*/
template <typename Base>
template <typename VectorBase>
VectorBase ADFun<Base>::Reverse(size_t p, const VectorBase &w)
{	// constants
	const Base zero(0);

	// temporary indices
	size_t i, j, k;

	// number of independent variables
	size_t n = ind_taddr_.size();

	// number of dependent variables
	size_t m = dep_taddr_.size();

	pod_vector<Base> Partial;
	Partial.extend(total_num_var_ * p);

	// update maximum memory requirement
	// memoryMax = std::max( memoryMax,
	// 	Memory() + total_num_var_ * p * sizeof(Base)
	// );

	// check VectorBase is Simple Vector class with Base type elements
	CheckSimpleVector<Base, VectorBase>();

	CPPAD_ASSERT_KNOWN(
		size_t(w.size()) == m || size_t(w.size()) == (m * p),
		"Argument w to Reverse does not have length equal to\n"
		"the dimension of the range for the corresponding ADFun."
	);
	CPPAD_ASSERT_KNOWN(
		p > 0,
		"The first argument to Reverse must be greater than zero."
	);
	CPPAD_ASSERT_KNOWN(
		taylor_per_var_ >= p,
		"Less that p taylor_ coefficients are currently stored"
		" in this ADFun object."
	);

	// initialize entire Partial matrix to zero
	for(i = 0; i < total_num_var_; i++)
		for(j = 0; j < p; j++)
			Partial[i * p + j] = zero;

	// set the dependent variable direction
	// (use += because two dependent variables can point to same location)
	for(i = 0; i < m; i++)
	{	CPPAD_ASSERT_UNKNOWN( dep_taddr_[i] < total_num_var_ );
		if( size_t(w.size()) == m )
			Partial[dep_taddr_[i] * p + p - 1] += w[i];
		else
		{	for(k = 0; k < p; k++)
				// ? should use += here, first make test to demonstrate bug
				Partial[ dep_taddr_[i] * p + k ] = w[i * p + k ];
		}
	}

	// evaluate the derivatives
	ReverseSweep(
		p - 1,
		n,
		total_num_var_,
		&play_,
		taylor_col_dim_,
		taylor_.data(),
		p,
		Partial.data()
	);

	// return the derivative values
	VectorBase value(n * p);
	for(j = 0; j < n; j++)
	{	CPPAD_ASSERT_UNKNOWN( ind_taddr_[j] < total_num_var_ );

		// independent variable taddr equals its operator taddr
		CPPAD_ASSERT_UNKNOWN( play_.GetOp( ind_taddr_[j] ) == InvOp );

		// by the Reverse Identity Theorem
		// partial of y^{(k)} w.r.t. u^{(0)} is equal to
		// partial of y^{(p-1)} w.r.t. u^{(p - 1 - k)}
		if( size_t(w.size()) == m )
		{	for(k = 0; k < p; k++)
				value[j * p + k ] =
					Partial[ind_taddr_[j] * p + p - 1 - k];
		}
		else
		{	for(k = 0; k < p; k++)
				value[j * p + k ] =
					Partial[ind_taddr_[j] * p + k];
		}
	}

	return value;
}

} // END CppAD namespace

# endif
<commit_msg>Use CPPAD_END_NAMESPACE to match CPPAD_BEGIN_NAMESPACE (prepare for automatic edit).<commit_after>/* $Id$ */
# ifndef CPPAD_REVERSE_INCLUDED
# define CPPAD_REVERSE_INCLUDED

/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*
$begin Reverse$$
$spell
	typename
	xk
	xp
	dw
	Ind
	uj
	std
	arg
	const
	taylor_
$$

$section Reverse Mode$$

$childtable%
	omh/reverse.omh
%$$

$end
-----------------------------------------------------------------------------
*/
# include <algorithm>
# include <cppad/local/pod_vector.hpp>

CPPAD_BEGIN_NAMESPACE
/*!
\file reverse.hpp
Compute derivatives using reverse mode.
*/

/*!
Use reverse mode to compute derivative of forward mode Taylor coefficients.

The function
\f$ X : {\rm R} \times {\rm R}^{n \times p} \rightarrow {\rm R} \f$
is defined by
\f[
X(t , u) = \sum_{k=0}^{p-1} u^{(k)} t^k
\f]
The function
\f$ Y : {\rm R} \times {\rm R}^{n \times p} \rightarrow {\rm R} \f$
is defined by
\f[
Y(t , u) = F[ X(t, u) ]
\f]
The function
\f$ W : {\rm R}^{n \times p} \rightarrow {\rm R} \f$ is defined by
\f[
W(u) = \sum_{k=0}^{p-1} ( w^{(k)} )^{\rm T}
\frac{1}{k !} \frac{ \partial^k } { t^k } Y(0, u)
\f]

\tparam Base
base type for the operator; i.e., this operation sequence was recorded
using AD< \a Base > and computations by this routine are done using type
\a Base.

\tparam VectorBase
is a Simple Vector class with elements of type \a Base.

\param p
is the number of the number of Taylor coefficients that are being
differentiated (per variable).

\param w
is the weighting for each of the Taylor coefficients corresponding
to dependent variables.
If the argument \a w has size <tt>m * p </tt>,
for \f$ k = 0 , \ldots , p-1 \f$ and \f$ i = 0, \ldots , m-1 \f$,
\f[
	w_i^{(k)} = w [ i * p + k ]
\f]
If the argument \a w has size \c m ,
for \f$ k = 0 , \ldots , p-1 \f$ and \f$ i = 0, \ldots , m-1 \f$,
\f[
w_i^{(k)} = \left\{ \begin{array}{ll}
	w [ i ] & {\rm if} \; k = p-1
	\\
	0       & {\rm otherwise}
\end{array} \right.
\f]

\return
Is a vector \f$ dw \f$ such that
for \f$ j = 0 , \ldots , n-1 \f$ and
\f$ k = 0 , \ldots , p-1 \f$
\f[
	dw[ j * p + k ] = W^{(1)} ( x )_{j,k}
\f]
where the matrix \f$ x \f$ is the value for \f$ u \f$
that corresponding to the forward mode Taylor coefficients
for the independent variables as specified by previous calls to Forward.

*/
template <typename Base>
template <typename VectorBase>
VectorBase ADFun<Base>::Reverse(size_t p, const VectorBase &w)
{	// constants
	const Base zero(0);

	// temporary indices
	size_t i, j, k;

	// number of independent variables
	size_t n = ind_taddr_.size();

	// number of dependent variables
	size_t m = dep_taddr_.size();

	pod_vector<Base> Partial;
	Partial.extend(total_num_var_ * p);

	// update maximum memory requirement
	// memoryMax = std::max( memoryMax,
	// 	Memory() + total_num_var_ * p * sizeof(Base)
	// );

	// check VectorBase is Simple Vector class with Base type elements
	CheckSimpleVector<Base, VectorBase>();

	CPPAD_ASSERT_KNOWN(
		size_t(w.size()) == m || size_t(w.size()) == (m * p),
		"Argument w to Reverse does not have length equal to\n"
		"the dimension of the range for the corresponding ADFun."
	);
	CPPAD_ASSERT_KNOWN(
		p > 0,
		"The first argument to Reverse must be greater than zero."
	);
	CPPAD_ASSERT_KNOWN(
		taylor_per_var_ >= p,
		"Less that p taylor_ coefficients are currently stored"
		" in this ADFun object."
	);

	// initialize entire Partial matrix to zero
	for(i = 0; i < total_num_var_; i++)
		for(j = 0; j < p; j++)
			Partial[i * p + j] = zero;

	// set the dependent variable direction
	// (use += because two dependent variables can point to same location)
	for(i = 0; i < m; i++)
	{	CPPAD_ASSERT_UNKNOWN( dep_taddr_[i] < total_num_var_ );
		if( size_t(w.size()) == m )
			Partial[dep_taddr_[i] * p + p - 1] += w[i];
		else
		{	for(k = 0; k < p; k++)
				// ? should use += here, first make test to demonstrate bug
				Partial[ dep_taddr_[i] * p + k ] = w[i * p + k ];
		}
	}

	// evaluate the derivatives
	ReverseSweep(
		p - 1,
		n,
		total_num_var_,
		&play_,
		taylor_col_dim_,
		taylor_.data(),
		p,
		Partial.data()
	);

	// return the derivative values
	VectorBase value(n * p);
	for(j = 0; j < n; j++)
	{	CPPAD_ASSERT_UNKNOWN( ind_taddr_[j] < total_num_var_ );

		// independent variable taddr equals its operator taddr
		CPPAD_ASSERT_UNKNOWN( play_.GetOp( ind_taddr_[j] ) == InvOp );

		// by the Reverse Identity Theorem
		// partial of y^{(k)} w.r.t. u^{(0)} is equal to
		// partial of y^{(p-1)} w.r.t. u^{(p - 1 - k)}
		if( size_t(w.size()) == m )
		{	for(k = 0; k < p; k++)
				value[j * p + k ] =
					Partial[ind_taddr_[j] * p + p - 1 - k];
		}
		else
		{	for(k = 0; k < p; k++)
				value[j * p + k ] =
					Partial[ind_taddr_[j] * p + k];
		}
	}

	return value;
}

CPPAD_END_NAMESPACE
# endif
<|endoftext|>


<commit_before>#pragma once
#include <algorithm>
#include <initializer_list>
#include <stdexcept>
#include <utility>
#include <vector>

#include "base/helpers.hpp"
#include "is_equal_to_zero.hpp"
#include "maths.hpp"
#include "random.hpp"

struct maximal_element_search_tag {};
struct prime_modulo_calculations_tag {};

template<typename T>
class Matrix {
public:
	using value_type = T;
	using size_type = std::size_t;

	using vector_container_type = std::vector<value_type>;
	using matrix_container_type = std::vector<vector_container_type>;

	Matrix(const size_type rows_cnt, const size_type cols_cnt, const value_type mod = 1000000007) :
			rows_cnt_(rows_cnt),
			cols_cnt_(cols_cnt),
			data_(rows_cnt, vector_container_type(cols_cnt, 0)),
			mod_(mod)
	{}

	explicit Matrix(const std::initializer_list<std::initializer_list<value_type>>& initializer_list, const value_type mod = 1000000007) :
			rows_cnt_(initializer_list.size()),
			cols_cnt_(0),
			mod_(mod)
	{
		data_.reserve(initializer_list.size());
		for (const auto& row : initializer_list) {
			if (data_.empty()) {
				cols_cnt_ = row.size();
			} else {
				if (cols_cnt_ != row.size()) {
					throw std::out_of_range("Matrix<T> initializer list must have rows of the same size");
				}
			}
			data_.emplace_back(row);
		}
	}

	template<typename U>
	Matrix(const Matrix<U>& matrix) :
			rows_cnt_(matrix.rows_cnt()),
			cols_cnt_(matrix.cols_cnt()),
			data_(matrix.rows_cnt(), vector_container_type(matrix.cols_cnt()))
	{
		for (size_type i = 0; i < rows_cnt_; ++i) {
			for (size_type j = 0; j < cols_cnt_; ++j) {
				data_[i][j] = static_cast<value_type>(matrix[i][j]);
			}
		}
	}

	size_type get_matrix_rank() const;
	size_type get_matrix_rank(maximal_element_search_tag) const;
	size_type get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const;

	void swap_rows(const size_type i, const size_type j) {
		data_[i].swap(data_[j]);
	}

	void swap_cols(const size_type i, const size_type j) {
		for (auto& row : data_) {
			std::swap(row[i], row[j]);
		}
	}

	void shuffle() {
		shuffle_rows();
		shuffle_cols();
	}

	void shuffle_cols() {
		matrix_container_type tmp(rows_cnt_, cols_cnt_);
		std::vector<size_type> indices(cols_cnt_);
		for (size_type i = 0; i < cols_cnt_; ++i) {
			indices[i] = i;
		}
		std::shuffle(indices.begin(), indices.end(), Random::random_engine());
		for (size_type j = 0; j < cols_cnt_; ++j) {
			size_type index = indices[j];
			for (size_type row = 0; row < rows_cnt_; ++row) {
				tmp[row][j] = data_[row][index];
			}
		}
		data_.swap(tmp);
	}

	void shuffle_rows() {
		matrix_container_type tmp;
		tmp.reserve(rows_cnt_);
		std::vector<size_type> indices(rows_cnt_);
		for (size_type i = 0; i < rows_cnt_; ++i) {
			indices[i] = i;
		}
		std::shuffle(indices.begin(), indices.end(), Random::random_engine());
		for (const auto& index : indices) {
			tmp.emplace_back(data_[index]);
		}
		data_.swap(tmp);
	}

	typename matrix_container_type::iterator begin() {
		return data_.begin();
	}

	typename matrix_container_type::const_iterator begin() const {
		return data_.begin();
	}

	typename matrix_container_type::iterator end() {
		return data_.end();
	}

	typename matrix_container_type::const_iterator end() const {
		return data_.end();
	}

	vector_container_type get_column(const size_type index) const {
		vector_container_type column;
		column.reserve(rows_cnt_);
		for (const auto& row : data_) {
			column.emplace_back(row[index]);
		}
		return column;
	}

	vector_container_type& operator [](const size_type index) {
		return data_[index];
	}

	const vector_container_type& operator [](const size_type index) const {
		return data_[index];
	}

	constexpr size_type rows_cnt() const {
		return rows_cnt_;
	}

	constexpr size_type cols_cnt() const {
		return cols_cnt_;
	}

	Matrix operator *(const Matrix& rhs) const {
		Matrix result(rows_cnt_, rhs.cols_cnt_);
		for (size_type i = 0; i < rows_cnt_; i++) {
			for (size_type k = 0; k < rhs.cols_cnt_; k++) {
				for (size_type j = 0; j < rhs.rows_cnt_; j++) {
					result[i][k] += data_[i][j] * rhs[j][k];
				}
			}
		}
		return result;
	}

	Matrix& operator *=(const Matrix& rhs) {
		Matrix result = operator *(rhs);
		swap(result);
		return *this;
	}

	template<typename U>
	Matrix binpow(U b) const {
		static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow.");
		Matrix ret = identity_matrix(rows_cnt_, cols_cnt_);
		Matrix a = *this;
		while (b != 0) {
			if ((b & 1) != 0) {
				ret *= a;
			}
			a *= a;
			b >>= 1;
		}
		return ret;
	}

	void swap(Matrix& rhs) {
		data_.swap(rhs.data_);
		std::swap(mod_, rhs.mod_);
		std::swap(rows_cnt_, rhs.rows_cnt_);
		std::swap(cols_cnt_, rhs.cols_cnt_);
	}

	static Matrix identity_matrix(const size_type rows_cnt, const size_type cols_cnt) {
		Matrix result(rows_cnt, cols_cnt);
		for (size_type i = 0; i < std::min(rows_cnt, cols_cnt); ++i) {
			result[i][i] = 1;
		}
		return result;
	}

private:
	size_type rows_cnt_;
	size_type cols_cnt_;
	matrix_container_type data_;

	value_type mod_;
};

template <typename T>
typename Matrix<T>::size_type Matrix<T>::get_matrix_rank() const {
	Matrix<long double> tmp(*this);
	std::vector<bool> used(rows_cnt_, false);
	size_type rank = cols_cnt_;
	for (size_type col = 0; col < cols_cnt_; ++col) {
		size_type best_row = std::numeric_limits<size_type>::max();
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (!used[row] && !is_equal_to_zero(tmp[row][col])) {
				best_row = row;
				break;
			}
		}
		if (best_row == std::numeric_limits<size_type>::max()) {
			--rank;
			continue;
		}
		used[best_row] = true;
		for (size_type j = col + 1; j < cols_cnt_; ++j) {
			tmp[best_row][j] /= tmp[best_row][col];
		}
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (used[row] || is_equal_to_zero(tmp[row][col])) {
				continue;
			}
			for (size_type j = col + 1; j < cols_cnt_; ++j) {
				tmp[row][j] -= tmp[best_row][j] * tmp[row][col];
			}
		}
	}
	return rank;
}

template <typename T>
typename Matrix<T>::size_type Matrix<T>::get_matrix_rank(maximal_element_search_tag) const {
	Matrix<long double> tmp(*this);
	std::vector<bool> used(rows_cnt_, false);
	size_type rank = 0;
	for (size_type col = 0; col < cols_cnt_; ++col) {
		value_type max_value = EPS;
		size_type best_row = std::numeric_limits<size_type>::max();
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (!used[row] && umax(max_value, abs(tmp[row][col]))) {
				best_row = row;
			}
		}
		if (best_row == std::numeric_limits<size_type>::max()) {
			continue;
		}
		++rank;
		used[best_row] = true;
		for (size_type j = col + 1; j < cols_cnt_; ++j) {
			tmp[best_row][j] /= tmp[best_row][col];
		}
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (used[row] || is_equal_to_zero(tmp[row][col])) {
				continue;
			}
			for (size_type j = col + 1; j < cols_cnt_; ++j) {
				tmp[row][j] -= tmp[best_row][j] * tmp[row][col];
			}
		}
	}
	return rank;
}

template <typename T>
typename Matrix<T>::size_type Matrix<T>::get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const {
	static_assert(std::is_integral<value_type>::value, "Integral type required to process calculations by prime modulo");
	Matrix<long long> tmp(*this);
	for (auto& row : tmp) {
		for (auto& col : row) {
			if (col < 0) {
				col += mod;
			}
		}
	}
	std::vector<bool> used(rows_cnt_, false);
	size_type rank = cols_cnt_;
	for (size_type col = 0; col < cols_cnt_; ++col) {
		size_type best_row = std::numeric_limits<size_type>::max();
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (!used[row] && !is_equal_to_zero(tmp[row][col])) {
				best_row = row;
				break;
			}
		}
		if (best_row == std::numeric_limits<size_type>::max()) {
			--rank;
			continue;
		}
		used[best_row] = true;
		for (size_type j = col + 1; j < cols_cnt_; ++j) {
			mul_mod(tmp[best_row][j], inverseElement(tmp[best_row][col], mod), mod);
		}
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (used[row] || is_equal_to_zero(tmp[row][col])) {
				continue;
			}
			for (size_type j = col + 1; j < cols_cnt_; ++j) {
				long long x = tmp[best_row][j];
				mul_mod(x, tmp[row][col], mod);
				sub_mod(tmp[row][j], x, mod);
			}
		}
	}
	return rank;
}
<commit_msg>Minor refactoring in Matrix class.<commit_after>#pragma once
#include <algorithm>
#include <initializer_list>
#include <stdexcept>
#include <utility>
#include <vector>

#include "base/helpers.hpp"
#include "is_equal_to_zero.hpp"
#include "maths.hpp"
#include "random.hpp"

struct maximal_element_search_tag {};
struct prime_modulo_calculations_tag {};

template<typename T>
class Matrix {
public:
	using value_type = T;
	using size_type = std::size_t;

	using vector_container_type = std::vector<value_type>;
	using matrix_container_type = std::vector<vector_container_type>;

	Matrix(const size_type rows_cnt, const size_type cols_cnt, const value_type mod = 1000000007) :
			rows_cnt_(rows_cnt),
			cols_cnt_(cols_cnt),
			data_(rows_cnt, vector_container_type(cols_cnt, 0)),
			mod_(mod)
	{}

	Matrix(const std::initializer_list<std::initializer_list<value_type>>& initializer_list, const value_type mod = 1000000007) :
			rows_cnt_(initializer_list.size()),
			cols_cnt_(0),
			mod_(mod)
	{
		data_.reserve(initializer_list.size());
		for (const auto& row : initializer_list) {
			if (data_.empty()) {
				cols_cnt_ = row.size();
			} else {
				if (cols_cnt_ != row.size()) {
					throw std::out_of_range("Matrix<T> initializer list must have rows of the same size");
				}
			}
			data_.emplace_back(row);
		}
	}

	template<typename U>
	explicit Matrix(const Matrix<U>& matrix) :
			rows_cnt_(matrix.rows_cnt()),
			cols_cnt_(matrix.cols_cnt()),
			data_(matrix.rows_cnt(), vector_container_type(matrix.cols_cnt()))
	{
		for (size_type i = 0; i < rows_cnt_; ++i) {
			for (size_type j = 0; j < cols_cnt_; ++j) {
				data_[i][j] = static_cast<value_type>(matrix[i][j]);
			}
		}
	}

	size_type get_matrix_rank() const;
	size_type get_matrix_rank(maximal_element_search_tag) const;
	size_type get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const;

	void swap_rows(const size_type i, const size_type j) {
		data_[i].swap(data_[j]);
	}

	void swap_cols(const size_type i, const size_type j) {
		for (auto& row : data_) {
			std::swap(row[i], row[j]);
		}
	}

	void shuffle() {
		shuffle_rows();
		shuffle_cols();
	}

	void shuffle_cols() {
		matrix_container_type tmp(rows_cnt_, cols_cnt_);
		std::vector<size_type> indices(cols_cnt_);
		for (size_type i = 0; i < cols_cnt_; ++i) {
			indices[i] = i;
		}
		std::shuffle(indices.begin(), indices.end(), Random::random_engine());
		for (size_type j = 0; j < cols_cnt_; ++j) {
			size_type index = indices[j];
			for (size_type row = 0; row < rows_cnt_; ++row) {
				tmp[row][j] = data_[row][index];
			}
		}
		data_.swap(tmp);
	}

	void shuffle_rows() {
		matrix_container_type tmp;
		tmp.reserve(rows_cnt_);
		std::vector<size_type> indices(rows_cnt_);
		for (size_type i = 0; i < rows_cnt_; ++i) {
			indices[i] = i;
		}
		std::shuffle(indices.begin(), indices.end(), Random::random_engine());
		for (const auto& index : indices) {
			tmp.emplace_back(data_[index]);
		}
		data_.swap(tmp);
	}

	typename matrix_container_type::iterator begin() {
		return data_.begin();
	}

	typename matrix_container_type::const_iterator begin() const {
		return data_.begin();
	}

	typename matrix_container_type::iterator end() {
		return data_.end();
	}

	typename matrix_container_type::const_iterator end() const {
		return data_.end();
	}

	vector_container_type get_column(const size_type index) const {
		vector_container_type column;
		column.reserve(rows_cnt_);
		for (const auto& row : data_) {
			column.emplace_back(row[index]);
		}
		return column;
	}

	vector_container_type& operator [](const size_type index) {
		return data_[index];
	}

	const vector_container_type& operator [](const size_type index) const {
		return data_[index];
	}

	constexpr size_type rows_cnt() const {
		return rows_cnt_;
	}

	constexpr size_type cols_cnt() const {
		return cols_cnt_;
	}

	Matrix multiply(const Matrix& rhs) const {
		Matrix result(rows_cnt_, rhs.cols_cnt_);
		for (size_type i = 0; i < rows_cnt_; i++) {
			for (size_type k = 0; k < rhs.cols_cnt_; k++) {
				for (size_type j = 0; j < rhs.rows_cnt_; j++) {
					result[i][k] += data_[i][j] * rhs[j][k];
				}
			}
		}
		return result;
	}

	Matrix operator *(const Matrix& rhs) const {
		return multiply(rhs);
	}

	Matrix& operator *=(const Matrix& rhs) {
		Matrix result = multiply(rhs);
		swap(result);
		return *this;
	}

	template<typename U>
	Matrix binpow(U b) const {
		static_assert(std::is_integral<U>::value, "Degree must be integral. For real degree use pow.");
		Matrix ret = identity_matrix(rows_cnt_, cols_cnt_);
		Matrix a = *this;
		while (b != 0) {
			if ((b & 1) != 0) {
				ret *= a;
			}
			a *= a;
			b >>= 1;
		}
		return ret;
	}

	void swap(Matrix& rhs) {
		data_.swap(rhs.data_);
		std::swap(mod_, rhs.mod_);
		std::swap(rows_cnt_, rhs.rows_cnt_);
		std::swap(cols_cnt_, rhs.cols_cnt_);
	}

	static Matrix identity_matrix(const size_type rows_cnt, const size_type cols_cnt) {
		Matrix result(rows_cnt, cols_cnt);
		for (size_type i = 0; i < std::min(rows_cnt, cols_cnt); ++i) {
			result[i][i] = 1;
		}
		return result;
	}

private:
	size_type rows_cnt_;
	size_type cols_cnt_;
	matrix_container_type data_;

	value_type mod_;
};

template <typename T>
typename Matrix<T>::size_type Matrix<T>::get_matrix_rank() const {
	Matrix<long double> tmp(*this);
	std::vector<bool> used(rows_cnt_, false);
	size_type rank = cols_cnt_;
	for (size_type col = 0; col < cols_cnt_; ++col) {
		size_type best_row = std::numeric_limits<size_type>::max();
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (!used[row] && !is_equal_to_zero(tmp[row][col])) {
				best_row = row;
				break;
			}
		}
		if (best_row == std::numeric_limits<size_type>::max()) {
			--rank;
			continue;
		}
		used[best_row] = true;
		for (size_type j = col + 1; j < cols_cnt_; ++j) {
			tmp[best_row][j] /= tmp[best_row][col];
		}
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (used[row] || is_equal_to_zero(tmp[row][col])) {
				continue;
			}
			for (size_type j = col + 1; j < cols_cnt_; ++j) {
				tmp[row][j] -= tmp[best_row][j] * tmp[row][col];
			}
		}
	}
	return rank;
}

template <typename T>
typename Matrix<T>::size_type Matrix<T>::get_matrix_rank(maximal_element_search_tag) const {
	Matrix<long double> tmp(*this);
	std::vector<bool> used(rows_cnt_, false);
	size_type rank = 0;
	for (size_type col = 0; col < cols_cnt_; ++col) {
		value_type max_value = EPS;
		size_type best_row = std::numeric_limits<size_type>::max();
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (!used[row] && umax(max_value, abs(tmp[row][col]))) {
				best_row = row;
			}
		}
		if (best_row == std::numeric_limits<size_type>::max()) {
			continue;
		}
		++rank;
		used[best_row] = true;
		for (size_type j = col + 1; j < cols_cnt_; ++j) {
			tmp[best_row][j] /= tmp[best_row][col];
		}
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (used[row] || is_equal_to_zero(tmp[row][col])) {
				continue;
			}
			for (size_type j = col + 1; j < cols_cnt_; ++j) {
				tmp[row][j] -= tmp[best_row][j] * tmp[row][col];
			}
		}
	}
	return rank;
}

template <typename T>
typename Matrix<T>::size_type Matrix<T>::get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const {
	static_assert(std::is_integral<value_type>::value, "Integral type required to process calculations by prime modulo");
	Matrix<long long> tmp(*this);
	for (auto& row : tmp) {
		for (auto& col : row) {
			if (col < 0) {
				col += mod;
			}
		}
	}
	std::vector<bool> used(rows_cnt_, false);
	size_type rank = cols_cnt_;
	for (size_type col = 0; col < cols_cnt_; ++col) {
		size_type best_row = std::numeric_limits<size_type>::max();
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (!used[row] && !is_equal_to_zero(tmp[row][col])) {
				best_row = row;
				break;
			}
		}
		if (best_row == std::numeric_limits<size_type>::max()) {
			--rank;
			continue;
		}
		used[best_row] = true;
		for (size_type j = col + 1; j < cols_cnt_; ++j) {
			mul_mod(tmp[best_row][j], inverseElement(tmp[best_row][col], mod), mod);
		}
		for (size_type row = 0; row < rows_cnt_; ++row) {
			if (used[row] || is_equal_to_zero(tmp[row][col])) {
				continue;
			}
			for (size_type j = col + 1; j < cols_cnt_; ++j) {
				long long x = tmp[best_row][j];
				mul_mod(x, tmp[row][col], mod);
				sub_mod(tmp[row][j], x, mod);
			}
		}
	}
	return rank;
}
<|endoftext|>


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

#include <string>

#include "cpu/base.hh"
#include "cpu/cpu_exec_context.hh"
#include "cpu/exec_context.hh"

#if FULL_SYSTEM
#include "base/callback.hh"
#include "base/cprintf.hh"
#include "base/output.hh"
#include "base/trace.hh"
#include "cpu/profile.hh"
#include "cpu/quiesce_event.hh"
#include "kern/kernel_stats.hh"
#include "sim/serialize.hh"
#include "sim/sim_exit.hh"
#include "sim/system.hh"
#include "arch/stacktrace.hh"
#else
#include "sim/process.hh"
#endif

using namespace std;

// constructor
#if FULL_SYSTEM
CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, System *_sys,
                         AlphaITB *_itb, AlphaDTB *_dtb,
                         FunctionalMemory *_mem)
    : _status(ExecContext::Unallocated), cpu(_cpu), thread_num(_thread_num),
      cpu_id(-1), lastActivate(0), lastSuspend(0), mem(_mem), itb(_itb),
      dtb(_dtb), system(_sys), memctrl(_sys->memctrl), physmem(_sys->physmem),
      profile(NULL), func_exe_inst(0), storeCondFailures(0)
{
    proxy = new ProxyExecContext<CPUExecContext>(this);

    quiesceEvent = new EndQuiesceEvent(proxy);

    memset(&regs, 0, sizeof(RegFile));

    if (cpu->params->profile) {
        profile = new FunctionProfile(system->kernelSymtab);
        Callback *cb =
            new MakeCallback<CPUExecContext,
            &CPUExecContext::dumpFuncProfile>(this);
        registerExitCallback(cb);
    }

    // let's fill with a dummy node for now so we don't get a segfault
    // on the first cycle when there's no node available.
    static ProfileNode dummyNode;
    profileNode = &dummyNode;
    profilePC = 3;
}
#else
CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num,
                         Process *_process, int _asid)
    : _status(ExecContext::Unallocated),
      cpu(_cpu), thread_num(_thread_num), cpu_id(-1), lastActivate(0),
      lastSuspend(0), process(_process), mem(NULL), asid(_asid),
      func_exe_inst(0), storeCondFailures(0)
{
    memset(&regs, 0, sizeof(RegFile));
    proxy = new ProxyExecContext<CPUExecContext>(this);
}

CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num,
                         FunctionalMemory *_mem, int _asid)
    : cpu(_cpu), thread_num(_thread_num), process(0), mem(NULL), asid(_asid),
      func_exe_inst(0), storeCondFailures(0)
{
    memset(&regs, 0, sizeof(RegFile));
    proxy = new ProxyExecContext<CPUExecContext>(this);
}

CPUExecContext::CPUExecContext(RegFile *regFile)
    : cpu(NULL), thread_num(-1), process(NULL), mem(NULL), asid(-1),
      func_exe_inst(0), storeCondFailures(0)
{
    regs = *regFile;
    proxy = new ProxyExecContext<CPUExecContext>(this);
}

#endif

CPUExecContext::~CPUExecContext()
{
    delete proxy;
}

#if FULL_SYSTEM
void
CPUExecContext::dumpFuncProfile()
{
    std::ostream *os = simout.create(csprintf("profile.%s.dat", cpu->name()));
    profile->dump(proxy, *os);
}

void
CPUExecContext::profileClear()
{
    if (profile)
        profile->clear();
}

void
CPUExecContext::profileSample()
{
    if (profile)
        profile->sample(profileNode, profilePC);
}

#endif

void
CPUExecContext::takeOverFrom(ExecContext *oldContext)
{
    // some things should already be set up
    assert(mem == oldContext->getMemPtr());
#if FULL_SYSTEM
    assert(system == oldContext->getSystemPtr());
#else
    assert(process == oldContext->getProcessPtr());
#endif

    // copy over functional state
    _status = oldContext->status();
    copyArchRegs(oldContext);
    cpu_id = oldContext->readCpuId();
#if !FULL_SYSTEM
    func_exe_inst = oldContext->readFuncExeInst();
#endif

    storeCondFailures = 0;

    oldContext->setStatus(ExecContext::Unallocated);
}

void
CPUExecContext::serialize(ostream &os)
{
    SERIALIZE_ENUM(_status);
    regs.serialize(os);
    // thread_num and cpu_id are deterministic from the config
    SERIALIZE_SCALAR(func_exe_inst);
    SERIALIZE_SCALAR(inst);

#if FULL_SYSTEM
    Tick quiesceEndTick = 0;
    if (quiesceEvent->scheduled())
        quiesceEndTick = quiesceEvent->when();
    SERIALIZE_SCALAR(quiesceEndTick);

#endif
}

void
CPUExecContext::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_ENUM(_status);
    regs.unserialize(cp, section);
    // thread_num and cpu_id are deterministic from the config
    UNSERIALIZE_SCALAR(func_exe_inst);
    UNSERIALIZE_SCALAR(inst);

#if FULL_SYSTEM
    Tick quiesceEndTick;
    UNSERIALIZE_SCALAR(quiesceEndTick);
    if (quiesceEndTick)
        quiesceEvent->schedule(quiesceEndTick);
#endif
}

void
CPUExecContext::activate(int delay)
{
    if (status() == ExecContext::Active)
        return;

    lastActivate = curTick;

    if (status() == ExecContext::Unallocated) {
        cpu->activateWhenReady(thread_num);
        return;
    }

    _status = ExecContext::Active;

    // status() == Suspended
    cpu->activateContext(thread_num, delay);
}

void
CPUExecContext::suspend()
{
    if (status() == ExecContext::Suspended)
        return;

    lastActivate = curTick;
    lastSuspend = curTick;
/*
#if FULL_SYSTEM
    // Don't change the status from active if there are pending interrupts
    if (cpu->check_interrupts()) {
        assert(status() == ExecContext::Active);
        return;
    }
#endif
*/
    _status = ExecContext::Suspended;
    cpu->suspendContext(thread_num);
}

void
CPUExecContext::deallocate()
{
    if (status() == ExecContext::Unallocated)
        return;

    _status = ExecContext::Unallocated;
    cpu->deallocateContext(thread_num);
}

void
CPUExecContext::halt()
{
    if (status() == ExecContext::Halted)
        return;

    _status = ExecContext::Halted;
    cpu->haltContext(thread_num);
}

void
CPUExecContext::regStats(const string &name)
{
}

void
CPUExecContext::copyArchRegs(ExecContext *xc)
{
    // First loop through the integer registers.
    for (int i = 0; i < AlphaISA::NumIntRegs; ++i) {
        setIntReg(i, xc->readIntReg(i));
    }

    // Then loop through the floating point registers.
    for (int i = 0; i < AlphaISA::NumFloatRegs; ++i) {
        setFloatRegDouble(i, xc->readFloatRegDouble(i));
        setFloatRegInt(i, xc->readFloatRegInt(i));
    }

    // Copy misc. registers
    regs.miscRegs.copyMiscRegs(xc);

    // Lastly copy PC/NPC
    setPC(xc->readPC());
    setNextPC(xc->readNextPC());
}

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

#include <string>

#include "cpu/base.hh"
#include "cpu/cpu_exec_context.hh"
#include "cpu/exec_context.hh"

#if FULL_SYSTEM
#include "base/callback.hh"
#include "base/cprintf.hh"
#include "base/output.hh"
#include "base/trace.hh"
#include "cpu/profile.hh"
#include "cpu/quiesce_event.hh"
#include "kern/kernel_stats.hh"
#include "sim/serialize.hh"
#include "sim/sim_exit.hh"
#include "sim/system.hh"
#include "arch/stacktrace.hh"
#else
#include "sim/process.hh"
#endif

using namespace std;

// constructor
#if FULL_SYSTEM
CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num, System *_sys,
                         AlphaITB *_itb, AlphaDTB *_dtb,
                         FunctionalMemory *_mem)
    : _status(ExecContext::Unallocated), cpu(_cpu), thread_num(_thread_num),
      cpu_id(-1), lastActivate(0), lastSuspend(0), mem(_mem), itb(_itb),
      dtb(_dtb), system(_sys), memctrl(_sys->memctrl), physmem(_sys->physmem),
      profile(NULL), func_exe_inst(0), storeCondFailures(0)
{
    proxy = new ProxyExecContext<CPUExecContext>(this);

    quiesceEvent = new EndQuiesceEvent(proxy);

    memset(&regs, 0, sizeof(RegFile));

    if (cpu->params->profile) {
        profile = new FunctionProfile(system->kernelSymtab);
        Callback *cb =
            new MakeCallback<CPUExecContext,
            &CPUExecContext::dumpFuncProfile>(this);
        registerExitCallback(cb);
    }

    // let's fill with a dummy node for now so we don't get a segfault
    // on the first cycle when there's no node available.
    static ProfileNode dummyNode;
    profileNode = &dummyNode;
    profilePC = 3;
}
#else
CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num,
                         Process *_process, int _asid)
    : _status(ExecContext::Unallocated),
      cpu(_cpu), thread_num(_thread_num), cpu_id(-1), lastActivate(0),
      lastSuspend(0), process(_process), mem(process->getMemory()), asid(_asid),
      func_exe_inst(0), storeCondFailures(0)
{
    memset(&regs, 0, sizeof(RegFile));
    proxy = new ProxyExecContext<CPUExecContext>(this);
}

CPUExecContext::CPUExecContext(BaseCPU *_cpu, int _thread_num,
                         FunctionalMemory *_mem, int _asid)
    : cpu(_cpu), thread_num(_thread_num), process(0), mem(NULL), asid(_asid),
      func_exe_inst(0), storeCondFailures(0)
{
    memset(&regs, 0, sizeof(RegFile));
    proxy = new ProxyExecContext<CPUExecContext>(this);
}

CPUExecContext::CPUExecContext(RegFile *regFile)
    : cpu(NULL), thread_num(-1), process(NULL), mem(NULL), asid(-1),
      func_exe_inst(0), storeCondFailures(0)
{
    regs = *regFile;
    proxy = new ProxyExecContext<CPUExecContext>(this);
}

#endif

CPUExecContext::~CPUExecContext()
{
    delete proxy;
}

#if FULL_SYSTEM
void
CPUExecContext::dumpFuncProfile()
{
    std::ostream *os = simout.create(csprintf("profile.%s.dat", cpu->name()));
    profile->dump(proxy, *os);
}

void
CPUExecContext::profileClear()
{
    if (profile)
        profile->clear();
}

void
CPUExecContext::profileSample()
{
    if (profile)
        profile->sample(profileNode, profilePC);
}

#endif

void
CPUExecContext::takeOverFrom(ExecContext *oldContext)
{
    // some things should already be set up
    assert(mem == oldContext->getMemPtr());
#if FULL_SYSTEM
    assert(system == oldContext->getSystemPtr());
#else
    assert(process == oldContext->getProcessPtr());
#endif

    // copy over functional state
    _status = oldContext->status();
    copyArchRegs(oldContext);
    cpu_id = oldContext->readCpuId();
#if !FULL_SYSTEM
    func_exe_inst = oldContext->readFuncExeInst();
#endif

    storeCondFailures = 0;

    oldContext->setStatus(ExecContext::Unallocated);
}

void
CPUExecContext::serialize(ostream &os)
{
    SERIALIZE_ENUM(_status);
    regs.serialize(os);
    // thread_num and cpu_id are deterministic from the config
    SERIALIZE_SCALAR(func_exe_inst);
    SERIALIZE_SCALAR(inst);

#if FULL_SYSTEM
    Tick quiesceEndTick = 0;
    if (quiesceEvent->scheduled())
        quiesceEndTick = quiesceEvent->when();
    SERIALIZE_SCALAR(quiesceEndTick);

#endif
}

void
CPUExecContext::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_ENUM(_status);
    regs.unserialize(cp, section);
    // thread_num and cpu_id are deterministic from the config
    UNSERIALIZE_SCALAR(func_exe_inst);
    UNSERIALIZE_SCALAR(inst);

#if FULL_SYSTEM
    Tick quiesceEndTick;
    UNSERIALIZE_SCALAR(quiesceEndTick);
    if (quiesceEndTick)
        quiesceEvent->schedule(quiesceEndTick);
#endif
}

void
CPUExecContext::activate(int delay)
{
    if (status() == ExecContext::Active)
        return;

    lastActivate = curTick;

    if (status() == ExecContext::Unallocated) {
        cpu->activateWhenReady(thread_num);
        return;
    }

    _status = ExecContext::Active;

    // status() == Suspended
    cpu->activateContext(thread_num, delay);
}

void
CPUExecContext::suspend()
{
    if (status() == ExecContext::Suspended)
        return;

    lastActivate = curTick;
    lastSuspend = curTick;
/*
#if FULL_SYSTEM
    // Don't change the status from active if there are pending interrupts
    if (cpu->check_interrupts()) {
        assert(status() == ExecContext::Active);
        return;
    }
#endif
*/
    _status = ExecContext::Suspended;
    cpu->suspendContext(thread_num);
}

void
CPUExecContext::deallocate()
{
    if (status() == ExecContext::Unallocated)
        return;

    _status = ExecContext::Unallocated;
    cpu->deallocateContext(thread_num);
}

void
CPUExecContext::halt()
{
    if (status() == ExecContext::Halted)
        return;

    _status = ExecContext::Halted;
    cpu->haltContext(thread_num);
}

void
CPUExecContext::regStats(const string &name)
{
}

void
CPUExecContext::copyArchRegs(ExecContext *xc)
{
    // First loop through the integer registers.
    for (int i = 0; i < AlphaISA::NumIntRegs; ++i) {
        setIntReg(i, xc->readIntReg(i));
    }

    // Then loop through the floating point registers.
    for (int i = 0; i < AlphaISA::NumFloatRegs; ++i) {
        setFloatRegDouble(i, xc->readFloatRegDouble(i));
        setFloatRegInt(i, xc->readFloatRegInt(i));
    }

    // Copy misc. registers
    regs.miscRegs.copyMiscRegs(xc);

    // Lastly copy PC/NPC
    setPC(xc->readPC());
    setNextPC(xc->readNextPC());
}

<|endoftext|>


<commit_before>#define CATCH_CONFIG_MAIN
#define CATCH_CONFIG_COUNTER
#include "Catch.hpp"

#include <vector>
#include <functional>
#include <boost/asio.hpp>
#include "ModbusConsts.hpp"
#include "ModbusTypes.hpp"
#include "ModbusDecoder.hpp"
#include "ModbusEncoder.hpp"
#include "ModbusServerDevice.hpp"
#include "ModbusServer.hpp"

class ServerDevice : public modbus::tcp::ServerDevice {
public:
    ServerDevice(const modbus::tcp::UnitId& unitId) : modbus::tcp::ServerDevice(unitId) {}
};

TEST_CASE("server must respond to read coils req", "[server]") {
    ServerDevice dev(modbus::tcp::UnitId(0xab));

    boost::asio::io_service io;
    modbus::tcp::Server server(io, dev);

    const boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 50000);
    server.start(ep, [](){
    });
    io.run_one();

    boost::asio::ip::tcp::socket client(io);
    client.connect(ep);
    io.run_one();

    std::vector<uint8_t> req;
    modbus::tcp::Encoder encoder(modbus::tcp::UnitId(0xab), modbus::tcp::TransactionId(0x02));
    encoder.encodeReadCoilsReq(modbus::tcp::Address(0x1020), modbus::tcp::NumBits(4), req);

    boost::asio::write(client, boost::asio::buffer(req));

    io.run_one();
    io.run_one();

    std::vector<uint8_t> rsp;
    rsp.resize(sizeof(modbus::tcp::ExceptionRsp));
    boost::asio::read(client, boost::asio::buffer(rsp));

    server.stop();
    io.run();

    REQUIRE(rsp == (std::vector<uint8_t>{0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xab, 0x81, 0x01}));
}
<commit_msg>Validate done callback is triggered upon server shutdown<commit_after>#define CATCH_CONFIG_MAIN
#define CATCH_CONFIG_COUNTER
#include "Catch.hpp"

#include <vector>
#include <functional>
#include <boost/asio.hpp>
#include "ModbusConsts.hpp"
#include "ModbusTypes.hpp"
#include "ModbusDecoder.hpp"
#include "ModbusEncoder.hpp"
#include "ModbusServerDevice.hpp"
#include "ModbusServer.hpp"

class ServerDevice : public modbus::tcp::ServerDevice {
public:
    ServerDevice(const modbus::tcp::UnitId& unitId) : modbus::tcp::ServerDevice(unitId) {}
};

TEST_CASE("server must respond to read coils req", "[server]") {
    ServerDevice dev(modbus::tcp::UnitId(0xab));

    boost::asio::io_service io;
    modbus::tcp::Server server(io, dev);
    bool serverDone = false;

    const boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 50000);
    server.start(ep, [&serverDone](){
        serverDone = true;
    });
    io.run_one();

    boost::asio::ip::tcp::socket client(io);
    client.connect(ep);
    io.run_one();

    std::vector<uint8_t> req;
    modbus::tcp::Encoder encoder(modbus::tcp::UnitId(0xab), modbus::tcp::TransactionId(0x02));
    encoder.encodeReadCoilsReq(modbus::tcp::Address(0x1020), modbus::tcp::NumBits(4), req);

    boost::asio::write(client, boost::asio::buffer(req));

    io.run_one();
    io.run_one();

    std::vector<uint8_t> rsp;
    rsp.resize(sizeof(modbus::tcp::ExceptionRsp));
    boost::asio::read(client, boost::asio::buffer(rsp));

    server.stop();
    io.run_one();
    io.run_one();
    io.run_one();
    io.run_one();
    io.run_one();
    io.run_one();
    io.run_one();
    io.run_one();

    REQUIRE(serverDone == true);
    REQUIRE(rsp == (std::vector<uint8_t>{0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xab, 0x81, 0x01}));
}
<|endoftext|>


<commit_before><commit_msg>[김형준] 클라이언트 퀘스트 노출내용 버그 수정<commit_after><|endoftext|>