<commit_before>#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );

	return 0;
}

=============================================================

#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";

	strcat(s1, "Melaniya!");
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
	return 0;
}

===============================================
Подава брой символи "strlen" :
fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );

===============================================

Добавя "strcat":
strcat(s1, "- From team! :)");

================================================

Сравнява "strcmp":
strcmp("Hello", "Hello") = 0
strcmp(s1, "Hello") = 1
strcmp("Hello", s1) = -1

================================================
Търси съвпадение на символ в стринга "*strchr" и дава съдържание:
fprintf (stdout,"strchr -> %c\n",*strchr("Hello", 'H'));

ако не ползване * се получава НОТА :) превърта;
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

    char s1[]= "Hello, Mel. Today is sunday. Let's go party!";

  	strcat(s1, "- From team! :)");

fprintf (stdout,"strcmp -> %d\n",strcmp("Hello", "Hello"));

fprintf (stdout,"strchr -> %c\n",strchr("Hello", 'H'));

fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );
	return 0;
}
================================================
адрес за обръщане на масив в обратен ред

http://www.introprogramming.info/intro-csharp-book/read-online/glava7-masivi/

================================================

#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)

{

    char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
    int i;

fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );

for (i=0; i<strlen(s1);i++)

fprintf (stdout,"[%c]",s1[i]);

	return 0;
}

<commit_msg>Update experians.cpp<commit_after>#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );

	return 0;
}

=============================================================

#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

     char s1[]= "Hello, Mel. Today is sunday. Let's go party!";

	strcat(s1, "Melaniya!");
fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );
	return 0;
}

===============================================
Подава брой символи "strlen" :
fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );

===============================================

Добавя "strcat":
strcat(s1, "- From team! :)");

================================================

Сравнява "strcmp":
strcmp("Hello", "Hello") = 0
strcmp(s1, "Hello") = 1
strcmp("Hello", s1) = -1

================================================
Търси съвпадение на символ в стринга "*strchr" и дава съдържание:
fprintf (stdout,"strchr -> %c\n",*strchr("Hello", 'H'));

ако не ползване * се получава НОТА :) превърта;
#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{

    char s1[]= "Hello, Mel. Today is sunday. Let's go party!";

  	strcat(s1, "- From team! :)");

fprintf (stdout,"strcmp -> %d\n",strcmp("Hello", "Hello"));

fprintf (stdout,"strchr -> %c\n",strchr("Hello", 'H'));

fprintf (stdout,"strlen -> %s -> %d\n",s1,strlen(s1) );
	return 0;
}
================================================
адрес за обръщане на масив в обратен ред

http://www.introprogramming.info/intro-csharp-book/read-online/glava7-masivi/

================================================

#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)

{

    char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
    int i;

fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );

for (i=0; i<strlen(s1);i++)

fprintf (stdout,"[%c]",s1[i]);

	return 0;
}

=============================================

#include <stdio.h>
#include <iostream>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)

{

    char s1[]= "Hello, Mel. Today is sunday. Let's go party!";
    int i;

fprintf (stdout,"%s -> %d\n",s1,strlen(s1) );

for (i=strlen(s1)-1;i>=0;i--)

fprintf (stdout,"%c",s1[i]);

	return 0;
}

<|endoftext|>


<commit_before><commit_msg>Sketcher: Fix geometry state synchronisation routine<commit_after><|endoftext|>


<commit_before>#include "db.hh"
#include "util.hh"

#include <memory>

#include <db_cxx.h>

/* Wrapper classes that ensures that the database is closed upon
   object destruction. */
class Db2 : public Db
{
public:
    Db2(DbEnv *env, u_int32_t flags) : Db(env, flags) { }
    ~Db2() { close(0); }
};

class DbcClose
{
    Dbc * cursor;
public:
    DbcClose(Dbc * c) : cursor(c) { }
    ~DbcClose() { cursor->close(); }
};

static auto_ptr<Db2> openDB(const string & filename, const string & dbname,
    bool readonly)
{
    auto_ptr<Db2> db(new Db2(0, 0));

    db->open(filename.c_str(), dbname.c_str(),
        DB_HASH, readonly ? DB_RDONLY : DB_CREATE, 0666);

    return db;
}

static void rethrow(DbException & e)
{
    throw Error(e.what());
}

void createDB(const string & filename, const string & dbname)
{
    try {
        openDB(filename, dbname, false);
    } catch (DbException e) { rethrow(e); }
}

bool queryDB(const string & filename, const string & dbname,
    const string & key, string & data)
{
    try {

        int err;
        auto_ptr<Db2> db = openDB(filename, dbname, true);

        Dbt kt((void *) key.c_str(), key.length());
        Dbt dt;

        err = db->get(0, &kt, &dt, 0);
        if (err) return false;

        if (!dt.get_data())
            data = "";
        else
            data = string((char *) dt.get_data(), dt.get_size());

    } catch (DbException e) { rethrow(e); }

    return true;
}

bool queryListDB(const string & filename, const string & dbname,
    const string & key, Strings & data)
{
    string d;

    if (!queryDB(filename, dbname, key, d))
        return false;

    string::iterator it = d.begin();

    while (it != d.end()) {

        if (it + 4 > d.end())
            throw Error(format("short db entry: `%1%'") % d);

        unsigned int len;
        len = (unsigned char) *it++;
        len |= ((unsigned char) *it++) << 8;
        len |= ((unsigned char) *it++) << 16;
        len |= ((unsigned char) *it++) << 24;

        if (it + len > d.end())
            throw Error(format("short db entry: `%1%'") % d);

        string s;
        while (len--) s += *it++;

        data.push_back(s);
    }

    return true;
}

void setDB(const string & filename, const string & dbname,
    const string & key, const string & data)
{
    try {
        auto_ptr<Db2> db = openDB(filename, dbname, false);
        Dbt kt((void *) key.c_str(), key.length());
        Dbt dt((void *) data.c_str(), data.length());
        db->put(0, &kt, &dt, 0);
    } catch (DbException e) { rethrow(e); }
}

void setListDB(const string & filename, const string & dbname,
    const string & key, const Strings & data)
{
    string d;

    for (Strings::const_iterator it = data.begin();
         it != data.end(); it++)
    {
        string s = *it;
        unsigned int len = s.size();

        d += len & 0xff;
        d += (len >> 8) & 0xff;
        d += (len >> 16) & 0xff;
        d += (len >> 24) & 0xff;

        d += s;
    }

    setDB(filename, dbname, key, d);
}

void delDB(const string & filename, const string & dbname,
    const string & key)
{
    try {
        auto_ptr<Db2> db = openDB(filename, dbname, false);
        Dbt kt((void *) key.c_str(), key.length());
        db->del(0, &kt, 0);
    } catch (DbException e) { rethrow(e); }
}

void enumDB(const string & filename, const string & dbname,
    Strings & keys)
{
    try {

        auto_ptr<Db2> db = openDB(filename, dbname, true);

        Dbc * cursor;
        db->cursor(0, &cursor, 0);
        DbcClose cursorCloser(cursor);

        Dbt kt, dt;
        while (cursor->get(&kt, &dt, DB_NEXT) != DB_NOTFOUND)
            keys.push_back(
                string((char *) kt.get_data(), kt.get_size()));

    } catch (DbException e) { rethrow(e); }
}
<commit_msg>* Don't sync the database on close.  This was killing performance.   (Of course, the real problem is that we open the database for   *every* operation; we should only open it once.  And we should use   transactions.)<commit_after>#include "db.hh"
#include "util.hh"

#include <memory>

#include <db_cxx.h>

/* Wrapper classes that ensures that the database is closed upon
   object destruction. */
class Db2 : public Db
{
public:
    Db2(DbEnv *env, u_int32_t flags) : Db(env, flags) { }
    ~Db2() { close(DB_NOSYNC); }
};

class DbcClose
{
    Dbc * cursor;
public:
    DbcClose(Dbc * c) : cursor(c) { }
    ~DbcClose() { cursor->close(); }
};

static auto_ptr<Db2> openDB(const string & filename, const string & dbname,
    bool readonly)
{
    auto_ptr<Db2> db(new Db2(0, 0));

    db->open(filename.c_str(), dbname.c_str(),
        DB_HASH, readonly ? DB_RDONLY : DB_CREATE, 0666);

    return db;
}

static void rethrow(DbException & e)
{
    throw Error(e.what());
}

void createDB(const string & filename, const string & dbname)
{
    try {
        openDB(filename, dbname, false);
    } catch (DbException e) { rethrow(e); }
}

bool queryDB(const string & filename, const string & dbname,
    const string & key, string & data)
{
    try {

        int err;
        auto_ptr<Db2> db = openDB(filename, dbname, true);

        Dbt kt((void *) key.c_str(), key.length());
        Dbt dt;

        err = db->get(0, &kt, &dt, 0);
        if (err) return false;

        if (!dt.get_data())
            data = "";
        else
            data = string((char *) dt.get_data(), dt.get_size());

    } catch (DbException e) { rethrow(e); }

    return true;
}

bool queryListDB(const string & filename, const string & dbname,
    const string & key, Strings & data)
{
    string d;

    if (!queryDB(filename, dbname, key, d))
        return false;

    string::iterator it = d.begin();

    while (it != d.end()) {

        if (it + 4 > d.end())
            throw Error(format("short db entry: `%1%'") % d);

        unsigned int len;
        len = (unsigned char) *it++;
        len |= ((unsigned char) *it++) << 8;
        len |= ((unsigned char) *it++) << 16;
        len |= ((unsigned char) *it++) << 24;

        if (it + len > d.end())
            throw Error(format("short db entry: `%1%'") % d);

        string s;
        while (len--) s += *it++;

        data.push_back(s);
    }

    return true;
}

void setDB(const string & filename, const string & dbname,
    const string & key, const string & data)
{
    try {
        auto_ptr<Db2> db = openDB(filename, dbname, false);
        Dbt kt((void *) key.c_str(), key.length());
        Dbt dt((void *) data.c_str(), data.length());
        db->put(0, &kt, &dt, 0);
    } catch (DbException e) { rethrow(e); }
}

