<commit_before>/*
 * Scanner.cpp
 *
 *  Created on: Mar 24, 2016
 *      Author: James Hong
 */

#include "scan/Scanner.h"

#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cassert>
#include <cstring>
#include <sstream>

#include "ble/helper.h"
#include "Debug.h"

#define EIR_NAME_SHORT		0x08
#define EIR_NAME_COMPLETE  	0x09

Scanner::Scanner() {
	/*
	 * Set these intervals high since we are filtering duplicates manually.
	 */
	scanInterval = 0x0100;	// TODO these should be configurable
	scanWindow = 0x0010;

	running.reset(new std::atomic_flag(true));
}

Scanner::~Scanner() {
	running->clear();
}

static void scanDaemon(std::shared_ptr<std::atomic_flag> terminated, std::vector<DiscoveryHandler> handlers,
		uint16_t scanInterval, uint16_t scanWindow);
void Scanner::start() {
	std::thread t = std::thread(&scanDaemon, running, handlers, scanInterval, scanWindow);
	t.detach();
}

void Scanner::registerHandler(DiscoveryHandler handler) {
	handlers.push_back(handler);
}

static struct hci_filter startScanHelper(int deviceHandle, uint16_t scanInterval, uint16_t scanWindow) {
	int result = hci_le_set_scan_parameters(deviceHandle,
			0,						// type (0 is passive)
			htobs(scanInterval),	// interval
			htobs(scanWindow), 		// window
			0, 						// own_type
			0, 						// filter
			1000);					// to (for timeout)
	if (result < 0) {
		pwarn("failed to set LE scan parameters");
	}

	result = hci_le_set_scan_enable(deviceHandle,
			0x01,		// enable
			0, 			// do not filter duplicates
			1000);		// to (see above)
	if (result < 0) {
		pwarn("failed to set scan enable");
	}

	struct hci_filter oldFilter = { 0 };
	socklen_t oldFilterLen = sizeof(oldFilter);
	result = getsockopt(deviceHandle, SOL_HCI, HCI_FILTER, &oldFilter, &oldFilterLen);
	if (result < 0) {
		throw ScannerException("failed to save old hci filter");
	}

	struct hci_filter newFilter;
	hci_filter_clear(&newFilter);
	hci_filter_set_ptype(HCI_EVENT_PKT, &newFilter);
	hci_filter_set_event(EVT_LE_META_EVENT, &newFilter);
	result = setsockopt(deviceHandle, SOL_HCI, HCI_FILTER, &newFilter, sizeof(newFilter));
	if (result < 0) {
		throw ScannerException("failed to set new hci filter");
	}

	return oldFilter;
}

//static void stopScanHelper(int deviceHandle, struct hci_filter oldFilter) {
//	int result = hci_le_set_scan_enable(deviceHandle,
//			0, 		// disable
//			1, 		// filter_dup
//			1000);	// to
//	if (result < 0) {
//		pwarn("failed to disable scan");
//	}
//
//	result = setsockopt(deviceHandle, SOL_HCI, HCI_FILTER, &oldFilter, sizeof(oldFilter));
//	if (result < 0) {
//		pwarn("failed to replace old hci filter");
//	}
//}

static int deviceHandle = -1;
//static struct hci_filter oldFilter;
static void scanDaemon(std::shared_ptr<std::atomic_flag> running, std::vector<DiscoveryHandler> handlers,
		uint16_t scanInterval, uint16_t scanWindow) {
	if (debug) {
		pdebug("scanDaemon started");
	}

	int deviceId = hci_get_route(NULL);
	if (deviceId < 0) {
		throw ScannerException("could not get hci device");
	}

	deviceHandle = hci_open_dev(deviceId);
	if (deviceHandle < 0) {
		throw ScannerException("could not get handle to hci device");
	}

 	startScanHelper(deviceHandle, scanInterval, scanWindow);
	std::atexit([]{
		if (deviceHandle >= 0) {
			if (debug_scan) {
				pdebug("stopping scan and closing device");
			}
//			stopScanHelper(deviceHandle, oldFilter);
			hci_close_dev(deviceHandle);
		}
	});

	uint8_t buf[HCI_MAX_EVENT_SIZE];
	while (running->test_and_set()) {
		int n = read(deviceHandle, buf, sizeof(buf));
		if (n <= 0) {
			break;
		} else if (n < (1 + HCI_EVENT_HDR_SIZE)) {
			if (debug_scan) {
				pwarn("read less than hci evt header");
			}
			continue;
		}

		evt_le_meta_event *meta = (evt_le_meta_event *) (buf + (1 + HCI_EVENT_HDR_SIZE));
		switch (meta->subevent) {
		case EVT_LE_ADVERTISING_REPORT: {
			le_advertising_info *info = (le_advertising_info *) (meta->data + 1);

			std::string addr = ba2str_cpp(info->bdaddr);
			LEPeripheral::AddrType addrType = (info->bdaddr_type == LE_PUBLIC_ADDRESS) ?
					LEPeripheral::AddrType::PUBLIC : LEPeripheral::AddrType::RANDOM;
			std::string name = "";
			int i = 0;
			while (i < info->length) {
				int len = info->data[i];
				if (info->data[i + 1] == EIR_NAME_SHORT || info->data[i + 1] == EIR_NAME_COMPLETE) {
					char name_c_str[len];
					name_c_str[len - 1] = '\0';
					memcpy(name_c_str, info->data + i + 2, len - 1);
					name = std::string(name_c_str);
				}
				i += len + 1;
			}

			if (debug_scan) {
				std::stringstream ss;
				ss << "advertisement for " << addr << "\t"
						<< ((addrType == LEPeripheral::AddrType::PUBLIC) ? "public" : "random") << "\t" << name;
				pdebug(ss.str());
			}

			for (auto &cb : handlers) {
				bool isRunning = running->test_and_set();
				if (isRunning) {
					/*
					 * TODO: not quite memory safe
					 */
					cb(addr, peripheral_info_t { name, info->bdaddr, addrType });
				} else {
					running->clear();
					break;
				}
			}
			break;
		}
		case EVT_LE_CONN_COMPLETE:	// start scanning again
			startScanHelper(deviceHandle, scanInterval, scanWindow);
			break;
		}
	}

	if (debug) {
		pdebug("scanDaemon exited");
	}
}
<commit_msg>Add comments to scanner.<commit_after>/*
 * Scanner.cpp
 *
 *  Created on: Mar 24, 2016
 *      Author: James Hong
 */

#include "scan/Scanner.h"

#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cassert>
#include <cstring>
#include <sstream>

#include "ble/helper.h"
#include "Debug.h"

#define EIR_NAME_SHORT		0x08
#define EIR_NAME_COMPLETE  	0x09

Scanner::Scanner() {
	/*
	 * Set these intervals high since we are filtering duplicates manually.
	 */
	scanInterval = 0x0100;	// TODO these should be configurable
	scanWindow = 0x0010;

	running.reset(new std::atomic_flag(true));
}

Scanner::~Scanner() {
	running->clear();

	/*
	 * Can't join daemon since shutdown(SHUR_RDWR) doesn't work on hci sockets. Have to destruct without waiting.
	 */
}

static void scanDaemon(std::shared_ptr<std::atomic_flag> terminated, std::vector<DiscoveryHandler> handlers,
		uint16_t scanInterval, uint16_t scanWindow);
void Scanner::start() {
	std::thread t = std::thread(&scanDaemon, running, handlers, scanInterval, scanWindow);
	t.detach();
}

void Scanner::registerHandler(DiscoveryHandler handler) {
	handlers.push_back(handler);
}

static struct hci_filter startScanHelper(int deviceHandle, uint16_t scanInterval, uint16_t scanWindow) {
	int result = hci_le_set_scan_parameters(deviceHandle,
			0,						// type (0 is passive)
			htobs(scanInterval),	// interval
			htobs(scanWindow), 		// window
			0, 						// own_type
			0, 						// filter
			1000);					// to (for timeout)
	if (result < 0) {
		pwarn("failed to set LE scan parameters");
	}

	result = hci_le_set_scan_enable(deviceHandle,
			0x01,		// enable
			0, 			// do not filter duplicates
			1000);		// to (see above)
	if (result < 0) {
		pwarn("failed to set scan enable");
	}

	struct hci_filter oldFilter = { 0 };
	socklen_t oldFilterLen = sizeof(oldFilter);
	result = getsockopt(deviceHandle, SOL_HCI, HCI_FILTER, &oldFilter, &oldFilterLen);
	if (result < 0) {
		throw ScannerException("failed to save old hci filter");
	}

	struct hci_filter newFilter;
	hci_filter_clear(&newFilter);
	hci_filter_set_ptype(HCI_EVENT_PKT, &newFilter);
	hci_filter_set_event(EVT_LE_META_EVENT, &newFilter);
	result = setsockopt(deviceHandle, SOL_HCI, HCI_FILTER, &newFilter, sizeof(newFilter));
	if (result < 0) {
		throw ScannerException("failed to set new hci filter");
	}

	return oldFilter;
}

//static void stopScanHelper(int deviceHandle, struct hci_filter oldFilter) {
//	int result = hci_le_set_scan_enable(deviceHandle,
//			0, 		// disable
//			1, 		// filter_dup
//			1000);	// to
//	if (result < 0) {
//		pwarn("failed to disable scan");
//	}
//
//	result = setsockopt(deviceHandle, SOL_HCI, HCI_FILTER, &oldFilter, sizeof(oldFilter));
//	if (result < 0) {
//		pwarn("failed to replace old hci filter");
//	}
//}

/*
 * TODO: this is a hack
 */
