<commit_before>#include <iostream>
#include <algorithm>
using namespace std;

bool binary_search(int* arr, int begin, int end, int element)
{
	if (begin < end)
	{
		if (element == arr[(begin+end)/2])
		{
			return true;
		}
		else if (element < arr[(begin+end)/2])
		{
			binary_search(arr, begin, (begin+end)/2, element);
		}
		else
			binary_search(arr, ((begin+end)/2) +1, end, element);
	}
	else
		return false;

}

int main(int argc, char const *argv[])
{
	int arr[] = {2, 4, 5, 23, 434, 12, 45, 65 , 34};
	int size = sizeof(arr)/sizeof(arr[0]);
	sort(arr, arr + size);
	int element = 34;
	binary_search(arr, 0, size, element)? cout<<"Found"<<endl:cout<<"Not found"<<endl;

	return 0;
}<commit_msg>return added<commit_after>#include <iostream>
#include <algorithm>
using namespace std;

bool binary_search(int* arr, int begin, int end, int element)
{
	if (begin < end)
	{
		if (element == arr[(begin+end)/2])
		{
			return true;
		}
		else if (element < arr[(begin+end)/2])
		{
			return binary_search(arr, begin, (begin+end)/2, element);
		}
		else
			return binary_search(arr, ((begin+end)/2) +1, end, element);
	}
	else
		return false;

}

int main(int argc, char const *argv[])
{
	int arr[] = {2, 4, 5, 23, 434, 12, 45, 65 , 34};
	int size = sizeof(arr)/sizeof(arr[0]);
	sort(arr, arr + size);
	int element = 1;
	binary_search(arr, 0, size, element)? cout<<"Found"<<endl:cout<<"Not found"<<endl;

	return 0;
}<|endoftext|>


<commit_before>//===- CallGraph.cpp - Build a Module's call graph ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CallGraph class and provides the BasicCallGraph
// default implementation.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/CallSite.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

#include <map>

using namespace llvm;

namespace llvm {
  void initializeAACallGraphPass(PassRegistry&);
  void initializeCallGraphWrapperPassAnalysisGroup(PassRegistry&);
}

namespace {

//===----------------------------------------------------------------------===//
// AACallGraph class definition
//
class AACallGraph : public CallGraphWrapperPass {

public:
  static char ID; // Class identification, replacement for typeinfo
  AACallGraph() {
      initializeAACallGraphPass(*PassRegistry::getPassRegistry());
    }

  // runOnModule - Compute the call graph for the specified module.
  virtual bool runOnModule(Module &M) override {
    CallGraphWrapperPass::runOnModule(M);
    return false;
  }

  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.setPreservesAll();
  }

  virtual void print(raw_ostream &OS, const Module *) const override {
    CallGraphWrapperPass::print(OS, 0);
  }

  virtual void releaseMemory() override  {
    CallGraphWrapperPass::releaseMemory();
  }

private:

};

} //End anonymous namespace

INITIALIZE_AG_PASS(AACallGraph, CallGraphWrapperPass, "aliascg",
                   "Alias Analysis CallGraph Construction", false, true, true)

char AACallGraph::ID = 0;

// Enuse that users of CallGraph.h also link with this file
DEFINING_FILE_FOR(AACallGraph)
<commit_msg>removing Macro at the end of AACallGraph.cpp. Breaks comilation with llvm-3.8<commit_after>//===- CallGraph.cpp - Build a Module's call graph ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the CallGraph class and provides the BasicCallGraph
// default implementation.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/CallSite.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

#include <map>

using namespace llvm;

namespace llvm {
  void initializeAACallGraphPass(PassRegistry&);
  void initializeCallGraphWrapperPassAnalysisGroup(PassRegistry&);
}

namespace {

//===----------------------------------------------------------------------===//
// AACallGraph class definition
//
class AACallGraph : public CallGraphWrapperPass {

public:
  static char ID; // Class identification, replacement for typeinfo
  AACallGraph() {
      initializeAACallGraphPass(*PassRegistry::getPassRegistry());
    }

  // runOnModule - Compute the call graph for the specified module.
  virtual bool runOnModule(Module &M) override {
    CallGraphWrapperPass::runOnModule(M);
    return false;
  }

  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.setPreservesAll();
  }

  virtual void print(raw_ostream &OS, const Module *) const override {
    CallGraphWrapperPass::print(OS, 0);
  }

  virtual void releaseMemory() override  {
    CallGraphWrapperPass::releaseMemory();
  }

private:

};

} //End anonymous namespace

INITIALIZE_AG_PASS(AACallGraph, CallGraphWrapperPass, "aliascg",
                   "Alias Analysis CallGraph Construction", false, true, true)

char AACallGraph::ID = 0;

// Enuse that users of CallGraph.h also link with this file

<|endoftext|>