void setListDB(const string & filename, const string & dbname,
    const string & key, const Strings & data)
{
    string d;

    for (Strings::const_iterator it = data.begin();
         it != data.end(); it++)
    {
        string s = *it;
        unsigned int len = s.size();

        d += len & 0xff;
        d += (len >> 8) & 0xff;
        d += (len >> 16) & 0xff;
        d += (len >> 24) & 0xff;

        d += s;
    }

    setDB(filename, dbname, key, d);
}

void delDB(const string & filename, const string & dbname,
    const string & key)
{
    try {
        auto_ptr<Db2> db = openDB(filename, dbname, false);
        Dbt kt((void *) key.c_str(), key.length());
        db->del(0, &kt, 0);
    } catch (DbException e) { rethrow(e); }
}

void enumDB(const string & filename, const string & dbname,
    Strings & keys)
{
    try {

        auto_ptr<Db2> db = openDB(filename, dbname, true);

        Dbc * cursor;
        db->cursor(0, &cursor, 0);
        DbcClose cursorCloser(cursor);

        Dbt kt, dt;
        while (cursor->get(&kt, &dt, DB_NEXT) != DB_NOTFOUND)
            keys.push_back(
                string((char *) kt.get_data(), kt.get_size()));

    } catch (DbException e) { rethrow(e); }
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include "test_precomp.hpp"

#include <vector>
#include <string>
using namespace std;
using namespace cv;

class CV_MserTest : public cvtest::BaseTest
{
public:
    CV_MserTest();
protected:
    void run(int);
	int LoadBoxes(const char* path, vector<CvBox2D>& boxes);
	int SaveBoxes(const char* path, const vector<CvBox2D>& boxes);
	int CompareBoxes(const vector<CvBox2D>& boxes1,const vector<CvBox2D>& boxes2, float max_rel_diff = 0.01f);
};

CV_MserTest::CV_MserTest()
{
}

int CV_MserTest::LoadBoxes(const char* path, vector<CvBox2D>& boxes)
{
	boxes.clear();
	FILE* f = fopen(path,"r");

	if (f==NULL)
	{
		return 0;
	}

	while (!feof(f))
	{
		CvBox2D box;
		fscanf(f,"%f,%f,%f,%f,%f\n",&box.angle,&box.center.x,&box.center.y,&box.size.width,&box.size.height);
		boxes.push_back(box);
	}
	fclose(f);
	return 1;
}

int CV_MserTest::SaveBoxes(const char* path, const vector<CvBox2D>& boxes)
{
	FILE* f = fopen(path,"w");
	if (f==NULL)
	{
		return 0;
	}
	for (int i=0;i<(int)boxes.size();i++)
	{
		fprintf(f,"%f,%f,%f,%f,%f\n",boxes[i].angle,boxes[i].center.x,boxes[i].center.y,boxes[i].size.width,boxes[i].size.height);
	}
	fclose(f);
	return 1;
}

int CV_MserTest::CompareBoxes(const vector<CvBox2D>& boxes1,const vector<CvBox2D>& boxes2, float max_rel_diff)
{
	if (boxes1.size() != boxes2.size())
		return 0;

	for (int i=0; i<(int)boxes1.size();i++)
	{
		float rel_diff;
		if (!((boxes1[i].angle == 0.0f) && (abs(boxes2[i].angle) < max_rel_diff)))
		{
			rel_diff = abs(boxes1[i].angle-boxes2[i].angle)/abs(boxes1[i].angle);
			if (rel_diff > max_rel_diff)
				return i;
		}

		if (!((boxes1[i].center.x == 0.0f) && (abs(boxes2[i].center.x) < max_rel_diff)))
		{
			rel_diff = abs(boxes1[i].center.x-boxes2[i].center.x)/abs(boxes1[i].center.x);
			if (rel_diff > max_rel_diff)
				return i;
		}

		if (!((boxes1[i].center.y == 0.0f) && (abs(boxes2[i].center.y) < max_rel_diff)))
		{
			rel_diff = abs(boxes1[i].center.y-boxes2[i].center.y)/abs(boxes1[i].center.y);
			if (rel_diff > max_rel_diff)
				return i;
		}
		if (!((boxes1[i].size.width == 0.0f) && (abs(boxes2[i].size.width) < max_rel_diff)))
		{
			rel_diff = abs(boxes1[i].size.width-boxes2[i].size.width)/abs(boxes1[i].size.width);
			if (rel_diff > max_rel_diff)
			return i;
		}

		if (!((boxes1[i].size.height == 0.0f) && (abs(boxes2[i].size.height) < max_rel_diff)))
		{
			rel_diff = abs(boxes1[i].size.height-boxes2[i].size.height)/abs(boxes1[i].size.height);
			if (rel_diff > max_rel_diff)
				return i;
		}
	}

	return -1;
}

void CV_MserTest::run(int)
{
	string image_path = string(ts->get_data_path()) + "mser/puzzle.png";

	IplImage* img = cvLoadImage( image_path.c_str());
	if (!img)
	{
		ts->printf( cvtest::TS::LOG, "Unable to open image mser/puzzle.png\n");
		ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA);
		return;
	}

	CvSeq* contours;
	CvMemStorage* storage= cvCreateMemStorage();
	IplImage* hsv = cvCreateImage( cvGetSize( img ), IPL_DEPTH_8U, 3 );
	cvCvtColor( img, hsv, CV_BGR2YCrCb );
	CvMSERParams params = cvMSERParams();//cvMSERParams( 5, 60, cvRound(.2*img->width*img->height), .25, .2 );
	cvExtractMSER( hsv, NULL, &contours, storage, params );

	vector<CvBox2D> boxes;
	vector<CvBox2D> boxes_orig;
	for ( int i = 0; i < contours->total; i++ )
	{
		CvContour* r = *(CvContour**)cvGetSeqElem( contours, i );
		CvBox2D box = cvFitEllipse2( r );
		box.angle=(float)CV_PI/2-box.angle;
		boxes.push_back(box);
	}

	string boxes_path = string(ts->get_data_path()) + "mser/boxes.txt";

	if (!LoadBoxes(boxes_path.c_str(),boxes_orig))
	{
		SaveBoxes(boxes_path.c_str(),boxes);
		ts->printf( cvtest::TS::LOG, "Unable to open data file mser/boxes.txt\n");
		ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA);
		return;
	}

	const float dissimularity = 0.01f;
	int n_box = CompareBoxes(boxes_orig,boxes,dissimularity);
	if (n_box < 0)
	{
		ts->set_failed_test_info(cvtest::TS::OK);
	}
	else
	{
		ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
		ts->printf( cvtest::TS::LOG, "Incorrect correspondence in %d box\n",n_box);
	}

	cvReleaseMemStorage(&storage);
	cvReleaseImage(&hsv);
	cvReleaseImage(&img);
}

TEST(Features2d_MSER, regression) { CV_MserTest test; test.safe_run(); }

<commit_msg>corrected angular difference check in MSER test (thanks to Pieter-Jan Busschaert for the patch)<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include "test_precomp.hpp"

#include <vector>
#include <string>
using namespace std;
using namespace cv;

class CV_MserTest : public cvtest::BaseTest
{
public:
    CV_MserTest();
protected:
    void run(int);
    int LoadBoxes(const char* path, vector<CvBox2D>& boxes);
    int SaveBoxes(const char* path, const vector<CvBox2D>& boxes);
    int CompareBoxes(const vector<CvBox2D>& boxes1,const vector<CvBox2D>& boxes2, float max_rel_diff = 0.01f);
};

CV_MserTest::CV_MserTest()
{
}

int CV_MserTest::LoadBoxes(const char* path, vector<CvBox2D>& boxes)
{
    boxes.clear();
    FILE* f = fopen(path,"r");

    if (f==NULL)
    {
        return 0;
    }

    while (!feof(f))
    {
        CvBox2D box;
        fscanf(f,"%f,%f,%f,%f,%f\n",&box.angle,&box.center.x,&box.center.y,&box.size.width,&box.size.height);
        boxes.push_back(box);
    }
    fclose(f);
    return 1;
}

int CV_MserTest::SaveBoxes(const char* path, const vector<CvBox2D>& boxes)
{
    FILE* f = fopen(path,"w");
    if (f==NULL)
    {
        return 0;
    }
    for (int i=0;i<(int)boxes.size();i++)
    {
        fprintf(f,"%f,%f,%f,%f,%f\n",boxes[i].angle,boxes[i].center.x,boxes[i].center.y,boxes[i].size.width,boxes[i].size.height);
    }
    fclose(f);
    return 1;
}

int CV_MserTest::CompareBoxes(const vector<CvBox2D>& boxes1,const vector<CvBox2D>& boxes2, float max_rel_diff)
{
    if (boxes1.size() != boxes2.size())
        return 0;

    for (int i=0; i<(int)boxes1.size();i++)
    {
        float rel_diff;
        if (!((boxes1[i].angle == 0.0f) && (abs(boxes2[i].angle) < max_rel_diff)))
        {
            float angle_diff = (float)fmod(boxes1[i].angle - boxes2[i].angle, 180);
            // for angular correctness, it makes no sense to use a "relative" error.
            // a 1-degree error around 5 degrees is equally bas as around 250 degrees.
            // in correct cases, angle_diff can now be a bit above 0 or a bit below 180
            if (angle_diff > 90.0f)
            {
                    angle_diff -= 180.0f;
            }
            rel_diff = (float)fabs(angle_diff);
            if (rel_diff > max_rel_diff)
                return i;
        }

        if (!((boxes1[i].center.x == 0.0f) && (abs(boxes2[i].center.x) < max_rel_diff)))
        {
            rel_diff = abs(boxes1[i].center.x-boxes2[i].center.x)/abs(boxes1[i].center.x);
            if (rel_diff > max_rel_diff)
                return i;
        }

        if (!((boxes1[i].center.y == 0.0f) && (abs(boxes2[i].center.y) < max_rel_diff)))
        {
            rel_diff = abs(boxes1[i].center.y-boxes2[i].center.y)/abs(boxes1[i].center.y);
            if (rel_diff > max_rel_diff)
                return i;
        }
        if (!((boxes1[i].size.width == 0.0f) && (abs(boxes2[i].size.width) < max_rel_diff)))
        {
            rel_diff = abs(boxes1[i].size.width-boxes2[i].size.width)/abs(boxes1[i].size.width);
            if (rel_diff > max_rel_diff)
            return i;
        }

        if (!((boxes1[i].size.height == 0.0f) && (abs(boxes2[i].size.height) < max_rel_diff)))
        {
            rel_diff = abs(boxes1[i].size.height-boxes2[i].size.height)/abs(boxes1[i].size.height);
            if (rel_diff > max_rel_diff)
                return i;
        }
    }

    return -1;
}