static int staticDeviceHandle = -1;
static void scanDaemon(std::shared_ptr<std::atomic_flag> running, std::vector<DiscoveryHandler> handlers,
		uint16_t scanInterval, uint16_t scanWindow) {
	if (debug) {
		pdebug("scanDaemon started");
	}

	int deviceId = hci_get_route(NULL);
	if (deviceId < 0) {
		throw ScannerException("could not get hci device");
	}

	int deviceHandle = hci_open_dev(deviceId);
	if (deviceHandle < 0) {
		throw ScannerException("could not get handle to hci device");
	} else {
		staticDeviceHandle = deviceHandle;
	}

 	startScanHelper(deviceHandle, scanInterval, scanWindow);
	std::atexit([]{
		if (staticDeviceHandle >= 0) {
			if (debug_scan) {
				pdebug("stopping scan and closing device");
			}
//			stopScanHelper(staticDeviceHandle, staticOldFilter);
			hci_close_dev(staticDeviceHandle);
		}
	});

	uint8_t buf[HCI_MAX_EVENT_SIZE];
	while (running->test_and_set()) {
		int n = read(deviceHandle, buf, sizeof(buf));
		if (n <= 0) {
			break;
		} else if (n < (1 + HCI_EVENT_HDR_SIZE)) {
			if (debug_scan) {
				pwarn("read less than hci evt header");
			}
			continue;
		}

		evt_le_meta_event *meta = (evt_le_meta_event *) (buf + (1 + HCI_EVENT_HDR_SIZE));
		switch (meta->subevent) {
		case EVT_LE_ADVERTISING_REPORT: {
			le_advertising_info *info = (le_advertising_info *) (meta->data + 1);

			std::string addr = ba2str_cpp(info->bdaddr);
			LEPeripheral::AddrType addrType = (info->bdaddr_type == LE_PUBLIC_ADDRESS) ?
					LEPeripheral::AddrType::PUBLIC : LEPeripheral::AddrType::RANDOM;
			std::string name = "";
			int i = 0;
			while (i < info->length) {
				int len = info->data[i];
				if (info->data[i + 1] == EIR_NAME_SHORT || info->data[i + 1] == EIR_NAME_COMPLETE) {
					char name_c_str[len];
					name_c_str[len - 1] = '\0';
					memcpy(name_c_str, info->data + i + 2, len - 1);
					name = std::string(name_c_str);
				}
				i += len + 1;
			}

			if (debug_scan) {
				std::stringstream ss;
				ss << "advertisement for " << addr << "\t"
						<< ((addrType == LEPeripheral::AddrType::PUBLIC) ? "public" : "random") << "\t" << name;
				pdebug(ss.str());
			}

			for (auto &cb : handlers) {
				bool isRunning = running->test_and_set();
				if (isRunning) {
					/*
					 * Not quite memory safe on exit
					 */
					cb(addr, peripheral_info_t { name, info->bdaddr, addrType });
				} else {
					running->clear();
					break;
				}
			}
			break;
		}
		case EVT_LE_CONN_COMPLETE:	// start scanning again
			startScanHelper(deviceHandle, scanInterval, scanWindow);
			break;
		}
	}

	if (debug) {
		pdebug("scanDaemon exited");
	}
}
<|endoftext|>


<commit_before>// Azimjon Pulatov U1710014
// Lab Assignment 2 & 3
// 9/27/2017

// SWAPPING MACHINE

#include <iostream>
#include <math.h>
using namespace std;
int main0() {
	int a, b;
	a = 5;
	b = 6;

	//swapping
	a = a + b;
	b = a - b;
	a = a - b;

	cout << "a is " << a << endl;
	cout << "b is " << b << endl;

	system("pause");
	return 0;
}

// MAX FINDER

int main1() {
	int a, b, c, max;
	cout << "Instert 3 integers to find out the greatest" << endl;
	cin >> a >> b >> c;

	max = (a > b) ? a : b;
	max = (max > c) ? max : c;

	cout << "Max is " << max << endl;

	system("pause");
	return 0;
}

// LEAP YEAR FINDER
int main2(){

	int year;
	cout << "GIMME THE YEAR TO TEST ITS LEAPITY";
	cin >> year;

	if (year % 4 == 0 && (year % 400 == 0 && year% 100 !=0 ))
	{
		cout << "Yeah, it's surely a leap year" << endl;
	}
	else
	{
		cout << "Sorry, It's not going to be a leap year" << endl;
	}

	system("pause");
	return 0;

}

// EVENODD MACHINE
int main3(){

	int num;
	cout << "GIMME THE NUMBER TO TEST ITS ODDNESS";
	cin >> num;

	if (num % 2 == 0)
	{
		cout << "Even!" << endl;
	}
	else
	{
		cout << "ODD!" << endl;
	}

	system("pause");
	return 0;

}

// TEMPERATURE CONVERTION
int main(){

	float temp, type, result;
	cout << "CHOOSE TYPE OF CONVERSION:\n1. CELCIUS to FAHRENHEIT \n2. FAHRENHEIT to CELCIUS " << endl;
	cin >> type;
	cout << "NOW, GIMME THE TEMPERATURE: ";
	cin >> temp;

	if (type == 1)
	{
		result = 1.8*temp + 32;
		cout << "RESULT: " << result << endl;
	}
	else if (type == 2)
	{
		result = (5 / 9)*temp - 32;
		cout << "RESULT: " << result << endl;
	}
	else {
		cout << "OK, THEN";
	}

	system("pause");
	return 0;

}

/*
// AREA AND CIRCUMFERENCE IF CIRCLE
int main(){
const float pi = 3.1415;

float radius, area, circumference;
cout << "Gimme the Radius: ";
cin >> radius;
circumference = 2 * radius*pi;
area = radius*radius*pi;
cout << "\nHere is the area: " << area << endl;
cout << "here is circumference: " << circumference << endl;

system("pause");
return 0;
}

//AREA of SCALANE TRIANLGE
int main(){
float side1, side2, side3, semiper, area;
cout << "Gimme the 3 sides of triangle: "<< endl;
cin >> side1>> side2 >> side3;
if (side1 + side2 > side3 && side1 + side3 > side2 && side3 + side2 > side1)
{
semiper = (side1 + side2 + side3) / 2;
area = sqrt(semiper*(semiper - side1)*(semiper - side3)*(semiper - side2));

cout << "\nArea is: " << area << endl;
}
else
{
cout << "Triangle does not exist";
}

system("pause");
return 0;

}

//AREA OF equterial triangle
int main(){
float area, side;
cout << "Gimme the side of equterial triangle: " << endl;
cin >> side;

if (side > 0)
{
area = (side*side*sqrt(3)) / 4;
cout << "Area of triangle is " << area << endl << endl;
}
else {
cout << "NaN";
}
system("pause");
return 0;
}

// AREA of right triangle
int main(){
float area, side1, side2;
cout << "Gimme the 2 sides of right triangle: " << endl;
cin >> side1 >> side2;

if (side1 > 0 && side2>0)
{
area = (side1*side2) / 2;
cout << "Area of triangle is " << area << endl << endl;
}
else {
cout << "NaN";
}

system("pause");
return 0;

}

//AREA OF CIRCLE

int main(){
const float pi = 3.1415;

float radius, area;
cout << "Gimme the Radius: ";
cin >> radius;

if (radius > 0)
{
area = radius*radius*pi;
cout << "\nHere is the area: " << area << endl;

} else {

cout << "Stop lying today";

}

system("pause");
return 0;
}

//AREA of RECTANGLE
int main(){
float area, side1, side2;
cout << "Gimme the 2 sides of rectangle: " << endl;
cin >> side1 >> side2;

if (side1 > 0 && side2>0)
{
area = (side1*side2);
cout << "Area of rectangle is " << area << endl << endl;
}
else {
cout << "Lying is sin";
}

system("pause");
return 0;

}

//AREA of SQUARE
int main(){
float area, side;
cout << "Gimme the side of square: " << endl;
cin >> side;

if (side > 0)
{
area = (side*side);
cout << "Area of square is " << area << endl << endl;
}
else {
cout << "Wow, You are a big lier";
}

system("pause");
return 0;

}
*/<commit_msg>Delete u1710014.cpp<commit_after><|endoftext|>