<commit_before>/*

Copyright (c) 2010, Arvid Norberg
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 author 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 "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/error_code.hpp"

#include <fstream>

using namespace libtorrent;

int test_main()
{
	int http_port = start_web_server();
	int udp_port = start_tracker();

	int prev_udp_announces = g_udp_tracker_requests;
	int prev_http_announces = g_http_tracker_requests;

	int const alert_mask = alert::all_categories
		& ~alert::progress_notification
		& ~alert::stats_notification;

	session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask);

	settings_pack pack;
	pack.set_int(settings_pack::half_open_limit, 1);
	pack.set_bool(settings_pack::announce_to_all_trackers, true);
	pack.set_bool(settings_pack::announce_to_all_tiers, true);
	s->apply_settings(pack);

	error_code ec;
	create_directory("./tmp1_tracker", ec);
	std::ofstream file("./tmp1_tracker/temporary");
	boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	char tracker_url[200];
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 0);

	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 1);

	add_torrent_params addp;
	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.ti = t;
	addp.save_path = "./tmp1_tracker";
	torrent_handle h = s->add_torrent(addp);

	for (int i = 0; i < 100; ++i)
	{
		print_alerts(*s, "s");
		test_sleep(100);
		if (g_udp_tracker_requests == prev_udp_announces + 1
			&& g_http_tracker_requests == prev_http_announces + 1) break;
	}

	// we should have announced to the tracker by now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	// we should have announced the stopped event now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2);

	// ========================================
	// test that we move on to try the next tier if the first one fails
	// ========================================

	s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask);

	pack.clear();
	pack.set_int(settings_pack::half_open_limit, 1);
	pack.set_bool(settings_pack::announce_to_all_trackers, true);
	pack.set_bool(settings_pack::announce_to_all_tiers, true);
	pack.set_int(settings_pack::tracker_completion_timeout, 2);
	pack.set_int(settings_pack::tracker_receive_timeout, 1);
	s->apply_settings(pack);

	create_directory("./tmp2_tracker", ec);
	file.open("./tmp2_tracker/temporary");
	t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	// this should fail
	snprintf(tracker_url, sizeof(tracker_url), "udp://www.google.com:80/announce");
	t->add_tracker(tracker_url, 0);

	// and this should fail
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce");
	t->add_tracker(tracker_url, 1);

	// this should be announced to
	// udp trackers are prioritized if they're on the same host as an http one
	// so this must be before the http one on 127.0.0.1
	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 2);

	// and this should not be announced to (since the one before it succeeded)
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 3);

	prev_udp_announces = g_udp_tracker_requests;
	prev_http_announces = g_http_tracker_requests;

	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.ti = t;
	addp.save_path = "./tmp2_tracker";
	h = s->add_torrent(addp);

	for (int i = 0; i < 10; ++i)
	{
		print_alerts(*s, "s");
		test_sleep(1000);
		if (g_udp_tracker_requests == prev_udp_announces + 1) break;
	}

	test_sleep(1000);

	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	stop_tracker();
	stop_web_server();

	return 0;
}

<commit_msg>one more UAC path fix in unit test<commit_after>/*

Copyright (c) 2010, Arvid Norberg
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 author 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 "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/error_code.hpp"

#include <fstream>

using namespace libtorrent;

int test_main()
{
	int http_port = start_web_server();
	int udp_port = start_tracker();

	int prev_udp_announces = g_udp_tracker_requests;
	int prev_http_announces = g_http_tracker_requests;

	int const alert_mask = alert::all_categories
		& ~alert::progress_notification
		& ~alert::stats_notification;

	session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask);

	settings_pack pack;
	pack.set_int(settings_pack::half_open_limit, 1);
	pack.set_bool(settings_pack::announce_to_all_trackers, true);
	pack.set_bool(settings_pack::announce_to_all_tiers, true);
	s->apply_settings(pack);

	error_code ec;
	create_directory("tmp1_tracker", ec);
	std::ofstream file(combine_path("tmp1_tracker", "temporary").c_str());
	boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	char tracker_url[200];
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 0);

	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 1);

	add_torrent_params addp;
	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.ti = t;
	addp.save_path = "tmp1_tracker";
	torrent_handle h = s->add_torrent(addp);

	for (int i = 0; i < 100; ++i)
	{
		print_alerts(*s, "s");
		test_sleep(100);
		if (g_udp_tracker_requests == prev_udp_announces + 1
			&& g_http_tracker_requests == prev_http_announces + 1) break;
	}

	// we should have announced to the tracker by now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	// we should have announced the stopped event now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2);

	// ========================================
	// test that we move on to try the next tier if the first one fails
	// ========================================

	s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask);

	pack.clear();
	pack.set_int(settings_pack::half_open_limit, 1);
	pack.set_bool(settings_pack::announce_to_all_trackers, true);
	pack.set_bool(settings_pack::announce_to_all_tiers, true);
	pack.set_int(settings_pack::tracker_completion_timeout, 2);
	pack.set_int(settings_pack::tracker_receive_timeout, 1);
	s->apply_settings(pack);

	create_directory("tmp2_tracker", ec);
	file.open(combine_path("tmp2_tracker", "temporary").c_str());
	t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	// this should fail
	snprintf(tracker_url, sizeof(tracker_url), "udp://www.google.com:80/announce");
	t->add_tracker(tracker_url, 0);

	// and this should fail
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce");
	t->add_tracker(tracker_url, 1);

	// this should be announced to
	// udp trackers are prioritized if they're on the same host as an http one
	// so this must be before the http one on 127.0.0.1
	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 2);

	// and this should not be announced to (since the one before it succeeded)
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 3);

	prev_udp_announces = g_udp_tracker_requests;
	prev_http_announces = g_http_tracker_requests;

	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.ti = t;
	addp.save_path = "tmp2_tracker";
	h = s->add_torrent(addp);

	for (int i = 0; i < 10; ++i)
	{
		print_alerts(*s, "s");
		test_sleep(1000);
		if (g_udp_tracker_requests == prev_udp_announces + 1) break;
	}

	test_sleep(1000);

	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	stop_tracker();
	stop_web_server();

	return 0;
}

<|endoftext|>


<commit_before>
/***************************************************************************
 *   This file is part of the AudioThumbs.                                 *
 *   Copyright (C) 2009 Vytautas Mickus <vmickus@gmail.com>                *
 *   Copyright (C) 2011 Raizner Evgeniy <razrfalcon@gmail.com>             *
 *   Copyright (C) 2014 eplightning <me2.legion@gmail.com>                 *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or modify  *
 *   it  under the terms of the GNU Lesser General Public License version  *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,            *
 *   MA  02110-1301  USA                                                   *
 ***************************************************************************/

#include "AudioThumbs.h"

#include <QImage>
#include <QFile>
#include <QMimeDatabase>
#include <QMimeType>

#include <taglib/fileref.h>
#include <taglib/id3v2tag.h>
#include <taglib/mpegfile.h>
#include <taglib/attachedpictureframe.h>
#include <taglib/flacfile.h>
#include <taglib/flacpicture.h>
#include <taglib/mp4file.h>
#include <taglib/mp4properties.h>
#include <taglib/mp4tag.h>
#include <taglib/mp4coverart.h>
#include <taglib/xiphcomment.h>
#include <taglib/xingheader.h>
#include <taglib/oggflacfile.h>
#include <taglib/oggfile.h>
#include <taglib/vorbisfile.h>

#include <FLAC++/metadata.h>

extern "C"
{
    Q_DECL_EXPORT ThumbCreator *new_creator()
    {
        return new ATCreator;
    }
}

ATCreator::ATCreator()
{

}

ATCreator::~ATCreator()
{

}

bool ATCreator::create ( const QString &path, int /*w*/, int /*h*/, QImage &img )
{
    bool bRet = false;

    QMimeDatabase db;
    QMimeType type = db.mimeTypeForFile(path);

    if (type.name() == "audio/mpeg") {
        TagLib::MPEG::File mp3File(path.toUtf8());
        TagLib::ID3v2::Tag *mp3Tag = mp3File.ID3v2Tag();
        TagLib::ID3v2::FrameList fList = mp3Tag->frameList("APIC");
        TagLib::ID3v2::AttachedPictureFrame *pic;
        pic = static_cast<TagLib::ID3v2::AttachedPictureFrame *>(fList.front());
        if (!pic->picture().isEmpty()) {
            img.loadFromData((const uchar *) pic->picture().data(),pic->picture().size());
            bRet = true;
        }

    } else if (type.name() == "audio/flac" || type.name() == "audio/x-flac") {
        TagLib::FLAC::File ff(path.toUtf8());
        TagLib::List<TagLib::FLAC::Picture *> coverList;

        if (!ff.pictureList().isEmpty()) {
            coverList.append(ff.pictureList().front());
            TagLib::ByteVector coverData = coverList.front()->data();
            QByteArray data;
            data.setRawData(coverData.data(),coverData.size());
            img.loadFromData(data);
            bRet = true;
            return bRet;
        }

    } else if (type.name() == "audio/mp4") {
        TagLib::MP4::File mp4file(path.toUtf8());
        TagLib::MP4::Tag *tag = mp4file.tag();
        TagLib::MP4::ItemListMap map=tag->itemListMap();
        QByteArray data;

        if (!map.isEmpty()) {
            for (TagLib::MP4::ItemListMap::ConstIterator it = map.begin(); it != map.end(); ++it) {
                TagLib::MP4::CoverArtList coverList=(*it).second.toCoverArtList();
                    if (!coverList.isEmpty()) {
                        TagLib::MP4::CoverArt cover=coverList[0];

                        TagLib::ByteVector coverData=cover.data();
                        data.setRawData(coverData.data(),coverData.size());
                        img.loadFromData(data);

                        bRet = true;
                        return bRet;
                  }
              }
         }
    } else if (type.name() == "audio/x-vorbis+ogg" || type.name() == "audio/ogg") {
	// this part from Coquillo audio tag editor
        TagLib::Ogg::Vorbis::File file(path.toUtf8());
        TagLib::Ogg::XiphComment *tag = file.tag();

        if (tag->contains("METADATA_BLOCK_PICTURE")) {
            TagLib::StringList blocks = tag->fieldListMap()["METADATA_BLOCK_PICTURE"];

            for (uint i = 0; i < blocks.size(); i++) {
                QByteArray data = QByteArray::fromBase64(blocks[i].toCString());
                QDataStream s(&data, QIODevice::ReadOnly);

                int type;
                uint mimelen;
                int descrlen;
                int datalen;

                int w;
                int h;
                int c;
                int ic;

                char * mime;
                char * descr;
                char * pic;

                s >> type;
                s >> mimelen;

                mime = new char[mimelen+1];
                s.readRawData(mime, mimelen);

                mime[mimelen] = 0;

                s >> descrlen;

                descr = new char[descrlen+1];
                s.readRawData(descr, descrlen);

                descr[descrlen] = 0;

                s >> w >> h >> c >> ic >> datalen;

                if (!datalen)
                  return false;

                pic = new char[datalen];
                s.readRawData(pic, datalen);
                img = QImage::fromData(QByteArray(pic, datalen));

                bRet = true;
            }
        }
    }

    return bRet;
}

