<commit_before>/*
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include <proxygen/lib/utils/ZlibStreamDecompressor.h>

#include <folly/io/Cursor.h>

using folly::IOBuf;
using std::unique_ptr;

// IOBuf uses 24 bytes of data for bookeeping purposes, so requesting for 480
// bytes of data will be rounded up to an allocation of 512 bytes.  (If we
// requested for 512 bytes exactly IOBuf would round this up to 768, since it
// needs 24 extra bytes of its own.)
#ifndef NO_LIB_GFLAGS
  DEFINE_int64(zlib_buffer_growth, 480,
               "The buffer growth size to use during IOBuf zlib inflation");
  DEFINE_int64(zlib_buffer_minsize, 64,
               "The minimum buffer size to use before growing during IOBuf "
               "zlib inflation");
#endif

namespace proxygen {

#ifdef NO_LIB_GFLAGS
  int64_t FLAGS_zlib_buffer_growth = 480;
  int64_t FLAGS_zlib_buffer_minsize = 64;
#endif

void ZlibStreamDecompressor::init(ZlibCompressionType type) {
  DCHECK(type_ == ZlibCompressionType::NONE) << "Must be uninitialized";
  type_ = type;
  status_ = Z_OK;
  zlibStream_.zalloc = Z_NULL;
  zlibStream_.zfree = Z_NULL;
  zlibStream_.opaque = Z_NULL;
  zlibStream_.total_in = 0;
  zlibStream_.next_in = Z_NULL;
  zlibStream_.avail_in = 0;
  zlibStream_.avail_out = 0;
  zlibStream_.next_out = Z_NULL;

  DCHECK(type != ZlibCompressionType::NONE);
  status_ = inflateInit2(&zlibStream_, static_cast<int>(type_));
}

ZlibStreamDecompressor::ZlibStreamDecompressor(ZlibCompressionType type)
    : type_(ZlibCompressionType::NONE), status_(Z_OK) {
  init(type);
}

ZlibStreamDecompressor::~ZlibStreamDecompressor() {
  if (type_ != ZlibCompressionType::NONE) {
    status_ = inflateEnd(&zlibStream_);
  }
}

std::unique_ptr<IOBuf> ZlibStreamDecompressor::decompress(const IOBuf* in) {
  auto out = IOBuf::create(FLAGS_zlib_buffer_growth);
  auto appender = folly::io::Appender(out.get(),
      FLAGS_zlib_buffer_growth);

  const IOBuf* crtBuf = in;
  size_t offset = 0;
  while (true) {
    // Advance to the next IOBuf if necessary
    DCHECK_GE(crtBuf->length(), offset);
    if (crtBuf->length() == offset) {
      crtBuf = crtBuf->next();
      offset = 0;
      if (crtBuf == in) {
        // We hit the end of the IOBuf chain, and are done.
        break;
      }
    }

    // The decompressor says we should have finished
    if (status_ == Z_STREAM_END) {
      // we convert this into a stream error
      status_ = Z_STREAM_ERROR;
      // we should probably bump up a counter here
      LOG(ERROR) << "error uncompressing buffer: reached end of zlib data "
        "before the end of the buffer";
      return nullptr;
    }

    // Ensure there is space in the output IOBuf
    appender.ensure(FLAGS_zlib_buffer_minsize);
    DCHECK_GT(appender.length(), 0);

    const size_t origAvailIn = crtBuf->length() - offset;
    zlibStream_.next_in = const_cast<uint8_t*>(crtBuf->data() + offset);
    zlibStream_.avail_in = origAvailIn;
    zlibStream_.next_out = appender.writableData();
    zlibStream_.avail_out = appender.length();
    status_ = inflate(&zlibStream_, Z_PARTIAL_FLUSH);
    if (status_ != Z_OK && status_ != Z_STREAM_END) {
      LOG(ERROR) << "error uncompressing buffer: r=" << status_;
      return nullptr;
    }

    // Adjust the input offset ahead
    auto inConsumed = origAvailIn - zlibStream_.avail_in;
    offset += inConsumed;
    // Move output buffer ahead
    auto outMove = appender.length() - zlibStream_.avail_out;
    appender.append(outMove);
  }

  return out;
}

}
<commit_msg>Fires all the time so we're temporarily bumping it to INFO<commit_after>/*
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include <proxygen/lib/utils/ZlibStreamDecompressor.h>

#include <folly/io/Cursor.h>

using folly::IOBuf;
using std::unique_ptr;

// IOBuf uses 24 bytes of data for bookeeping purposes, so requesting for 480
// bytes of data will be rounded up to an allocation of 512 bytes.  (If we
// requested for 512 bytes exactly IOBuf would round this up to 768, since it
// needs 24 extra bytes of its own.)
#ifndef NO_LIB_GFLAGS
  DEFINE_int64(zlib_buffer_growth, 480,
               "The buffer growth size to use during IOBuf zlib inflation");
  DEFINE_int64(zlib_buffer_minsize, 64,
               "The minimum buffer size to use before growing during IOBuf "
               "zlib inflation");
#endif

namespace proxygen {

#ifdef NO_LIB_GFLAGS
  int64_t FLAGS_zlib_buffer_growth = 480;
  int64_t FLAGS_zlib_buffer_minsize = 64;
#endif

void ZlibStreamDecompressor::init(ZlibCompressionType type) {
  DCHECK(type_ == ZlibCompressionType::NONE) << "Must be uninitialized";
  type_ = type;
  status_ = Z_OK;
  zlibStream_.zalloc = Z_NULL;
  zlibStream_.zfree = Z_NULL;
  zlibStream_.opaque = Z_NULL;
  zlibStream_.total_in = 0;
  zlibStream_.next_in = Z_NULL;
  zlibStream_.avail_in = 0;
  zlibStream_.avail_out = 0;
  zlibStream_.next_out = Z_NULL;

  DCHECK(type != ZlibCompressionType::NONE);
  status_ = inflateInit2(&zlibStream_, static_cast<int>(type_));
}

ZlibStreamDecompressor::ZlibStreamDecompressor(ZlibCompressionType type)
    : type_(ZlibCompressionType::NONE), status_(Z_OK) {
  init(type);
}

ZlibStreamDecompressor::~ZlibStreamDecompressor() {
  if (type_ != ZlibCompressionType::NONE) {
    status_ = inflateEnd(&zlibStream_);
  }
}

std::unique_ptr<IOBuf> ZlibStreamDecompressor::decompress(const IOBuf* in) {
  auto out = IOBuf::create(FLAGS_zlib_buffer_growth);
  auto appender = folly::io::Appender(out.get(),
      FLAGS_zlib_buffer_growth);

  const IOBuf* crtBuf = in;
  size_t offset = 0;
  while (true) {
    // Advance to the next IOBuf if necessary
    DCHECK_GE(crtBuf->length(), offset);
    if (crtBuf->length() == offset) {
      crtBuf = crtBuf->next();
      offset = 0;
      if (crtBuf == in) {
        // We hit the end of the IOBuf chain, and are done.
        break;
      }
    }

    // The decompressor says we should have finished
    if (status_ == Z_STREAM_END) {
      // we convert this into a stream error
      status_ = Z_STREAM_ERROR;
      // we should probably bump up a counter here
      LOG(ERROR) << "error uncompressing buffer: reached end of zlib data "
        "before the end of the buffer";
      return nullptr;
    }

    // Ensure there is space in the output IOBuf
    appender.ensure(FLAGS_zlib_buffer_minsize);
    DCHECK_GT(appender.length(), 0);

    const size_t origAvailIn = crtBuf->length() - offset;
    zlibStream_.next_in = const_cast<uint8_t*>(crtBuf->data() + offset);
    zlibStream_.avail_in = origAvailIn;
    zlibStream_.next_out = appender.writableData();
    zlibStream_.avail_out = appender.length();
    status_ = inflate(&zlibStream_, Z_PARTIAL_FLUSH);
    if (status_ != Z_OK && status_ != Z_STREAM_END) {
      LOG(INFO) << "error uncompressing buffer: r=" << status_;
      return nullptr;
    }

    // Adjust the input offset ahead
    auto inConsumed = origAvailIn - zlibStream_.avail_in;
    offset += inConsumed;
    // Move output buffer ahead
    auto outMove = appender.length() - zlibStream_.avail_out;
    appender.append(outMove);
  }

  return out;
}

}
<|endoftext|>


<commit_before>/*

Copyright (c) 2015, Project OSRM, Dennis Luxen, others
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.

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 HOLDER 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 "../Library/OSRM.h"
#include "../Util/git_sha.hpp"
#include "../Util/ProgramOptions.h"
#include "../Util/simple_logger.hpp"

#include <osrm/Reply.h>
#include <osrm/RouteParameters.h>
#include <osrm/ServerPaths.h>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <iostream>
#include <stack>
#include <string>
#include <sstream>

// Dude, real recursions on the OS stack? You must be brave...
void print_tree(boost::property_tree::ptree const &property_tree, const unsigned recursion_depth)
{
    auto end = property_tree.end();
    for (auto tree_iterator = property_tree.begin(); tree_iterator != end; ++tree_iterator)
    {
        for (unsigned current_recursion = 0; current_recursion < recursion_depth;
             ++current_recursion)
        {
            std::cout << " " << std::flush;
        }
        std::cout << tree_iterator->first << ": " << tree_iterator->second.get_value<std::string>()
                  << std::endl;
        print_tree(tree_iterator->second, recursion_depth + 1);
    }
}

int main(int argc, const char *argv[])
{
    LogPolicy::GetInstance().Unmute();
    try
    {
        std::string ip_address;
        int ip_port, requested_thread_num;
        bool use_shared_memory = false, trial = false;
        ServerPaths server_paths;
        if (!GenerateServerProgramOptions(argc,
                                          argv,
                                          server_paths,
                                          ip_address,
                                          ip_port,
                                          requested_thread_num,
                                          use_shared_memory,
                                          trial))
        {
            return 0;
        }

        SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION;

        OSRM routing_machine(server_paths, use_shared_memory);

        RouteParameters route_parameters;
        route_parameters.zoom_level = 18;           // no generalization
        route_parameters.print_instructions = true; // turn by turn instructions
        route_parameters.alternate_route = true;    // get an alternate route, too
        route_parameters.geometry = true;           // retrieve geometry of route
        route_parameters.compression = true;        // polyline encoding
        route_parameters.check_sum = UINT_MAX;      // see wiki
        route_parameters.service = "viaroute";      // that's routing
        route_parameters.output_format = "json";
        route_parameters.jsonp_parameter = ""; // set for jsonp wrapping
        route_parameters.language = "";        // unused atm
        // route_parameters.hints.push_back(); // see wiki, saves I/O if done properly

        // start_coordinate
        route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION,
                                                  13.438640 * COORDINATE_PRECISION);
        // target_coordinate
        route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION,
                                                  13.415852 * COORDINATE_PRECISION);
        http::Reply osrm_reply;
        routing_machine.RunQuery(route_parameters, osrm_reply);

        // attention: super-inefficient hack below:

        std::stringstream my_stream;
        for (const auto &element : osrm_reply.content)
        {
            std::cout << element;
            my_stream << element;
        }
        std::cout << std::endl;

        boost::property_tree::ptree property_tree;
        boost::property_tree::read_json(my_stream, property_tree);

        print_tree(property_tree, 0);
    }
    catch (std::exception &current_exception)
    {
        SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what();
        return -1;
    }
    return 0;
}
<commit_msg>fix initialization of simple client<commit_after>/*

Copyright (c) 2015, Project OSRM, Dennis Luxen, others
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.

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 HOLDER 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 "../Library/OSRM.h"
#include "../Util/git_sha.hpp"
#include "../Util/ProgramOptions.h"
#include "../Util/simple_logger.hpp"

#include <osrm/Reply.h>
#include <osrm/RouteParameters.h>
#include <osrm/ServerPaths.h>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <iostream>
#include <stack>
#include <string>
#include <sstream>

// Dude, real recursions on the OS stack? You must be brave...
void print_tree(boost::property_tree::ptree const &property_tree, const unsigned recursion_depth)
{
    auto end = property_tree.end();
    for (auto tree_iterator = property_tree.begin(); tree_iterator != end; ++tree_iterator)
    {
        for (unsigned current_recursion = 0; current_recursion < recursion_depth;
             ++current_recursion)
        {
            std::cout << " " << std::flush;
        }
        std::cout << tree_iterator->first << ": " << tree_iterator->second.get_value<std::string>()
                  << std::endl;
        print_tree(tree_iterator->second, recursion_depth + 1);
    }
}

int main(int argc, const char *argv[])
{
    LogPolicy::GetInstance().Unmute();
    try
    {
        std::string ip_address;
        int ip_port, requested_thread_num;
        bool use_shared_memory = false, trial_run = false;
        ServerPaths server_paths;

        const unsigned init_result = GenerateServerProgramOptions(argc,
                                                                  argv,
                                                                  server_paths,
                                                                  ip_address,
                                                                  ip_port,
                                                                  requested_thread_num,
                                                                  use_shared_memory,
                                                                  trial_run);

        if (init_result == INIT_FAILED)
        {
            return 0;
        }

        SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION;

        OSRM routing_machine(server_paths, use_shared_memory);

        RouteParameters route_parameters;
        route_parameters.zoom_level = 18;           // no generalization
        route_parameters.print_instructions = true; // turn by turn instructions
        route_parameters.alternate_route = true;    // get an alternate route, too
        route_parameters.geometry = true;           // retrieve geometry of route
        route_parameters.compression = true;        // polyline encoding
        route_parameters.check_sum = UINT_MAX;      // see wiki
        route_parameters.service = "viaroute";      // that's routing
        route_parameters.output_format = "json";
        route_parameters.jsonp_parameter = ""; // set for jsonp wrapping
        route_parameters.language = "";        // unused atm
        // route_parameters.hints.push_back(); // see wiki, saves I/O if done properly

        // start_coordinate
        route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION,
                                                  13.438640 * COORDINATE_PRECISION);
        // target_coordinate
        route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION,
                                                  13.415852 * COORDINATE_PRECISION);
        http::Reply osrm_reply;
        routing_machine.RunQuery(route_parameters, osrm_reply);

        // attention: super-inefficient hack below:

        std::stringstream my_stream;
        for (const auto &element : osrm_reply.content)
        {
            std::cout << element;
            my_stream << element;
        }
        std::cout << std::endl;

        boost::property_tree::ptree property_tree;
        boost::property_tree::read_json(my_stream, property_tree);

        print_tree(property_tree, 0);
    }
    catch (std::exception &current_exception)
    {
        SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what();
        return -1;
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Samplebuffer.cpp
 *
 *  Created on: Dec 4, 2013
 *      Author: gwue
 */