<commit_before> /*************************************************************************
 *
 *  $RCSfile: svgfontexport.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: ka $ $Date: 2002-08-05 13:40:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SVGFONTEXPORT_HXX
#define SVGFONTEXPORT_HXX

#include <comphelper/stl_types.hxx>
#include "svgfilter.hxx"
#include "svgwriter.hxx"

// -----------------
// - SVGFontExport -
// -----------------

class SVGFontExport
{
    typedef ::std::hash_map< ::rtl::OUString, ::std::set< sal_Unicode >, ::comphelper::UStringHash > GlyphMap;
    typedef ::std::vector< ObjectRepresentation > ObjectVector;

private:

    SvXMLExport&        mrExport;
    GlyphMap            maGlyphs;
    ObjectVector        maObjects;
    sal_uInt32          mnCurFontId;

    void                implCollectGlyphs();
    void                implEmbedFont( const ::rtl::OUString& rFontName, const ::std::set< sal_Unicode >& rGlyphs );
    void                implEmbedGlyph( OutputDevice& rOut, const ::rtl::OUString& rGlyphs );

public:

                        SVGFontExport( SvXMLExport& rExport, const ::std::vector< ObjectRepresentation >& rObjects );
                        ~SVGFontExport();

    void                EmbedFonts();
    ::rtl::OUString     GetMappedFontName( const ::rtl::OUString& rFontName ) const;
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.556); FILE MERGED 2005/09/05 14:31:10 rt 1.1.556.1: #i54170# Change license header: remove SISSL<commit_after> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svgfontexport.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:56:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SVGFONTEXPORT_HXX
#define SVGFONTEXPORT_HXX

#include <comphelper/stl_types.hxx>
#include "svgfilter.hxx"
#include "svgwriter.hxx"

// -----------------
// - SVGFontExport -
// -----------------

class SVGFontExport
{
    typedef ::std::hash_map< ::rtl::OUString, ::std::set< sal_Unicode >, ::comphelper::UStringHash > GlyphMap;
    typedef ::std::vector< ObjectRepresentation > ObjectVector;

private:

    SvXMLExport&        mrExport;
    GlyphMap            maGlyphs;
    ObjectVector        maObjects;
    sal_uInt32          mnCurFontId;

    void                implCollectGlyphs();
    void                implEmbedFont( const ::rtl::OUString& rFontName, const ::std::set< sal_Unicode >& rGlyphs );
    void                implEmbedGlyph( OutputDevice& rOut, const ::rtl::OUString& rGlyphs );

public:

                        SVGFontExport( SvXMLExport& rExport, const ::std::vector< ObjectRepresentation >& rObjects );
                        ~SVGFontExport();

    void                EmbedFonts();
    ::rtl::OUString     GetMappedFontName( const ::rtl::OUString& rFontName ) const;
};

#endif
<|endoftext|>


<commit_before>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-09-11 GONG Chen <chen.sst@gmail.com>
//
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/key_table.h>
#include <rime/menu.h>
#include <rime/schema.h>
#include <rime/gear/selector.h>

namespace rime {

Selector::Selector(const Ticket& ticket) : Processor(ticket) {
}

ProcessResult Selector::ProcessKeyEvent(const KeyEvent& key_event) {
  if (key_event.release())
    return kNoop;
  Context* ctx = engine_->context();
  if (!ctx->composition() || ctx->composition()->empty())
    return kNoop;
  Segment& current_segment(ctx->composition()->back());
  if (!current_segment.menu || current_segment.HasTag("raw"))
    return kNoop;
  int ch = key_event.keycode();
  if (ch == XK_Prior || ch == XK_KP_Prior) {
    PageUp(ctx);
    return kAccepted;
  }
  if (ch == XK_Next || ch == XK_KP_Next) {
    PageDown(ctx);
    return kAccepted;
  }
  if (ch == XK_Up || ch == XK_KP_Up) {
    CursorUp(ctx);
    return kAccepted;
  }
  if (ch == XK_Down || ch == XK_KP_Down) {
    CursorDown(ctx);
    return kAccepted;
  }
  if (ch == XK_Home || ch == XK_KP_Home) {
    if (Home(ctx))
      return kAccepted;
  }
  if (ch == XK_End || ch == XK_KP_End) {
    if (End(ctx))
      return kAccepted;
  }
  int index = -1;
  const std::string& select_keys(engine_->schema()->select_keys());
  if (!select_keys.empty()) {
    size_t pos = select_keys.find(ch);
    if (pos != std::string::npos) {
      index = static_cast<int>(pos);
    }
  }
  else if (ch >= XK_0 && ch <= XK_9)
    index = ((ch - XK_0) + 9) % 10;
  else if (ch >= XK_KP_0 && ch <= XK_KP_9)
    index = ((ch - XK_KP_0) + 9) % 10;
  if (index >= 0) {
    SelectCandidateAt(ctx, index);
    return kAccepted;
  }
  // not handled
  return kNoop;
}

bool Selector::PageUp(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty())
    return false;
  int page_size = engine_->schema()->page_size();
  int selected_index = comp->back().selected_index;
  int index = selected_index < page_size ? 0 : selected_index - page_size;
  comp->back().selected_index = index;
  comp->back().tags.insert("paging");
  return true;
}

bool Selector::PageDown(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty() || !comp->back().menu)
    return false;
  int page_size = engine_->schema()->page_size();
  int index = comp->back().selected_index + page_size;
  int page_start = (index / page_size) * page_size;
  int candidate_count = comp->back().menu->Prepare(page_start + page_size);
  if (candidate_count <= page_start)
    return false;
  if (index >= candidate_count)
    index = candidate_count - 1;
  comp->back().selected_index = index;
  comp->back().tags.insert("paging");
  return true;

}

bool Selector::CursorUp(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty())
    return false;
  int index = comp->back().selected_index;
  if (index <= 0)
    return false;
  comp->back().selected_index = index - 1;
  comp->back().tags.insert("paging");
  return true;
}

bool Selector::CursorDown(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty() || !comp->back().menu)
    return false;
  int index = comp->back().selected_index + 1;
  int candidate_count = comp->back().menu->Prepare(index + 1);
  if (candidate_count <= index)
    return false;
  comp->back().selected_index = index;
  comp->back().tags.insert("paging");
  return true;
}

bool Selector::Home(Context* ctx) {
  if (ctx->composition()->empty())
    return false;
  Segment& seg(ctx->composition()->back());
  if (seg.selected_index > 0) {
    seg.selected_index = 0;
    return true;
  }
  return false;
}

bool Selector::End(Context* ctx) {
  if (ctx->caret_pos() < ctx->input().length()) {
    // navigator should handle this
    return false;
  }
  // this is cool:
  return Home(ctx);
}

bool Selector::SelectCandidateAt(Context* ctx, int index) {
  Composition* comp = ctx->composition();
  if (comp->empty())
    return false;
  int page_size = engine_->schema()->page_size();
  if (index >= page_size)
    return false;
  int selected_index = comp->back().selected_index;
  int page_start = (selected_index / page_size) * page_size;
  return ctx->Select(page_start + index);
}

}  // namespace rime
<commit_msg>selector: fix user defined select keys (XK_Right conflicts with 'S' in Squirrel).<commit_after>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-09-11 GONG Chen <chen.sst@gmail.com>
//
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/key_table.h>
#include <rime/menu.h>
#include <rime/schema.h>
#include <rime/gear/selector.h>

namespace rime {

Selector::Selector(const Ticket& ticket) : Processor(ticket) {
}

ProcessResult Selector::ProcessKeyEvent(const KeyEvent& key_event) {
  if (key_event.release() || key_event.alt())
    return kNoop;
  Context* ctx = engine_->context();
  if (!ctx->composition() || ctx->composition()->empty())
    return kNoop;
  Segment& current_segment(ctx->composition()->back());
  if (!current_segment.menu || current_segment.HasTag("raw"))
    return kNoop;
  int ch = key_event.keycode();
  if (ch == XK_Prior || ch == XK_KP_Prior) {
    PageUp(ctx);
    return kAccepted;
  }
  if (ch == XK_Next || ch == XK_KP_Next) {
    PageDown(ctx);
    return kAccepted;
  }
  if (ch == XK_Up || ch == XK_KP_Up) {
    CursorUp(ctx);
    return kAccepted;
  }
  if (ch == XK_Down || ch == XK_KP_Down) {
    CursorDown(ctx);
    return kAccepted;
  }
  if (ch == XK_Home || ch == XK_KP_Home) {
    if (Home(ctx))
      return kAccepted;
  }
  if (ch == XK_End || ch == XK_KP_End) {
    if (End(ctx))
      return kAccepted;
  }
  int index = -1;
  const std::string& select_keys(engine_->schema()->select_keys());
  if (!select_keys.empty() &&
      !key_event.ctrl() &&
      ch >= 0x20 && ch < 0x7f) {
    size_t pos = select_keys.find((char)ch);
    if (pos != std::string::npos) {
      index = static_cast<int>(pos);
    }
  }
  else if (ch >= XK_0 && ch <= XK_9)
    index = ((ch - XK_0) + 9) % 10;
  else if (ch >= XK_KP_0 && ch <= XK_KP_9)
    index = ((ch - XK_KP_0) + 9) % 10;
  if (index >= 0) {
    SelectCandidateAt(ctx, index);
    return kAccepted;
  }
  // not handled
  return kNoop;
}

bool Selector::PageUp(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty())
    return false;
  int page_size = engine_->schema()->page_size();
  int selected_index = comp->back().selected_index;
  int index = selected_index < page_size ? 0 : selected_index - page_size;
  comp->back().selected_index = index;
  comp->back().tags.insert("paging");
  return true;
}

bool Selector::PageDown(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty() || !comp->back().menu)
    return false;
  int page_size = engine_->schema()->page_size();
  int index = comp->back().selected_index + page_size;
  int page_start = (index / page_size) * page_size;
  int candidate_count = comp->back().menu->Prepare(page_start + page_size);
  if (candidate_count <= page_start)
    return false;
  if (index >= candidate_count)
    index = candidate_count - 1;
  comp->back().selected_index = index;
  comp->back().tags.insert("paging");
  return true;

}

bool Selector::CursorUp(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty())
    return false;
  int index = comp->back().selected_index;
  if (index <= 0)
    return false;
  comp->back().selected_index = index - 1;
  comp->back().tags.insert("paging");
  return true;
}

bool Selector::CursorDown(Context* ctx) {
  Composition* comp = ctx->composition();
  if (comp->empty() || !comp->back().menu)
    return false;
  int index = comp->back().selected_index + 1;
  int candidate_count = comp->back().menu->Prepare(index + 1);
  if (candidate_count <= index)
    return false;
  comp->back().selected_index = index;
  comp->back().tags.insert("paging");
  return true;
}

bool Selector::Home(Context* ctx) {
  if (ctx->composition()->empty())
    return false;
  Segment& seg(ctx->composition()->back());
  if (seg.selected_index > 0) {
    seg.selected_index = 0;
    return true;
  }
  return false;
}

bool Selector::End(Context* ctx) {
  if (ctx->caret_pos() < ctx->input().length()) {
    // navigator should handle this
    return false;
  }
  // this is cool:
  return Home(ctx);
}

bool Selector::SelectCandidateAt(Context* ctx, int index) {
  Composition* comp = ctx->composition();
  if (comp->empty())
    return false;
  int page_size = engine_->schema()->page_size();
  if (index >= page_size)
    return false;
  int selected_index = comp->back().selected_index;
  int page_start = (selected_index / page_size) * page_size;
  return ctx->Select(page_start + index);
}

}  // namespace rime
<|endoftext|>


<commit_before>#if defined(_DEBUG) || defined(DEBUG)

#include "debug.h"

FILE* Log::handle;
int Log::indent_count;

////////////////////////////////////////////////////////////////////////////////

void
Log::Write(const char* str)
{
  EnsureOpen();
  if (handle) {
    std::string s;
    for (int i = 0; i < indent_count; ++i) {
      s += "  ";
    }
    s += str;
    s += "\n";
    fwrite(s.c_str(), 1, s.length(), handle);
    fflush(handle);
  }
}

////////////////////////////////////////////////////////////////////////////////

void
Log::EnsureOpen()
{
  if (!handle) {

    #ifdef WIN32
      handle = fopen("C:/audiere_debug.log", "w");
    #else
      std::string home(getenv("HOME"));
      handle = fopen((home + "/audiere_debug.log").c_str(), "w");
    #endif

    atexit(Close);
  }
}

////////////////////////////////////////////////////////////////////////////////

void
Log::Close()
{
  fclose(handle);
}

////////////////////////////////////////////////////////////////////////////////

#endif
<commit_msg>fixing mild retardation on my part<commit_after>#if defined(_DEBUG) || defined(DEBUG)

#include "debug.h"

FILE* Log::handle;
int Log::indent_count;

////////////////////////////////////////////////////////////////////////////////

void
Log::Write(const char* str)
{
  EnsureOpen();
  if (handle) {
    std::string s(indent_count * 2, ' ');
    s += "\n";
    fwrite(s.c_str(), 1, s.length(), handle);
    fflush(handle);
  }
}

////////////////////////////////////////////////////////////////////////////////

void
Log::EnsureOpen()
{
  if (!handle) {

    #ifdef WIN32
      handle = fopen("C:/audiere_debug.log", "w");
    #else
      std::string home(getenv("HOME"));
      handle = fopen((home + "/audiere_debug.log").c_str(), "w");
    #endif

    atexit(Close);
  }
}

////////////////////////////////////////////////////////////////////////////////

void
Log::Close()
{
  fclose(handle);
}

////////////////////////////////////////////////////////////////////////////////

#endif
<|endoftext|>


<commit_before><commit_msg>No need to remove prev stack items<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: transliteration_OneToOne.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2003-04-28 16:54:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// prevent internal compiler error with MSVC6SP3
#include <utility>

#include <transliteration_OneToOne.hxx>

using namespace com::sun::star::uno;
using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

sal_Int16 SAL_CALL transliteration_OneToOne::getType() throw(RuntimeException)
{
        // This type is also defined in com/sun/star/util/TransliterationType.hdl
        return TransliterationType::ONE_TO_ONE;
}

OUString SAL_CALL
transliteration_OneToOne::folding( const OUString& inStr, sal_Int32 startPos,
        sal_Int32 nCount, Sequence< sal_Int32 >& offset) throw(RuntimeException)
{
        throw RuntimeException();
}

sal_Bool SAL_CALL
transliteration_OneToOne::equals( const OUString& str1, sal_Int32 pos1, sal_Int32 nCount1,
        sal_Int32& nMatch1, const OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 )
        throw(RuntimeException)
{
    throw RuntimeException();
}

Sequence< OUString > SAL_CALL
transliteration_OneToOne::transliterateRange( const OUString& str1, const OUString& str2 )
        throw(RuntimeException)
{
    throw RuntimeException();
}

OUString SAL_CALL
transliteration_OneToOne::transliterate( const OUString& inStr, sal_Int32 startPos,
    sal_Int32 nCount, Sequence< sal_Int32 >& offset)
    throw(RuntimeException)
{
    // Create a string buffer which can hold nCount + 1 characters.
    // The reference count is 0 now.
    rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h
    sal_Unicode * dst = newStr->buffer;
    const sal_Unicode * src = inStr.getStr() + startPos;

    // Allocate nCount length to offset argument.
    sal_Int32 *p, position;
    if (useOffset) {
        offset.realloc( nCount );
        p = offset.getArray();
        position = startPos;
    }

    // Translation
    while (nCount -- > 0) {
    sal_Unicode c = *src++;
    *dst ++ = func ? func( c) : (*table)[ c ];
    if (useOffset)
        *p ++ = position ++;
    }
    *dst = (sal_Unicode) 0;

    return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1.
}

sal_Unicode SAL_CALL
transliteration_OneToOne::transliterateChar2Char( sal_Unicode inChar) throw(RuntimeException, MultipleCharsOutputException)
{
    return func ? func( inChar) : (*table)[ inChar ];
}

} } } }

<commit_msg>INTEGRATION: CWS ooo20040704 (1.7.116); FILE MERGED 2004/06/30 13:10:57 waratah 1.7.116.1: #i30874# Add initial values to potentially uninitialised values<commit_after>/*************************************************************************
 *
 *  $RCSfile: transliteration_OneToOne.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-08 16:46:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

// prevent internal compiler error with MSVC6SP3
#include <utility>

#include <transliteration_OneToOne.hxx>

using namespace com::sun::star::uno;
using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

sal_Int16 SAL_CALL transliteration_OneToOne::getType() throw(RuntimeException)
{
        // This type is also defined in com/sun/star/util/TransliterationType.hdl
        return TransliterationType::ONE_TO_ONE;
}

OUString SAL_CALL
transliteration_OneToOne::folding( const OUString& inStr, sal_Int32 startPos,
        sal_Int32 nCount, Sequence< sal_Int32 >& offset) throw(RuntimeException)
{
        throw RuntimeException();
}

sal_Bool SAL_CALL
transliteration_OneToOne::equals( const OUString& str1, sal_Int32 pos1, sal_Int32 nCount1,
        sal_Int32& nMatch1, const OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 )
        throw(RuntimeException)
{
    throw RuntimeException();
}

Sequence< OUString > SAL_CALL
transliteration_OneToOne::transliterateRange( const OUString& str1, const OUString& str2 )
        throw(RuntimeException)
{
    throw RuntimeException();
}

OUString SAL_CALL
transliteration_OneToOne::transliterate( const OUString& inStr, sal_Int32 startPos,
    sal_Int32 nCount, Sequence< sal_Int32 >& offset)
    throw(RuntimeException)
{
    // Create a string buffer which can hold nCount + 1 characters.
    // The reference count is 0 now.
    rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h
    sal_Unicode * dst = newStr->buffer;
    const sal_Unicode * src = inStr.getStr() + startPos;

    // Allocate nCount length to offset argument.
    sal_Int32 *p = 0;
    sal_Int32 position = 0;
    if (useOffset) {
        offset.realloc( nCount );
        p = offset.getArray();
        position = startPos;
    }

    // Translation
    while (nCount -- > 0) {
    sal_Unicode c = *src++;
    *dst ++ = func ? func( c) : (*table)[ c ];
    if (useOffset)
        *p ++ = position ++;
    }
    *dst = (sal_Unicode) 0;

    return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1.
}

sal_Unicode SAL_CALL
transliteration_OneToOne::transliterateChar2Char( sal_Unicode inChar) throw(RuntimeException, MultipleCharsOutputException)
{
    return func ? func( inChar) : (*table)[ inChar ];
}

} } } }

<|endoftext|>


<commit_before>#ifndef CUKE_WIRESERVER_HPP_
#define CUKE_WIRESERVER_HPP_

#include "ProtocolHandler.hpp"

#include <string>

#include <boost/asio.hpp>

namespace cucumber {
namespace internal {

/**
 * Socket server that calls a protocol handler line by line
 */