ThumbCreator::Flags ATCreator::flags() const
{
    return (Flags)(None);
}
<commit_msg>Check if frameList is empty for mp3<commit_after>
/***************************************************************************
 *   This file is part of the AudioThumbs.                                 *
 *   Copyright (C) 2009 Vytautas Mickus <vmickus@gmail.com>                *
 *   Copyright (C) 2011 Raizner Evgeniy <razrfalcon@gmail.com>             *
 *   Copyright (C) 2014 eplightning <me2.legion@gmail.com>                 *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or modify  *
 *   it  under the terms of the GNU Lesser General Public License version  *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,            *
 *   MA  02110-1301  USA                                                   *
 ***************************************************************************/

#include "AudioThumbs.h"

#include <QImage>
#include <QFile>
#include <QMimeDatabase>
#include <QMimeType>

#include <taglib/fileref.h>
#include <taglib/id3v2tag.h>
#include <taglib/mpegfile.h>
#include <taglib/attachedpictureframe.h>
#include <taglib/flacfile.h>
#include <taglib/flacpicture.h>
#include <taglib/mp4file.h>
#include <taglib/mp4properties.h>
#include <taglib/mp4tag.h>
#include <taglib/mp4coverart.h>
#include <taglib/xiphcomment.h>
#include <taglib/xingheader.h>
#include <taglib/oggflacfile.h>
#include <taglib/oggfile.h>
#include <taglib/vorbisfile.h>

#include <FLAC++/metadata.h>

extern "C"
{
    Q_DECL_EXPORT ThumbCreator *new_creator()
    {
        return new ATCreator;
    }
}

ATCreator::ATCreator()
{

}

ATCreator::~ATCreator()
{

}

bool ATCreator::create ( const QString &path, int /*w*/, int /*h*/, QImage &img )
{
    bool bRet = false;

    QMimeDatabase db;
    QMimeType type = db.mimeTypeForFile(path);

    if (type.name() == "audio/mpeg") {
        TagLib::MPEG::File mp3File(path.toUtf8());
        TagLib::ID3v2::Tag *mp3Tag = mp3File.ID3v2Tag();
        TagLib::ID3v2::FrameList fList = mp3Tag->frameList("APIC");
        if (!fList.isEmpty()) {
            TagLib::ID3v2::AttachedPictureFrame *pic;
            pic = static_cast<TagLib::ID3v2::AttachedPictureFrame *>(fList.front());
            if (!pic->picture().isEmpty()) {
                img.loadFromData((const uchar *) pic->picture().data(),pic->picture().size());
                bRet = true;
            }
        }
    } else if (type.name() == "audio/flac" || type.name() == "audio/x-flac") {
        TagLib::FLAC::File ff(path.toUtf8());
        TagLib::List<TagLib::FLAC::Picture *> coverList;

        if (!ff.pictureList().isEmpty()) {
            coverList.append(ff.pictureList().front());
            TagLib::ByteVector coverData = coverList.front()->data();
            QByteArray data;
            data.setRawData(coverData.data(),coverData.size());
            img.loadFromData(data);
            bRet = true;
            return bRet;
        }

    } else if (type.name() == "audio/mp4") {
        TagLib::MP4::File mp4file(path.toUtf8());
        TagLib::MP4::Tag *tag = mp4file.tag();
        TagLib::MP4::ItemListMap map=tag->itemListMap();
        QByteArray data;

        if (!map.isEmpty()) {
            for (TagLib::MP4::ItemListMap::ConstIterator it = map.begin(); it != map.end(); ++it) {
                TagLib::MP4::CoverArtList coverList=(*it).second.toCoverArtList();
                    if (!coverList.isEmpty()) {
                        TagLib::MP4::CoverArt cover=coverList[0];

                        TagLib::ByteVector coverData=cover.data();
                        data.setRawData(coverData.data(),coverData.size());
                        img.loadFromData(data);

                        bRet = true;
                        return bRet;
                  }
              }
         }
    } else if (type.name() == "audio/x-vorbis+ogg" || type.name() == "audio/ogg") {
	// this part from Coquillo audio tag editor
        TagLib::Ogg::Vorbis::File file(path.toUtf8());
        TagLib::Ogg::XiphComment *tag = file.tag();

        if (tag->contains("METADATA_BLOCK_PICTURE")) {
            TagLib::StringList blocks = tag->fieldListMap()["METADATA_BLOCK_PICTURE"];

            for (uint i = 0; i < blocks.size(); i++) {
                QByteArray data = QByteArray::fromBase64(blocks[i].toCString());
                QDataStream s(&data, QIODevice::ReadOnly);

                int type;
                uint mimelen;
                int descrlen;
                int datalen;

                int w;
                int h;
                int c;
                int ic;

                char * mime;
                char * descr;
                char * pic;

                s >> type;
                s >> mimelen;

                mime = new char[mimelen+1];
                s.readRawData(mime, mimelen);

                mime[mimelen] = 0;

                s >> descrlen;

                descr = new char[descrlen+1];
                s.readRawData(descr, descrlen);

                descr[descrlen] = 0;

                s >> w >> h >> c >> ic >> datalen;

                if (!datalen)
                  return false;

                pic = new char[datalen];
                s.readRawData(pic, datalen);
                img = QImage::fromData(QByteArray(pic, datalen));

                bRet = true;
            }
        }
    }

    return bRet;
}

ThumbCreator::Flags ATCreator::flags() const
{
    return (Flags)(None);
}
<|endoftext|>


<commit_before>/**
 * \author Andreas Misje
 * \date 2017
 * \copyright MIT
 */

#include "QDrive.h"
#include "BlockDevice.h"
#include "FileSystem.h"
using namespace QDrive;
#include <QDBusArgument>

BlockDevice::BlockDevice(const QDBusObjectPath &path, QObject *parent)
	: DBusObject(path, parent)
{
}

bool BlockDevice::isValid() const
{
	try
	{
		return isBlockDevice(path(),replyTimeout());
	}
	catch (const DBusException &exception)
	{
		return false;
	}
}

bool BlockDevice::isBlockDevice(const QDBusObjectPath &path, int replyTimeout)
{
	return QDrive::hasInterface(path, Interface::UDisks2("Block"), replyTimeout);
}

bool BlockDevice::isBlockDevice(const QList<QString> &interfaces)
{
	return interfaces.contains(Interface::UDisks2("Block"));
}

QString BlockDevice::device() const
{
	return dbusProperty(Interface::UDisks2("Block"), "Device").toString();
}

QString BlockDevice::preferredDevice() const
{
	return dbusProperty(Interface::UDisks2("Block"), "PreferredDevice").toString();
}

QStringList BlockDevice::symlinks() const
{
	return aayToStringList(dbusProperty(Interface::UDisks2("Block"), "Symlinks")
			.value<QDBusArgument>());
}

int BlockDevice::deviceNumber() const
{
	return dbusProperty(Interface::UDisks2("Block"), "DeviceNumber").toInt();
}