void CV_MserTest::run(int)
{
    string image_path = string(ts->get_data_path()) + "mser/puzzle.png";

    IplImage* img = cvLoadImage( image_path.c_str());
    if (!img)
    {
        ts->printf( cvtest::TS::LOG, "Unable to open image mser/puzzle.png\n");
        ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA);
        return;
    }

    CvSeq* contours;
    CvMemStorage* storage= cvCreateMemStorage();
    IplImage* hsv = cvCreateImage( cvGetSize( img ), IPL_DEPTH_8U, 3 );
    cvCvtColor( img, hsv, CV_BGR2YCrCb );
    CvMSERParams params = cvMSERParams();//cvMSERParams( 5, 60, cvRound(.2*img->width*img->height), .25, .2 );
    cvExtractMSER( hsv, NULL, &contours, storage, params );

    vector<CvBox2D> boxes;
    vector<CvBox2D> boxes_orig;
    for ( int i = 0; i < contours->total; i++ )
    {
        CvContour* r = *(CvContour**)cvGetSeqElem( contours, i );
        CvBox2D box = cvFitEllipse2( r );
        box.angle=(float)CV_PI/2-box.angle;
        boxes.push_back(box);
    }

    string boxes_path = string(ts->get_data_path()) + "mser/boxes.txt";
    string calc_boxes_path = string(ts->get_data_path()) + "mser/boxes.calc.txt";

    if (!LoadBoxes(boxes_path.c_str(),boxes_orig))
    {
        SaveBoxes(boxes_path.c_str(),boxes);
        ts->printf( cvtest::TS::LOG, "Unable to open data file mser/boxes.txt\n");
        ts->set_failed_test_info(cvtest::TS::FAIL_MISSING_TEST_DATA);
        return;
    }

    const float dissimularity = 0.01f;
    int n_box = CompareBoxes(boxes_orig,boxes,dissimularity);
    if (n_box < 0)
    {
        ts->set_failed_test_info(cvtest::TS::OK);
    }
    else
    {
        SaveBoxes(calc_boxes_path.c_str(), boxes);
        ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
        ts->printf( cvtest::TS::LOG, "Incorrect correspondence in box %d\n",n_box);
    }

    cvReleaseMemStorage(&storage);
    cvReleaseImage(&hsv);
    cvReleaseImage(&img);
}

TEST(Features2d_MSER, regression) { CV_MserTest test; test.safe_run(); }

<|endoftext|>


<commit_before>/*
 Itay Marom
 Cisco Systems, Inc.
*/

/*
Copyright (c) 2015-2015 Cisco Systems, Inc.

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

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

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

#include "trex_watchdog.h"
#include "trex_exception.h"

#include <assert.h>
#include <unistd.h>
#include <sstream>

#include <sys/ptrace.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <dlfcn.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <iostream>
#include  <stdexcept>

static TrexMonitor *global_monitor;

const char *get_exe_name();

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer, 128, pipe.get()) != NULL) {
            result += buffer;
        }
    }
    return result;
}

// This function produces a stack backtrace with demangled function & method names.
__attribute__((noinline))
std::string Backtrace(int skip = 1)
{
    void *callstack[128];
    const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
    char buf[1024];
    int nFrames = backtrace(callstack, nMaxFrames);
    char **symbols = backtrace_symbols(callstack, nFrames);

    std::ostringstream trace_buf;
    for (int i = skip; i < nFrames; i++) {

        Dl_info info;
        if (dladdr(callstack[i], &info) && info.dli_sname) {
            char *demangled = NULL;
            int status = -1;
            if (info.dli_sname[0] == '_')
                demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
            snprintf(buf, sizeof(buf), "%-3d %*p %s + %zd\n",
                     i, int(2 + sizeof(void*) * 2), callstack[i],
                     status == 0 ? demangled :
                     info.dli_sname == 0 ? symbols[i] : info.dli_sname,
                     (char *)callstack[i] - (char *)info.dli_saddr);
            free(demangled);
        } else {
            snprintf(buf, sizeof(buf), "%-3d %*p %s\n",
                     i, int(2 + sizeof(void*) * 2), callstack[i], symbols[i]);
        }
        trace_buf << buf;
    }
    free(symbols);
    if (nFrames == nMaxFrames)
        trace_buf << "[truncated]\n";

    /* add the addr2line info */
    std::stringstream addr2line;

    addr2line << "/usr/bin/addr2line -s -e " << get_exe_name() << " ";
    for (int i = skip; i < nFrames; i++) {
        addr2line << callstack[i] << " ";
    }

    trace_buf << "\n\n*** addr2line information follows ***\n\n";
    try {
        trace_buf << exec(addr2line.str().c_str());
    } catch (std::runtime_error &e) {
        trace_buf << "\n" << e.what();
    }

    return trace_buf.str();
}

__attribute__((noinline))
static void _callstack_signal_handler(int signr, siginfo_t *info, void *secret) {
    std::stringstream ss;

    double now = now_sec();

    ss << "WATCHDOG: task '" << global_monitor->get_name() << "' has not responded for more than " << global_monitor->get_interval(now) << " seconds - timeout is " << global_monitor->get_timeout_sec() << " seconds";

    std::string backtrace = Backtrace();
    ss << "\n\n*** traceback follows ***\n\n" << backtrace << "\n";

    throw std::runtime_error(ss.str());
}

/**************************************
 * Trex Monitor object
 *************************************/

void TrexMonitor::create(const std::string &name, double timeout_sec) {
    m_tid              = pthread_self();
    m_name             = name;
    m_timeout_sec      = timeout_sec;
    m_base_timeout_sec = timeout_sec;
    m_tickled          = true;
    m_ts               = 0;
    m_io_ref_cnt       = 0;

    /* the rare case of m_active_time_sec set out of order with tickled */
    asm volatile("mfence" ::: "memory");
}

/**************************************
 * Trex watchdog
 *************************************/

void TrexWatchDog::init(bool enable){
    m_enable = enable;
    if (m_enable) {
        register_signal();
    }
}

/**
 * get pointer to monitor of current thread
 * (NULL if no monitor)
 *
 */
TrexMonitor * TrexWatchDog::get_current_monitor() {

    for (int i = 0; i < m_mon_count; i++) {
        if ( m_monitors[i]->get_tid() == pthread_self() ) {
            return m_monitors[i];
        }
    }

    return NULL;
}

/**
 * register a monitor
 * this function is thread safe
 *
 */
void TrexWatchDog::register_monitor(TrexMonitor *monitor) {
    if (!m_enable){
        return;
    }

    /* critical section start */
    std::unique_lock<std::mutex> lock(m_lock);

    /* sanity - not a must but why not... */
    TrexMonitor * cur_monitor = get_current_monitor();
    if ( cur_monitor != NULL || cur_monitor == monitor ) {
        std::stringstream ss;
        ss << "WATCHDOG: double register detected\n\n" << Backtrace();
        throw TrexException(ss.str());
    }

    /* check capacity */
    if (m_mon_count == MAX_MONITORS) {
        std::stringstream ss;
        ss << "WATCHDOG: too many registered monitors\n\n" << Backtrace();
        throw TrexException(ss.str());
    }

    /* add monitor */
    m_monitors[m_mon_count++] = monitor;

    /* critical section end */
    lock.unlock();

}

void TrexWatchDog::start() {

    if (!m_enable){
        return ;
    }

    m_active = true;
    m_thread = new std::thread(&TrexWatchDog::_main, this);
    if (!m_thread) {
        throw TrexException("unable to create watchdog thread");
    }
}

void TrexWatchDog::stop() {

    if (!m_enable){
        return ;
    }

    m_active = false;

    if (m_thread) {
        m_thread->join();
        delete m_thread;
        m_thread = NULL;
    }
}

/**
 * main loop
 *
 */
void TrexWatchDog::_main() noexcept {

    pthread_setname_np(pthread_self(), "Trex Watchdog");

    assert(m_enable == true);

    /* start main loop */
    while (m_active) {

        dsec_t now = now_sec();

        /* to be on the safe side - read the count with a lock */
        std::unique_lock<std::mutex> lock(m_lock);
        int count = m_mon_count;
        lock.unlock();

        for (int i = 0; i < count; i++) {
            TrexMonitor *monitor = m_monitors[i];

            /* skip non expired monitors */
            if (!monitor->is_expired(now)) {
                continue;
            }

            /* it has expired but it was tickled */
            if (monitor->is_tickled()) {
                monitor->reset(now);
                continue;
            }

            /* crash */
            global_monitor = monitor;

            pthread_kill(monitor->get_tid(), SIGALRM);

            /* nothing to do more... the other thread will terminate, but if not - we terminate */
            sleep(5);
            fprintf(stderr, "\n\n*** WATCHDOG violation detected on task '%s' which have failed to response to the signal ***\n\n", monitor->get_name().c_str());
            abort();
        }

        /* the internal clock - 250 ms */
        delay(250);
    }
}

void TrexWatchDog::register_signal() {
    /* do this once */
    if (g_signal_init) {
        return;
    }

    /* register a handler on SIG ALARM */
    struct sigaction sa;
    memset (&sa, '\0', sizeof(sa));

    sa.sa_flags = SA_SIGINFO;
    sa.sa_sigaction = _callstack_signal_handler;

    int rc = sigaction(SIGALRM , &sa, NULL);
    assert(rc == 0);

    g_signal_init = true;
}

bool TrexWatchDog::g_signal_init = false;

<commit_msg>assert now produces a detailed backtrace and even publish to Python as an event<commit_after>/*
 Itay Marom
 Cisco Systems, Inc.
*/