class SocketServer {
public:
    /**
      * Constructor for DI
      */
    SocketServer(const ProtocolHandler *protocolHandler);

    /**
     * Accept one connection
     */
    virtual void acceptOnce() = 0;

protected:
    const ProtocolHandler *protocolHandler;
    boost::asio::io_service ios;

    template <typename Protocol, typename Service>
    void doListen(boost::asio::basic_socket_acceptor<Protocol, Service>& acceptor,
            const typename Protocol::endpoint& endpoint);
    template <typename Protocol, typename Service>
    void doAcceptOnce(boost::asio::basic_socket_acceptor<Protocol, Service>& acceptor);
    void processStream(std::iostream &stream);
};

/**
 * Socket server that calls a protocol handler line by line
 */
class TCPSocketServer : public SocketServer {
public:
    /**
     * Type definition for TCP port
     */
    typedef unsigned short port_type;

    /**
      * Constructor for DI
      */
    TCPSocketServer(const ProtocolHandler *protocolHandler);

    /**
     * Bind and listen to a TCP port
     */
    void listen(const port_type port);

    /**
     * Bind and listen to a TCP port on the given endpoint
     */
    void listen(const boost::asio::ip::tcp::endpoint endpoint);

    /**
     * Endpoint (IP address and port number) that this server is currently
     * listening on.
     *
     * @throw boost::system::system_error when not listening on any socket or
     *        the endpoint cannot be determined.
     */
    boost::asio::ip::tcp::endpoint listenEndpoint() const;

    virtual void acceptOnce();

private:
    boost::asio::ip::tcp::acceptor acceptor;
};

#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
/**
 * Socket server that calls a protocol handler line by line
 */
class UnixSocketServer : public SocketServer {
public:
    /**
      * Constructor for DI
      */
    UnixSocketServer(const ProtocolHandler *protocolHandler);

    /**
     * Bind and listen on a local stream socket
     */
    void listen(const std::string& unixPath);

    /**
     * Port number that this server is currently listening on.
     *
     * @throw boost::system::system_error when not listening on any socket or
     *        the endpoint cannot be determined.
     */
    boost::asio::local::stream_protocol::endpoint listenEndpoint() const;

    virtual void acceptOnce();

    ~UnixSocketServer();

private:
    boost::asio::local::stream_protocol::acceptor acceptor;
};
#endif

}
}

#endif /* CUKE_WIRESERVER_HPP_ */
<commit_msg>add missing virtual destructor in base class SocketServer used by TCPSocketServer<commit_after>#ifndef CUKE_WIRESERVER_HPP_
#define CUKE_WIRESERVER_HPP_

#include "ProtocolHandler.hpp"

#include <string>

#include <boost/asio.hpp>

namespace cucumber {
namespace internal {

/**
 * Socket server that calls a protocol handler line by line
 */
class SocketServer {
public:
    /**
      * Constructor for DI
      */
    SocketServer(const ProtocolHandler *protocolHandler);
    virtual ~SocketServer() {}

    /**
     * Accept one connection
     */
    virtual void acceptOnce() = 0;

protected:
    const ProtocolHandler *protocolHandler;
    boost::asio::io_service ios;

    template <typename Protocol, typename Service>
    void doListen(boost::asio::basic_socket_acceptor<Protocol, Service>& acceptor,
            const typename Protocol::endpoint& endpoint);
    template <typename Protocol, typename Service>
    void doAcceptOnce(boost::asio::basic_socket_acceptor<Protocol, Service>& acceptor);
    void processStream(std::iostream &stream);
};

/**
 * Socket server that calls a protocol handler line by line
 */
class TCPSocketServer : public SocketServer {
public:
    /**
     * Type definition for TCP port
     */
    typedef unsigned short port_type;

    /**
      * Constructor for DI
      */
    TCPSocketServer(const ProtocolHandler *protocolHandler);

    /**
     * Bind and listen to a TCP port
     */
    void listen(const port_type port);

    /**
     * Bind and listen to a TCP port on the given endpoint
     */
    void listen(const boost::asio::ip::tcp::endpoint endpoint);

    /**
     * Endpoint (IP address and port number) that this server is currently
     * listening on.
     *
     * @throw boost::system::system_error when not listening on any socket or
     *        the endpoint cannot be determined.
     */
    boost::asio::ip::tcp::endpoint listenEndpoint() const;

    virtual void acceptOnce();

private:
    boost::asio::ip::tcp::acceptor acceptor;
};

#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
/**
 * Socket server that calls a protocol handler line by line
 */
class UnixSocketServer : public SocketServer {
public:
    /**
      * Constructor for DI
      */
    UnixSocketServer(const ProtocolHandler *protocolHandler);