QString BlockDevice::id() const
{
	return dbusProperty(Interface::UDisks2("Block"), "Id").toString();
}

qulonglong BlockDevice::size() const
{
	return dbusProperty(Interface::UDisks2("Block"), "Size").toULongLong();
}

bool BlockDevice::isReadOnly() const
{
	return dbusProperty(Interface::UDisks2("Block"), "ReadOnly").toBool();
}

QDBusObjectPath BlockDevice::drive() const
{
	return dbusProperty(Interface::UDisks2("Block"), "Drive").value<QDBusObjectPath>();
}

QObject *BlockDevice::driveObject() const
{
	return new Drive(drive());
}

QString BlockDevice::usage() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdUsage").toString();
}

QString BlockDevice::type() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdType").toString();
}

QString BlockDevice::label() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdLabel").toString();
}

QString BlockDevice::uuid() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdUUID").toString();
}

QDBusObjectPath BlockDevice::cryptoDevicePath() const
{
	return dbusProperty(Interface::UDisks2("Block"), "CryptoBackingDevice").value<QDBusObjectPath>();
}

QObject *BlockDevice::cryptoDeviceObject()
{
	auto path = cryptoDevicePath();
	if (!path.path().isEmpty())
		return new BlockDevice(path, this);

	return {};
}

bool BlockDevice::isSystem() const
{
	return dbusProperty(Interface::UDisks2("Block"), "HintSystem").toBool();
}

QString BlockDevice::name() const
{
	return dbusProperty(Interface::UDisks2("Block"), "HintName").toString();
}

bool BlockDevice::hasFileSystem() const
{
	return FileSystem::isFileSystem(path(), replyTimeout());
}

QDBusObjectPath BlockDevice::fileSystem() const
{
	if (hasFileSystem())
		return path();

	return {};
}

QDebug operator <<(QDebug d, const QDrive::BlockDevice &blockDevice)
{
	d.nospace() << "Block device " << blockDevice.path().path() << ":\n";

	bool valid = blockDevice.isValid();
	d.nospace() << "  valid:\t\t" << valid;
	if (valid)
	{
		d.nospace() << "\n  device:\t\t" << blockDevice.device() << '\n';
		d.nospace() << "  ID:\t\t\t" << blockDevice.id() << '\n';
		d.nospace() << "  size:\t\t\t" << blockDevice.size() << '\n';
		d.nospace() << "  read-only:\t\t" << blockDevice.isReadOnly() << '\n';
		d.nospace() << "  drive:\t\t" << blockDevice.drive().path() << '\n';
		d.nospace() << "  label:\t\t" << blockDevice.label() << '\n';
		d.nospace() << "  UUID:\t\t\t" << blockDevice.uuid() << '\n';
		d.nospace() << "  symlinks:\t\t" << blockDevice.symlinks() << '\n';
		d.nospace() << "  has fs:\t\t" << blockDevice.hasFileSystem() << '\n';
	}

	return d.nospace();
}
<commit_msg>BlockDevice: Return empty string instead of "/" if no drive<commit_after>/**
 * \author Andreas Misje
 * \date 2017
 * \copyright MIT
 */

#include "QDrive.h"
#include "BlockDevice.h"
#include "FileSystem.h"
using namespace QDrive;
#include <QDBusArgument>

BlockDevice::BlockDevice(const QDBusObjectPath &path, QObject *parent)
	: DBusObject(path, parent)
{
}

bool BlockDevice::isValid() const
{
	try
	{
		return isBlockDevice(path(),replyTimeout());
	}
	catch (const DBusException &exception)
	{
		return false;
	}
}

bool BlockDevice::isBlockDevice(const QDBusObjectPath &path, int replyTimeout)
{
	return QDrive::hasInterface(path, Interface::UDisks2("Block"), replyTimeout);
}

bool BlockDevice::isBlockDevice(const QList<QString> &interfaces)
{
	return interfaces.contains(Interface::UDisks2("Block"));
}

QString BlockDevice::device() const
{
	return dbusProperty(Interface::UDisks2("Block"), "Device").toString();
}

QString BlockDevice::preferredDevice() const
{
	return dbusProperty(Interface::UDisks2("Block"), "PreferredDevice").toString();
}

QStringList BlockDevice::symlinks() const
{
	return aayToStringList(dbusProperty(Interface::UDisks2("Block"), "Symlinks")
			.value<QDBusArgument>());
}

int BlockDevice::deviceNumber() const
{
	return dbusProperty(Interface::UDisks2("Block"), "DeviceNumber").toInt();
}

QString BlockDevice::id() const
{
	return dbusProperty(Interface::UDisks2("Block"), "Id").toString();
}

qulonglong BlockDevice::size() const
{
	return dbusProperty(Interface::UDisks2("Block"), "Size").toULongLong();
}

bool BlockDevice::isReadOnly() const
{
	return dbusProperty(Interface::UDisks2("Block"), "ReadOnly").toBool();
}

QDBusObjectPath BlockDevice::drive() const
{
	auto path = dbusProperty(Interface::UDisks2("Block"), "Drive").value<QDBusObjectPath>();
	if (path.path() == "/")
		return {};

	return path;
}

QObject *BlockDevice::driveObject() const
{
	return new Drive(drive());
}

QString BlockDevice::usage() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdUsage").toString();
}

QString BlockDevice::type() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdType").toString();
}

QString BlockDevice::label() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdLabel").toString();
}

QString BlockDevice::uuid() const
{
	return dbusProperty(Interface::UDisks2("Block"), "IdUUID").toString();
}

QDBusObjectPath BlockDevice::cryptoDevicePath() const
{
	return dbusProperty(Interface::UDisks2("Block"), "CryptoBackingDevice").value<QDBusObjectPath>();
}

QObject *BlockDevice::cryptoDeviceObject()
{
	auto path = cryptoDevicePath();
	if (!path.path().isEmpty())
		return new BlockDevice(path, this);

	return {};
}

bool BlockDevice::isSystem() const
{
	return dbusProperty(Interface::UDisks2("Block"), "HintSystem").toBool();
}

QString BlockDevice::name() const
{
	return dbusProperty(Interface::UDisks2("Block"), "HintName").toString();
}

bool BlockDevice::hasFileSystem() const
{
	return FileSystem::isFileSystem(path(), replyTimeout());
}

QDBusObjectPath BlockDevice::fileSystem() const
{
	if (hasFileSystem())
		return path();

	return {};
}

QDebug operator <<(QDebug d, const QDrive::BlockDevice &blockDevice)
{
	d.nospace() << "Block device " << blockDevice.path().path() << ":\n";

	bool valid = blockDevice.isValid();
	d.nospace() << "  valid:\t\t" << valid;
	if (valid)
	{
		d.nospace() << "\n  device:\t\t" << blockDevice.device() << '\n';
		d.nospace() << "  ID:\t\t\t" << blockDevice.id() << '\n';
		d.nospace() << "  size:\t\t\t" << blockDevice.size() << '\n';
		d.nospace() << "  read-only:\t\t" << blockDevice.isReadOnly() << '\n';
		d.nospace() << "  drive:\t\t" << blockDevice.drive().path() << '\n';
		d.nospace() << "  label:\t\t" << blockDevice.label() << '\n';
		d.nospace() << "  UUID:\t\t\t" << blockDevice.uuid() << '\n';
		d.nospace() << "  symlinks:\t\t" << blockDevice.symlinks() << '\n';
		d.nospace() << "  has fs:\t\t" << blockDevice.hasFileSystem() << '\n';
	}

	return d.nospace();
}
<|endoftext|>


<commit_before>#include "makewea.h"
#include "gtest/gtest.h"