/*
Copyright (c) 2015-2015 Cisco Systems, Inc.

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

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

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

#include "trex_watchdog.h"
#include "trex_exception.h"
#include "trex_stateless.h"

#include <assert.h>
#include <unistd.h>
#include <sstream>

#include <sys/ptrace.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <dlfcn.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <iostream>
#include  <stdexcept>

static TrexMonitor *global_monitor;

const char *get_exe_name();

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer, 128, pipe.get()) != NULL) {
            result += buffer;
        }
    }
    return result;
}

// This function produces a stack backtrace with demangled function & method names.
__attribute__((noinline))
std::string Backtrace(int skip = 1)
{
    void *callstack[128];
    const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
    char buf[1024];
    int nFrames = backtrace(callstack, nMaxFrames);
    char **symbols = backtrace_symbols(callstack, nFrames);

    std::ostringstream trace_buf;
    for (int i = skip; i < nFrames; i++) {

        Dl_info info;
        if (dladdr(callstack[i], &info) && info.dli_sname) {
            char *demangled = NULL;
            int status = -1;
            if (info.dli_sname[0] == '_')
                demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
            snprintf(buf, sizeof(buf), "%-3d %*p %s + %zd\n",
                     i, int(2 + sizeof(void*) * 2), callstack[i],
                     status == 0 ? demangled :
                     info.dli_sname == 0 ? symbols[i] : info.dli_sname,
                     (char *)callstack[i] - (char *)info.dli_saddr);
            free(demangled);
        } else {
            snprintf(buf, sizeof(buf), "%-3d %*p %s\n",
                     i, int(2 + sizeof(void*) * 2), callstack[i], symbols[i]);
        }
        trace_buf << buf;
    }
    free(symbols);
    if (nFrames == nMaxFrames)
        trace_buf << "[truncated]\n";

    /* add the addr2line info */
    std::stringstream addr2line;

    addr2line << "/usr/bin/addr2line -s -e " << get_exe_name() << " ";
    for (int i = skip; i < nFrames; i++) {
        addr2line << callstack[i] << " ";
    }

    trace_buf << "\n\n*** addr2line information follows ***\n\n";
    try {
        trace_buf << exec(addr2line.str().c_str());
    } catch (std::runtime_error &e) {
        trace_buf << "\n" << e.what();
    }

    return trace_buf.str();
}

__attribute__((noinline))
static void _callstack_signal_handler(int signr, siginfo_t *info, void *secret) {
    std::stringstream ss;

    double now = now_sec();

    ss << "WATCHDOG: task '" << global_monitor->get_name() << "' has not responded for more than " << global_monitor->get_interval(now) << " seconds - timeout is " << global_monitor->get_timeout_sec() << " seconds";

    std::string backtrace = Backtrace();
    ss << "\n\n*** traceback follows ***\n\n" << backtrace << "\n";

    throw std::runtime_error(ss.str());
}

/**
 * hook assert failure function
 */
extern "C" {

    /* thread local storage - to avoid multiple threads calling assert */
    static __thread bool g_in_assert = false;

    extern void __assert_fail (const char *__assertion, const char *__file, unsigned int __line, const char *__function) throw () {

        /* double assert - make sure no re-entrant calls, simply call abort directly */
        if (g_in_assert) {
            abort();
        }

        /* mark it */
        g_in_assert = true;

        std::string cause = "assert: " + std::string(__file) + ":" + std::to_string(__line) + " " + std::string(__function) + " Assertion '" + std::string(__assertion) + "' failed.";

        std::stringstream ss;
        ss << cause;
        ss << "\n\n*** traceback follows ***\n\n" << Backtrace() << "\n";

        /* if under stateless mode - try to publish an event */
        if ( (get_stateless_obj()) && (get_stateless_obj()->get_publisher()) ) {
            Json::Value data;
            data["cause"] = "assert: " + std::string(__file) + ":" + std::to_string(__line) +  " Assertion '" + std::string(__assertion) + "' failed.";

            get_stateless_obj()->get_publisher()->publish_event(TrexPublisher::EVENT_SERVER_STOPPED, data);
        }

        throw std::runtime_error(ss.str());
    }

}

/**************************************
 * Trex Monitor object
 *************************************/

void TrexMonitor::create(const std::string &name, double timeout_sec) {
    m_tid              = pthread_self();
    m_name             = name;
    m_timeout_sec      = timeout_sec;
    m_base_timeout_sec = timeout_sec;
    m_tickled          = true;
    m_ts               = 0;
    m_io_ref_cnt       = 0;

    /* the rare case of m_active_time_sec set out of order with tickled */
    asm volatile("mfence" ::: "memory");
}

/**************************************
 * Trex watchdog
 *************************************/

void TrexWatchDog::init(bool enable){
    m_enable = enable;
    if (m_enable) {
        register_signal();
    }
}

/**
 * get pointer to monitor of current thread
 * (NULL if no monitor)
 *
 */
TrexMonitor * TrexWatchDog::get_current_monitor() {

    for (int i = 0; i < m_mon_count; i++) {
        if ( m_monitors[i]->get_tid() == pthread_self() ) {
            return m_monitors[i];
        }
    }

    return NULL;
}

/**
 * register a monitor
 * this function is thread safe
 *
 */
void TrexWatchDog::register_monitor(TrexMonitor *monitor) {
    if (!m_enable){
        return;
    }

    /* critical section start */
    std::unique_lock<std::mutex> lock(m_lock);

    /* sanity - not a must but why not... */
    TrexMonitor * cur_monitor = get_current_monitor();
    if ( cur_monitor != NULL || cur_monitor == monitor ) {
        std::stringstream ss;
        ss << "WATCHDOG: double register detected\n\n" << Backtrace();
        throw TrexException(ss.str());
    }

    /* check capacity */
    if (m_mon_count == MAX_MONITORS) {
        std::stringstream ss;
        ss << "WATCHDOG: too many registered monitors\n\n" << Backtrace();
        throw TrexException(ss.str());
    }

    /* add monitor */
    m_monitors[m_mon_count++] = monitor;

    /* critical section end */
    lock.unlock();

}

void TrexWatchDog::start() {

    if (!m_enable){
        return ;
    }

    m_active = true;
    m_thread = new std::thread(&TrexWatchDog::_main, this);
    if (!m_thread) {
        throw TrexException("unable to create watchdog thread");
    }
}

void TrexWatchDog::stop() {

    if (!m_enable){
        return ;
    }

    m_active = false;

    if (m_thread) {
        m_thread->join();
        delete m_thread;
        m_thread = NULL;
    }
}

/**
 * main loop
 *
 */
void TrexWatchDog::_main() noexcept {

    pthread_setname_np(pthread_self(), "Trex Watchdog");

    assert(m_enable == true);

    /* start main loop */
    while (m_active) {

        dsec_t now = now_sec();

        /* to be on the safe side - read the count with a lock */
        std::unique_lock<std::mutex> lock(m_lock);
        int count = m_mon_count;
        lock.unlock();

        for (int i = 0; i < count; i++) {
            TrexMonitor *monitor = m_monitors[i];

            /* skip non expired monitors */
            if (!monitor->is_expired(now)) {
                continue;
            }

            /* it has expired but it was tickled */
            if (monitor->is_tickled()) {
                monitor->reset(now);
                continue;
            }

            /* crash */
            global_monitor = monitor;

            pthread_kill(monitor->get_tid(), SIGALRM);

            /* nothing to do more... the other thread will terminate, but if not - we terminate */
            sleep(5);
            fprintf(stderr, "\n\n*** WATCHDOG violation detected on task '%s' which have failed to response to the signal ***\n\n", monitor->get_name().c_str());
            abort();
        }

        /* the internal clock - 250 ms */
        delay(250);
    }
}

void TrexWatchDog::register_signal() {
    /* do this once */
    if (g_signal_init) {
        return;
    }

    /* register a handler on SIG ALARM */
    struct sigaction sa;
    memset (&sa, '\0', sizeof(sa));

    sa.sa_flags = SA_SIGINFO;
    sa.sa_sigaction = _callstack_signal_handler;

    int rc = sigaction(SIGALRM , &sa, NULL);
    assert(rc == 0);

    g_signal_init = true;
}

bool TrexWatchDog::g_signal_init = false;

<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include <test_precomp.hpp>
#include <time.h>

#ifdef HAVE_CUDA
using cv::gpu::GpuMat;

// show detection results on input image with cv::imshow
#define SHOW_DETECTIONS

#if defined SHOW_DETECTIONS
# define SHOW(res)           \
    cv::imshow(#res, result);\
    cv::waitKey(0);
#else
# define SHOW(res)
#endif

#define GPU_TEST_P(fixture, name, params)                         \
    class fixture##_##name : public fixture {                     \
     public:                                                      \
      fixture##_##name() {}                                       \
     protected:                                                   \
      virtual void body();                                        \
    };                                                            \
    TEST_P(fixture##_##name, name /*none*/){ body();}             \
    INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);  \
    void fixture##_##name::body()

typedef std::tr1::tuple<std::string, std::string, int> roi_fixture_t;

struct SoftCascadeTest : public ::testing::TestWithParam<roi_fixture_t>
{
    typedef cv::gpu::SoftCascade::Detection detection_t;
    static cv::Rect getFromTable(int idx)
    {
        static const cv::Rect rois[] =
        {
            cv::Rect( 65,  20,  35, 80),
            cv::Rect( 95,  35,  45, 40),
            cv::Rect( 45,  35,  45, 40),
            cv::Rect( 25,  27,  50, 45),
            cv::Rect(100,  50,  45, 40),

            cv::Rect( 60,  30,  45, 40),
            cv::Rect( 40,  55,  50, 40),
            cv::Rect( 48,  37,  72, 80),
            cv::Rect( 48,  32,  85, 58),
            cv::Rect( 48,   0,  32, 27)
        };

        return rois[idx];
    }

    static std::string itoa(long i)
    {
        static char s[65];
        sprintf(s, "%ld", i);
        return std::string(s);
    }