    /**
     * Bind and listen on a local stream socket
     */
    void listen(const std::string& unixPath);

    /**
     * Port number that this server is currently listening on.
     *
     * @throw boost::system::system_error when not listening on any socket or
     *        the endpoint cannot be determined.
     */
    boost::asio::local::stream_protocol::endpoint listenEndpoint() const;

    virtual void acceptOnce();

    ~UnixSocketServer();

private:
    boost::asio::local::stream_protocol::acceptor acceptor;
};
#endif

}
}

#endif /* CUKE_WIRESERVER_HPP_ */
<|endoftext|>


<commit_before>#include "emacs.h"

namespace ledger {

void format_emacs_transactions::write_entry(entry_t& entry)
{
  out << (((unsigned long)entry.beg_pos) + 1) << " ";

  out << (entry.state == entry_t::CLEARED ? "t" : "nil") << " ";

  out << "(" << (entry.date / 65536) << " "
      << (entry.date % 65536) << " 0) ";

  if (entry.code.empty())
    out << "nil ";
  else
    out << "\"" << entry.code << "\" ";

  if (entry.payee.empty())
    out << "nil";
  else
    out << "\"" << entry.payee << "\"";

  out << "\n";
}

void format_emacs_transactions::operator()(transaction_t& xact)
{
  if (! transaction_has_xdata(xact) ||
      ! (transaction_xdata_(xact).dflags & TRANSACTION_DISPLAYED)) {
    if (! last_entry) {
      out << "((";
      write_entry(*xact.entry);
    }
    else if (xact.entry != last_entry) {
      out << ")\n (";
      write_entry(*xact.entry);
    }
    else {
      out << "\n";
    }

    out << "  (\"" << xact.account->fullname() << "\" \""
	<< xact.amount << "\"";
    if (xact.cost)
      out << " \"" << *xact.cost << "\"";
    else if (! xact.note.empty())
      out << " nil";
    if (! xact.note.empty())
      out << " \"" << xact.note << "\"";
    out << ")";

    last_entry = xact.entry;

    transaction_xdata(xact).dflags |= TRANSACTION_DISPLAYED;
  }
}

} // namespace ledger

#ifdef USE_BOOST_PYTHON

#include <boost/python.hpp>

using namespace boost::python;
using namespace ledger;

void export_emacs()
{
  typedef
    pystream_handler_wrap<format_emacs_transactions, transaction_t>
    format_emacs_transactions_wrap;

  class_< format_emacs_transactions_wrap, bases<item_handler<transaction_t> > >
    ("FormatEmacsTransactions",
     init<PyObject *>()[with_custodian_and_ward<1, 2>()])
    .def("flush", &format_emacs_transactions_wrap::flush)
    .def("__call__", &format_emacs_transactions_wrap::operator())
    ;
}