TEST(WeatherTests, ReadEpw)
{
  MakeWea data;
  data.parseWeather(":/resources/USA_PA_Lancaster.AP.725116_TMY3.epw");
  // Check location
  EXPECT_EQ("Lancaster", data.place().toStdString());
  EXPECT_EQ("40.12", data.latitude().toStdString());
  EXPECT_EQ("-76.30", data.longitude().toStdString());
  EXPECT_EQ("-5.0", data.timeZone().toStdString());
  EXPECT_EQ("126.0", data.elevation().toStdString());
  ASSERT_EQ(8760,data.month().size());
  // Spot check of data
  //EXPECT_EQ("",data.month()[710].toStdString());
  //EXPECT_EQ("",data.day()[710].toStdString());
  EXPECT_EQ(14.5,data.hour()[710]);
  EXPECT_EQ("0",data.directNormal()[710].toStdString());
  EXPECT_EQ("67",data.directHorizontal()[710].toStdString());
}

TEST(WeatherTests, WriteWea)
{

}
<commit_msg>Finish up EPW read test<commit_after>#include "makewea.h"
#include "gtest/gtest.h"

TEST(WeatherTests, ReadEpw)
{
  MakeWea data;
  data.parseWeather(":/resources/USA_PA_Lancaster.AP.725116_TMY3.epw");
  // Check location
  EXPECT_EQ("Lancaster", data.place().toStdString());
  EXPECT_EQ("40.12", data.latitude().toStdString());
  EXPECT_EQ("-76.30", data.longitude().toStdString());
  EXPECT_EQ("-5.0", data.timeZone().toStdString());
  EXPECT_EQ("126.0", data.elevation().toStdString());
  ASSERT_EQ(8760,data.month().size());
  // Spot check of data
  EXPECT_EQ(1,data.month()[710]);
  EXPECT_EQ(30,data.day()[710]);
  EXPECT_EQ(14.5,data.hour()[710]);
  EXPECT_EQ("0",data.directNormal()[710].toStdString());
  EXPECT_EQ("67",data.directHorizontal()[710].toStdString());
}

TEST(WeatherTests, WriteWea)
{

}
<|endoftext|>


<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <CommandLine.hpp>

void processCommandLineOptions(isa::utils::ArgumentList &argumentList, Options &options, DeviceOptions &deviceOptions, DataOptions &dataOptions, HostMemoryDumpFiles & hostMemoryDumpFiles, KernelConfigurations &kernelConfigurations, GeneratorOptions &generatorOptions, AstroData::Observation &observation)
{
    try
    {
        options.debug = argumentList.getSwitch("-debug");
        options.print = argumentList.getSwitch("-print");
        options.dataDump = argumentList.getSwitch("-data_dump");
        if (options.dataDump)
        {
            hostMemoryDumpFiles.dumpFilesPrefix = argumentList.getSwitchArgument<std::string>("-dump_prefix");
        }
        options.splitBatchesDedispersion = argumentList.getSwitch("-splitbatches_dedispersion");
        options.subbandDedispersion = argumentList.getSwitch("-subband_dedispersion");
        options.compactResults = argumentList.getSwitch("-compact_results");
        options.threshold = argumentList.getSwitchArgument<float>("-threshold");
        deviceOptions.platformID = argumentList.getSwitchArgument<unsigned int>("-opencl_platform");
        deviceOptions.deviceID = argumentList.getSwitchArgument<unsigned int>("-opencl_device");
        deviceOptions.deviceName = argumentList.getSwitchArgument<std::string>("-device_name");
        deviceOptions.synchronized = argumentList.getSwitch("-sync");
        AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument<std::string>("-padding_file"));
        if (argumentList.getSwitch("-snr_standard"))
        {
            options.snrMode = SNRMode::Standard;
        }
        else if (argumentList.getSwitch("-snr_momad"))
        {
            options.snrMode = SNRMode::Momad;
        }
        else
        {
            // Default option right now is to use the standard mode.
            options.snrMode = SNRMode::Standard;
        }
        if ( inputBits >= 8 )
        {
            options.downsampling = argumentList.getSwitch("-downsampling");
            if ( options.downsampling )
            {
                observation.setDownsampling(argumentList.getSwitchArgument<unsigned int>("-downsampling_factor"));
                Integration::readTunedIntegrationBeforeDedispersionConf(kernelConfigurations.downsamplingParameters, argumentList.getSwitchArgument<std::string>("-downsampling_configuration"));
            }
        }
        dataOptions.dataLOFAR = argumentList.getSwitch("-lofar");
#ifndef HAVE_HDF5
        if (dataOptions.dataLOFAR)
        {
            std::cerr << "Not compiled with HDF5 support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_HDF5
        dataOptions.dataPSRDADA = argumentList.getSwitch("-dada");
#ifndef HAVE_PSRDADA
        if (dataOptions.dataPSRDADA)
        {
            std::cerr << "Not compiled with PSRDADA support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_PSRDADA
        dataOptions.dataSIGPROC = argumentList.getSwitch("-sigproc");
        if (!((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA) || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC)) || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR)) || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)))
        {
            std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl;
            throw std::exception();
        }
        dataOptions.channelsFile = argumentList.getSwitchArgument<std::string>("-zapped_channels");
        dataOptions.integrationFile = argumentList.getSwitchArgument<std::string>("-integration_steps");
        if (!options.subbandDedispersion)
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_file"));
        }
        else
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_stepone_file"));
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_steptwo_file"));
        }
        Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters, argumentList.getSwitchArgument<std::string>("-integration_file"));
        if (options.snrMode == SNRMode::Standard)
        {
            SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument<std::string>("-snr_file"));
        }
        else if (options.snrMode == SNRMode::Momad)
        {
            SNR::readTunedSNRConf(kernelConfigurations.maxParameters, argumentList.getSwitchArgument<std::string>("-max_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansAbsoluteDeviationParameters, argumentList.getSwitchArgument<std::string>("-momad_file"));
        }
        if (dataOptions.dataLOFAR)
        {
#ifdef HAVE_HDF5
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.headerFile = argumentList.getSwitchArgument<std::string>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            dataOptions.limit = argumentList.getSwitch("-limit");
            if (dataOptions.limit)
            {
                observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            }
#endif // HAVE_HDF5
        }
        else if (dataOptions.dataSIGPROC)
        {
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.streamingMode = argumentList.getSwitch("-stream");
            dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument<unsigned int>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
        }
        else if (dataOptions.dataPSRDADA)
        {
#ifdef HAVE_PSRDADA
            dataOptions.dadaKey = std::stoi("0x" + argumentList.getSwitchArgument<std::string>("-dada_key"), 0, 16);
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), 1, 1.0f, 1.0f);
            }
            else
            {
                observation.setFrequencyRange(1, 1, 1.0f, 1.0f);
            }
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
#endif // HAVE_PSRDADA
        }
        else
        {
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
            generatorOptions.random = argumentList.getSwitch("-random");
            generatorOptions.width = argumentList.getSwitchArgument<unsigned int>("-width");
            generatorOptions.DM = argumentList.getSwitchArgument<float>("-dm");
        }
        dataOptions.outputFile = argumentList.getSwitchArgument<std::string>("-output");
        if (options.subbandDedispersion)
        {
            observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-subbanding_dms"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_first"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_step"), true);
        }
        observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-dms"),
                               argumentList.getSwitchArgument<float>("-dm_first"),
                               argumentList.getSwitchArgument<float>("-dm_step"));
    }
    catch (isa::utils::EmptyCommandLine &err)
    {
        usage(argumentList.getName());
        throw;
    }
    catch (isa::utils::SwitchNotFound &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
}