    static std::string getImageName(int level)
    {
        time_t rawtime;
        struct tm * timeinfo;
        char buffer [80];

        time ( &rawtime );
        timeinfo = localtime ( &rawtime );

        strftime (buffer,80,"%Y-%m-%d--%H-%M-%S",timeinfo);
        return "gpu_rec_level_" + itoa(level)+ "_" + std::string(buffer) + ".png";
    }

    static void print(std::ostream &out, const detection_t& d)
    {
        out << "\x1b[32m[ detection]\x1b[0m ("
            << std::setw(4)  << d.x
            << " "
            << std::setw(4)  << d.y
            << ") ("
            << std::setw(4)  << d.w
            << " "
            << std::setw(4)  << d.h
            << ") "
            << std::setw(12) << d.confidence
            <<  std::endl;
    }

    static void printTotal(std::ostream &out, int detbytes)
    {
        out << "\x1b[32m[          ]\x1b[0m Total detections " << (detbytes / sizeof(detection_t)) << std::endl;
    }

    static void writeResult(const cv::Mat& result, const int level)
    {
        std::string path = cv::tempfile(getImageName(level).c_str());
        cv::imwrite(path, result);
        std::cout << "\x1b[32m" << "[          ]" << std::endl << "[ stored in]"<< "\x1b[0m" << path << std::endl;
    }
};

GPU_TEST_P(SoftCascadeTest, detectInROI,
    testing::Combine(
        testing::Values(std::string("../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("../cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 5)))
{
    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path() + GET_PARAM(1));
    ASSERT_FALSE(coloredCpu.empty());

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(cvtest::TS::ptr()->get_data_path() + GET_PARAM(0)));

    GpuMat colored(coloredCpu), objectBoxes(1, 16384, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1), trois;
    rois.setTo(0);

    int nroi = GET_PARAM(2);
    cv::Mat result(coloredCpu);
    cv::RNG rng;
    for (int i = 0; i < nroi; ++i)
    {
        cv::Rect r = getFromTable(rng(10));
        GpuMat sub(rois, r);
        sub.setTo(1);
        r.x *= 4; r.y *= 4; r.width *= 4; r.height *= 4;
        cv::rectangle(result, r, cv::Scalar(0, 0, 255, 255), 1);
    }

    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(colored, trois, objectBoxes);

    ///
    cv::Mat dt(objectBoxes);
    typedef cv::gpu::SoftCascade::Detection detection_t;

    detection_t* dts = (detection_t*)dt.data;

    printTotal(std::cout, dt.cols);
    for (int i = 0; i  < (int)(dt.cols / sizeof(detection_t)); ++i)
    {
        detection_t d = dts[i];
        print(std::cout, d);
        cv::rectangle(result, cv::Rect(d.x, d.y, d.w, d.h), cv::Scalar(255, 0, 0, 255), 1);
    }

    SHOW(result);
}

GPU_TEST_P(SoftCascadeTest, detectInLevel,
        testing::Combine(
        testing::Values(std::string("../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("../cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 47)
        ))
{
    std::string xml =  cvtest::TS::ptr()->get_data_path() + GET_PARAM(0);
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path() + GET_PARAM(1));
    ASSERT_FALSE(coloredCpu.empty());

    typedef cv::gpu::SoftCascade::Detection detection_t;
    GpuMat colored(coloredCpu), objectBoxes(1, 100 * sizeof(detection_t), CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(1);

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    int level = GET_PARAM(2);
    cascade.detectMultiScale(colored, trois, objectBoxes, 1, level);

    cv::Mat dt(objectBoxes);

    detection_t* dts = (detection_t*)dt.data;
    cv::Mat result(coloredCpu);

    printTotal(std::cout, dt.cols);
    for (int i = 0; i  < (int)(dt.cols / sizeof(detection_t)); ++i)
    {
        detection_t d = dts[i];
        print(std::cout, d);
        cv::rectangle(result, cv::Rect(d.x, d.y, d.w, d.h), cv::Scalar(255, 0, 0, 255), 1);
    }

    writeResult(result, level);
    SHOW(result);
}

TEST(SoftCascadeTest, readCascade)
{
    std::string xml = cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/icf-template.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));
}

TEST(SoftCascadeTest, detect)
{
    std::string xml =  cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path()
        + "../cv/cascadeandhog/bahnhof/image_00000000_0.png");
    ASSERT_FALSE(coloredCpu.empty());

    GpuMat colored(coloredCpu), objectBoxes(1, 100000, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(0);
    GpuMat sub(rois, cv::Rect(rois.cols / 4, rois.rows / 4,rois.cols / 2, rois.rows / 2));
    sub.setTo(cv::Scalar::all(1));

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(colored, trois, objectBoxes);

    typedef cv::gpu::SoftCascade::Detection Detection;
    cv::Mat detections(objectBoxes);
    ASSERT_EQ(detections.cols / sizeof(Detection) ,3670U);
}

TEST(SoftCascadeTest, detectOnIntegral)
{
    std::string xml =  cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    std::string intPath = cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/integrals.xml";
    cv::FileStorage fs(intPath, cv::FileStorage::READ);
    ASSERT_TRUE(fs.isOpened());

    GpuMat hogluv(121 * 10, 161, CV_32SC1);
    for (int i = 0; i < 10; ++i)
    {
        cv::Mat channel;
        fs[std::string("channel") + SoftCascadeTest::itoa(i)] >> channel;
        GpuMat gchannel(hogluv, cv::Rect(0, 121 * i, 161, 121));
        gchannel.upload(channel);
    }

    GpuMat objectBoxes(1, 100000, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(1);

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(hogluv, trois, objectBoxes);

    typedef cv::gpu::SoftCascade::Detection Detection;
    cv::Mat detections(objectBoxes);

    ASSERT_EQ(detections.cols / sizeof(Detection) ,2042U);
}
#endif<commit_msg>add DeviceInfo parameter to the soft cascade tests<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include <test_precomp.hpp>
#include <time.h>

#ifdef HAVE_CUDA
using cv::gpu::GpuMat;

// show detection results on input image with cv::imshow
#define SHOW_DETECTIONS

#if defined SHOW_DETECTIONS
# define SHOW(res)           \
    cv::imshow(#res, result);\
    cv::waitKey(0);
#else
# define SHOW(res)
#endif

#define GPU_TEST_P(fixture, name, params)                         \
    class fixture##_##name : public fixture {                     \
     public:                                                      \
      fixture##_##name() {}                                       \
     protected:                                                   \
      virtual void body();                                        \
    };                                                            \
    TEST_P(fixture##_##name, name /*none*/){ body();}             \
    INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);  \
    void fixture##_##name::body()

namespace {

    typedef cv::gpu::SoftCascade::Detection Detection;

    static cv::Rect getFromTable(int idx)
    {
        static const cv::Rect rois[] =
        {
            cv::Rect( 65,  20,  35, 80),
            cv::Rect( 95,  35,  45, 40),
            cv::Rect( 45,  35,  45, 40),
            cv::Rect( 25,  27,  50, 45),
            cv::Rect(100,  50,  45, 40),

            cv::Rect( 60,  30,  45, 40),
            cv::Rect( 40,  55,  50, 40),
            cv::Rect( 48,  37,  72, 80),
            cv::Rect( 48,  32,  85, 58),
            cv::Rect( 48,   0,  32, 27)
        };

        return rois[idx];
    }

    static std::string itoa(long i)
    {
        static char s[65];
        sprintf(s, "%ld", i);
        return std::string(s);
    }

    static std::string getImageName(int level)
    {
        time_t rawtime;
        struct tm * timeinfo;
        char buffer [80];

        time ( &rawtime );
        timeinfo = localtime ( &rawtime );

        strftime (buffer,80,"%Y-%m-%d--%H-%M-%S",timeinfo);
        return "gpu_rec_level_" + itoa(level)+ "_" + std::string(buffer) + ".png";
    }

    static void print(std::ostream &out, const Detection& d)
    {
        out << "\x1b[32m[ detection]\x1b[0m ("
            << std::setw(4)  << d.x
            << " "
            << std::setw(4)  << d.y
            << ") ("
            << std::setw(4)  << d.w
            << " "
            << std::setw(4)  << d.h
            << ") "
            << std::setw(12) << d.confidence
            <<  std::endl;
    }

    static void printTotal(std::ostream &out, int detbytes)
    {
        out << "\x1b[32m[          ]\x1b[0m Total detections " << (detbytes / sizeof(Detection)) << std::endl;
    }

    static void writeResult(const cv::Mat& result, const int level)
    {
        std::string path = cv::tempfile(getImageName(level).c_str());
        cv::imwrite(path, result);
        std::cout << "\x1b[32m" << "[          ]" << std::endl << "[ stored in]"<< "\x1b[0m" << path << std::endl;
    }
}

typedef ::testing::TestWithParam<std::tr1::tuple<cv::gpu::DeviceInfo, std::string, std::string, int> > SoftCascadeTestRoi;
GPU_TEST_P(SoftCascadeTestRoi, detect,
    testing::Combine(
        ALL_DEVICES,
        testing::Values(std::string("../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("../cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 5)))
{
    cv::gpu::setDevice(GET_PARAM(0).deviceID());
    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path() + GET_PARAM(2));
    ASSERT_FALSE(coloredCpu.empty());

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(cvtest::TS::ptr()->get_data_path() + GET_PARAM(1)));

    GpuMat colored(coloredCpu), objectBoxes(1, 16384, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1), trois;
    rois.setTo(0);

    int nroi = GET_PARAM(3);
    cv::Mat result(coloredCpu);
    cv::RNG rng;
    for (int i = 0; i < nroi; ++i)
    {
        cv::Rect r = getFromTable(rng(10));
        GpuMat sub(rois, r);
        sub.setTo(1);
        r.x *= 4; r.y *= 4; r.width *= 4; r.height *= 4;
        cv::rectangle(result, r, cv::Scalar(0, 0, 255, 255), 1);
    }

    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(colored, trois, objectBoxes);

    cv::Mat dt(objectBoxes);
    typedef cv::gpu::SoftCascade::Detection Detection;

    Detection* dts = (Detection*)dt.data;

    printTotal(std::cout, dt.cols);
    for (int i = 0; i  < (int)(dt.cols / sizeof(Detection)); ++i)
    {
        Detection d = dts[i];
        print(std::cout, d);
        cv::rectangle(result, cv::Rect(d.x, d.y, d.w, d.h), cv::Scalar(255, 0, 0, 255), 1);
    }

    SHOW(result);
}