#include "Soundbuffer.hpp"

Soundbuffer::Soundbuffer()
{
	SoundgatesConfig* cfg = SoundgatesConfig::getInstance();
	this->SOUNDBUFFERSIZE = (int) (cfg->getConf(CFG_SOUND_BUFFER_SIZE));
	this->ALSACHARS = (int) (cfg->getConf(CFG_ALSA_CHUNKS));
	unsigned int samplerate = (unsigned int) (cfg->getConf(CFG_SAMPLE_RATE));

	this->buffer = (char*) malloc(this->SOUNDBUFFERSIZE * sizeof(char));

	int err;

	// Always offer chunks of the same size to ALSA
	this->alsaSamples = ALSACHARS / this->getFrameSize();
	this->sane = true;
	this->running = true;
	this->playing = false;
	this->writeoffset = 0;
	this->readoffset = 0;
	for (int i = 0; i < SOUNDBUFFERSIZE; i++)
	{
		this->buffer[i] = 0;
	}

	snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;

	if ((err = snd_pcm_open(&(this->pcm_handle), "plughw:0,0", stream, 0)) < 0)
	{
		fprintf(stderr, "cannot open audio device (%s)\n", snd_strerror(err));
		this->sane = false;
	}

	if ((err = snd_pcm_hw_params_malloc(&this->hw_params)) < 0)
	{
		fprintf(stderr,
				"cannot allocate record hardware parameter structure (%s)\n",
				snd_strerror(err));
		this->sane = false;
	}

	if ((err = snd_pcm_hw_params_any(this->pcm_handle, this->hw_params)) < 0)
	{
		fprintf(stderr, "cannot initialize hardware parameter structure (%s)\n",
				snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_hw_params_set_access(this->pcm_handle, this->hw_params,
			SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
	{
		fprintf(stderr, "cannot set access type (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	//TODO only one format supported right now. should be made selectable in the future
	// Currently, it is set to Unsigned Integer 32 Bit, Little Endian.
	// If you change this here, every function that operates on sound data would need to be adjusted accordingly!
	if ((err = snd_pcm_hw_params_set_format(this->pcm_handle, this->hw_params,
			SND_PCM_FORMAT_S32_LE)) < 0)
	{
		fprintf(stderr, "cannot set sample format (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_hw_params_set_buffer_size(this->pcm_handle,
			this->hw_params, 2048)) < 0)
	{
		fprintf(stderr, "cannot set buffer size (%s)\n", snd_strerror(err));
		this->sane = false;
	}

	//TODO Handling for unsupported sampling rates
	unsigned int exact_rate = samplerate;
	if ((err = snd_pcm_hw_params_set_rate_near(this->pcm_handle,
			this->hw_params, &exact_rate, 0)) < 0)
	{
		fprintf(stderr, "cannot set sample rate (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if (samplerate != exact_rate)
	{
		printf("Rate %i not supported, set to %i \n", samplerate, exact_rate);
	}

	// TODO For now, only one channel. Increase this to two channels in the future
	if ((err = snd_pcm_hw_params_set_channels(this->pcm_handle, this->hw_params,
			1)) < 0)
	{
		fprintf(stderr, "cannot set channel count (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_hw_params(this->pcm_handle, this->hw_params)) < 0)
	{
		fprintf(stderr, "cannot set parameters (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_prepare(this->pcm_handle)) < 0)
	{
		fprintf(stderr, "cannot prepare audio interface for use (%s)\n",
				snd_strerror(err));
		this->sane = false;
	}

	// If no errors occured we can create our playback thread
	//TODO uncomment this
//	if (this->sane)
	{
		this->bufferThread = boost::thread(&Soundbuffer::run, this);
	}
}

void Soundbuffer::run()
{
	int nframes;
	int err = 0;
	snd_pcm_prepare(this->pcm_handle);

	while (this->running)
	{
		// Wait for the playback to start
		if (!this->playing)
		{
			usleep(50000);
		}
		else
		{
			nframes = 0;

			// Wait for the audio device to become ready (or timeout after a second)
			if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
			{
				fprintf(stderr, "poll failed (%s)\n", snd_strerror(err));
				this->running = 0;
			}

			// Ask the audio device how many frames it can accept
			if ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
			{
				fprintf(stderr, "unknown ALSA avail update return value (%s)\n",
						snd_strerror(nframes));
				this->running = 0;
			}

			// Only write to the soundcard if alsa requested enough frames
			if (nframes >= this->alsaSamples)
			{
				this->mutex.lock();
				char* frames = this->getNextFrames();

				if ((err = snd_pcm_writei(this->pcm_handle, frames,
						this->alsaSamples)) < 0)
				{
					fprintf(stderr, "write to audio interface failed (%s)\n",
							snd_strerror(err));
					this->running = 0;
				}
				this->mutex.unlock();

			}
		}
	}
}

Soundbuffer::~Soundbuffer()
{
}

char* Soundbuffer::getNextFrames()
{
	bool ptr_return = false;

	// Advance readbuffer by ALSACHUNKS
	int nextReadOffset = this->readoffset + ALSACHARS;
	// If we reached the end, restart from the beginning
	if (nextReadOffset >= SOUNDBUFFERSIZE)
	{
		nextReadOffset = 0;
		ptr_return = true;
	}
	// We might read samples faster than we produce them.
	// In that case we don't want to advance the readoffset past the writeoffset
	// Write and read offset are allowed to be same. This would mean the buffer is completely filled.
	// Therefore, don't check for equality here.
	if ( 	(!ptr_return && (this->readoffset < this->writeoffset && nextReadOffset > this->writeoffset )) ||
		 	(ptr_return  && (this->readoffset < this->writeoffset)))
	{
		std::cerr
				<< "Buffer has run dry! This should not happen! Will now play previous samples again! RO:" << this->readoffset << "  WO:" << this->writeoffset
				<< std::endl;
	}
	else
	{
		this->readoffset = nextReadOffset;
	}

	char* buffer_ptr = this->buffer + this->readoffset;
	return buffer_ptr;
}

void Soundbuffer::startPlayback()
{
	this->playing = true;
}

void Soundbuffer::stopThread()
{
	this->running = false;
	this->bufferThread.join();
}

void Soundbuffer::testPlayback()
{
	printf("Starting test playback!\n");
	int err;
	int nframes = 0;
	char sine[SOUNDBUFFERSIZE];
	double phase = 0;

	for (double freq = 27.5; freq < 4187; freq *=
			1.0594630943592952645618252949463)
	{
		printf("Freq: %f\n", freq);
		for (int i = 0; i < 50; i++)
		{
			if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
			{
				fprintf(stderr, "poll failed (%s)\n", strerror(err));
				return;
			}
			if ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
			{
				fprintf(stderr, "unknown ALSA avail update return value (%d)\n",
						nframes);
				return;
			}
			if (nframes > SOUNDBUFFERSIZE / 4)
			{
				nframes = SOUNDBUFFERSIZE / 4;
			}
			for (int j = 0; j < nframes; j++)
			{
				((int*) sine)[j] = (int) (sin(phase) * INT_MAX);

				phase += (2 * M_PI / 44100.0) * freq;

				if (phase > M_PI * 2)
				{
					phase -= M_PI * 2;
				}
			}

			if ((err = snd_pcm_writei(this->pcm_handle, sine, nframes)) < 0)
			{
				fprintf(stderr, "write to audio interface failed (%s)\n",
						snd_strerror(err));
				return;
			}
		}
	}

	printf("Stopping test playback!\n");
}

void Soundbuffer::fillbuffer(char* data, int size)
{
	if ((size & (size - 1)) != 0)
	{
		std::cerr << "You need to fill the buffer with array sizes x^2"
				<< std::endl;
		return;
	}
	if (size >= SOUNDBUFFERSIZE)
	{
		std::cerr << "Too many samples. Might be at most "
				<< SOUNDBUFFERSIZE / 2 << std::endl;
		return;
	}

	while (!this->canAcceptData(size))
	{
		usleep(100);
	}

	this->mutex.lock();
	for (int i = 0; i < size; i++)
	{
		this->buffer[this->writeoffset] = data[i];
		this->writeoffset++;
		if (this->writeoffset >= SOUNDBUFFERSIZE)
		{
			this->writeoffset = 0;
		}
	}
	this->mutex.unlock();

}

bool Soundbuffer::canAcceptData(int size)
{
	int free;

	this->mutex.lock();
	if (this->writeoffset > this->readoffset)
	{
		free = this->readoffset + (SOUNDBUFFERSIZE - this->writeoffset);
	}
	else if (this->writeoffset < this->readoffset)
	{
		free = this->readoffset - this->writeoffset;
	}
	else
	{
		//write and readoffset equal ---> buffer is full
		free = 0;
	}
	this->mutex.unlock();

	if (free >= size)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int Soundbuffer::getFrameSize()
{
	return 4;
}
<commit_msg>ALSA wird nun neu initialisiert wenn der Buffer leer läuft anstatt die Ausgabe komplett zu beenden<commit_after>/*
 * Samplebuffer.cpp
 *
 *  Created on: Dec 4, 2013
 *      Author: gwue
 */

#include "Soundbuffer.hpp"

Soundbuffer::Soundbuffer()
{
	SoundgatesConfig* cfg = SoundgatesConfig::getInstance();
	this->SOUNDBUFFERSIZE = (int) (cfg->getConf(CFG_SOUND_BUFFER_SIZE));
	this->ALSACHARS = (int) (cfg->getConf(CFG_ALSA_CHUNKS));
	unsigned int samplerate = (unsigned int) (cfg->getConf(CFG_SAMPLE_RATE));

	this->buffer = (char*) malloc(this->SOUNDBUFFERSIZE * sizeof(char));

	int err;

	// Always offer chunks of the same size to ALSA
	this->alsaSamples = ALSACHARS / this->getFrameSize();
	this->sane = true;
	this->running = true;
	this->playing = false;
	this->writeoffset = 0;
	this->readoffset = 0;
	for (int i = 0; i < SOUNDBUFFERSIZE; i++)
	{
		this->buffer[i] = 0;
	}

	snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;

	if ((err = snd_pcm_open(&(this->pcm_handle), "plughw:0,0", stream, 0)) < 0)
	{
		fprintf(stderr, "cannot open audio device (%s)\n", snd_strerror(err));
		this->sane = false;
	}

	if ((err = snd_pcm_hw_params_malloc(&this->hw_params)) < 0)
	{
		fprintf(stderr,
				"cannot allocate record hardware parameter structure (%s)\n",
				snd_strerror(err));
		this->sane = false;
	}

	if ((err = snd_pcm_hw_params_any(this->pcm_handle, this->hw_params)) < 0)
	{
		fprintf(stderr, "cannot initialize hardware parameter structure (%s)\n",
				snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_hw_params_set_access(this->pcm_handle, this->hw_params,
			SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
	{
		fprintf(stderr, "cannot set access type (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	//TODO only one format supported right now. should be made selectable in the future
	// Currently, it is set to Unsigned Integer 32 Bit, Little Endian.
	// If you change this here, every function that operates on sound data would need to be adjusted accordingly!
	if ((err = snd_pcm_hw_params_set_format(this->pcm_handle, this->hw_params,
			SND_PCM_FORMAT_S32_LE)) < 0)
	{
		fprintf(stderr, "cannot set sample format (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_hw_params_set_buffer_size(this->pcm_handle,
			this->hw_params, 2048)) < 0)
	{
		fprintf(stderr, "cannot set buffer size (%s)\n", snd_strerror(err));
		this->sane = false;
	}

	//TODO Handling for unsupported sampling rates
	unsigned int exact_rate = samplerate;
	if ((err = snd_pcm_hw_params_set_rate_near(this->pcm_handle,
			this->hw_params, &exact_rate, 0)) < 0)
	{
		fprintf(stderr, "cannot set sample rate (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if (samplerate != exact_rate)
	{
		printf("Rate %i not supported, set to %i \n", samplerate, exact_rate);
	}

	// TODO For now, only one channel. Increase this to two channels in the future
	if ((err = snd_pcm_hw_params_set_channels(this->pcm_handle, this->hw_params,
			1)) < 0)
	{
		fprintf(stderr, "cannot set channel count (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_hw_params(this->pcm_handle, this->hw_params)) < 0)
	{
		fprintf(stderr, "cannot set parameters (%s)\n", snd_strerror(err));
		this->sane = false;
	}
	if ((err = snd_pcm_prepare(this->pcm_handle)) < 0)
	{
		fprintf(stderr, "cannot prepare audio interface for use (%s)\n",
				snd_strerror(err));
		this->sane = false;
	}

	// If no errors occured we can create our playback thread
	//TODO uncomment this
//	if (this->sane)
	{
		this->bufferThread = boost::thread(&Soundbuffer::run, this);
	}
}

void Soundbuffer::run()
{
	int nframes;
	int err = 0;
	bool bufferUnderrun = false;
	snd_pcm_prepare(this->pcm_handle);

	while (this->running)
	{
		// Wait for the playback to start
		if (!this->playing)
		{
			usleep(50000);
		}
		else
		{
			//If a buffer underrun occured, we need to reinitialize the ALSA device
			if (bufferUnderrun)
			{
				snd_pcm_prepare(this->pcm_handle);
				bufferUnderrun =false;
			}

			nframes = 0;

			// Wait for the audio device to become ready (or timeout after a second)
			if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
			{
				fprintf(stderr, "poll failed (%s): Most likely a buffer underrun occured\n", snd_strerror(err));
				bufferUnderrun = true;
				//	this->running = 0;
			}

			// Ask the audio device how many frames it can accept
			if (!bufferUnderrun && (nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
			{
				fprintf(stderr, "unknown ALSA avail update return value (%s)\n",
						snd_strerror(nframes));
				this->running = 0;
			}

			// Only write to the soundcard if alsa requested enough frames
			if (!bufferUnderrun && (nframes >= this->alsaSamples))
			{
				this->mutex.lock();
				char* frames = this->getNextFrames();

				if ((err = snd_pcm_writei(this->pcm_handle, frames,
						this->alsaSamples)) < 0)
				{
					fprintf(stderr, "write to audio interface failed (%s)\n",
							snd_strerror(err));
					this->running = 0;
				}
				this->mutex.unlock();

			}
		}
	}
}

Soundbuffer::~Soundbuffer()
{
}

char* Soundbuffer::getNextFrames()
{
	bool ptr_return = false;

	// Advance readbuffer by ALSACHUNKS
	int nextReadOffset = this->readoffset + ALSACHARS;
	// If we reached the end, restart from the beginning
	if (nextReadOffset >= SOUNDBUFFERSIZE)
	{
		nextReadOffset = 0;
		ptr_return = true;
	}
	// We might read samples faster than we produce them.
	// In that case we don't want to advance the readoffset past the writeoffset
	// Write and read offset are allowed to be same. This would mean the buffer is completely filled.
	// Therefore, don't check for equality here.
	if ( 	(!ptr_return && (this->readoffset < this->writeoffset && nextReadOffset > this->writeoffset )) ||
		 	(ptr_return  && (this->readoffset < this->writeoffset)))
	{
		std::cerr
				<< "Buffer has run dry! This should not happen! Will now play previous samples again! RO:" << this->readoffset << "  WO:" << this->writeoffset
				<< std::endl;
	}
	else
	{
		this->readoffset = nextReadOffset;
	}

	char* buffer_ptr = this->buffer + this->readoffset;
	return buffer_ptr;
}

void Soundbuffer::startPlayback()
{
	this->playing = true;
}

void Soundbuffer::stopThread()
{
	this->running = false;
	this->bufferThread.join();
}

void Soundbuffer::testPlayback()
{
	printf("Starting test playback!\n");
	int err;
	int nframes = 0;
	char sine[SOUNDBUFFERSIZE];
	double phase = 0;

	for (double freq = 27.5; freq < 4187; freq *=
			1.0594630943592952645618252949463)
	{
		printf("Freq: %f\n", freq);
		for (int i = 0; i < 50; i++)
		{
			if ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)
			{
				fprintf(stderr, "poll failed (%s)\n", strerror(err));
				return;
			}
			if ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)
			{
				fprintf(stderr, "unknown ALSA avail update return value (%d)\n",
						nframes);
				return;
			}
			if (nframes > SOUNDBUFFERSIZE / 4)
			{
				nframes = SOUNDBUFFERSIZE / 4;
			}
			for (int j = 0; j < nframes; j++)
			{
				((int*) sine)[j] = (int) (sin(phase) * INT_MAX);

				phase += (2 * M_PI / 44100.0) * freq;

				if (phase > M_PI * 2)
				{
					phase -= M_PI * 2;
				}
			}

			if ((err = snd_pcm_writei(this->pcm_handle, sine, nframes)) < 0)
			{
				fprintf(stderr, "write to audio interface failed (%s)\n",
						snd_strerror(err));
				return;
			}
		}
	}

	printf("Stopping test playback!\n");
}

void Soundbuffer::fillbuffer(char* data, int size)
{
	if ((size & (size - 1)) != 0)
	{
		std::cerr << "You need to fill the buffer with array sizes x^2"
				<< std::endl;
		return;
	}
	if (size >= SOUNDBUFFERSIZE)
	{
		std::cerr << "Too many samples. Might be at most "
				<< SOUNDBUFFERSIZE / 2 << std::endl;
		return;
	}

	while (!this->canAcceptData(size))
	{
		usleep(100);
	}

	this->mutex.lock();
	for (int i = 0; i < size; i++)
	{
		this->buffer[this->writeoffset] = data[i];
		this->writeoffset++;
		if (this->writeoffset >= SOUNDBUFFERSIZE)
		{
			this->writeoffset = 0;
		}
	}
	this->mutex.unlock();

}

bool Soundbuffer::canAcceptData(int size)
{
	int free;

	this->mutex.lock();
	if (this->writeoffset > this->readoffset)
	{
		free = this->readoffset + (SOUNDBUFFERSIZE - this->writeoffset);
	}
	else if (this->writeoffset < this->readoffset)
	{
		free = this->readoffset - this->writeoffset;
	}
	else
	{
		//write and readoffset equal ---> buffer is full
		free = 0;
	}
	this->mutex.unlock();

	if (free >= size)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int Soundbuffer::getFrameSize()
{
	return 4;
}
<|endoftext|>


<commit_before>#include "Router.h"

// Add a link id to the router's link vector
void Router::addLink(std::string link_id) {
    links.push_back(link_id);
}

// Add a (host, link) pair indicating which link to route to given a host
void Router::addRouting(std::string targ_host, std::string targ_link) {
  routing_table[targ_host] = targ_link;
}

// Return the proper link to route to given a host
std::string Router::getRouting(std::string targ_host) {
    // should probably do some error checking
    return routing_table[targ_host];
}

// Make new event with same packet going to proper link
void Router::giveEvent(std::shared_ptr<Event> e) {
    // Get PacketEvent
    PacketEvent packet_event = *(std::static_pointer_cast<PacketEvent>(e));

    // strip necessary info out of packet event
    Packet pkt = packet_event.packet;
    std::string dest = getRouting(pkt.final_dest);
    // make new event
    auto new_event = std::make_shared<PacketEvent>(dest, this->getID(), packet_event.eventTime(), pkt);
    // put on event heap
    eventHeap.push(new_event);
}
<commit_msg>share everything<commit_after>#include "Router.h"

// Add a link id to the router's link vector
void Router::addLink(std::string link_id) {
    links.push_back(link_id);
}

// Add a (host, link) pair indicating which link to route to given a host
void Router::addRouting(std::string targ_host, std::string targ_link) {
  routing_table[targ_host] = targ_link;
}

// Return the proper link to route to given a host
std::string Router::getRouting(std::string targ_host) {
    // should probably do some error checking
    return routing_table[targ_host];
}

// Make new event with same packet going to proper link
void Router::giveEvent(std::shared_ptr<Event> e) {
    // Get PacketEvent
    PacketEvent packet_event = *(std::static_pointer_cast<PacketEvent>(e));

    // strip necessary info out of packet event
    std::shared_ptr<Packet> pkt = packet_event.packet;
    std::string dest = getRouting(pkt->final_dest);
    // make new event
    auto new_event = std::make_shared<PacketEvent>(dest, this->getID(), packet_event.eventTime(), pkt);
    // put on event heap
    eventHeap.push(new_event);
}
<|endoftext|>


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

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

#ifndef _CHART2_CATEGORYPOSITIONHELPER_HXX
#include "CategoryPositionHelper.hxx"
#endif

//.............................................................................
namespace chart
{
//.............................................................................
//using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;

CategoryPositionHelper::CategoryPositionHelper( double fSeriesCount, double fCategoryWidth )
    : m_fSeriesCount(fSeriesCount)
    , m_fCategoryWidth(fCategoryWidth)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(1.0)
{
}

CategoryPositionHelper::CategoryPositionHelper( const CategoryPositionHelper& rSource )
    : m_fSeriesCount( rSource.m_fSeriesCount )
    , m_fCategoryWidth( rSource.m_fCategoryWidth )
    , m_fInnerDistance( rSource.m_fInnerDistance )
    , m_fOuterDistance( rSource.m_fOuterDistance )
{
}

CategoryPositionHelper::CategoryPositionHelper()
    : m_fSeriesCount(1.0)
    , m_fCategoryWidth(1.0)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(0.0)
{
}

CategoryPositionHelper::~CategoryPositionHelper()
{
}

double CategoryPositionHelper::getSlotWidth() const
{
    double fWidth = m_fCategoryWidth /
                (  m_fSeriesCount
                 + m_fOuterDistance
                 + m_fInnerDistance*( m_fSeriesCount - 1.0) );
    return fWidth;
}

double CategoryPositionHelper::getSlotPos( double fCategoryX, double fSeriesNumber ) const
{
    //the returned position is in the middle of the rect
    //fSeriesNumber 0...n-1
    double fPos = fCategoryX - (m_fCategoryWidth/2.0)
           + (m_fOuterDistance/2.0 + fSeriesNumber*(1.0+m_fInnerDistance)) * getSlotWidth()
           + getSlotWidth()/2.0;

    return fPos;
}

void CategoryPositionHelper::setInnerDistance( double fInnerDistance )
{
    if( fInnerDistance < -1.0 )
        fInnerDistance = -1.0;
    if( fInnerDistance > 1.0 )
        fInnerDistance = 1.0;
    m_fInnerDistance = fInnerDistance;
}

void CategoryPositionHelper::setOuterDistance( double fOuterDistance )
{
    if( fOuterDistance < 0.0 )
        fOuterDistance = 0.0;
    if( fOuterDistance > 6.0 )
        fOuterDistance = 6.0;
    m_fOuterDistance = fOuterDistance;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.4.126); FILE MERGED 2008/04/01 10:50:40 thb 1.4.126.2: #i85898# Stripping all external header guards 2008/03/28 16:44:38 rt 1.4.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: CategoryPositionHelper.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

//.............................................................................
namespace chart
{
//.............................................................................
//using namespace ::com::sun::star;
//using namespace ::com::sun::star::chart2;

CategoryPositionHelper::CategoryPositionHelper( double fSeriesCount, double fCategoryWidth )
    : m_fSeriesCount(fSeriesCount)
    , m_fCategoryWidth(fCategoryWidth)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(1.0)
{
}

CategoryPositionHelper::CategoryPositionHelper( const CategoryPositionHelper& rSource )
    : m_fSeriesCount( rSource.m_fSeriesCount )
    , m_fCategoryWidth( rSource.m_fCategoryWidth )
    , m_fInnerDistance( rSource.m_fInnerDistance )
    , m_fOuterDistance( rSource.m_fOuterDistance )
{
}

CategoryPositionHelper::CategoryPositionHelper()
    : m_fSeriesCount(1.0)
    , m_fCategoryWidth(1.0)
    , m_fInnerDistance(0.0)
    , m_fOuterDistance(0.0)
{
}

CategoryPositionHelper::~CategoryPositionHelper()
{
}

double CategoryPositionHelper::getSlotWidth() const
{
    double fWidth = m_fCategoryWidth /
                (  m_fSeriesCount
                 + m_fOuterDistance
                 + m_fInnerDistance*( m_fSeriesCount - 1.0) );
    return fWidth;
}

double CategoryPositionHelper::getSlotPos( double fCategoryX, double fSeriesNumber ) const
{
    //the returned position is in the middle of the rect
    //fSeriesNumber 0...n-1
    double fPos = fCategoryX - (m_fCategoryWidth/2.0)
           + (m_fOuterDistance/2.0 + fSeriesNumber*(1.0+m_fInnerDistance)) * getSlotWidth()
           + getSlotWidth()/2.0;

    return fPos;
}

void CategoryPositionHelper::setInnerDistance( double fInnerDistance )
{
    if( fInnerDistance < -1.0 )
        fInnerDistance = -1.0;
    if( fInnerDistance > 1.0 )
        fInnerDistance = 1.0;
    m_fInnerDistance = fInnerDistance;
}

void CategoryPositionHelper::setOuterDistance( double fOuterDistance )
{
    if( fOuterDistance < 0.0 )
        fOuterDistance = 0.0;
    if( fOuterDistance > 6.0 )
        fOuterDistance = 6.0;
    m_fOuterDistance = fOuterDistance;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>/*
 *  Main authors:
 *     Kevin Leo <kevin.leo@monash.edu>
 *     Andrea Rendl <andrea.rendl@nicta.com.au>
 *     Guido Tack <guido.tack@monash.edu>
 */

/* 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/. */

#include <minizinc/solvers/gecode/fzn_space.hh>
#include <minizinc/solvers/gecode_solverinstance.hh>

using namespace Gecode;

namespace MiniZinc {

  FznSpace::FznSpace(bool share, FznSpace& f) : Space(share, f) {
    // integer variables
    iv.resize(f.iv.size());
    for(int i=0; i<iv.size(); i++)
      iv[i].update(*this, share, f.iv[i]);
    for(int i=0; i<f.iv_introduced.size(); i++)
      iv_introduced.push_back(f.iv_introduced[i]);
    for(int i=0; i<f.iv_defined.size(); i++)
      iv_defined.push_back(f.iv_defined[i]);
    if(f._copyAuxVars) {
      IntVarArgs iva;
      for (int i=0; i<f.iv_aux.size(); i++) {
        if (!f.iv_aux[i].assigned()) {
          iva << IntVar();
          iva[iva.size()-1].update(*this, share, f.iv_aux[i]);
        }
      }
      iv_aux = IntVarArray(*this, iva);
    }

    // boolean variables
    bv.resize(f.bv.size());
    for(int i=0; i<bv.size(); i++)
      bv[i].update(*this, share, f.bv[i]);
    if (f._copyAuxVars) {
      BoolVarArgs bva;
      for (int i=0; i<f.bv_aux.size(); i++) {
        if (!f.bv_aux[i].assigned()) {
          bva << BoolVar();
          bva[bva.size()-1].update(*this, share, f.bv_aux[i]);
        }
      }
      bv_aux = BoolVarArray(*this, bva);
    }
    for(int i=0; i<f.bv_introduced.size(); i++)
      bv_introduced.push_back(f.bv_introduced[i]);

#ifdef GECODE_HAS_SET_VARS
    sv.resize(f.sv.size());
    for(int i=0; i<sv.size(); i++)
      sv[i].update(*this, share, f.sv[i]);
    if (f._copyAuxVars) {
      SetVarArgs sva;
      for (int i=0; i<f.sv_aux.size(); i++) {
        if (!f.sv_aux[i].assigned()) {
          sva << SetVar();
          sva[sva.size()-1].update(*this, share, f.sv_aux[i]);
        }
      }
      sv_aux = SetVarArray(*this, sva);
    }
    for(int i=0; i<f.sv_introduced.size(); i++)
      sv_introduced.push_back(f.sv_introduced[i]);
#endif

#ifdef GECODE_HAS_FLOAT_VARS
    fv.resize(f.fv.size());
    for(int i=0; i<fv.size(); i++)
      fv[i].update(*this, share, f.fv[i]);
    if (f._copyAuxVars) {
      FloatVarArgs fva;
      for (int i=0; i<f.fv_aux.size(); i++) {
        if (!f.fv_aux[i].assigned()) {
          fva << FloatVar();
          fva[fva.size()-1].update(*this, share, f.fv_aux[i]);
        }
      }
      fv_aux = FloatVarArray(*this, fva);
    }
#endif

    _optVarIsInt = f._optVarIsInt;
  }

  Gecode::Space*
    FznSpace::copy(bool share) {
      return new FznSpace(share, *this);
    }

  void
    FznSpace::constrain(const Space& s) {
      if (_optVarIsInt) {
        if (_solveType == MiniZinc::SolveI::SolveType::ST_MIN)
          rel(*this, iv[_optVarIdx], IRT_LE,
              static_cast<const FznSpace*>(&s)->iv[_optVarIdx].val());
        else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)
          rel(*this, iv[_optVarIdx], IRT_GR,
              static_cast<const FznSpace*>(&s)->iv[_optVarIdx].val());
      } else {
#ifdef GECODE_HAS_FLOAT_VARS
        if (_solveType == MiniZinc::SolveI::SolveType::ST_MIN)
          rel(*this, fv[_optVarIdx], FRT_LE,
              static_cast<const FznSpace*>(&s)->fv[_optVarIdx].val());
        else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)
          rel(*this, fv[_optVarIdx], FRT_GR,
              static_cast<const FznSpace*>(&s)->fv[_optVarIdx].val());
#endif
      }
    }

}
<commit_msg>Gecode Solver: fzn_space copying: copy _solveType<commit_after>/*
 *  Main authors:
 *     Kevin Leo <kevin.leo@monash.edu>
 *     Andrea Rendl <andrea.rendl@nicta.com.au>
 *     Guido Tack <guido.tack@monash.edu>
 */

/* 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/. */

#include <minizinc/solvers/gecode/fzn_space.hh>
#include <minizinc/solvers/gecode_solverinstance.hh>

using namespace Gecode;

namespace MiniZinc {

  FznSpace::FznSpace(bool share, FznSpace& f) : Space(share, f) {
    // integer variables
    iv.resize(f.iv.size());
    for(int i=0; i<iv.size(); i++)
      iv[i].update(*this, share, f.iv[i]);
    for(int i=0; i<f.iv_introduced.size(); i++)
      iv_introduced.push_back(f.iv_introduced[i]);
    for(int i=0; i<f.iv_defined.size(); i++)
      iv_defined.push_back(f.iv_defined[i]);
    if(f._copyAuxVars) {
      IntVarArgs iva;
      for (int i=0; i<f.iv_aux.size(); i++) {
        if (!f.iv_aux[i].assigned()) {
          iva << IntVar();
          iva[iva.size()-1].update(*this, share, f.iv_aux[i]);
        }
      }
      iv_aux = IntVarArray(*this, iva);
    }

    // boolean variables
    bv.resize(f.bv.size());
    for(int i=0; i<bv.size(); i++)
      bv[i].update(*this, share, f.bv[i]);
    if (f._copyAuxVars) {
      BoolVarArgs bva;
      for (int i=0; i<f.bv_aux.size(); i++) {
        if (!f.bv_aux[i].assigned()) {
          bva << BoolVar();
          bva[bva.size()-1].update(*this, share, f.bv_aux[i]);
        }
      }
      bv_aux = BoolVarArray(*this, bva);
    }
    for(int i=0; i<f.bv_introduced.size(); i++)
      bv_introduced.push_back(f.bv_introduced[i]);

#ifdef GECODE_HAS_SET_VARS
    sv.resize(f.sv.size());
    for(int i=0; i<sv.size(); i++)
      sv[i].update(*this, share, f.sv[i]);
    if (f._copyAuxVars) {
      SetVarArgs sva;
      for (int i=0; i<f.sv_aux.size(); i++) {
        if (!f.sv_aux[i].assigned()) {
          sva << SetVar();
          sva[sva.size()-1].update(*this, share, f.sv_aux[i]);
        }
      }
      sv_aux = SetVarArray(*this, sva);
    }
    for(int i=0; i<f.sv_introduced.size(); i++)
      sv_introduced.push_back(f.sv_introduced[i]);
#endif

#ifdef GECODE_HAS_FLOAT_VARS
    fv.resize(f.fv.size());
    for(int i=0; i<fv.size(); i++)
      fv[i].update(*this, share, f.fv[i]);
    if (f._copyAuxVars) {
      FloatVarArgs fva;
      for (int i=0; i<f.fv_aux.size(); i++) {
        if (!f.fv_aux[i].assigned()) {
          fva << FloatVar();
          fva[fva.size()-1].update(*this, share, f.fv_aux[i]);
        }
      }
      fv_aux = FloatVarArray(*this, fva);
    }
#endif

    _optVarIsInt = f._optVarIsInt;
    _solveType = f._solveType;
  }

  Gecode::Space*
    FznSpace::copy(bool share) {
      return new FznSpace(share, *this);
    }

  void
    FznSpace::constrain(const Space& s) {
      if (_optVarIsInt) {
        if (_solveType == MiniZinc::SolveI::SolveType::ST_MIN)
          rel(*this, iv[_optVarIdx], IRT_LE,
              static_cast<const FznSpace*>(&s)->iv[_optVarIdx].val());
        else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)
          rel(*this, iv[_optVarIdx], IRT_GR,
              static_cast<const FznSpace*>(&s)->iv[_optVarIdx].val());
      } else {
#ifdef GECODE_HAS_FLOAT_VARS
        if (_solveType == MiniZinc::SolveI::SolveType::ST_MIN)
          rel(*this, fv[_optVarIdx], FRT_LE,
              static_cast<const FznSpace*>(&s)->fv[_optVarIdx].val());
        else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)
          rel(*this, fv[_optVarIdx], FRT_GR,
              static_cast<const FznSpace*>(&s)->fv[_optVarIdx].val());
#endif
      }
    }

}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

using namespace std;

int search(vector<int> &a, int x) {
  // Preventing to call size function every iteration
  int m; // Index of middle element
  size_t n = a.size(); // Length of vector
  int l = 0, r = n - 1;

  while (l <= r) {
    m = l + (r - l) / 2;
    if (a[m] == x) {
      return m;
    }
    if (a[m] < x) {
      l = m + 1;
    } else {
      r = m - 1;
    }
  }
  return -1;
}

int main(){

  // Getting user input and declaring vars
  int x;
  cin >> x; // This will be our find value
  size_t n;
  cin >> n; // Given sorted array size
  vector<int> a(n);

  for (size_t i = 0; i < n; i++)
    cin >> a[i];

  cout << "Index is : " << search(a, x) << endl;

  return 0;
}
<commit_msg>updated binary search suggested changes<commit_after>#include <iostream>
#include <vector>

using namespace std;

int search(vector<int> &a, int x) {

  size_t n = a.size();
  int l = 0;
  int r = n - 1;

  while (l <= r) {

    int m = l + (r - l) / 2;

    if (a[m] == x) {
      return m;
    }
    if (a[m] < x) {
      l = m + 1;
    } else {
      r = m - 1;
    }

  }
  return -1;
}

int main(){

  // Getting user input and declaring vars
  int x;
  cin >> x;
  size_t n;
  cin >> n;
  vector<int> a(n);

  for (size_t i = 0; i < n; i++)
    cin >> a[i];

  cout << "Index is : " << search(a, x) << endl;

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Undo disabled toolstrip test, now that upstream bug is fixed.<commit_after><|endoftext|>


<commit_before><commit_msg>Revert 40769 - Remove flaky label from RSS tests.<commit_after><|endoftext|>


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

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script didn't run.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result);
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script ran.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result);
  EXPECT_TRUE(result);
}

// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
// Hanging on ChromeOS and linux: http://crbug.com/53991
#define MAYBE_IncognitoSplitMode DISABLED_IncognitoSplitMode
#else
#define MAYBE_IncognitoSplitMode IncognitoSplitMode
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
// Hangy, http://crbug.com/53869.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* incognito_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Disable IncognitoSplitMode everywhere, it's failing and hangy. Working on a fix.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script didn't run.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result);
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script ran.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result);
  EXPECT_TRUE(result);
}

// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
// Hanging/failing: http://crbug.com/53991
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
// Hangy, http://crbug.com/53869.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* incognito_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>


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

#include "base/nss_util.h"
#include "base/nss_util_internal.h"

#include <nss.h>
#include <plarena.h>
#include <prerror.h>
#include <prinit.h>
#include <prtime.h>
#include <pk11pub.h>
#include <secmod.h>

#include "base/file_util.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/string_util.h"

#if defined(USE_NSS)
#include "base/lock.h"
#include "base/scoped_ptr.h"
#endif // defined(USE_NSS)

// On some platforms, we use NSS for SSL only -- we don't use NSS for crypto
// or certificate verification, and we don't use the NSS certificate and key
// databases.
#if defined(OS_MACOSX) || defined(OS_WIN)
#define USE_NSS_FOR_SSL_ONLY 1
#endif

namespace {

#if !defined(USE_NSS_FOR_SSL_ONLY)
std::string GetDefaultConfigDirectory() {
  FilePath home = file_util::GetHomeDir();
  if (home.empty()) {
    LOG(ERROR) << "$HOME is not set.";
    return std::string();
  }
  FilePath dir(home);
  dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
  if (!file_util::CreateDirectory(dir)) {
    LOG(ERROR) << "Failed to create ~/.pki/nssdb directory.";
    return std::string();
  }
  return dir.value();
}

// On non-chromeos platforms, return the default config directory.
// On chromeos, return a read-only directory with fake root CA certs for testing
// (which will not exist on non-testing images).  These root CA certs are used
// by the local Google Accounts server mock we use when testing our login code.
// If this directory is not present, NSS_Init() will fail.  It is up to the
// caller to failover to NSS_NoDB_Init() at that point.
std::string GetInitialConfigDirectory() {
#if defined(OS_CHROMEOS)
  static const char kReadOnlyCertDB[] = "/etc/fake_root_ca/nssdb";
  return std::string(kReadOnlyCertDB);
#else
  return GetDefaultConfigDirectory();
#endif  // defined(OS_CHROMEOS)
}

// Load nss's built-in root certs.
SECMODModule *InitDefaultRootCerts() {
  const char* kModulePath = "libnssckbi.so";
  char modparams[1024];
  snprintf(modparams, sizeof(modparams),
           "name=\"Root Certs\" library=\"%s\"", kModulePath);
  SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE);
  if (root)
    return root;

  // Aw, snap.  Can't find/load root cert shared library.
  // This will make it hard to talk to anybody via https.
  NOTREACHED();
  return NULL;
}
#endif  // !defined(USE_NSS_FOR_SSL_ONLY)

// A singleton to initialize/deinitialize NSPR.
// Separate from the NSS singleton because we initialize NSPR on the UI thread.
class NSPRInitSingleton {
 public:
  NSPRInitSingleton() {
    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
  }

  ~NSPRInitSingleton() {
    PL_ArenaFinish();
    PRStatus prstatus = PR_Cleanup();
    if (prstatus != PR_SUCCESS) {
      LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
    }
  }
};

class NSSInitSingleton {
 public:
  NSSInitSingleton()
      : real_db_slot_(NULL),
        root_(NULL),
        chromeos_user_logged_in_(false) {
    base::EnsureNSPRInit();

    // We *must* have NSS >= 3.12.3.  See bug 26448.
    COMPILE_ASSERT(
        (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
        (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
        (NSS_VMAJOR > 3),
        nss_version_check_failed);
    // Also check the run-time NSS version.
    // NSS_VersionCheck is a >= check, not strict equality.
    if (!NSS_VersionCheck("3.12.3")) {
      // It turns out many people have misconfigured NSS setups, where
      // their run-time NSPR doesn't match the one their NSS was compiled
      // against.  So rather than aborting, complain loudly.
      LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed.  "
                    "We depend on NSS >= 3.12.3, and this error is not fatal "
                    "only because many people have busted NSS setups (for "
                    "example, using the wrong version of NSPR). "
                    "Please upgrade to the latest NSS and NSPR, and if you "
                    "still get this error, contact your distribution "
                    "maintainer.";
    }

    SECStatus status = SECFailure;
#if defined(USE_NSS_FOR_SSL_ONLY)
    // Use the system certificate store, so initialize NSS without database.
    status = NSS_NoDB_Init(NULL);
    if (status != SECSuccess) {
      LOG(ERROR) << "Error initializing NSS without a persistent "
                    "database: NSS error code " << PR_GetError();
    }
#else
    std::string database_dir = GetInitialConfigDirectory();
    if (!database_dir.empty()) {
      // Initialize with a persistent database (likely, ~/.pki/nssdb).
      // Use "sql:" which can be shared by multiple processes safely.
      std::string nss_config_dir =
          StringPrintf("sql:%s", database_dir.c_str());
#if defined(OS_CHROMEOS)
      status = NSS_Init(nss_config_dir.c_str());
#else
      status = NSS_InitReadWrite(nss_config_dir.c_str());
#endif
      if (status != SECSuccess) {
        LOG(ERROR) << "Error initializing NSS with a persistent "
                      "database (" << nss_config_dir
                   << "): NSS error code " << PR_GetError();
      }
    }
    if (status != SECSuccess) {
      LOG(WARNING) << "Initialize NSS without a persistent database "
                      "(~/.pki/nssdb).";
      status = NSS_NoDB_Init(NULL);
      if (status != SECSuccess) {
        LOG(ERROR) << "Error initializing NSS without a persistent "
                      "database: NSS error code " << PR_GetError();
        return;
      }
    }

    // If we haven't initialized the password for the NSS databases,
    // initialize an empty-string password so that we don't need to
    // log in.
    PK11SlotInfo* slot = PK11_GetInternalKeySlot();
    if (slot) {
      // PK11_InitPin may write to the keyDB, but no other thread can use NSS
      // yet, so we don't need to lock.
      if (PK11_NeedUserInit(slot))
        PK11_InitPin(slot, NULL, NULL);
      PK11_FreeSlot(slot);
    }

    // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
    // is fixed, we will no longer need the lock. We should detect this and not
    // initialize a Lock here.
    write_lock_.reset(new Lock());

    root_ = InitDefaultRootCerts();
#endif  // defined(USE_NSS_FOR_SSL_ONLY)
  }

  ~NSSInitSingleton() {
    if (real_db_slot_) {
      SECMOD_CloseUserDB(real_db_slot_);
      PK11_FreeSlot(real_db_slot_);
      real_db_slot_ = NULL;
    }
    if (root_) {
      SECMOD_UnloadUserModule(root_);
      SECMOD_DestroyModule(root_);
      root_ = NULL;
    }

    SECStatus status = NSS_Shutdown();
    if (status != SECSuccess) {
      // We LOG(INFO) because this failure is relatively harmless
      // (leaking, but we're shutting down anyway).
      LOG(INFO) << "NSS_Shutdown failed; see "
                   "http://code.google.com/p/chromium/issues/detail?id=4609";
    }
  }

#if defined(OS_CHROMEOS)
  void OpenPersistentNSSDB() {
    if (!chromeos_user_logged_in_) {
      chromeos_user_logged_in_ = true;

      const std::string modspec =
          StringPrintf("configDir='%s' tokenDescription='Real NSS database'",
                       GetDefaultConfigDirectory().c_str());
      real_db_slot_ = SECMOD_OpenUserDB(modspec.c_str());
      if (real_db_slot_ == NULL) {
        LOG(ERROR) << "Error opening persistent database (" << modspec
                   << "): NSS error code " << PR_GetError();
      } else {
        if (PK11_NeedUserInit(real_db_slot_))
          PK11_InitPin(real_db_slot_, NULL, NULL);
      }
    }
  }
#endif  // defined(OS_CHROMEOS)

  PK11SlotInfo* GetDefaultKeySlot() {
    if (real_db_slot_)
      return PK11_ReferenceSlot(real_db_slot_);
    return PK11_GetInternalKeySlot();
  }

#if defined(USE_NSS)
  Lock* write_lock() {
    return write_lock_.get();
  }
#endif // defined(USE_NSS)

 private:
  PK11SlotInfo* real_db_slot_;  // Overrides internal key slot if non-NULL.
  SECMODModule *root_;
  bool chromeos_user_logged_in_;
#if defined(USE_NSS)
  scoped_ptr<Lock> write_lock_;
#endif // defined(USE_NSS)
};

}  // namespace

namespace base {

void EnsureNSPRInit() {
  Singleton<NSPRInitSingleton>::get();
}

void EnsureNSSInit() {
  Singleton<NSSInitSingleton>::get();
}

#if defined(USE_NSS)
Lock* GetNSSWriteLock() {
  return Singleton<NSSInitSingleton>::get()->write_lock();
}

AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
  // May be NULL if the lock is not needed in our version of NSS.
  if (lock_)
    lock_->Acquire();
}

AutoNSSWriteLock::~AutoNSSWriteLock() {
  if (lock_) {
    lock_->AssertAcquired();
    lock_->Release();
  }
}
#endif  // defined(USE_NSS)

#if defined(OS_CHROMEOS)
void OpenPersistentNSSDB() {
  Singleton<NSSInitSingleton>::get()->OpenPersistentNSSDB();
}
#endif

// TODO(port): Implement this more simply.  We can convert by subtracting an
// offset (the difference between NSPR's and base::Time's epochs).
Time PRTimeToBaseTime(PRTime prtime) {
  PRExplodedTime prxtime;
  PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);

  base::Time::Exploded exploded;
  exploded.year         = prxtime.tm_year;
  exploded.month        = prxtime.tm_month + 1;
  exploded.day_of_week  = prxtime.tm_wday;
  exploded.day_of_month = prxtime.tm_mday;
  exploded.hour         = prxtime.tm_hour;
  exploded.minute       = prxtime.tm_min;
  exploded.second       = prxtime.tm_sec;
  exploded.millisecond  = prxtime.tm_usec / 1000;

  return Time::FromUTCExploded(exploded);
}

PK11SlotInfo* GetDefaultNSSKeySlot() {
  return Singleton<NSSInitSingleton>::get()->GetDefaultKeySlot();
}

}  // namespace base
<commit_msg>NSS's filesystem speed detection doesn't work with the latest versions of sqlite, such as 3.6.22.  Set the NSS_SDB_USE_CACHE environment variable to "yes" to override NSS's detection if the database is on NFS.<commit_after>// Copyright (c) 2008-2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/nss_util.h"
#include "base/nss_util_internal.h"

#include <nss.h>
#include <plarena.h>
#include <prerror.h>
#include <prinit.h>
#include <prtime.h>
#include <pk11pub.h>
#include <secmod.h>

#if defined(OS_LINUX)
#include <linux/magic.h>
#include <sys/vfs.h>
#endif

#include "base/file_util.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/string_util.h"

// USE_NSS means we use NSS for everything crypto-related.  If USE_NSS is not
// defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
// use NSS for crypto or certificate verification, and we don't use the NSS
// certificate and key databases.
#if defined(USE_NSS)
#include "base/env_var.h"
#include "base/lock.h"
#include "base/scoped_ptr.h"
#endif  // defined(USE_NSS)

namespace {

#if defined(USE_NSS)
FilePath GetDefaultConfigDirectory() {
  FilePath dir = file_util::GetHomeDir();
  if (dir.empty()) {
    LOG(ERROR) << "Failed to get home directory.";
    return dir;
  }
  dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
  if (!file_util::CreateDirectory(dir)) {
    LOG(ERROR) << "Failed to create ~/.pki/nssdb directory.";
    dir.clear();
  }
  return dir;
}

// On non-chromeos platforms, return the default config directory.
// On chromeos, return a read-only directory with fake root CA certs for testing
// (which will not exist on non-testing images).  These root CA certs are used
// by the local Google Accounts server mock we use when testing our login code.
// If this directory is not present, NSS_Init() will fail.  It is up to the
// caller to failover to NSS_NoDB_Init() at that point.
FilePath GetInitialConfigDirectory() {
#if defined(OS_CHROMEOS)
  static const FilePath::CharType kReadOnlyCertDB[] =
      FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
  return FilePath(kReadOnlyCertDB);
#else
  return GetDefaultConfigDirectory();
#endif  // defined(OS_CHROMEOS)
}

// NSS creates a local cache of the sqlite database if it detects that the
// filesystem the database is on is much slower than the local disk.  The
// detection doesn't work with the latest versions of sqlite, such as 3.6.22
// (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561).  So we set
// the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
// detection when database_dir is on NFS.  See http://crbug.com/48585.
//
// TODO(wtc): port this function to other USE_NSS platforms.  It is defined
// only for OS_LINUX simply because the statfs structure is OS-specific.
void UseLocalCacheOfNSSDatabaseIfNFS(const FilePath& database_dir) {
#if defined(OS_LINUX)
  struct statfs buf;
  if (statfs(database_dir.value().c_str(), &buf) == 0) {
    if (buf.f_type == NFS_SUPER_MAGIC) {
      scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create());
      const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
      if (!env->HasEnv(use_cache_env_var))
        env->SetEnv(use_cache_env_var, "yes");
    }
  }
#endif  // defined(OS_LINUX)
}

// Load nss's built-in root certs.
SECMODModule *InitDefaultRootCerts() {
  const char* kModulePath = "libnssckbi.so";
  char modparams[1024];
  snprintf(modparams, sizeof(modparams),
           "name=\"Root Certs\" library=\"%s\"", kModulePath);
  SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE);
  if (root)
    return root;

  // Aw, snap.  Can't find/load root cert shared library.
  // This will make it hard to talk to anybody via https.
  NOTREACHED();
  return NULL;
}
#endif  // defined(USE_NSS)

// A singleton to initialize/deinitialize NSPR.
// Separate from the NSS singleton because we initialize NSPR on the UI thread.
class NSPRInitSingleton {
 public:
  NSPRInitSingleton() {
    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
  }

  ~NSPRInitSingleton() {
    PL_ArenaFinish();
    PRStatus prstatus = PR_Cleanup();
    if (prstatus != PR_SUCCESS) {
      LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
    }
  }
};

class NSSInitSingleton {
 public:
  NSSInitSingleton()
      : real_db_slot_(NULL),
        root_(NULL),
        chromeos_user_logged_in_(false) {
    base::EnsureNSPRInit();

    // We *must* have NSS >= 3.12.3.  See bug 26448.
    COMPILE_ASSERT(
        (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
        (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
        (NSS_VMAJOR > 3),
        nss_version_check_failed);
    // Also check the run-time NSS version.
    // NSS_VersionCheck is a >= check, not strict equality.
    if (!NSS_VersionCheck("3.12.3")) {
      // It turns out many people have misconfigured NSS setups, where
      // their run-time NSPR doesn't match the one their NSS was compiled
      // against.  So rather than aborting, complain loudly.
      LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed.  "
                    "We depend on NSS >= 3.12.3, and this error is not fatal "
                    "only because many people have busted NSS setups (for "
                    "example, using the wrong version of NSPR). "
                    "Please upgrade to the latest NSS and NSPR, and if you "
                    "still get this error, contact your distribution "
                    "maintainer.";
    }

    SECStatus status = SECFailure;
#if !defined(USE_NSS)
    // Use the system certificate store, so initialize NSS without database.
    status = NSS_NoDB_Init(NULL);
    if (status != SECSuccess) {
      LOG(ERROR) << "Error initializing NSS without a persistent "
                    "database: NSS error code " << PR_GetError();
    }
#else
    FilePath database_dir = GetInitialConfigDirectory();
    if (!database_dir.empty()) {
      UseLocalCacheOfNSSDatabaseIfNFS(database_dir);

      // Initialize with a persistent database (likely, ~/.pki/nssdb).
      // Use "sql:" which can be shared by multiple processes safely.
      std::string nss_config_dir =
          StringPrintf("sql:%s", database_dir.value().c_str());
#if defined(OS_CHROMEOS)
      status = NSS_Init(nss_config_dir.c_str());
#else
      status = NSS_InitReadWrite(nss_config_dir.c_str());
#endif
      if (status != SECSuccess) {
        LOG(ERROR) << "Error initializing NSS with a persistent "
                      "database (" << nss_config_dir
                   << "): NSS error code " << PR_GetError();
      }
    }
    if (status != SECSuccess) {
      LOG(WARNING) << "Initialize NSS without a persistent database "
                      "(~/.pki/nssdb).";
      status = NSS_NoDB_Init(NULL);
      if (status != SECSuccess) {
        LOG(ERROR) << "Error initializing NSS without a persistent "
                      "database: NSS error code " << PR_GetError();
        return;
      }
    }

    // If we haven't initialized the password for the NSS databases,
    // initialize an empty-string password so that we don't need to
    // log in.
    PK11SlotInfo* slot = PK11_GetInternalKeySlot();
    if (slot) {
      // PK11_InitPin may write to the keyDB, but no other thread can use NSS
      // yet, so we don't need to lock.
      if (PK11_NeedUserInit(slot))
        PK11_InitPin(slot, NULL, NULL);
      PK11_FreeSlot(slot);
    }

    // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
    // is fixed, we will no longer need the lock. We should detect this and not
    // initialize a Lock here.
    write_lock_.reset(new Lock());

    root_ = InitDefaultRootCerts();
#endif  // !defined(USE_NSS)
  }

  ~NSSInitSingleton() {
    if (real_db_slot_) {
      SECMOD_CloseUserDB(real_db_slot_);
      PK11_FreeSlot(real_db_slot_);
      real_db_slot_ = NULL;
    }
    if (root_) {
      SECMOD_UnloadUserModule(root_);
      SECMOD_DestroyModule(root_);
      root_ = NULL;
    }

    SECStatus status = NSS_Shutdown();
    if (status != SECSuccess) {
      // We LOG(INFO) because this failure is relatively harmless
      // (leaking, but we're shutting down anyway).
      LOG(INFO) << "NSS_Shutdown failed; see "
                   "http://code.google.com/p/chromium/issues/detail?id=4609";
    }
  }

#if defined(OS_CHROMEOS)
  void OpenPersistentNSSDB() {
    if (!chromeos_user_logged_in_) {
      chromeos_user_logged_in_ = true;

      const std::string modspec =
          StringPrintf("configDir='%s' tokenDescription='Real NSS database'",
                       GetDefaultConfigDirectory().value().c_str());
      real_db_slot_ = SECMOD_OpenUserDB(modspec.c_str());
      if (real_db_slot_ == NULL) {
        LOG(ERROR) << "Error opening persistent database (" << modspec
                   << "): NSS error code " << PR_GetError();
      } else {
        if (PK11_NeedUserInit(real_db_slot_))
          PK11_InitPin(real_db_slot_, NULL, NULL);
      }
    }
  }
#endif  // defined(OS_CHROMEOS)

  PK11SlotInfo* GetDefaultKeySlot() {
    if (real_db_slot_)
      return PK11_ReferenceSlot(real_db_slot_);
    return PK11_GetInternalKeySlot();
  }

#if defined(USE_NSS)
  Lock* write_lock() {
    return write_lock_.get();
  }
#endif  // defined(USE_NSS)

 private:
  PK11SlotInfo* real_db_slot_;  // Overrides internal key slot if non-NULL.
  SECMODModule *root_;
  bool chromeos_user_logged_in_;
#if defined(USE_NSS)
  scoped_ptr<Lock> write_lock_;
#endif  // defined(USE_NSS)
};

}  // namespace

namespace base {

void EnsureNSPRInit() {
  Singleton<NSPRInitSingleton>::get();
}

void EnsureNSSInit() {
  Singleton<NSSInitSingleton>::get();
}

#if defined(USE_NSS)
Lock* GetNSSWriteLock() {
  return Singleton<NSSInitSingleton>::get()->write_lock();
}

AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
  // May be NULL if the lock is not needed in our version of NSS.
  if (lock_)
    lock_->Acquire();
}

AutoNSSWriteLock::~AutoNSSWriteLock() {
  if (lock_) {
    lock_->AssertAcquired();
    lock_->Release();
  }
}
#endif  // defined(USE_NSS)

#if defined(OS_CHROMEOS)
void OpenPersistentNSSDB() {
  Singleton<NSSInitSingleton>::get()->OpenPersistentNSSDB();
}
#endif

// TODO(port): Implement this more simply.  We can convert by subtracting an
// offset (the difference between NSPR's and base::Time's epochs).
Time PRTimeToBaseTime(PRTime prtime) {
  PRExplodedTime prxtime;
  PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);

  base::Time::Exploded exploded;
  exploded.year         = prxtime.tm_year;
  exploded.month        = prxtime.tm_month + 1;
  exploded.day_of_week  = prxtime.tm_wday;
  exploded.day_of_month = prxtime.tm_mday;
  exploded.hour         = prxtime.tm_hour;
  exploded.minute       = prxtime.tm_min;
  exploded.second       = prxtime.tm_sec;
  exploded.millisecond  = prxtime.tm_usec / 1000;

  return Time::FromUTCExploded(exploded);
}

PK11SlotInfo* GetDefaultNSSKeySlot() {
  return Singleton<NSSInitSingleton>::get()->GetDefaultKeySlot();
}

}  // namespace base
<|endoftext|>