void usage(const std::string &program)
{
    std::cerr << program << " [-debug] [-print] [-data_dump] -opencl_platform ... -opencl_device ... -device_name ... [-sync]";
    std::cerr << "  -padding_file ... -zapped_channels ... -integration_steps ... -integration_file ...";
    std::cerr << " [-splitbatches_dedispersion] [-subband_dedispersion] [-snr_standard | -snr_momad] [-downsampling]";
    std::cerr << " [-compact_results] -output ... -dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]";
#ifdef HAVE_HDF5
    std::cerr << " [-lofar]";
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    std::cerr << " [-dada]";
#endif // HAVE_PSRDADA
    std::cerr << std::endl;
    std::cerr << "\tData dump: -dump_prefix ..." << std::endl;
    std::cerr << "\tDownsampling: -downsampling_factor ... -downsampling_configuration ..." << std::endl;
    std::cerr << "\tDedispersion: -dedispersion_file ..." << std::endl;
    std::cerr << "\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...";
    std::cerr << "-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...";
    std::cerr << "-subbanding_dm_step ..." << std::endl;
    std::cerr << "\tStandard SNR: -snr_file" << std::endl;
    std::cerr << "\tMOMAD SNR: -max_file ... -mom_stepone_file ... -mom_steptwo_file ... -momad_file ..." << std::endl;
#ifdef HAVE_HDF5
    std::cerr << "\tLOFAR: -lofar -header ... -data ... [-limit]" << std::endl;
    std::cerr << "\t\t -limit -batches ..." << std::endl;
#endif // HAVE_HDF5
    std::cerr << "\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...";
    std::cerr << "-channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
#ifdef HAVE_PSRDADA
    std::cerr << "\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ..." << std::endl;
#endif // HAVE_PSRDADA
    std::cerr << "\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...";
    std::cerr << "-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
}
<commit_msg>Bug fixed.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <CommandLine.hpp>

void processCommandLineOptions(isa::utils::ArgumentList &argumentList, Options &options, DeviceOptions &deviceOptions, DataOptions &dataOptions, HostMemoryDumpFiles & hostMemoryDumpFiles, KernelConfigurations &kernelConfigurations, GeneratorOptions &generatorOptions, AstroData::Observation &observation)
{
    try
    {
        options.debug = argumentList.getSwitch("-debug");
        options.print = argumentList.getSwitch("-print");
        options.dataDump = argumentList.getSwitch("-data_dump");
        if (options.dataDump)
        {
            hostMemoryDumpFiles.dumpFilesPrefix = argumentList.getSwitchArgument<std::string>("-dump_prefix");
        }
        options.splitBatchesDedispersion = argumentList.getSwitch("-splitbatches_dedispersion");
        options.subbandDedispersion = argumentList.getSwitch("-subband_dedispersion");
        options.compactResults = argumentList.getSwitch("-compact_results");
        options.threshold = argumentList.getSwitchArgument<float>("-threshold");
        deviceOptions.platformID = argumentList.getSwitchArgument<unsigned int>("-opencl_platform");
        deviceOptions.deviceID = argumentList.getSwitchArgument<unsigned int>("-opencl_device");
        deviceOptions.deviceName = argumentList.getSwitchArgument<std::string>("-device_name");
        deviceOptions.synchronized = argumentList.getSwitch("-sync");
        AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument<std::string>("-padding_file"));
        if (argumentList.getSwitch("-snr_standard"))
        {
            options.snrMode = SNRMode::Standard;
        }
        else if (argumentList.getSwitch("-snr_momad"))
        {
            options.snrMode = SNRMode::Momad;
        }
        else
        {
            // Default option right now is to use the standard mode.
            options.snrMode = SNRMode::Standard;
        }
        if ( inputBits >= 8 )
        {
            options.downsampling = argumentList.getSwitch("-downsampling");
            if ( options.downsampling )
            {
                observation.setDownsampling(argumentList.getSwitchArgument<unsigned int>("-downsampling_factor"));
                Integration::readTunedIntegrationConf(kernelConfigurations.downsamplingParameters, argumentList.getSwitchArgument<std::string>("-downsampling_configuration"));
            }
        }
        dataOptions.dataLOFAR = argumentList.getSwitch("-lofar");
#ifndef HAVE_HDF5
        if (dataOptions.dataLOFAR)
        {
            std::cerr << "Not compiled with HDF5 support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_HDF5
        dataOptions.dataPSRDADA = argumentList.getSwitch("-dada");
#ifndef HAVE_PSRDADA
        if (dataOptions.dataPSRDADA)
        {
            std::cerr << "Not compiled with PSRDADA support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_PSRDADA
        dataOptions.dataSIGPROC = argumentList.getSwitch("-sigproc");
        if (!((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA) || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC)) || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR)) || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)))
        {
            std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl;
            throw std::exception();
        }
        dataOptions.channelsFile = argumentList.getSwitchArgument<std::string>("-zapped_channels");
        dataOptions.integrationFile = argumentList.getSwitchArgument<std::string>("-integration_steps");
        if (!options.subbandDedispersion)
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_file"));
        }
        else
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_stepone_file"));
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_steptwo_file"));
        }
        Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters, argumentList.getSwitchArgument<std::string>("-integration_file"));
        if (options.snrMode == SNRMode::Standard)
        {
            SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument<std::string>("-snr_file"));
        }
        else if (options.snrMode == SNRMode::Momad)
        {
            SNR::readTunedSNRConf(kernelConfigurations.maxParameters, argumentList.getSwitchArgument<std::string>("-max_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansAbsoluteDeviationParameters, argumentList.getSwitchArgument<std::string>("-momad_file"));
        }
        if (dataOptions.dataLOFAR)
        {
#ifdef HAVE_HDF5
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.headerFile = argumentList.getSwitchArgument<std::string>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            dataOptions.limit = argumentList.getSwitch("-limit");
            if (dataOptions.limit)
            {
                observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            }
#endif // HAVE_HDF5
        }
        else if (dataOptions.dataSIGPROC)
        {
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.streamingMode = argumentList.getSwitch("-stream");
            dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument<unsigned int>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
        }
        else if (dataOptions.dataPSRDADA)
        {
#ifdef HAVE_PSRDADA
            dataOptions.dadaKey = std::stoi("0x" + argumentList.getSwitchArgument<std::string>("-dada_key"), 0, 16);
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), 1, 1.0f, 1.0f);
            }
            else
            {
                observation.setFrequencyRange(1, 1, 1.0f, 1.0f);
            }
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
#endif // HAVE_PSRDADA
        }
        else
        {
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
            generatorOptions.random = argumentList.getSwitch("-random");
            generatorOptions.width = argumentList.getSwitchArgument<unsigned int>("-width");
            generatorOptions.DM = argumentList.getSwitchArgument<float>("-dm");
        }
        dataOptions.outputFile = argumentList.getSwitchArgument<std::string>("-output");
        if (options.subbandDedispersion)
        {
            observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-subbanding_dms"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_first"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_step"), true);
        }
        observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-dms"),
                               argumentList.getSwitchArgument<float>("-dm_first"),
                               argumentList.getSwitchArgument<float>("-dm_step"));
    }
    catch (isa::utils::EmptyCommandLine &err)
    {
        usage(argumentList.getName());
        throw;
    }
    catch (isa::utils::SwitchNotFound &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
}