typedef ::testing::TestWithParam<std::tr1::tuple<cv::gpu::DeviceInfo, std::string, std::string, int> > SoftCascadeTestLevel;
GPU_TEST_P(SoftCascadeTestLevel, detect,
        testing::Combine(
        ALL_DEVICES,
        testing::Values(std::string("../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("../cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 47)
        ))
{
    cv::gpu::setDevice(GET_PARAM(0).deviceID());

    std::string xml =  cvtest::TS::ptr()->get_data_path() + GET_PARAM(1);
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path() + GET_PARAM(2));
    ASSERT_FALSE(coloredCpu.empty());

    typedef cv::gpu::SoftCascade::Detection Detection;
    GpuMat colored(coloredCpu), objectBoxes(1, 100 * sizeof(Detection), CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(1);

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    int level = GET_PARAM(3);
    cascade.detectMultiScale(colored, trois, objectBoxes, 1, level);

    cv::Mat dt(objectBoxes);

    Detection* dts = (Detection*)dt.data;
    cv::Mat result(coloredCpu);

    printTotal(std::cout, dt.cols);
    for (int i = 0; i  < (int)(dt.cols / sizeof(Detection)); ++i)
    {
        Detection d = dts[i];
        print(std::cout, d);
        cv::rectangle(result, cv::Rect(d.x, d.y, d.w, d.h), cv::Scalar(255, 0, 0, 255), 1);
    }

    writeResult(result, level);
    SHOW(result);
}

TEST(SoftCascadeTest, readCascade)
{
    std::string xml = cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/icf-template.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));
}