#endif // USE_BOOST_PYTHON
<commit_msg>(write_entry): If an entry is marked pending, output the `pending' symbol in the Emacs output.<commit_after>#include "emacs.h"

namespace ledger {

void format_emacs_transactions::write_entry(entry_t& entry)
{
  out << (((unsigned long)entry.beg_pos) + 1) << " ";

  switch (entry.state) {
  case entry_t::CLEARED:
    out << "t ";
    break;
  case entry_t::PENDING:
    out << "pending ";
    break;
  case entry_t::UNCLEARED:
    out << "nil ";
    break;
  }

  out << "(" << (entry.date / 65536) << " "
      << (entry.date % 65536) << " 0) ";

  if (entry.code.empty())
    out << "nil ";
  else
    out << "\"" << entry.code << "\" ";

  if (entry.payee.empty())
    out << "nil";
  else
    out << "\"" << entry.payee << "\"";

  out << "\n";
}

void format_emacs_transactions::operator()(transaction_t& xact)
{
  if (! transaction_has_xdata(xact) ||
      ! (transaction_xdata_(xact).dflags & TRANSACTION_DISPLAYED)) {
    if (! last_entry) {
      out << "((";
      write_entry(*xact.entry);
    }
    else if (xact.entry != last_entry) {
      out << ")\n (";
      write_entry(*xact.entry);
    }
    else {
      out << "\n";
    }

    out << "  (\"" << xact.account->fullname() << "\" \""
	<< xact.amount << "\"";
    if (xact.cost)
      out << " \"" << *xact.cost << "\"";
    else if (! xact.note.empty())
      out << " nil";
    if (! xact.note.empty())
      out << " \"" << xact.note << "\"";
    out << ")";

    last_entry = xact.entry;

    transaction_xdata(xact).dflags |= TRANSACTION_DISPLAYED;
  }
}

} // namespace ledger

#ifdef USE_BOOST_PYTHON

#include <boost/python.hpp>

using namespace boost::python;
using namespace ledger;

void export_emacs()
{
  typedef
    pystream_handler_wrap<format_emacs_transactions, transaction_t>
    format_emacs_transactions_wrap;

  class_< format_emacs_transactions_wrap, bases<item_handler<transaction_t> > >
    ("FormatEmacsTransactions",
     init<PyObject *>()[with_custodian_and_ward<1, 2>()])
    .def("flush", &format_emacs_transactions_wrap::flush)
    .def("__call__", &format_emacs_transactions_wrap::operator())
    ;
}

#endif // USE_BOOST_PYTHON
<|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 "precomp.hpp"

using namespace cv;

Ptr<Feature2D> Feature2D::create( const String& feature2DType )
{
    return Algorithm::create<Feature2D>("Feature2D." + feature2DType);
}

/////////////////////// AlgorithmInfo for various detector & descriptors ////////////////////////////

/* NOTE!!!
   All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d().
   Otherwise, linker may throw away some seemingly unused stuff.
*/

CV_INIT_ALGORITHM(BRISK, "Feature2D.BRISK",
                   obj.info()->addParam(obj, "thres", obj.threshold);
                   obj.info()->addParam(obj, "octaves", obj.octaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF",
                  obj.info()->addParam(obj, "bytes", obj.bytes_));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST",
                  obj.info()->addParam(obj, "threshold", obj.threshold);
                  obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
                  obj.info()->addParam(obj, "type", obj.type));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR",
                  obj.info()->addParam(obj, "maxSize", obj.maxSize);
                  obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold);
                  obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
                  obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
                  obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(MSER, "Feature2D.MSER",
                  obj.info()->addParam(obj, "delta", obj.delta);
                  obj.info()->addParam(obj, "minArea", obj.minArea);
                  obj.info()->addParam(obj, "maxArea", obj.maxArea);
                  obj.info()->addParam(obj, "maxVariation", obj.maxVariation);
                  obj.info()->addParam(obj, "minDiversity", obj.minDiversity);
                  obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution);
                  obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold);
                  obj.info()->addParam(obj, "minMargin", obj.minMargin);
                  obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(ORB, "Feature2D.ORB",
                  obj.info()->addParam(obj, "nFeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor);
                  obj.info()->addParam(obj, "nLevels", obj.nlevels);
                  obj.info()->addParam(obj, "firstLevel", obj.firstLevel);
                  obj.info()->addParam(obj, "edgeThreshold", obj.edgeThreshold);
                  obj.info()->addParam(obj, "patchSize", obj.patchSize);
                  obj.info()->addParam(obj, "WTA_K", obj.WTA_K);
                  obj.info()->addParam(obj, "scoreType", obj.scoreType));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FREAK, "Feature2D.FREAK",
                  obj.info()->addParam(obj, "orientationNormalized", obj.orientationNormalized);
                  obj.info()->addParam(obj, "scaleNormalized", obj.scaleNormalized);
                  obj.info()->addParam(obj, "patternScale", obj.patternScale);
                  obj.info()->addParam(obj, "nbOctave", obj.nOctaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(GFTTDetector, "Feature2D.GFTT",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(SimpleBlobDetector, "Feature2D.SimpleBlob",
                  obj.info()->addParam(obj, "thresholdStep",    obj.params.thresholdStep);
                  obj.info()->addParam(obj, "minThreshold",     obj.params.minThreshold);
                  obj.info()->addParam(obj, "maxThreshold",     obj.params.maxThreshold);
                  obj.info()->addParam_(obj, "minRepeatability", (sizeof(size_t) == sizeof(uint64))?Param::UINT64 : Param::UNSIGNED_INT, &obj.params.minRepeatability, false, 0, 0);
                  obj.info()->addParam(obj, "minDistBetweenBlobs", obj.params.minDistBetweenBlobs);
                  obj.info()->addParam(obj, "filterByColor",    obj.params.filterByColor);
                  obj.info()->addParam(obj, "blobColor",        obj.params.blobColor);
                  obj.info()->addParam(obj, "filterByArea",     obj.params.filterByArea);
                  obj.info()->addParam(obj, "maxArea",          obj.params.maxArea);
                  obj.info()->addParam(obj, "filterByCircularity", obj.params.filterByCircularity);
                  obj.info()->addParam(obj, "maxCircularity",   obj.params.maxCircularity);
                  obj.info()->addParam(obj, "filterByInertia",  obj.params.filterByInertia);
                  obj.info()->addParam(obj, "maxInertiaRatio",  obj.params.maxInertiaRatio);
                  obj.info()->addParam(obj, "filterByConvexity", obj.params.filterByConvexity);
                  obj.info()->addParam(obj, "maxConvexity",     obj.params.maxConvexity);
                  );

///////////////////////////////////////////////////////////////////////////////////////////////////////////

class CV_EXPORTS HarrisDetector : public GFTTDetector
{
public:
    HarrisDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
                    int blockSize=3, bool useHarrisDetector=true, double k=0.04 );
    AlgorithmInfo* info() const;
};

inline HarrisDetector::HarrisDetector( int _maxCorners, double _qualityLevel, double _minDistance,
                    int _blockSize, bool _useHarrisDetector, double _k )
    : GFTTDetector( _maxCorners, _qualityLevel, _minDistance, _blockSize, _useHarrisDetector, _k ) {}

CV_INIT_ALGORITHM(HarrisDetector, "Feature2D.HARRIS",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense",
                  obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale);
                  obj.info()->addParam(obj, "featureScaleLevels", obj.featureScaleLevels);
                  obj.info()->addParam(obj, "featureScaleMul", obj.featureScaleMul);
                  obj.info()->addParam(obj, "initXyStep", obj.initXyStep);
                  obj.info()->addParam(obj, "initImgBound", obj.initImgBound);
                  obj.info()->addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale);
                  obj.info()->addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale));

CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid",
                  obj.info()->addParam<FeatureDetector>(obj, "detector", obj.detector, false, 0, 0, "Detector algorithm.");
                  obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints);
                  obj.info()->addParam(obj, "gridRows", obj.gridRows);
                  obj.info()->addParam(obj, "gridCols", obj.gridCols));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BFMatcher, "DescriptorMatcher.BFMatcher",
                  obj.info()->addParam(obj, "normType", obj.normType);
                  obj.info()->addParam(obj, "crossCheck", obj.crossCheck));

CV_INIT_ALGORITHM(FlannBasedMatcher, "DescriptorMatcher.FlannBasedMatcher",);

///////////////////////////////////////////////////////////////////////////////////////////////////////////

bool cv::initModule_features2d(void)
{
    bool all = true;
    all &= !BriefDescriptorExtractor_info_auto.name().empty();
    all &= !BRISK_info_auto.name().empty();
    all &= !FastFeatureDetector_info_auto.name().empty();
    all &= !StarDetector_info_auto.name().empty();
    all &= !MSER_info_auto.name().empty();
    all &= !FREAK_info_auto.name().empty();
    all &= !ORB_info_auto.name().empty();
    all &= !GFTTDetector_info_auto.name().empty();
    all &= !HarrisDetector_info_auto.name().empty();
    all &= !DenseFeatureDetector_info_auto.name().empty();
    all &= !GridAdaptedFeatureDetector_info_auto.name().empty();
    all &= !BFMatcher_info_auto.name().empty();
    all &= !FlannBasedMatcher_info_auto.name().empty();

    return all;
}
<commit_msg>Added comment to features2d_init.cpp explaining the reason for the extra parameters.<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 "precomp.hpp"

using namespace cv;

Ptr<Feature2D> Feature2D::create( const String& feature2DType )
{
    return Algorithm::create<Feature2D>("Feature2D." + feature2DType);
}

/////////////////////// AlgorithmInfo for various detector & descriptors ////////////////////////////

/* NOTE!!!
   All the AlgorithmInfo-related stuff should be in the same file as initModule_features2d().
   Otherwise, linker may throw away some seemingly unused stuff.
*/

CV_INIT_ALGORITHM(BRISK, "Feature2D.BRISK",
                   obj.info()->addParam(obj, "thres", obj.threshold);
                   obj.info()->addParam(obj, "octaves", obj.octaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BriefDescriptorExtractor, "Feature2D.BRIEF",
                  obj.info()->addParam(obj, "bytes", obj.bytes_));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST",
                  obj.info()->addParam(obj, "threshold", obj.threshold);
                  obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
                  obj.info()->addParam(obj, "type", obj.type));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(StarDetector, "Feature2D.STAR",
                  obj.info()->addParam(obj, "maxSize", obj.maxSize);
                  obj.info()->addParam(obj, "responseThreshold", obj.responseThreshold);
                  obj.info()->addParam(obj, "lineThresholdProjected", obj.lineThresholdProjected);
                  obj.info()->addParam(obj, "lineThresholdBinarized", obj.lineThresholdBinarized);
                  obj.info()->addParam(obj, "suppressNonmaxSize", obj.suppressNonmaxSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(MSER, "Feature2D.MSER",
                  obj.info()->addParam(obj, "delta", obj.delta);
                  obj.info()->addParam(obj, "minArea", obj.minArea);
                  obj.info()->addParam(obj, "maxArea", obj.maxArea);
                  obj.info()->addParam(obj, "maxVariation", obj.maxVariation);
                  obj.info()->addParam(obj, "minDiversity", obj.minDiversity);
                  obj.info()->addParam(obj, "maxEvolution", obj.maxEvolution);
                  obj.info()->addParam(obj, "areaThreshold", obj.areaThreshold);
                  obj.info()->addParam(obj, "minMargin", obj.minMargin);
                  obj.info()->addParam(obj, "edgeBlurSize", obj.edgeBlurSize));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(ORB, "Feature2D.ORB",
                  obj.info()->addParam(obj, "nFeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor);
                  obj.info()->addParam(obj, "nLevels", obj.nlevels);
                  obj.info()->addParam(obj, "firstLevel", obj.firstLevel);
                  obj.info()->addParam(obj, "edgeThreshold", obj.edgeThreshold);
                  obj.info()->addParam(obj, "patchSize", obj.patchSize);
                  obj.info()->addParam(obj, "WTA_K", obj.WTA_K);
                  obj.info()->addParam(obj, "scoreType", obj.scoreType));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(FREAK, "Feature2D.FREAK",
                  obj.info()->addParam(obj, "orientationNormalized", obj.orientationNormalized);
                  obj.info()->addParam(obj, "scaleNormalized", obj.scaleNormalized);
                  obj.info()->addParam(obj, "patternScale", obj.patternScale);
                  obj.info()->addParam(obj, "nbOctave", obj.nOctaves));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(GFTTDetector, "Feature2D.GFTT",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

///////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(SimpleBlobDetector, "Feature2D.SimpleBlob",
                  obj.info()->addParam(obj, "thresholdStep",    obj.params.thresholdStep);
                  obj.info()->addParam(obj, "minThreshold",     obj.params.minThreshold);
                  obj.info()->addParam(obj, "maxThreshold",     obj.params.maxThreshold);
                  obj.info()->addParam_(obj, "minRepeatability", (sizeof(size_t) == sizeof(uint64))?Param::UINT64 : Param::UNSIGNED_INT, &obj.params.minRepeatability, false, 0, 0);
                  obj.info()->addParam(obj, "minDistBetweenBlobs", obj.params.minDistBetweenBlobs);
                  obj.info()->addParam(obj, "filterByColor",    obj.params.filterByColor);
                  obj.info()->addParam(obj, "blobColor",        obj.params.blobColor);
                  obj.info()->addParam(obj, "filterByArea",     obj.params.filterByArea);
                  obj.info()->addParam(obj, "maxArea",          obj.params.maxArea);
                  obj.info()->addParam(obj, "filterByCircularity", obj.params.filterByCircularity);
                  obj.info()->addParam(obj, "maxCircularity",   obj.params.maxCircularity);
                  obj.info()->addParam(obj, "filterByInertia",  obj.params.filterByInertia);
                  obj.info()->addParam(obj, "maxInertiaRatio",  obj.params.maxInertiaRatio);
                  obj.info()->addParam(obj, "filterByConvexity", obj.params.filterByConvexity);
                  obj.info()->addParam(obj, "maxConvexity",     obj.params.maxConvexity);
                  );

///////////////////////////////////////////////////////////////////////////////////////////////////////////

class CV_EXPORTS HarrisDetector : public GFTTDetector
{
public:
    HarrisDetector( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1,
                    int blockSize=3, bool useHarrisDetector=true, double k=0.04 );
    AlgorithmInfo* info() const;
};

inline HarrisDetector::HarrisDetector( int _maxCorners, double _qualityLevel, double _minDistance,
                    int _blockSize, bool _useHarrisDetector, double _k )
    : GFTTDetector( _maxCorners, _qualityLevel, _minDistance, _blockSize, _useHarrisDetector, _k ) {}

CV_INIT_ALGORITHM(HarrisDetector, "Feature2D.HARRIS",
                  obj.info()->addParam(obj, "nfeatures", obj.nfeatures);
                  obj.info()->addParam(obj, "qualityLevel", obj.qualityLevel);
                  obj.info()->addParam(obj, "minDistance", obj.minDistance);
                  obj.info()->addParam(obj, "useHarrisDetector", obj.useHarrisDetector);
                  obj.info()->addParam(obj, "k", obj.k));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(DenseFeatureDetector, "Feature2D.Dense",
                  obj.info()->addParam(obj, "initFeatureScale", obj.initFeatureScale);
                  obj.info()->addParam(obj, "featureScaleLevels", obj.featureScaleLevels);
                  obj.info()->addParam(obj, "featureScaleMul", obj.featureScaleMul);
                  obj.info()->addParam(obj, "initXyStep", obj.initXyStep);
                  obj.info()->addParam(obj, "initImgBound", obj.initImgBound);
                  obj.info()->addParam(obj, "varyXyStepWithScale", obj.varyXyStepWithScale);
                  obj.info()->addParam(obj, "varyImgBoundWithScale", obj.varyImgBoundWithScale));

CV_INIT_ALGORITHM(GridAdaptedFeatureDetector, "Feature2D.Grid",
                  obj.info()->addParam<FeatureDetector>(obj, "detector", obj.detector, false, 0, 0, "Detector algorithm."); // Extra params added to avoid VS2013 fatal error in opencv2/core.hpp (decl. of addParam)
                  obj.info()->addParam(obj, "maxTotalKeypoints", obj.maxTotalKeypoints);
                  obj.info()->addParam(obj, "gridRows", obj.gridRows);
                  obj.info()->addParam(obj, "gridCols", obj.gridCols));

////////////////////////////////////////////////////////////////////////////////////////////////////////////

CV_INIT_ALGORITHM(BFMatcher, "DescriptorMatcher.BFMatcher",
                  obj.info()->addParam(obj, "normType", obj.normType);
                  obj.info()->addParam(obj, "crossCheck", obj.crossCheck));

CV_INIT_ALGORITHM(FlannBasedMatcher, "DescriptorMatcher.FlannBasedMatcher",);

///////////////////////////////////////////////////////////////////////////////////////////////////////////

bool cv::initModule_features2d(void)
{
    bool all = true;
    all &= !BriefDescriptorExtractor_info_auto.name().empty();
    all &= !BRISK_info_auto.name().empty();
    all &= !FastFeatureDetector_info_auto.name().empty();
    all &= !StarDetector_info_auto.name().empty();
    all &= !MSER_info_auto.name().empty();
    all &= !FREAK_info_auto.name().empty();
    all &= !ORB_info_auto.name().empty();
    all &= !GFTTDetector_info_auto.name().empty();
    all &= !HarrisDetector_info_auto.name().empty();
    all &= !DenseFeatureDetector_info_auto.name().empty();
    all &= !GridAdaptedFeatureDetector_info_auto.name().empty();
    all &= !BFMatcher_info_auto.name().empty();
    all &= !FlannBasedMatcher_info_auto.name().empty();

    return all;
}
<|endoftext|>


<commit_before>/// \file
/// \ingroup tutorial_v7
///
/// This macro generates two TH1D objects and build RLegend
/// In addition use of auto colors are shown
///
/// \macro_code
///
/// \date 2019-10-09
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!
/// \author Sergey Linev <s.linev@gsi.de>

/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOT/RHistDrawable.hxx"
#include "ROOT/RCanvas.hxx"
#include "ROOT/RLegend.hxx"
#include "TRandom.h"

// macro must be here while cling is not capable to load
// library automatically for outlined function see ROOT-10336
R__LOAD_LIBRARY(libROOTHistDraw)

using namespace ROOT::Experimental;

void draw_legend()
{
   // Create the histograms.
   RAxisConfig xaxis(25, 0., 10.);
   auto pHist = std::make_shared<RH1D>(xaxis);
   auto pHist2 = std::make_shared<RH1D>(xaxis);

   for (int n=0;n<1000;n++) {
      pHist->Fill(gRandom->Gaus(3,0.8));
      pHist2->Fill(gRandom->Gaus(7,1.2));
   }

   // Create a canvas to be displayed.
   auto canvas = RCanvas::Create("Canvas Title");

   // draw histogram
   auto draw1 = canvas->Draw(pHist);
   draw1->AttrLine().SetWidth(2).Color().SetAuto();

   // draw histogram
   auto draw2 = canvas->Draw(pHist2);
   draw2->AttrLine().SetWidth(4).Color().SetAuto();

   canvas->AssignAutoColors();

   auto legend = canvas->Draw<RLegend>(RPadPos(0.5_normal, 0.6_normal), RPadPos(0.9_normal,0.9_normal), "Legend title");
   legend->AttrBox().AttrFill().SetStyle(5).SetColor(RColor::kWhite);
   legend->AttrBox().AttrBorder().SetWidth(2).SetColor(RColor::kRed);
   legend->AddEntry(draw1, "histo1").SetLine("line_");
   legend->AddEntry(draw2, "histo2").SetLine("line_");

   canvas->Show();
}
<commit_msg>Fix v7/draw_legend.cxx tutorial<commit_after>/// \file
/// \ingroup tutorial_v7
///
/// This macro generates two TH1D objects and build RLegend
/// In addition use of auto colors are shown
///
/// \macro_code
///
/// \date 2019-10-09
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!
/// \author Sergey Linev <s.linev@gsi.de>

/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOT/RHistDrawable.hxx"
#include "ROOT/RCanvas.hxx"
#include "ROOT/RLegend.hxx"
#include "TRandom.h"

// macro must be here while cling is not capable to load
// library automatically for outlined function see ROOT-10336
R__LOAD_LIBRARY(libROOTHistDraw)

using namespace ROOT::Experimental;

void draw_legend()
{
   // Create the histograms.
   RAxisConfig xaxis(25, 0., 10.);
   auto pHist = std::make_shared<RH1D>(xaxis);
   auto pHist2 = std::make_shared<RH1D>(xaxis);

   for (int n=0;n<1000;n++) {
      pHist->Fill(gRandom->Gaus(3,0.8));
      pHist2->Fill(gRandom->Gaus(7,1.2));
   }

   // Create a canvas to be displayed.
   auto canvas = RCanvas::Create("Canvas Title");

   // draw histogram
   auto draw1 = canvas->Draw(pHist);
   draw1->AttrLine().SetWidth(2).AttrColor().SetAuto();

   // draw histogram
   auto draw2 = canvas->Draw(pHist2);
   draw2->AttrLine().SetWidth(4).AttrColor().SetAuto();

   canvas->AssignAutoColors();

   auto legend = canvas->Draw<RLegend>(RPadPos(0.5_normal, 0.6_normal), RPadPos(0.9_normal,0.9_normal), "Legend title");
   legend->AttrBox().AttrFill().SetStyle(5).SetColor(RColor::kWhite);
   legend->AttrBox().AttrBorder().SetWidth(2).SetColor(RColor::kRed);
   legend->AddEntry(draw1, "histo1").SetLine("line_");
   legend->AddEntry(draw2, "histo2").SetLine("line_");

   canvas->Show();
}
<|endoftext|>


<commit_before>// $Id: face_tri6.C,v 1.27 2006-12-27 07:21:27 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes

// Local includes
#include "side.h"
#include "edge_edge3.h"
#include "face_tri6.h"

// ------------------------------------------------------------
// Tri6 class static member initializations
const unsigned int Tri6::side_nodes_map[3][3] =
{
  {0, 1, 3}, // Side 0
  {1, 2, 4}, // Side 1
  {2, 0, 5}  // Side 2
};

#ifdef ENABLE_AMR

const float Tri6::_embedding_matrix[4][6][6] =
{
  // embedding matrix for child 0
  {
    //  0      1      2    3    4    5
    { 1.0,   0.0,   0.0, 0.0, 0.0, 0.0}, // 0
    { 0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 1
    { 0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {.375, -.125,   0.0, .75, 0.0, 0.0}, // 3
    { 0.0, -.125, -.125, 0.5, .25, 0.5}, // 4
    {.375,   0.0, -.125, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 1
  {
    //  0      1      2    3    4    5
    {  0.0,  0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,  1.0,   0.0, 0.0, 0.0, 0.0}, // 1
    {  0.0,  0.0,   0.0, 0.0, 1.0, 0.0}, // 2
    {-.125, .375,   0.0, .75, 0.0, 0.0}, // 3
    {  0.0, .375, -.125, 0.0, .75, 0.0}, // 4
    {-.125,  0.0, -.125, 0.5, 0.5, .25}  // 5
  },

  // embedding matrix for child 2
  {
    //  0       1     2    3    4    5
    {  0.0,   0.0,  0.0, 0.0, 0.0, 1.0}, // 0
    {  0.0,   0.0,  0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,  1.0, 0.0, 0.0, 0.0}, // 2
    {-.125, -.125,  0.0, .25, 0.5, 0.5}, // 3
    {  0.0, -.125, .375, 0.0, .75, 0.0}, // 4
    {-.125,   0.0, .375, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 3
  {
    //  0       1      2    3    4    5
    {  0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,   0.0,   0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {-.125,   0.0, -.125, 0.5, 0.5, .25}, // 3
    {-.125, -.125,   0.0, .25, 0.5, 0.5}, // 4
    {  0.0, -.125, -.125, 0.5, .25, 0.5}  // 5
  }
};

#endif

// ------------------------------------------------------------
// Tri6 class member functions

bool Tri6::is_vertex(const unsigned int i) const
{
  if (i < 3)
    return true;
  return false;
}

bool Tri6::is_edge(const unsigned int i) const
{
  if (i < 3)
    return false;
  return true;
}

bool Tri6::is_face(const unsigned int) const
{
  return false;
}

bool Tri6::is_node_on_side(const unsigned int n,
			   const unsigned int s) const
{
  assert(s < n_sides());
  for (unsigned int i = 0; i != 3; ++i)
    if (side_nodes_map[s][i] == n)
      return true;
  return false;
}

bool Tri6::has_affine_map() const
{
  // Make sure edges are straight
  if (!this->point(4).relative_fuzzy_equals
      ((this->point(0) + this->point(1))/2.))
    return false;
  if (!this->point(5).relative_fuzzy_equals
      ((this->point(1) + this->point(2))/2.))
    return false;
  if (!this->point(6).relative_fuzzy_equals
      ((this->point(2) + this->point(0))/2.))
    return false;

  error();
  return false;
}

unsigned int Tri6::key (const unsigned int s) const
{
  assert (s < this->n_sides());

  switch (s)
    {
    case 0:

      return
	this->compute_key (this->node(3));

    case 1:

      return
	this->compute_key (this->node(4));

    case 2:

      return
	this->compute_key (this->node(5));
    }

  // We will never get here...  Look at the code above.
  error();
  return 0;
}

AutoPtr<Elem> Tri6::build_side (const unsigned int i) const
{
  assert (i < this->n_sides());

  AutoPtr<Elem> ap(new Side<Edge3,Tri6>(this,i));
  return ap;

//   Edge3* edge = new Edge3;

//   switch (i)
//     {
//     case 0:
//       {
// 	edge->set_node(0) = this->get_node(0);
// 	edge->set_node(1) = this->get_node(1);
// 	edge->set_node(2) = this->get_node(3);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 1:
//       {
// 	edge->set_node(0) = this->get_node(1);
// 	edge->set_node(1) = this->get_node(2);
// 	edge->set_node(2) = this->get_node(4);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 2:
//       {
// 	edge->set_node(0) = this->get_node(2);
// 	edge->set_node(1) = this->get_node(0);
// 	edge->set_node(2) = this->get_node(5);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     default:
//       {
// 	error();
//       }
//     }

//   // We will never get here...  Look at the code above.
//   error();
//   AutoPtr<Elem> ap(NULL);  return ap;
}

void Tri6::connectivity(const unsigned int sf,
			const IOPackage iop,
			std::vector<unsigned int>& conn) const
{
  assert (sf < this->n_sub_elem());
  assert (iop != INVALID_IO_PACKAGE);

  switch (iop)
    {
    case TECPLOT:
      {
	conn.resize(4);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0)+1;
	    conn[1] = this->node(3)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(1)+1;
	    conn[2] = this->node(4)+1;
	    conn[3] = this->node(4)+1;

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(2)+1;
	    conn[3] = this->node(2)+1;

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  default:
	    error();
	  }
      }

    case VTK:
      {
	conn.resize(3);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0);
	    conn[1] = this->node(3);
	    conn[2] = this->node(5);

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3);
	    conn[1] = this->node(1);
	    conn[2] = this->node(4);

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5);
	    conn[1] = this->node(4);
	    conn[2] = this->node(2);

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3);
	    conn[1] = this->node(4);
	    conn[2] = this->node(5);

	    return;

	  default:
	    error();
	  }
      }

    default:
      error();
    }

  error();
}

unsigned short int Tri6::second_order_adjacent_vertex (const unsigned int n,
						       const unsigned int v) const
{
  assert (n >= this->n_vertices());
  assert (n <  this->n_nodes());
  assert (v < 2);
  return _second_order_adjacent_vertices[n-this->n_vertices()][v];
}

const unsigned short int Tri6::_second_order_adjacent_vertices[3][2] =
{
  {0, 1}, // vertices adjacent to node 3
  {1, 2}, // vertices adjacent to node 4
  {0, 2}  // vertices adjacent to node 5
};

std::pair<unsigned short int, unsigned short int>
Tri6::second_order_child_vertex (const unsigned int n) const
{
  assert (n >= this->n_vertices());
  assert (n < this->n_nodes());
  return std::pair<unsigned short int, unsigned short int>
    (_second_order_vertex_child_number[n],
     _second_order_vertex_child_index[n]);
}

const unsigned short int Tri6::_second_order_vertex_child_number[6] =
{
  99,99,99, // Vertices
  0,1,0     // Edges
};

const unsigned short int Tri6::_second_order_vertex_child_index[6] =
{
  99,99,99, // Vertices
  1,2,2     // Edges
};
<commit_msg>Fixed stupid indexing bug in has_affine_map()<commit_after>// $Id: face_tri6.C,v 1.28 2007-02-06 23:48:00 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes

// Local includes
#include "side.h"
#include "edge_edge3.h"
#include "face_tri6.h"

// ------------------------------------------------------------
// Tri6 class static member initializations
const unsigned int Tri6::side_nodes_map[3][3] =
{
  {0, 1, 3}, // Side 0
  {1, 2, 4}, // Side 1
  {2, 0, 5}  // Side 2
};

#ifdef ENABLE_AMR

const float Tri6::_embedding_matrix[4][6][6] =
{
  // embedding matrix for child 0
  {
    //  0      1      2    3    4    5
    { 1.0,   0.0,   0.0, 0.0, 0.0, 0.0}, // 0
    { 0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 1
    { 0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {.375, -.125,   0.0, .75, 0.0, 0.0}, // 3
    { 0.0, -.125, -.125, 0.5, .25, 0.5}, // 4
    {.375,   0.0, -.125, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 1
  {
    //  0      1      2    3    4    5
    {  0.0,  0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,  1.0,   0.0, 0.0, 0.0, 0.0}, // 1
    {  0.0,  0.0,   0.0, 0.0, 1.0, 0.0}, // 2
    {-.125, .375,   0.0, .75, 0.0, 0.0}, // 3
    {  0.0, .375, -.125, 0.0, .75, 0.0}, // 4
    {-.125,  0.0, -.125, 0.5, 0.5, .25}  // 5
  },

  // embedding matrix for child 2
  {
    //  0       1     2    3    4    5
    {  0.0,   0.0,  0.0, 0.0, 0.0, 1.0}, // 0
    {  0.0,   0.0,  0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,  1.0, 0.0, 0.0, 0.0}, // 2
    {-.125, -.125,  0.0, .25, 0.5, 0.5}, // 3
    {  0.0, -.125, .375, 0.0, .75, 0.0}, // 4
    {-.125,   0.0, .375, 0.0, 0.0, .75}  // 5
  },

  // embedding matrix for child 3
  {
    //  0       1      2    3    4    5
    {  0.0,   0.0,   0.0, 1.0, 0.0, 0.0}, // 0
    {  0.0,   0.0,   0.0, 0.0, 1.0, 0.0}, // 1
    {  0.0,   0.0,   0.0, 0.0, 0.0, 1.0}, // 2
    {-.125,   0.0, -.125, 0.5, 0.5, .25}, // 3
    {-.125, -.125,   0.0, .25, 0.5, 0.5}, // 4
    {  0.0, -.125, -.125, 0.5, .25, 0.5}  // 5
  }
};

#endif

// ------------------------------------------------------------
// Tri6 class member functions

bool Tri6::is_vertex(const unsigned int i) const
{
  if (i < 3)
    return true;
  return false;
}

bool Tri6::is_edge(const unsigned int i) const
{
  if (i < 3)
    return false;
  return true;
}

bool Tri6::is_face(const unsigned int) const
{
  return false;
}

bool Tri6::is_node_on_side(const unsigned int n,
			   const unsigned int s) const
{
  assert(s < n_sides());
  for (unsigned int i = 0; i != 3; ++i)
    if (side_nodes_map[s][i] == n)
      return true;
  return false;
}

bool Tri6::has_affine_map() const
{
  // Make sure edges are straight
  if (!this->point(3).relative_fuzzy_equals
      ((this->point(0) + this->point(1))/2.))
    return false;
  if (!this->point(4).relative_fuzzy_equals
      ((this->point(1) + this->point(2))/2.))
    return false;
  if (!this->point(5).relative_fuzzy_equals
      ((this->point(2) + this->point(0))/2.))
    return false;

  error();
  return false;
}

unsigned int Tri6::key (const unsigned int s) const
{
  assert (s < this->n_sides());

  switch (s)
    {
    case 0:

      return
	this->compute_key (this->node(3));

    case 1:

      return
	this->compute_key (this->node(4));

    case 2:

      return
	this->compute_key (this->node(5));
    }

  // We will never get here...  Look at the code above.
  error();
  return 0;
}

AutoPtr<Elem> Tri6::build_side (const unsigned int i) const
{
  assert (i < this->n_sides());

  AutoPtr<Elem> ap(new Side<Edge3,Tri6>(this,i));
  return ap;

//   Edge3* edge = new Edge3;

//   switch (i)
//     {
//     case 0:
//       {
// 	edge->set_node(0) = this->get_node(0);
// 	edge->set_node(1) = this->get_node(1);
// 	edge->set_node(2) = this->get_node(3);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 1:
//       {
// 	edge->set_node(0) = this->get_node(1);
// 	edge->set_node(1) = this->get_node(2);
// 	edge->set_node(2) = this->get_node(4);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     case 2:
//       {
// 	edge->set_node(0) = this->get_node(2);
// 	edge->set_node(1) = this->get_node(0);
// 	edge->set_node(2) = this->get_node(5);

// 	AutoPtr<Elem> ap(edge);  return ap;
//       }
//     default:
//       {
// 	error();
//       }
//     }

//   // We will never get here...  Look at the code above.
//   error();
//   AutoPtr<Elem> ap(NULL);  return ap;
}

void Tri6::connectivity(const unsigned int sf,
			const IOPackage iop,
			std::vector<unsigned int>& conn) const
{
  assert (sf < this->n_sub_elem());
  assert (iop != INVALID_IO_PACKAGE);

  switch (iop)
    {
    case TECPLOT:
      {
	conn.resize(4);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0)+1;
	    conn[1] = this->node(3)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(1)+1;
	    conn[2] = this->node(4)+1;
	    conn[3] = this->node(4)+1;

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(2)+1;
	    conn[3] = this->node(2)+1;

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3)+1;
	    conn[1] = this->node(4)+1;
	    conn[2] = this->node(5)+1;
	    conn[3] = this->node(5)+1;

	    return;

	  default:
	    error();
	  }
      }

    case VTK:
      {
	conn.resize(3);
	switch(sf)
	  {
	  case 0:
	    // linear sub-triangle 0
	    conn[0] = this->node(0);
	    conn[1] = this->node(3);
	    conn[2] = this->node(5);

	    return;

	  case 1:
	    // linear sub-triangle 1
	    conn[0] = this->node(3);
	    conn[1] = this->node(1);
	    conn[2] = this->node(4);

	    return;

	  case 2:
	    // linear sub-triangle 2
	    conn[0] = this->node(5);
	    conn[1] = this->node(4);
	    conn[2] = this->node(2);

	    return;

	  case 3:
	    // linear sub-triangle 3
	    conn[0] = this->node(3);
	    conn[1] = this->node(4);
	    conn[2] = this->node(5);

	    return;

	  default:
	    error();
	  }
      }

    default:
      error();
    }

  error();
}

unsigned short int Tri6::second_order_adjacent_vertex (const unsigned int n,
						       const unsigned int v) const
{
  assert (n >= this->n_vertices());
  assert (n <  this->n_nodes());
  assert (v < 2);
  return _second_order_adjacent_vertices[n-this->n_vertices()][v];
}

const unsigned short int Tri6::_second_order_adjacent_vertices[3][2] =
{
  {0, 1}, // vertices adjacent to node 3
  {1, 2}, // vertices adjacent to node 4
  {0, 2}  // vertices adjacent to node 5
};

std::pair<unsigned short int, unsigned short int>
Tri6::second_order_child_vertex (const unsigned int n) const
{
  assert (n >= this->n_vertices());
  assert (n < this->n_nodes());
  return std::pair<unsigned short int, unsigned short int>
    (_second_order_vertex_child_number[n],
     _second_order_vertex_child_index[n]);
}

const unsigned short int Tri6::_second_order_vertex_child_number[6] =
{
  99,99,99, // Vertices
  0,1,0     // Edges
};

const unsigned short int Tri6::_second_order_vertex_child_index[6] =
{
  99,99,99, // Vertices
  1,2,2     // Edges
};
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/guardian/common/guardian_gflags.h"

DEFINE_string(node_name, "guardian", "The chassis module name in proto");
DEFINE_string(module_name, "guardian", "Module name");

DEFINE_string(adapter_config_filename, "", "Path for adapter configuration");

DEFINE_double(guardian_cmd_freq, 10, "timer frequency.");

DEFINE_double(guardian_cmd_soft_stop_percentage, 30,
              "Soft stop perceptage when safe mode triggered");

DEFINE_double(guardian_cmd_emergency_stop_percentage, 100,
              "Emergency stop perceptage when safe mode triggered");

DEFINE_bool(guardian_enabled, false,
            "Enable guardian, safe mode activation enabled");
<commit_msg>Guardian : update soft/emergency stop threshold (#4420)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/guardian/common/guardian_gflags.h"

DEFINE_string(node_name, "guardian", "The chassis module name in proto");
DEFINE_string(module_name, "guardian", "Module name");

DEFINE_string(adapter_config_filename, "", "Path for adapter configuration");

DEFINE_double(guardian_cmd_freq, 10, "timer frequency.");

DEFINE_double(guardian_cmd_soft_stop_percentage, 25,
              "Soft stop perceptage when safe mode triggered");

DEFINE_double(guardian_cmd_emergency_stop_percentage, 50,
              "Emergency stop perceptage when safe mode triggered");

DEFINE_bool(guardian_enabled, false,
            "Enable guardian, safe mode activation enabled");
<|endoftext|>