void usage(const std::string &program)
{
    std::cerr << program << " [-debug] [-print] [-data_dump] -opencl_platform ... -opencl_device ... -device_name ... [-sync]";
    std::cerr << "  -padding_file ... -zapped_channels ... -integration_steps ... -integration_file ...";
    std::cerr << " [-splitbatches_dedispersion] [-subband_dedispersion] [-snr_standard | -snr_momad] [-downsampling]";
    std::cerr << " [-compact_results] -output ... -dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]";
#ifdef HAVE_HDF5
    std::cerr << " [-lofar]";
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    std::cerr << " [-dada]";
#endif // HAVE_PSRDADA
    std::cerr << std::endl;
    std::cerr << "\tData dump: -dump_prefix ..." << std::endl;
    std::cerr << "\tDownsampling: -downsampling_factor ... -downsampling_configuration ..." << std::endl;
    std::cerr << "\tDedispersion: -dedispersion_file ..." << std::endl;
    std::cerr << "\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...";
    std::cerr << "-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...";
    std::cerr << "-subbanding_dm_step ..." << std::endl;
    std::cerr << "\tStandard SNR: -snr_file" << std::endl;
    std::cerr << "\tMOMAD SNR: -max_file ... -mom_stepone_file ... -mom_steptwo_file ... -momad_file ..." << std::endl;
#ifdef HAVE_HDF5
    std::cerr << "\tLOFAR: -lofar -header ... -data ... [-limit]" << std::endl;
    std::cerr << "\t\t -limit -batches ..." << std::endl;
#endif // HAVE_HDF5
    std::cerr << "\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...";
    std::cerr << "-channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
#ifdef HAVE_PSRDADA
    std::cerr << "\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ..." << std::endl;
#endif // HAVE_PSRDADA
    std::cerr << "\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...";
    std::cerr << "-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
}
<|endoftext|>


<commit_before>ifndef COMMONTYPES_HPP_DEFINED
#define COMMONTYPES_HPP_DEFINED

namespace utymap {

struct BoundingBox
{
    double minLatitude;
    double minLongitude;
    double maxLatitude;
    double maxLongitude;

    inline void expand(const BoundingBox& bbox)
    {

    }
};

struct QuadKey
{
    int levelOfDetail;
    int tileX;
    int tileY;
};

}
#endif // COMMONTYPES_HPP_DEFINED
<commit_msg>remove obsolete file<commit_after><|endoftext|>


<commit_before>#include "cruntime.h" //to validate it, herein lay default implementations of it.
#include "wtf.h"  //error routine, a place to share a breakpoint for trouble.

/*CMSIS uses this function for doing things that must precede C init, such as turning on IO ports so that configuration commands in constructors function.
You can't use any static *object* but you can use static initialized plain old data */
void SystemInit(void); // __USE_CMSIS __USE_LPCOPEN

#pragma GCC diagnostic ignored "-Wmain"
int main(void); // entry point

/* my approach to dealing with errors is to start over. Once I've restored 'atExit' functionality you can do a while(1) there to prevent a restart */
extern void generateHardReset(void); // doesn't return! supplied by nvic.cpp as that is where reset hardware happens to reside.

//the linker script creates and initializes these constant structures, used by cstartup() to initialize ram:
//non-trivially initialized POD.
const extern RamInitBlock __data_segment__;//name coordinated with cortexm.ld
//zero initialized ram
const extern RamBlock __bss_segment__;  //name coordinated with cortexm.ld
//run all code in .init sections.
const extern InitRoutine __init_table__[];//name coordinated with cortexm.ld

/** every type of code driven initialization is invoked through a simple void fn(void)*/
typedef void (*InitRoutine)(void) ;
const extern InitRoutine __init_table__[];//name coordinated with cortexm.ld

/** this implementation trusts the linker script to null terminate the table */
void run_init( const InitRoutine * table){
  while(InitRoutine routine=*table++){
    (*routine)();
  }
}

// instead of tracking #defined symbols just dummy up the optional routines:
[[gnu::weak,gnu::optimize(3)]] void SystemInit(void) {
  return;
}

/** sometimes pure virtual functions that aren't overloaded get called anyway,
  * such as from extended classes prophylactically calling the overloaded parent,
    or constructors calling their pure virtual members */
extern "C" void __cxa_pure_virtual(){  /* upon call of pure virtual function */
  wtf(100000); /* ignore it, but have a place for a breakpoint */
}

/** Reset entry point. The chip itself has set up the stack pointer to top of ram, and then the PC to this. It has not set up a frame pointer.
 */
extern "C" //to make it easy to pass this to linker sanity checker.
[[gnu::naked,noreturn]] //we don't need no stinking stack frame (no params, no locals)
void cstartup(void){
  // initialize static variables
  RamInitBlock(__data_segment__).go();
  // Zero other static variables.
  RamBlock(__bss_segment__).go();
  // a CMSIS hook:
  SystemInit(); // stuff that C++ construction might need, like turning on hardware modules (e.g. my LPC::GPIO::Init())

  run_init(__init_table__);
  //incorporated by linker into our run_init:  __libc_init_array(); // C++ library initialization (includes constructors for static objects)
  main();
  // todo: find and execute destructors for static objects and do atexit routines.
  generateHardReset(); // auto restart on problems, design your system to tolerate spontaneous power cycles on fatal firmware error
}

// stack pointer is set to end of ram via linker script
void (*resetVector)(void) __attribute__((section(".vectors.1"))) = cstartup;
// rest of table is in nvic.cpp, trusting linker script to order files correctly per the numerical suffix

extern unsigned const __stack_limit__;//created in linker script
void stackFault(){
  unsigned here;
  if(&here <= &__stack_limit__){//todo: should add a few so that we can call wtf without risk
    wtf(99999999);
    generateHardReset();
  }
}

#ifdef __linux__  //for testing compiles with PC compiler etc.
const RamInitBlock __data_segment__={0,{0,0}};
const RamBlock __bss_segment__={0,0};
const InitRoutine __init_table__[]={nullptr};
const unsigned __stack_limit__(0);
#else
//destructor failure stuff, but ours won't ever actually fail
extern "C" int __aeabi_atexit(void *object, void (*destructor)(void *), void *dso_handle){
  return 0;
}

//extern "C" {
//  void __aeabi_atexit(){
//    wtf(-1);
//  }
//  void __dso_handle(){
//    wtf(-2);
//  }
//}
#endif
<commit_msg>commentary on the recurring linker issues with eabi_atexit<commit_after>#include "cruntime.h" //to validate it, herein lay default implementations of it.
#include "wtf.h"  //error routine, a place to share a breakpoint for trouble.

/*CMSIS uses this function for doing things that must precede C init, such as turning on IO ports so that configuration commands in constructors function.
You can't use any static *object* but you can use static initialized plain old data */
void SystemInit(void); // __USE_CMSIS __USE_LPCOPEN

#pragma GCC diagnostic ignored "-Wmain"
int main(void); // entry point

/* my approach to dealing with errors is to start over. Once I've restored 'atExit' functionality you can do a while(1) there to prevent a restart */
extern void generateHardReset(void); // doesn't return! supplied by nvic.cpp as that is where reset hardware happens to reside.

//the linker script creates and initializes these constant structures, used by cstartup() to initialize ram:
//non-trivially initialized POD.
const extern RamInitBlock __data_segment__;//name coordinated with cortexm.ld
//zero initialized ram
const extern RamBlock __bss_segment__;  //name coordinated with cortexm.ld
//run all code in .init sections.
const extern InitRoutine __init_table__[];//name coordinated with cortexm.ld

/** every type of code driven initialization is invoked through a simple void fn(void)*/
typedef void (*InitRoutine)(void) ;
const extern InitRoutine __init_table__[];//name coordinated with cortexm.ld

/** this implementation trusts the linker script to null terminate the table */
void run_init( const InitRoutine * table){
  while(InitRoutine routine=*table++){
    (*routine)();
  }
}