typedef ::testing::TestWithParam<cv::gpu::DeviceInfo > SoftCascadeTestAll;
GPU_TEST_P(SoftCascadeTestAll, detect,
        ALL_DEVICES
        )
{
    cv::gpu::setDevice(GetParam().deviceID());
    std::string xml =  cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    cv::Mat coloredCpu = cv::imread(cvtest::TS::ptr()->get_data_path()
        + "../cv/cascadeandhog/bahnhof/image_00000000_0.png");
    ASSERT_FALSE(coloredCpu.empty());

    GpuMat colored(coloredCpu), objectBoxes(1, 100000, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(0);
    GpuMat sub(rois, cv::Rect(rois.cols / 4, rois.rows / 4,rois.cols / 2, rois.rows / 2));
    sub.setTo(cv::Scalar::all(1));

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(colored, trois, objectBoxes);

    typedef cv::gpu::SoftCascade::Detection Detection;
    cv::Mat detections(objectBoxes);
    ASSERT_EQ(detections.cols / sizeof(Detection) ,3670U);
}

GPU_TEST_P(SoftCascadeTestAll, detectOnIntegral,
        ALL_DEVICES
        )
{
    cv::gpu::setDevice(GetParam().deviceID());
    std::string xml =  cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml";
    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(xml));

    std::string intPath = cvtest::TS::ptr()->get_data_path() + "../cv/cascadeandhog/integrals.xml";
    cv::FileStorage fs(intPath, cv::FileStorage::READ);
    ASSERT_TRUE(fs.isOpened());

    GpuMat hogluv(121 * 10, 161, CV_32SC1);
    for (int i = 0; i < 10; ++i)
    {
        cv::Mat channel;
        fs[std::string("channel") + itoa(i)] >> channel;
        GpuMat gchannel(hogluv, cv::Rect(0, 121 * i, 161, 121));
        gchannel.upload(channel);
    }

    GpuMat objectBoxes(1, 100000, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(1);

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(hogluv, trois, objectBoxes);

    typedef cv::gpu::SoftCascade::Detection Detection;
    cv::Mat detections(objectBoxes);

    ASSERT_EQ(detections.cols / sizeof(Detection) ,2042U);
}
#endif<|endoftext|>


<commit_before>#include "cmbNucDragLabel.h"

#include <QtGui>

cmbNucDragLabel::cmbNucDragLabel(const QString &text, QWidget *parent)
    : QLabel(text, parent)
{
    setAutoFillBackground(true);
    setFrameShape(QFrame::Panel);
    setFrameShadow(QFrame::Raised);
}
<commit_msg>set pin labels to center of pin<commit_after>#include "cmbNucDragLabel.h"

#include <QtGui>

cmbNucDragLabel::cmbNucDragLabel(const QString &text, QWidget *parent)
    : QLabel(text, parent)
{
    setAutoFillBackground(true);
    setFrameShape(QFrame::Panel);
    setFrameShadow(QFrame::Raised);
    setAcceptDrops(true);
    setAlignment(Qt::AlignCenter);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const int infty = 1000000007;

int N, M;
int edge[15][15];
int setcost[1 << 15];
int dp[1 << 15][15];

int main() {
  cin >> N >> M;
  fill(&edge[0][0], &edge[0][0]+15*15, infty);
  for (auto i = 0; i < M; ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    a--;
    b--;
    edge[a][b] = c;
    edge[b][a] = c;
  }
  fill(setcost, setcost+(1 << 15), 0);
  for (auto i = 0; i < (1 << N); ++i) {
    for (auto j = 0; j < N; ++j) {
      if (((i >> j) & 1) == 0) continue;
      for (auto k = 0; k < N; ++k) {
        if (((i >> k) & 1) == 0) continue;
        setcost[i] += edge[j][k];
      }
    }
  }
  fill(&dp[0][0], &dp[0][0]+(1 << 15)*15, infty);
  dp[1][0] = 0;
  for (auto x = 1; x < (1 << N); ++x) {
    for (auto i = 0; i < N; ++i) {
      if (((x >> i) & 1) == 0) continue;
      if (dp[x][i] >= infty) continue;
      for (auto j = 0; j < N; ++j) {
        if (((x >> j) & 1) == 1 ||
            edge[i][j] == infty) {
          continue;
        }
        int z = x | (1 << j);
        dp[z][j] = min(dp[z][j],
                       dp[x][i] + setcost[z] - setcost[x] - edge[i][j]);
      }
      int z = (((1 << N)-1)^x) & ((1 << N)-1); // all \setminus x
      int w = x - (1 << i); // x \setminus \{ i \}
      int y = z;
      do {
        dp[x | y][i] = min(dp[x | y][i],
                           dp[x][i] + setcost[w | y] - setcost[w] - setcost[y]);
        y = (y - 1) & z;
      } while (y != z);
    }
  }
  cout << dp[(1 << N)][N-1] << endl;
}
<commit_msg>submit F.cpp to 'F - Mole and Abandoned Mine' (arc078) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
#include <bitset>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const int infty = 1000000007;

int N, M;
int edge[15][15];
int setcost[1 << 15];
int dp[1 << 15][15];

auto two(int x) {
  return static_cast<std::bitset<4> >(x);
}

int main() {
  cin >> N >> M;
  fill(&edge[0][0], &edge[0][0]+15*15, infty);
  for (auto i = 0; i < M; ++i) {
    int a, b, c;
    cin >> a >> b >> c;
    a--;
    b--;
    edge[a][b] = c;
    edge[b][a] = c;
  }
  fill(setcost, setcost+(1 << 15), 0);
  for (auto i = 0; i < (1 << N); ++i) {
    for (auto j = 0; j < N; ++j) {
      if (((i >> j) & 1) == 0) continue;
      for (auto k = j+1; k < N; ++k) {
        if (((i >> k) & 1) == 0) continue;
        if (edge[j][k] == infty) continue;
        setcost[i] += edge[j][k];
      }
    }
  }
  fill(&dp[0][0], &dp[0][0]+(1 << 15)*15, infty);
  dp[1][0] = 0;
  for (auto x = 1; x < (1 << N); ++x) {
    for (auto i = 0; i < N; ++i) {
      if (((x >> i) & 1) == 0) continue;
      if (dp[x][i] >= infty) continue;
      // cerr << "x = " << two(x) << ", i = " << i << endl;
      // cerr << "nobashi" << endl;
      for (auto j = 0; j < N; ++j) {
        if (((x >> j) & 1) == 1 ||
            edge[i][j] == infty) {
          continue;
        }
        int z = x | (1 << j);
        dp[z][j] = min(dp[z][j],
                       dp[x][i] + setcost[z] - setcost[x] - edge[i][j]);
        // cerr << "setcost[" << two(z) << "] = " << setcost[z] << endl;
        // cerr << "setcost[" << two(x) << "] = " << setcost[x] << endl;
        // cerr << "edge[" << i << "][" << j << "] = " << edge[i][j] << endl;
        // cerr << "dp[" << two(z) << "][" << j << "] = " << dp[z][j] << endl;
      }
      // cerr << "tsuke" << endl;
      int z = (((1 << N)-1)^x) & ((1 << N)-1); // all \setminus x
      int w = x - (1 << i); // x \setminus \{ i \}
      int y = z;
      do {
        dp[x | y][i] = min(dp[x | y][i],
                           dp[x][i] + setcost[w | y] - setcost[w] - setcost[y]);
        // cerr << "dp[" << two(x | y) << "][" << i << "] = " << dp[x | y][i] << endl;
        y = (y - 1) & z;
      } while (y != z);
    }
  }
  cout << dp[(1 << N)-1][N-1] << endl;
}
<|endoftext|>


<commit_before>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-2-25 21:06:35
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const int MAX_SIZE = 1000010;
const long long MOD = 998244353;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

void init() {
  inv[1] = 1;
  for (int i=2; i<MAX_SIZE; i++) {
    inv[i] = ((MOD - inv[MOD%i]) * (MOD/i))%MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i=1; i<MAX_SIZE; i++) {
    fact[i] = (i * fact[i-1])%MOD;
    factinv[i] = (inv[i] * factinv[i-1])%MOD;
  }
}

long long C(int n, int k) {
  if (n >=0 && k >= 0 && n-k >= 0) {
    return ((fact[n] * factinv[k])%MOD * factinv[n-k])%MOD;
  }
  return 0;
}

long long power(long long x, long long n) {
  if (n == 0) {
    return 1;
  } else if (n%2 == 1) {
    return (x * power(x, n-1)) % MOD;
  } else {
    long long half = power(x, n/2);
    return (half * half) % MOD;
  }
}

long long gcm(long long a, long long b) {
  if (a < b) {
    return gcm(b, a);
  }
  if (b == 0) return a;
  return gcm(b, a%b);
}

ll N, K;

ll catalan(ll T, ll X, ll Y)
{
  return (C((X + Y) % MOD, X) + MOD - C((X + Y) % MOD, (Y + MOD - T) % MOD)) % MOD;
}

int main() {
  init();
  cin >> N >> K;
  ll ans = 0;
  for (ll R = 0; R <= K; R++)
  {
    ll B = K - R;
    if (R < B)
      continue;
    else if (R == B)
    {
      ans += catalan(R - N + 1, R, B - 1);
      ans %= MOD;
    }
    else if (B - R < N)
    {
      ans += catalan(R - N + 1, R, B);
      ans %= MOD;
    }
    else
    {
      ans += C(R + B, R);
      ans %= MOD;
    }
  }
  cout << ans << endl;
}
<commit_msg>submit E.cpp to 'E - Ball Eat Chameleons' (agc021) [C++14 (Clang 3.8.0)]<commit_after>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-2-25 21:06:35
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const int MAX_SIZE = 1000010;
const long long MOD = 998244353;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

void init() {
  inv[1] = 1;
  for (int i=2; i<MAX_SIZE; i++) {
    inv[i] = ((MOD - inv[MOD%i]) * (MOD/i))%MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i=1; i<MAX_SIZE; i++) {
    fact[i] = (i * fact[i-1])%MOD;
    factinv[i] = (inv[i] * factinv[i-1])%MOD;
  }
}

long long C(int n, int k) {
  if (n >=0 && k >= 0 && n-k >= 0) {
    return ((fact[n] * factinv[k])%MOD * factinv[n-k])%MOD;
  }
  return 0;
}

long long power(long long x, long long n) {
  if (n == 0) {
    return 1;
  } else if (n%2 == 1) {
    return (x * power(x, n-1)) % MOD;
  } else {
    long long half = power(x, n/2);
    return (half * half) % MOD;
  }
}

long long gcm(long long a, long long b) {
  if (a < b) {
    return gcm(b, a);
  }
  if (b == 0) return a;
  return gcm(b, a%b);
}

ll N, K;

ll catalan(ll T, ll X, ll Y)
{
  return (C((X + Y) % MOD, X) + MOD - C((X + Y) % MOD, (Y + MOD - T) % MOD)) % MOD;
}

int main() {
  init();
  cin >> N >> K;
  if (N > K)
  {
    cout << 0 << endl;
    return 0;
  }
  ll ans = 0;
  for (ll R = 0; R <= K; R++)
  {
    ll B = K - R;
    if (R < B)
      continue;
    else if (R == B)
    {
      ans += catalan(R - N + 1, R, B - 1);
      ans %= MOD;
    }
    else if (B - R < N)
    {
      ans += catalan(R - N + 1, R, B);
      ans %= MOD;
    }
    else
    {
      ans += C(R + B, R);
      ans %= MOD;
    }
  }
  cout << ans << endl;
}
<|endoftext|>


<commit_before>/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-7-2 20:45:55
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd()); uniform_int_distribution<int> ra(0, 99); ra(mt);
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const ll MOD = 1000000007;
const ll M = 250010;
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<ll> ra(1, MOD - 1);
typedef tuple<ll, ll> D;

int N;
string S;
map<ll, int> ans;
ll X;
ll X_inv;
ll C;
ll a[500100];
D g[250010];
map<ll, ll> G;

ll power2(int i)
{
  if (i == 0)
  {
    return 1;
  }
  else if (i % 2 == 0)
  {
    ll half = power2(i / 2);
    return (half * half) % MOD;
  }
  else
  {
    return (power2(i - 1) * X) % MOD;
  }
}

ll power(int i)
{
  if (i == 0)
  {
    return 1;
  }
  else if (i < 0)
  {
    return power2(MOD + i - 1);
  }
  return power2(i);
}

ll calc_hash()
{
  fill(a, a + 500100, 0);
  int P = M;
  for (auto e : S)
  {
    if (e == '+')
    {
      a[P]++;
    }
    else if (e == '-')
    {
      a[P]--;
    }
    else if (e == '>')
    {
      P++;
    }
    else
    {
      P--;
    }
  }
  ll res = 0;
  for (auto i = 0; i < 500100; i++)
  {
    res += (((MOD + a[i]) % MOD) * power(i - M)) % MOD;
    res %= MOD;
  }
  return res;
}

void calc_g()
{
  g[N] = D(1, 0);
  for (auto i = N - 1; i >= 0; i--)
  {
    ll A_prime = get<0>(g[i + 1]);
    ll B_prime = get<1>(g[i + 1]);
    ll A, B;
    if (S[i] == '+')
    {
      A = 1, B = MOD - 1;
    }
    else if (S[i] == '-')
    {
      A = 1, B = 1;
    }
    else if (S[i] == '>')
    {
      A = X_inv, B = 0;
    }
    else
    {
      A = X, B = 0;
    }
    g[i] = D((A_prime * A) % MOD,
             ((A_prime * B) % MOD + B_prime) % MOD);
  }
}

ll count_ans()
{
  ll res = 0;
  G.clear();
  for (int i = N; i >= 1; i--)
  {
    ll J = get<1>(g[i]);
    if (G.find(J) == G.end())
    {
      G[J] = 1;
    }
    else
    {
      G[J]++;
    }
    ll I = ((get<0>(g[i - 1]) * C) % MOD + get<1>(g[i - 1])) % MOD;

    if (G.find(I) != G.end())
    {
      // cerr << "i = " << i - 1 << ", cnt of j = " << G[I] << endl;
      res += G[I];
    }
  }
  return res;
}

void solve()
{
  X = ra(mt);
  X_inv = power(-1);
  C = calc_hash();
  calc_g();
  ll res = count_ans();
  if (ans.find(res) == ans.end())
  {
    ans[res] = 1;
  }
  else
  {
    ans[res]++;
  }
}

int main()
{
  cin >> N >> S;
  for (auto i = 0; i < 4; i++)
  {
    solve();
  }
  ll res = 0;
  int maxi = 0;
  for (auto e : ans)
  {
    ll a = e.first;
    int cnt = e.second;
    if (cnt > maxi)
    {
      cnt = maxi;
      res = a;
    }
  }
  cout << res << endl;
}<commit_msg>tried F.cpp to 'F'<commit_after>/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-7-2 20:45:55
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = std::bind(std::uniform_int_distribution<int>(0, 9), std::mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const ll MOD = 1000000007;
const ll M = 250010;
auto rd = bind(uniform_int_distribution<ll>(1, MOD - 1),
               mt19937(19920725));
uniform_int_distribution<ll> ra(1, MOD - 1);
typedef tuple<ll, ll> D;

int N;
string S;
map<ll, int> ans;
ll X;
ll X_inv;
ll C;
ll a[500100];
D g[250010];
map<ll, ll> G;

ll power2(int i)
{
  if (i == 0)
  {
    return 1;
  }
  else if (i % 2 == 0)
  {
    ll half = power2(i / 2);
    return (half * half) % MOD;
  }
  else
  {
    return (power2(i - 1) * X) % MOD;
  }
}

ll power(int i)
{
  if (i == 0)
  {
    return 1;
  }
  else if (i < 0)
  {
    return power2(MOD + i - 1);
  }
  return power2(i);
}

ll calc_hash()
{
  fill(a, a + 500100, 0);
  int P = M;
  for (auto e : S)
  {
    if (e == '+')
    {
      a[P]++;
    }
    else if (e == '-')
    {
      a[P]--;
    }
    else if (e == '>')
    {
      P++;
    }
    else
    {
      P--;
    }
  }
  ll res = 0;
  for (auto i = 0; i < 500100; i++)
  {
    res += (((MOD + a[i]) % MOD) * power(i - M)) % MOD;
    res %= MOD;
  }
  return res;
}

void calc_g()
{
  g[N] = D(1, 0);
  for (auto i = N - 1; i >= 0; i--)
  {
    ll A_prime = get<0>(g[i + 1]);
    ll B_prime = get<1>(g[i + 1]);
    ll A, B;
    if (S[i] == '+')
    {
      A = 1, B = MOD - 1;
    }
    else if (S[i] == '-')
    {
      A = 1, B = 1;
    }
    else if (S[i] == '>')
    {
      A = X_inv, B = 0;
    }
    else
    {
      A = X, B = 0;
    }
    g[i] = D((A_prime * A) % MOD,
             ((A_prime * B) % MOD + B_prime) % MOD);
  }
}

ll count_ans()
{
  ll res = 0;
  G.clear();
  for (int i = N; i >= 1; i--)
  {
    ll J = get<1>(g[i]);
    if (G.find(J) == G.end())
    {
      G[J] = 1;
    }
    else
    {
      G[J]++;
    }
    ll I = ((get<0>(g[i - 1]) * C) % MOD + get<1>(g[i - 1])) % MOD;

    if (G.find(I) != G.end())
    {
      cerr << "i = " << i - 1 << ", cnt of j = " << G[I] << endl;
      res += G[I];
    }
  }
  return res;
}

void solve()
{
  X = rd();
  X_inv = power(-1);
  C = calc_hash();
  calc_g();
  ll res = count_ans();
  if (ans.find(res) == ans.end())
  {
    ans[res] = 1;
  }
  else
  {
    ans[res]++;
  }
}

int main()
{
  cin >> N >> S;
  for (auto i = 0; i < 4; i++)
  {
    solve();
  }
  ll res = 0;
  int maxi = 0;
  for (auto e : ans)
  {
    ll a = e.first;
    int cnt = e.second;
    if (cnt > maxi)
    {
      cnt = maxi;
      res = a;
    }
  }
  cerr << res << endl;
}<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtNetwork>

#include "client.h"
#include "connection.h"
#include "peermanager.h"

static const qint32 BroadcastInterval = 2000;
static const unsigned broadcastPort = 45000;

PeerManager::PeerManager(Client *client)
    : QObject(client)
{
    this->client = client;

    QStringList envVariables;
    envVariables << "USERNAME.*" << "USER.*" << "USERDOMAIN.*"
                 << "HOSTNAME.*" << "DOMAINNAME.*";

    QStringList environment = QProcess::systemEnvironment();
    foreach (QString string, envVariables) {
        int index = environment.indexOf(QRegExp(string));
        if (index != -1) {
            QStringList stringList = environment.at(index).split("=");
            if (stringList.size() == 2) {
                username = stringList.at(1).toUtf8();
                break;
            }
        }
    }

    if (username.isEmpty())
#ifndef Q_OS_SYMBIAN
        username = "unknown";
#else
        username = "QtS60";
#endif

    updateAddresses();
    serverPort = 0;

    broadcastSocket.bind(QHostAddress::Any, broadcastPort, QUdpSocket::ShareAddress
                         | QUdpSocket::ReuseAddressHint);
    connect(&broadcastSocket, SIGNAL(readyRead()),
            this, SLOT(readBroadcastDatagram()));

    broadcastTimer.setInterval(BroadcastInterval);
    connect(&broadcastTimer, SIGNAL(timeout()),
            this, SLOT(sendBroadcastDatagram()));
}

void PeerManager::setServerPort(int port)
{
    serverPort = port;
}

QByteArray PeerManager::userName() const
{
    return username;
}

void PeerManager::startBroadcasting()
{
    broadcastTimer.start();
}

bool PeerManager::isLocalHostAddress(const QHostAddress &address)
{
    foreach (QHostAddress localAddress, ipAddresses) {
        if (address == localAddress)
            return true;
    }
    return false;
}

void PeerManager::sendBroadcastDatagram()
{
    QByteArray datagram(username);
    datagram.append('@');
    datagram.append(QByteArray::number(serverPort));

    bool validBroadcastAddresses = true;
    foreach (QHostAddress address, broadcastAddresses) {
        if (broadcastSocket.writeDatagram(datagram, address,
                                          broadcastPort) == -1)
            validBroadcastAddresses = false;
    }

    if (!validBroadcastAddresses)
        updateAddresses();
}

void PeerManager::readBroadcastDatagram()
{
    while (broadcastSocket.hasPendingDatagrams()) {
        QHostAddress senderIp;
        quint16 senderPort;
        QByteArray datagram;
        datagram.resize(broadcastSocket.pendingDatagramSize());
        if (broadcastSocket.readDatagram(datagram.data(), datagram.size(),
                                         &senderIp, &senderPort) == -1)
            continue;

        QList<QByteArray> list = datagram.split('@');
        if (list.size() != 2)
            continue;

        int senderServerPort = list.at(1).toInt();
        if (isLocalHostAddress(senderIp) && senderServerPort == serverPort)
            continue;

        if (!client->hasConnection(senderIp)) {
            Connection *connection = new Connection(this);
            emit newConnection(connection);
            connection->connectToHost(senderIp, senderServerPort);
        }
    }
}

void PeerManager::updateAddresses()
{
    broadcastAddresses.clear();
    ipAddresses.clear();
    foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces()) {
        foreach (QNetworkAddressEntry entry, interface.addressEntries()) {
            QHostAddress broadcastAddress = entry.broadcast();
            if (broadcastAddress != QHostAddress::Null && entry.ip() != QHostAddress::LocalHost) {
                //printf("entry.ip: %s\n", entry.ip().toString().toLatin1().data());
                //printf("entry.netmask: %s\n", entry.netmask().toString().toLatin1().data());
                //printf("entry.prefixLength: %i\n", entry.prefixLength());
                //printf("entry.broadcast %s \n", broadcastAddress.toString().toLatin1().data());
                broadcastAddresses << broadcastAddress;
                ipAddresses << entry.ip();
            }
        }
    }
}
<commit_msg>Remove commented-out code from examples.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtNetwork>

#include "client.h"
#include "connection.h"
#include "peermanager.h"

static const qint32 BroadcastInterval = 2000;
static const unsigned broadcastPort = 45000;

PeerManager::PeerManager(Client *client)
    : QObject(client)
{
    this->client = client;

    QStringList envVariables;
    envVariables << "USERNAME.*" << "USER.*" << "USERDOMAIN.*"
                 << "HOSTNAME.*" << "DOMAINNAME.*";

    QStringList environment = QProcess::systemEnvironment();
    foreach (QString string, envVariables) {
        int index = environment.indexOf(QRegExp(string));
        if (index != -1) {
            QStringList stringList = environment.at(index).split("=");
            if (stringList.size() == 2) {
                username = stringList.at(1).toUtf8();
                break;
            }
        }
    }

    if (username.isEmpty())
#ifndef Q_OS_SYMBIAN
        username = "unknown";
#else
        username = "QtS60";
#endif

    updateAddresses();
    serverPort = 0;

    broadcastSocket.bind(QHostAddress::Any, broadcastPort, QUdpSocket::ShareAddress
                         | QUdpSocket::ReuseAddressHint);
    connect(&broadcastSocket, SIGNAL(readyRead()),
            this, SLOT(readBroadcastDatagram()));

    broadcastTimer.setInterval(BroadcastInterval);
    connect(&broadcastTimer, SIGNAL(timeout()),
            this, SLOT(sendBroadcastDatagram()));
}

void PeerManager::setServerPort(int port)
{
    serverPort = port;
}

QByteArray PeerManager::userName() const
{
    return username;
}

void PeerManager::startBroadcasting()
{
    broadcastTimer.start();
}

bool PeerManager::isLocalHostAddress(const QHostAddress &address)
{
    foreach (QHostAddress localAddress, ipAddresses) {
        if (address == localAddress)
            return true;
    }
    return false;
}

void PeerManager::sendBroadcastDatagram()
{
    QByteArray datagram(username);
    datagram.append('@');
    datagram.append(QByteArray::number(serverPort));

    bool validBroadcastAddresses = true;
    foreach (QHostAddress address, broadcastAddresses) {
        if (broadcastSocket.writeDatagram(datagram, address,
                                          broadcastPort) == -1)
            validBroadcastAddresses = false;
    }

    if (!validBroadcastAddresses)
        updateAddresses();
}

void PeerManager::readBroadcastDatagram()
{
    while (broadcastSocket.hasPendingDatagrams()) {
        QHostAddress senderIp;
        quint16 senderPort;
        QByteArray datagram;
        datagram.resize(broadcastSocket.pendingDatagramSize());
        if (broadcastSocket.readDatagram(datagram.data(), datagram.size(),
                                         &senderIp, &senderPort) == -1)
            continue;

        QList<QByteArray> list = datagram.split('@');
        if (list.size() != 2)
            continue;

        int senderServerPort = list.at(1).toInt();
        if (isLocalHostAddress(senderIp) && senderServerPort == serverPort)
            continue;

        if (!client->hasConnection(senderIp)) {
            Connection *connection = new Connection(this);
            emit newConnection(connection);
            connection->connectToHost(senderIp, senderServerPort);
        }
    }
}

void PeerManager::updateAddresses()
{
    broadcastAddresses.clear();
    ipAddresses.clear();
    foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces()) {
        foreach (QNetworkAddressEntry entry, interface.addressEntries()) {
            QHostAddress broadcastAddress = entry.broadcast();
            if (broadcastAddress != QHostAddress::Null && entry.ip() != QHostAddress::LocalHost) {
                broadcastAddresses << broadcastAddress;
                ipAddresses << entry.ip();
            }
        }
    }
}
<|endoftext|>


<commit_before>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-12-15 21:49:53
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

const int C = 10000;
// const ll M = 1000000007;

int N;
int A[200010];
int K[C];

bool solve(int X)
{
  fill(K, K + A[0], 0);
  for (auto i = 0; i < N - 1; i++)
  {
    if (A[i] > A[i + 1])
    {
      continue;
    }
    else
    {
      bool ok = false;
      for (auto j = A[i] - 1; j >= 0; j--)
      {
        K[j]++;
        if (K[j] == X)
        {
          K[j] = 0;
        }
        else
        {
          ok = true;
          break;
        }
      }
      if (!ok)
      {
        return false;
      }
      for (auto j = A[i]; j < A[i + 1]; j++)
      {
        K[j] = 0;
      }
    }
  }
  return true;
}

int main()
{
  cin >> N;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
    A[i] = min(C, A[i]);
  }
  reverse(A, A + N);
  int ub = N;
  int lb = 0;
  while (ub - lb > 1)
  {
    int t = (ub + lb) / 2;
    if (solve(t))
    {
      ub = t;
    }
    else
    {
      lb = t;
    }
  }
  cout << ub << endl;
}<commit_msg>submit C.cpp to 'C - Lexicographic constraints' (agc029) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-12-15 21:49:53
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

const int C = 100;
// const ll M = 1000000007;

int N;
int A[200010];
int K[C];

bool solve(int X)
{
  fill(K, K + A[0], 0);
  for (auto i = 0; i < N - 1; i++)
  {
    if (A[i] > A[i + 1])
    {
      continue;
    }
    else if (A[i] == C + 1)
    {
      continue;
    }
    else
    {
      bool ok = false;
      for (auto j = A[i] - 1; j >= 0; j--)
      {
        K[j]++;
        if (K[j] == X)
        {
          K[j] = 0;
        }
        else
        {
          ok = true;
          break;
        }
      }
      if (!ok)
      {
        return false;
      }
      for (auto j = A[i]; j < A[i + 1]; j++)
      {
        K[j] = 0;
      }
    }
  }
  return true;
}

int main()
{
  cin >> N;
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
    A[i] = min(C + 1, A[i]);
  }
  reverse(A, A + N);
  int ub = N;
  int lb = 0;
  while (ub - lb > 1)
  {
    int t = (ub + lb) / 2;
    if (solve(t))
    {
      ub = t;
    }
    else
    {
      lb = t;
    }
  }
  cout << ub << endl;
}<|endoftext|>