// instead of tracking #defined symbols just dummy up the optional routines:
[[gnu::weak,gnu::optimize(3)]] void SystemInit(void) {
  return;
}

/** sometimes pure virtual functions that aren't overloaded get called anyway,
  * such as from extended classes prophylactically calling the overloaded parent,
    or constructors calling their pure virtual members */
extern "C" void __cxa_pure_virtual(){  /* upon call of pure virtual function */
  wtf(100000); /* ignore it, but have a place for a breakpoint */
}

/** Reset entry point. The chip itself has set up the stack pointer to top of ram, and then the PC to this. It has not set up a frame pointer.
 */
extern "C" //to make it easy to pass this to linker sanity checker.
[[gnu::naked,noreturn]] //we don't need no stinking stack frame (no params, no locals)
void cstartup(void){
  // initialize static variables
  RamInitBlock(__data_segment__).go();
  // Zero other static variables.
  RamBlock(__bss_segment__).go();
  // a CMSIS hook:
  SystemInit(); // stuff that C++ construction might need, like turning on hardware modules (e.g. my LPC::GPIO::Init())

  run_init(__init_table__);
  //incorporated by linker into our run_init:  __libc_init_array(); // C++ library initialization (includes constructors for static objects)
  main();
  // todo: find and execute destructors for static objects and do atexit routines.
  generateHardReset(); // auto restart on problems, design your system to tolerate spontaneous power cycles on fatal firmware error
}

// stack pointer is set to end of ram via linker script
void (*resetVector)(void) __attribute__((section(".vectors.1"))) = cstartup;
// rest of table is in nvic.cpp, trusting linker script to order files correctly per the numerical suffix

extern unsigned const __stack_limit__;//created in linker script
void stackFault(){
  unsigned here;
  if(&here <= &__stack_limit__){//todo: should add a few so that we can call wtf without risk
    wtf(99999999);
    generateHardReset();
  }
}

#ifdef __linux__  //for testing compiles with PC compiler etc.
const RamInitBlock __data_segment__={0,{0,0}};
const RamBlock __bss_segment__={0,0};
const InitRoutine __init_table__[]={nullptr};
const unsigned __stack_limit__(0);
#else
//destructor failure stuff, but ours won't ever actually fail
extern "C" int __aeabi_atexit(void *object, void (*destructor)(void *), void *dso_handle){
  return 0;
}

//these guys get linked in when you have explicit destructors, even if those destructores are "=default".
//... that keeps on rehappening due to the warning of 'have virtual functions but not virtual destructor' inspiring the creation of pointless destructors.
//... which I guess is a potential burden- not having destructors on classes that happen to be used statically, but might be useful 'automatically' as well.
//extern "C" {
//  void __aeabi_atexit(){
//    wtf(-1);
//  }
//  void __dso_handle(){
//    wtf(-2);
//  }
//}
#endif
<|endoftext|>


<commit_before>#include "FrameBuffer.h"

#include <assert.h>

#include "DinodeckGL.h"
#include "DDLog.h"

const unsigned int NUM_BUFFERS = 1;

void FrameBuffer::DestroyBuffer()
{
	// Only reset the id, if it exists
	if(mBufferId != 0)
	{
		glDeleteFramebuffers(NUM_BUFFERS, &mBufferId);
		mBufferId = 0;
	}

	if(mTextureId != 0)
	{
		glDeleteTextures(NUM_BUFFERS, &mTextureId);
		mTextureId = 0;
	}
}

void FrameBuffer::Reset(unsigned width, unsigned height)
{
	dsprintf("FrameBuffer Reset: width [%d] height: [%d]",
	         width, height);
	DestroyBuffer();
	// // 1. Create the frame buffer
	glGenFramebuffers(NUM_BUFFERS, &mBufferId);
	glBindFramebuffer(GL_FRAMEBUFFER, mBufferId);

	// // 2. Create texture to associate w/ frame buffer
	GLuint prevTexture = 0;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*) &prevTexture);
	{
		glGenTextures(NUM_BUFFERS, &mTextureId);
	 	glBindTexture(GL_TEXTURE_2D, mTextureId);

		const int LEVEL_OF_DETAIL = 0;
		glTexImage2D(GL_TEXTURE_2D,
					 LEVEL_OF_DETAIL,
					 GL_RGB,
					 width, height,
					 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	}

	// 3. Set texture as framebuffer
	glFramebufferTexture(GL_FRAMEBUFFER,
	                     GL_COLOR_ATTACHMENT0,
	                     mTextureId, 0);

	// 4. Set list of draw buffers (not really sure what this is!)
	GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
	glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers

	if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
	{
		dsprintf("Error: Failed to setup framebuffer.\n");
	}

	// Restore previous texture
	glBindTexture(GL_TEXTURE_2D, prevTexture);
	Disable();
}

void FrameBuffer::Enable()
{
	assert(mBufferId != 0);
	glBindFramebuffer(GL_FRAMEBUFFER, mBufferId);
}

void FrameBuffer::Disable()
{
	// Default the draw surface to the window
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

<commit_msg>Used more standard framebuffer function<commit_after>#include "FrameBuffer.h"

#include <assert.h>

#include "DinodeckGL.h"
#include "DDLog.h"

const unsigned int NUM_BUFFERS = 1;

void FrameBuffer::DestroyBuffer()
{
	// Only reset the id, if it exists
	if(mBufferId != 0)
	{
		glDeleteFramebuffers(NUM_BUFFERS, &mBufferId);
		mBufferId = 0;
	}

	if(mTextureId != 0)
	{
		glDeleteTextures(NUM_BUFFERS, &mTextureId);
		mTextureId = 0;
	}
}

void FrameBuffer::Reset(unsigned width, unsigned height)
{
	dsprintf("FrameBuffer Reset: width [%d] height: [%d]",
	         width, height);
	DestroyBuffer();
	// // 1. Create the frame buffer
	glGenFramebuffers(NUM_BUFFERS, &mBufferId);
	glBindFramebuffer(GL_FRAMEBUFFER, mBufferId);

	// // 2. Create texture to associate w/ frame buffer
	GLuint prevTexture = 0;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*) &prevTexture);
	{
		glGenTextures(NUM_BUFFERS, &mTextureId);
	 	glBindTexture(GL_TEXTURE_2D, mTextureId);

		const int LEVEL_OF_DETAIL = 0;
		glTexImage2D(GL_TEXTURE_2D,
					 LEVEL_OF_DETAIL,
					 GL_RGB,
					 width, height,
					 0, GL_RGB, GL_UNSIGNED_BYTE, 0);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	}

	// void glFramebufferTexture2D(GLenum target,
	//                             GLenum attachment,
	//                             GLenum textarget,
	//                             GLuint texture,
	//                             GLint level);

	// 3. Set texture as framebuffer
	glFramebufferTexture2D(GL_FRAMEBUFFER,
	                    GL_COLOR_ATTACHMENT0,
						GL_TEXTURE_2D,
	                    mTextureId, 0);
	// glFramebufferTexture(GL_FRAMEBUFFER,
	//                      GL_COLOR_ATTACHMENT0,
	//                      mTextureId, 0);

	// 4. Set list of draw buffers (not really sure what this is!)
	GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
	glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers

	if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
	{
		dsprintf("Error: Failed to setup framebuffer.\n");
	}

	// Restore previous texture
	glBindTexture(GL_TEXTURE_2D, prevTexture);
	Disable();
}

void FrameBuffer::Enable()
{
	assert(mBufferId != 0);
	glBindFramebuffer(GL_FRAMEBUFFER, mBufferId);
}

void FrameBuffer::Disable()
{
	// Default the draw surface to the window
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

<|endoftext|>