<commit_before>/* AFE Firmware for smart home devices, Website: https://afe.smartnydom.pl/ */

#include <AFE-API-HTTP.h>
#include <AFE-Configuration.h>

#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLE
#include <AFE-API-HTTP-Domoticz.h>
#include <AFE-API-MQTT-Domoticz.h>
#else
#include <AFE-API-MQTT-Standard.h>
#endif

/* ---------Headers ---------*/

void initializeMQTTAPI(void);
void initializeHTTPAPI(void);
#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED
void initializeHTTPDomoticzAPI(void);
#endif // AFE_CONFIG_API_DOMOTICZ_ENABLED

/* --------- Body -----------*/

AFEAPIHTTP HttpAPI;
#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED
AFEAPIMQTTDomoticz MqttAPI;
AFEAPIHTTPDomoticz HttpDomoticzAPI;
#else
AFEAPIMQTTStandard MqttAPI;
#endif

/* Initializing MQTT API */
void initializeMQTTAPI(void) {
  if (Device.getMode() != AFE_MODE_ACCESS_POINT &&
      Device.configuration.api.mqtt) {

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: Initializing MQTT");
#endif

#ifdef AFE_CONFIG_HARDWARE_LED
    MqttAPI.begin(&Data, &Device, &Led);
#else
    MqttAPI.begin(&Data, &Device);
#endif

#ifdef AFE_CONFIG_HARDWARE_RELAY
    if (Device.configuration.noOfRelays > 0) {
      MqttAPI.addClass(&Relay[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_SWITCH
    if (Device.configuration.noOfSwitches > 0) {
      MqttAPI.addClass(&Switch[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_ADC_VCC
    if (Device.configuration.isAnalogInput) {
      MqttAPI.addClass(&AnalogInput);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BMEX80
    // @TODO Missing noOf check
    MqttAPI.addClass(&BMEX80Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_HPMA115S0
    MqttAPI.addClass(&HPMA115S0Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_BH1750
    // @TODO Missing noOf check
    MqttAPI.addClass(&BH1750Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_AS3935
    MqttAPI.addClass(&AS3935Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR
    MqttAPI.addClass(&AnemometerSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR
    MqttAPI.addClass(&RainSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_GATE
    // @TODO Missing noOf check
    MqttAPI.addClass(&Gate[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_CONTACTRON

    MqttAPI.addClass(&Contactron[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_DS18B20
    if (Device.configuration.noOfDS18B20s > 0) {
      MqttAPI.addClass(&DS18B20Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_DHT
    if (Device.configuration.noOfDHTs > 0) {
      MqttAPI.addClass(&DHTSensor[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_REGULATOR
    if (Device.configuration.noOfRegulators > 0) {
      MqttAPI.addClass(&Regulator[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
    if (Device.configuration.noOfThermalProtectors > 0) {
      MqttAPI.addClass(&ThermalProtector[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BINARY_SENSOR
    if (Device.configuration.noOfBinarySensors > 0) {
      MqttAPI.addClass(&BinarySensor[0]);
    }
#endif

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: MQTT init completed");
#endif
  }
}

/* Initializing HTTP API */
void initializeHTTPAPI(void) {
  if (Device.getMode() != AFE_MODE_ACCESS_POINT) {

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: Initializing MQTT");
#endif

#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED
    HttpAPI.begin(&Device, &WebServer, &Data, &MqttAPI, &HttpDomoticzAPI);
#else
    HttpAPI.begin(&Device, &WebServer, &Data, &MqttAPI);
#endif

#ifdef AFE_CONFIG_HARDWARE_RELAY
    if (Device.configuration.noOfRelays > 0) {
      HttpAPI.addClass(&Relay[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_ADC_VCC
    if (Device.configuration.isAnalogInput) {
      HttpAPI.addClass(&AnalogInput);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BMEX80
    // @TODO Missing noOf check
    HttpAPI.addClass(&BMEX80Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_HPMA115S0
    HttpAPI.addClass(&HPMA115S0Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_BH1750
    // @TODO Missing noOf check
    HttpAPI.addClass(&BH1750Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_AS3935
    HttpAPI.addClass(&AS3935Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR
    HttpAPI.addClass(&AnemometerSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR
    HttpAPI.addClass(&RainSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_GATE
    // @TODO Missing noOf check
    HttpAPI.addClass(&Gate[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_CONTACTRON
    // @TODO Missing noOf check
    HttpAPI.addClass(&Contactron[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_DS18B20
    if (Device.configuration.noOfDS18B20s > 0) {
      HttpAPI.addClass(&DS18B20Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_DHT
    if (Device.configuration.noOfDHTs > 0) {
      HttpAPI.addClass(&DHTSensor[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_REGULATOR
    if (Device.configuration.noOfRegulators > 0) {
      HttpAPI.addClass(&Regulator[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
    if (Device.configuration.noOfThermalProtectors > 0) {
      HttpAPI.addClass(&ThermalProtector[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BINARY_SENSOR
    if (Device.configuration.noOfBinarySensors > 0) {
      HttpAPI.addClass(&BinarySensor[0]);
    }
#endif

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: HTTP init completed");
#endif
  }
}

/* Initializing Domoticz HTTP API */
#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED

void initializeHTTPDomoticzAPI(void) {
  if (Device.getMode() != AFE_MODE_ACCESS_POINT &&
      Device.configuration.api.domoticz) {

#ifdef AFE_CONFIG_HARDWARE_LED
    HttpDomoticzAPI.begin(&Data, &Device, &Led);
#else
    HttpDomoticzAPI.begin(&Data, &Device);
#endif

#ifdef AFE_CONFIG_HARDWARE_RELAY
    if (Device.configuration.noOfRelays > 0) {
      HttpDomoticzAPI.addClass(&Relay[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_SWITCH
    if (Device.configuration.noOfSwitches > 0) {
      HttpDomoticzAPI.addClass(&Switch[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_ADC_VCC
    if (Device.configuration.isAnalogInput) {
      HttpDomoticzAPI.addClass(&AnalogInput);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BMEX80
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&BMEX80Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_HPMA115S0
    HttpDomoticzAPI.addClass(&HPMA115S0Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_BH1750
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&BH1750Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_AS3935
    HttpDomoticzAPI.addClass(&AS3935Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR
    HttpDomoticzAPI.addClass(&AnemometerSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR
    HttpDomoticzAPI.addClass(&RainSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_CONTACTRON
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&Contactron[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_GATE
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&Gate[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_DS18B20
    if (Device.configuration.noOfDS18B20s > 0) {
      HttpDomoticzAPI.addClass(&DS18B20Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_DHT
    if (Device.configuration.noOfDHTs > 0) {
      HttpDomoticzAPI.addClass(&DHTSensor[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_REGULATOR
    if (Device.configuration.noOfRegulators > 0) {
      HttpDomoticzAPI.addClass(&Regulator[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
    if (Device.configuration.noOfThermalProtectors > 0) {
      HttpDomoticzAPI.addClass(&ThermalProtector[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BINARY_SENSOR
    if (Device.configuration.noOfBinarySensors > 0) {
      HttpDomoticzAPI.addClass(&BinarySensor[0]);
    }
#endif

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: MQTT init completed");
#endif
  }
}

#endif // AFE_CONFIG_API_DOMOTICZ_ENABLED<commit_msg>T6-2.5.1<commit_after>/* AFE Firmware for smart home devices, Website: https://afe.smartnydom.pl/ */

#include <AFE-API-HTTP.h>
#include <AFE-Configuration.h>

#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLE
#include <AFE-API-HTTP-Domoticz.h>
#include <AFE-API-MQTT-Domoticz.h>
#else
#include <AFE-API-MQTT-Standard.h>
#endif

/* ---------Headers ---------*/

void initializeMQTTAPI(void);
void initializeHTTPAPI(void);
#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED
void initializeHTTPDomoticzAPI(void);
#endif // AFE_CONFIG_API_DOMOTICZ_ENABLED

/* --------- Body -----------*/

AFEAPIHTTP HttpAPI;
#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED
AFEAPIMQTTDomoticz MqttAPI;
AFEAPIHTTPDomoticz HttpDomoticzAPI;
#else
AFEAPIMQTTStandard MqttAPI;
#endif

/* Initializing MQTT API */
void initializeMQTTAPI(void) {
  if (Device.getMode() != AFE_MODE_ACCESS_POINT &&
      Device.configuration.api.mqtt) {

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: Initializing MQTT");
#endif

#ifdef AFE_CONFIG_HARDWARE_LED
    MqttAPI.begin(&Data, &Device, &Led);
#else
    MqttAPI.begin(&Data, &Device);
#endif

#ifdef AFE_CONFIG_HARDWARE_RELAY
    if (Device.configuration.noOfRelays > 0) {
      MqttAPI.addClass(&Relay[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_SWITCH
    if (Device.configuration.noOfSwitches > 0) {
      MqttAPI.addClass(&Switch[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_ADC_VCC
    if (Device.configuration.isAnalogInput) {
      MqttAPI.addClass(&AnalogInput);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BMEX80
    if (Device.configuration.noOfBMEX80s > 0) {
      MqttAPI.addClass(&BMEX80Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_HPMA115S0
    if (Device.configuration.noOfHPMA115S0s > 0) {
      MqttAPI.addClass(&HPMA115S0Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BH1750
    if (Device.configuration.noOfBH1750s > 0) {
      MqttAPI.addClass(&BH1750Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_AS3935
    if (Device.configuration.noOfAS3935s > 0) {
      MqttAPI.addClass(&AS3935Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR
    if (Device.configuration.noOfAnemometerSensors > 0) {
      MqttAPI.addClass(&AnemometerSensor);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR
    if (Device.configuration.noOfRainmeterSensors > 0) {
      MqttAPI.addClass(&RainSensor);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_GATE
    if (Device.configuration.noOfGates > 0) {
      MqttAPI.addClass(&Gate[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_CONTACTRON
    if (Device.configuration.noOfContactrons > 0) {
      MqttAPI.addClass(&Contactron[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_DS18B20
    if (Device.configuration.noOfDS18B20s > 0) {
      MqttAPI.addClass(&DS18B20Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_DHT
    if (Device.configuration.noOfDHTs > 0) {
      MqttAPI.addClass(&DHTSensor[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_REGULATOR
    if (Device.configuration.noOfRegulators > 0) {
      MqttAPI.addClass(&Regulator[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
    if (Device.configuration.noOfThermalProtectors > 0) {
      MqttAPI.addClass(&ThermalProtector[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BINARY_SENSOR
    if (Device.configuration.noOfBinarySensors > 0) {
      MqttAPI.addClass(&BinarySensor[0]);
    }
#endif

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: MQTT init completed");
#endif
  }
}

/* Initializing HTTP API */
void initializeHTTPAPI(void) {
  if (Device.getMode() != AFE_MODE_ACCESS_POINT) {

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: Initializing MQTT");
#endif

#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED
    HttpAPI.begin(&Device, &WebServer, &Data, &MqttAPI, &HttpDomoticzAPI);
#else
    HttpAPI.begin(&Device, &WebServer, &Data, &MqttAPI);
#endif

#ifdef AFE_CONFIG_HARDWARE_RELAY
    if (Device.configuration.noOfRelays > 0) {
      HttpAPI.addClass(&Relay[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_ADC_VCC
    if (Device.configuration.isAnalogInput) {
      HttpAPI.addClass(&AnalogInput);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BMEX80
    // @TODO Missing noOf check
    HttpAPI.addClass(&BMEX80Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_HPMA115S0
    HttpAPI.addClass(&HPMA115S0Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_BH1750
    // @TODO Missing noOf check
    HttpAPI.addClass(&BH1750Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_AS3935
    HttpAPI.addClass(&AS3935Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR
    HttpAPI.addClass(&AnemometerSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR
    HttpAPI.addClass(&RainSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_GATE
    // @TODO Missing noOf check
    HttpAPI.addClass(&Gate[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_CONTACTRON
    // @TODO Missing noOf check
    HttpAPI.addClass(&Contactron[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_DS18B20
    if (Device.configuration.noOfDS18B20s > 0) {
      HttpAPI.addClass(&DS18B20Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_DHT
    if (Device.configuration.noOfDHTs > 0) {
      HttpAPI.addClass(&DHTSensor[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_REGULATOR
    if (Device.configuration.noOfRegulators > 0) {
      HttpAPI.addClass(&Regulator[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
    if (Device.configuration.noOfThermalProtectors > 0) {
      HttpAPI.addClass(&ThermalProtector[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BINARY_SENSOR
    if (Device.configuration.noOfBinarySensors > 0) {
      HttpAPI.addClass(&BinarySensor[0]);
    }
#endif

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: HTTP init completed");
#endif
  }
}

/* Initializing Domoticz HTTP API */
#ifdef AFE_CONFIG_API_DOMOTICZ_ENABLED

void initializeHTTPDomoticzAPI(void) {
  if (Device.getMode() != AFE_MODE_ACCESS_POINT &&
      Device.configuration.api.domoticz) {

#ifdef AFE_CONFIG_HARDWARE_LED
    HttpDomoticzAPI.begin(&Data, &Device, &Led);
#else
    HttpDomoticzAPI.begin(&Data, &Device);
#endif

#ifdef AFE_CONFIG_HARDWARE_RELAY
    if (Device.configuration.noOfRelays > 0) {
      HttpDomoticzAPI.addClass(&Relay[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_SWITCH
    if (Device.configuration.noOfSwitches > 0) {
      HttpDomoticzAPI.addClass(&Switch[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_ADC_VCC
    if (Device.configuration.isAnalogInput) {
      HttpDomoticzAPI.addClass(&AnalogInput);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BMEX80
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&BMEX80Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_HPMA115S0
    HttpDomoticzAPI.addClass(&HPMA115S0Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_BH1750
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&BH1750Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_AS3935
    HttpDomoticzAPI.addClass(&AS3935Sensor[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR
    HttpDomoticzAPI.addClass(&AnemometerSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR
    HttpDomoticzAPI.addClass(&RainSensor);
#endif

#ifdef AFE_CONFIG_HARDWARE_CONTACTRON
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&Contactron[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_GATE
    // @TODO Missing noOf check
    HttpDomoticzAPI.addClass(&Gate[0]);
#endif

#ifdef AFE_CONFIG_HARDWARE_DS18B20
    if (Device.configuration.noOfDS18B20s > 0) {
      HttpDomoticzAPI.addClass(&DS18B20Sensor[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_DHT
    if (Device.configuration.noOfDHTs > 0) {
      HttpDomoticzAPI.addClass(&DHTSensor[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_REGULATOR
    if (Device.configuration.noOfRegulators > 0) {
      HttpDomoticzAPI.addClass(&Regulator[0]);
    }
#endif

#ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
    if (Device.configuration.noOfThermalProtectors > 0) {
      HttpDomoticzAPI.addClass(&ThermalProtector[0]);
    }
#endif

#ifdef AFE_CONFIG_HARDWARE_BINARY_SENSOR
    if (Device.configuration.noOfBinarySensors > 0) {
      HttpDomoticzAPI.addClass(&BinarySensor[0]);
    }
#endif

#ifdef DEBUG
    Serial << endl << F("INFO: BOOT: API: MQTT init completed");
#endif
  }
}

#endif // AFE_CONFIG_API_DOMOTICZ_ENABLED<|endoftext|>


<commit_before><commit_msg>Also bypass definitions of functions not used on Android or iOS<commit_after><|endoftext|>


<commit_before>#include "mitkContour.h"
#include "mitkCommon.h"

#include <fstream>
int mitkContourTest(int argc, char* argv[])
{
  mitk::Contour::Pointer contour;
  std::cout << "Testing mitk::Contour::New(): ";
  contour = mitk::Contour::New();
  if (contour.IsNull()) {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  std::cout << "Testing mitk::Contour::AddVertex(): ";
  mitk::ITKPoint3D p;
  p.Fill(0);
  contour->AddVertex(p);
  p.Fill(1);
  contour->AddVertex(p);
  p.Fill(2);
  contour->AddVertex(p);

  if (contour->GetNumberOfPoints() != 3)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout << "Testing mitk::Contour::GetPoints()";
  mitk::Contour::PointsContainerPointer points = contour->GetPoints();
  if ( points.IsNull() )
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout << "Testing mitk::Contour::Initialize()";
  contour->Initialize();
  if (contour->GetNumberOfPoints() != 0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  contour->SetPoints(points);
  if ( contour->GetNumberOfPoints() != 3)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    };

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>extended<commit_after>#include "mitkContour.h"
#include "mitkCommon.h"

#include <fstream>
int mitkContourTest(int argc, char* argv[])
{
  mitk::Contour::Pointer contour;
  std::cout << "Testing mitk::Contour::New(): ";
  contour = mitk::Contour::New();
  if (contour.IsNull()) {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else {
  std::cout<<"[PASSED]"<<std::endl;
  }

  std::cout << "Testing mitk::Contour::AddVertex(): ";
  mitk::ITKPoint3D p;
  p.Fill(0);
  contour->AddVertex(p);
  p.Fill(1);
  contour->AddVertex(p);
  p.Fill(2);
  contour->AddVertex(p);

  if (contour->GetNumberOfPoints() != 3)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout << "Testing mitk::Contour::GetPoints()";
  mitk::Contour::PointsContainerPointer points = contour->GetPoints();
  if ( points.IsNull() )
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout << "Testing mitk::Contour::Initialize()";
  contour->Initialize();
  if (contour->GetNumberOfPoints() != 0)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  contour->SetPoints(points);
  if ( contour->GetNumberOfPoints() != 3)
    {
      std::cout<<"[FAILED]"<<std::endl;
      return EXIT_FAILURE;
    };

  mitk::Contour::PathPointer path =  contour->GetContourPath();
  if ( path.IsNull() )
    {
    return EXIT_FAILURE;
    }

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// FRAGMENT(includes)
#include <seqan/file.h>
#include <seqan/index.h>
#include <seqan/store.h>
#include <iostream>

using namespace seqan;

// FRAGMENT(load_reads)
int main (int argc, char const * argv[])
{
	FragmentStore<> fragStore;
	if (argc < 2 ||	!loadReads(fragStore, argv[1]))
		return 1;

// FRAGMENT(output)

	typedef FragmentStore<>::TReadSeqStore TReadSeqStore;
	typedef GetValue<TReadSeqStore>::Type TReadSeq;
	typedef Index<TReadSeqStore, Index_QGram<Shape<Dna, UngappedShape<11> >, OpenAddressing> > TIndex;
	typedef Pattern<TIndex, Swift<SwiftSemiGlobal> > TPattern;
	typedef Finder<TReadSeq, Swift<SwiftSemiGlobal> > TFinder;

	TIndex index(fragStore.readSeqStore);
	TPattern pattern(index);
	for (unsigned i = 0; i < length(fragStore.readSeqStore); ++i)
	{
		if ((i % 1000) == 0) std::cout << "." << std::flush;
		TFinder finder(fragStore.readSeqStore[i]);
		while (find(finder, pattern, 0.1))
		{
			if (i == position(pattern).i1) continue;
			// do further alignment here
/*			std::cout << "Found possible overlap of " << std::endl;
			std::cout << "\t" << range(finder) << std::endl;
			std::cout << "\t" << seqs[position(pattern).i1] << std::endl;
*/		}
	}

	return 0;
}

<commit_msg>frag changed<commit_after>// FRAGMENT(includes)
#include <seqan/file.h>
#include <seqan/index.h>
#include <seqan/store.h>
#include <iostream>

using namespace seqan;

// FRAGMENT(load_reads)
int main (int argc, char const * argv[])
{
	FragmentStore<> fragStore;
	if (argc < 2 ||	!loadReads(fragStore, argv[1]))
		return 1;

// FRAGMENT(filter)

	typedef FragmentStore<>::TReadSeqStore TReadSeqStore;
	typedef GetValue<TReadSeqStore>::Type TReadSeq;
	typedef Index<TReadSeqStore, Index_QGram<Shape<Dna, UngappedShape<11> >, OpenAddressing> > TIndex;
	typedef Pattern<TIndex, Swift<SwiftSemiGlobal> > TPattern;
	typedef Finder<TReadSeq, Swift<SwiftSemiGlobal> > TFinder;

	TIndex index(fragStore.readSeqStore);
	TPattern pattern(index);
	for (unsigned i = 0; i < length(fragStore.readSeqStore); ++i)
	{
		if ((i % 1000) == 0) std::cout << "." << std::flush;
		TFinder finder(fragStore.readSeqStore[i]);
		while (find(finder, pattern, 0.1))
		{
			if (i == position(pattern).i1) continue;
			// do further alignment here
/*			std::cout << "Found possible overlap of " << std::endl;
			std::cout << "\t" << range(finder) << std::endl;
			std::cout << "\t" << seqs[position(pattern).i1] << std::endl;
*/		}
	}

	return 0;
}

<|endoftext|>


<commit_before>//
//  fld.cpp
//  express
//
//  Created by Adam Roberts on 3/20/11.
//  Copyright 2011 Adam Roberts. All rights reserved.
//

#include "fld.h"
#include "main.h"
#include <numeric>
#include <boost/assign.hpp>
#include <iostream>
#include <fstream>
#include <boost/math/distributions/normal.hpp>

using namespace std;

const vector<double> KERNEL = boost::assign::list_of(-2.7725887222397811)(-1.3862943611198906)(-0.98082925301172619)(-1.3862943611198906)(-2.7725887222397811);

FLD::FLD(double alpha, size_t max_val, size_t mean, size_t std_dev) :
    _hist(max_val+1),
    _tot_mass(HUGE_VAL),
    _sum(HUGE_VAL),
    _min(max_val)
{
    assert(KERNEL.size() % 2 == 1);
    boost::math::normal norm(mean, std_dev);

    double tot = log(alpha*max_val);

    for (size_t i = 1; i <= max_val; ++i)
    {
        double mass = tot + log(boost::math::cdf(norm,i+0.5) - boost::math::cdf(norm,i-0.5));
        _hist[i] = mass;
        _sum = log_sum(_sum, log((double)i)+mass);
        _tot_mass = log_sum(_tot_mass, mass);
    }
}

size_t FLD::max_val() const
{
    return _hist.size()-1;
}

void FLD::add_val(size_t len, double mass)
{
    WriteLock lock(_lock);

    if (len > max_val()) return;
    if (len < _min) _min = len;

    size_t offset = len - KERNEL.size()/2;

    for (size_t i = 0; i < KERNEL.size(); i++)
    {
        double k_mass = mass + KERNEL[i];
        _hist[offset] = log_sum(_hist[offset], k_mass);
        _sum = log_sum(_sum, log((double)offset++)+k_mass);
    }
    _tot_mass = log_sum(_tot_mass, mass);
}

double FLD::pdf(size_t len) const
{
    ReadLock lock(_lock);

    if (len < 1 || len > max_val())
        return HUGE_VAL;
    return _hist[len]-_tot_mass;
}

double FLD::tot_mass() const
{
    ReadLock lock(_lock);

    return _tot_mass;
}

double FLD::mean() const
{
    ReadLock lock(_lock);

    return _sum - tot_mass();
}

string FLD::to_string() const
{
    ReadLock lock(_lock);

    string s = "";
    char buffer[50];
    for(size_t i = 0; i <= max_val(); i++)
    {
        sprintf(buffer, "%e\t",sexp(pdf(i)));
        s += buffer;
    }
    s.erase(s.length()-1,1);
    return s;
}

void FLD::append_output(ofstream& outfile) const
{
    ReadLock lock(_lock);

    outfile << ">Fragment Length Distribution (0-" << max_val() << ")\n";
    outfile << to_string() << endl;
}
<commit_msg>Fixed buffer overrun in fld<commit_after>//
//  fld.cpp
//  express
//
//  Created by Adam Roberts on 3/20/11.
//  Copyright 2011 Adam Roberts. All rights reserved.
//

#include "fld.h"
#include "main.h"
#include <numeric>
#include <boost/assign.hpp>
#include <iostream>
#include <fstream>
#include <boost/math/distributions/normal.hpp>

using namespace std;

const vector<double> KERNEL = boost::assign::list_of(-2.7725887222397811)(-1.3862943611198906)(-0.98082925301172619)(-1.3862943611198906)(-2.7725887222397811);

FLD::FLD(double alpha, size_t max_val, size_t mean, size_t std_dev) :
    _hist(max_val+1),
    _tot_mass(HUGE_VAL),
    _sum(HUGE_VAL),
    _min(max_val)
{
    assert(KERNEL.size() % 2 == 1);
    boost::math::normal norm(mean, std_dev);

    double tot = log(alpha*max_val);

    for (size_t i = 1; i <= max_val; ++i)
    {
        double mass = tot + log(boost::math::cdf(norm,i+0.5) - boost::math::cdf(norm,i-0.5));
        _hist[i] = mass;
        _sum = log_sum(_sum, log((double)i)+mass);
        _tot_mass = log_sum(_tot_mass, mass);
    }
}

size_t FLD::max_val() const
{
    return _hist.size()-1;
}

void FLD::add_val(size_t len, double mass)
{
    WriteLock lock(_lock);

    if (len > max_val()) return;
    if (len < _min) _min = len;

    size_t offset = len - KERNEL.size()/2;

    for (size_t i = 0; i < KERNEL.size(); i++)
    {
        if (offset > 0 && offset <= max_val())
        {
            double k_mass = mass + KERNEL[i];
            _hist[offset] = log_sum(_hist[offset], k_mass);
            _sum = log_sum(_sum, log((double)offset)+k_mass);
        }
        offset++;
    }
    _tot_mass = log_sum(_tot_mass, mass);
}

double FLD::pdf(size_t len) const
{
    ReadLock lock(_lock);

    if (len < 1 || len > max_val())
        return HUGE_VAL;
    return _hist[len]-_tot_mass;
}

double FLD::tot_mass() const
{
    ReadLock lock(_lock);

    return _tot_mass;
}

double FLD::mean() const
{
    ReadLock lock(_lock);

    return _sum - tot_mass();
}

string FLD::to_string() const
{
    ReadLock lock(_lock);

    string s = "";
    char buffer[50];
    for(size_t i = 0; i <= max_val(); i++)
    {
        sprintf(buffer, "%e\t",sexp(pdf(i)));
        s += buffer;
    }
    s.erase(s.length()-1,1);
    return s;
}

void FLD::append_output(ofstream& outfile) const
{
    ReadLock lock(_lock);

    outfile << ">Fragment Length Distribution (0-" << max_val() << ")\n";
    outfile << to_string() << endl;
}
<|endoftext|>


<commit_before>/**
 * \file LMSFilter.cpp
 */

#include "LMSFilter.h"

#include <complex>
#include <cstdint>
#include <stdexcept>

#include <Eigen/Core>

#include <ATK/Core/TypeTraits.h>

namespace ATK
{
  template<typename DataType_>
  class LMSFilter<DataType_>::LMSFilterImpl
  {
  public:
    typedef Eigen::Matrix<DataType_, Eigen::Dynamic, 1> wType;
    typedef Eigen::Map<const wType> xType;

    wType w;
    /// Memory factor
    double alpha;
    /// line search
    double mu;

    LMSFilterImpl(std::size_t size)
    :w(wType::Zero(size, 1)), alpha(.99), mu(0.05)
    {
    }

    typedef void (LMSFilterImpl::*UpdateFunction)(const xType& x, DataType error);

    void update(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x;
    }

    void update_normalized(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x / (std::numeric_limits<DataType>::epsilon() + static_cast<DataType>(x.squaredNorm()));
    }

    void update_signerror(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x;
    }

    void update_signdata(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error * x.array() / (x.cwiseAbs().cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon()));
    }

    void update_signsign(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x.array() / (x.cwiseAbs().cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon()));
    }

    UpdateFunction select(Mode mode)
    {
      switch (mode)
      {
      case Mode::NORMAL:
        return &LMSFilterImpl::update;
      case Mode::NORMALIZED:
        return &LMSFilterImpl::update_normalized;
      case Mode::SIGNERROR:
        return &LMSFilterImpl::update_signerror;
      case Mode::SIGNDATA:
        return &LMSFilterImpl::update_signdata;
      case Mode::SIGNSIGN:
        return &LMSFilterImpl::update_signsign;

      default:
        return &LMSFilterImpl::update;
      }
    }
  };

  template<typename DataType_>
  LMSFilter<DataType_>::LMSFilter(std::size_t size)
  :Parent(2, 1), impl(new LMSFilterImpl(size)), mode(Mode::NORMAL), global_size(size)
  {
    input_delay = size + 1;
  }

  template<typename DataType_>
  LMSFilter<DataType_>::~LMSFilter()
  {
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_size(std::size_t size)
  {
    if(size == 0)
    {
      throw std::out_of_range("Size must be strictly positive");
    }

    input_delay = size+1;
    this->global_size = size;
  }

  template<typename DataType_>
  std::size_t LMSFilter<DataType_>::get_size() const
  {
    return global_size;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_memory(double memory)
  {
    if (memory >= 1)
    {
      throw std::out_of_range("Memory must be less than 1");
    }
    if (memory <= 0)
    {
      throw std::out_of_range("Memory must be strictly positive");
    }

    impl->alpha = memory;
  }

  template<typename DataType_>
  double LMSFilter<DataType_>::get_memory() const
  {
    return impl->alpha;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_mu(double mu)
  {
    if (mu >= 1)
    {
      throw std::out_of_range("Mu must be less than 1");
    }
    if (mu <= 0)
    {
      throw std::out_of_range("Mu must be strictly positive");
    }

    impl->mu = mu;
  }

  template<typename DataType_>
  double LMSFilter<DataType_>::get_mu() const
  {
    return impl->mu;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_mode(Mode mode)
  {
    this->mode = mode;
  }

  template<typename DataType_>
  typename LMSFilter<DataType_>::Mode LMSFilter<DataType_>::get_mode() const
  {
    return mode;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::process_impl(std::size_t size) const
  {
    const DataType* ATK_RESTRICT input = converted_inputs[0];
    const DataType* ATK_RESTRICT ref = converted_inputs[1];
    DataType* ATK_RESTRICT output = outputs[0];

    auto update_function = impl->select(mode);

    for(std::size_t i = 0; i < size; ++i)
    {
      typename LMSFilterImpl::xType x(input - global_size + i, global_size, 1);
      output[i] = impl->w.conjugate().dot(x);

      (impl.get()->*update_function)(x, TypeTraits<DataType>::conj(ref[i] - output[i]));
    }
  }

  template<typename DataType_>
  const DataType_* LMSFilter<DataType_>::get_w() const
  {
    return impl->w.data();
  }

  template class LMSFilter<float>;
  template class LMSFilter<double>;
  template class LMSFilter<std::complex<double>>;
}
<commit_msg>Allow complex<float> for LMS as well as complex<double><commit_after>/**
 * \file LMSFilter.cpp
 */

#include "LMSFilter.h"

#include <complex>
#include <cstdint>
#include <stdexcept>

#include <Eigen/Core>

#include <ATK/Core/TypeTraits.h>

namespace ATK
{
  template<typename DataType_>
  class LMSFilter<DataType_>::LMSFilterImpl
  {
  public:
    typedef Eigen::Matrix<DataType_, Eigen::Dynamic, 1> wType;
    typedef Eigen::Map<const wType> xType;

    wType w;
    /// Memory factor
    double alpha;
    /// line search
    double mu;

    LMSFilterImpl(std::size_t size)
    :w(wType::Zero(size, 1)), alpha(.99), mu(0.05)
    {
    }

    typedef void (LMSFilterImpl::*UpdateFunction)(const xType& x, DataType error);

    void update(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x;
    }

    void update_normalized(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error * x / (std::numeric_limits<DataType>::epsilon() + static_cast<DataType>(x.squaredNorm()));
    }

    void update_signerror(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x;
    }

    void update_signdata(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error * x.array() / (x.cwiseAbs().cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon()));
    }

    void update_signsign(const xType& x, DataType error)
    {
      w = static_cast<DataType>(alpha) * w.array() + static_cast<DataType>(mu) * error / (std::numeric_limits<DataType>::epsilon() + std::abs(error)) * x.array() / (x.cwiseAbs().cast<DataType>().array() + static_cast<DataType>(std::numeric_limits<DataType>::epsilon()));
    }

    UpdateFunction select(Mode mode)
    {
      switch (mode)
      {
      case Mode::NORMAL:
        return &LMSFilterImpl::update;
      case Mode::NORMALIZED:
        return &LMSFilterImpl::update_normalized;
      case Mode::SIGNERROR:
        return &LMSFilterImpl::update_signerror;
      case Mode::SIGNDATA:
        return &LMSFilterImpl::update_signdata;
      case Mode::SIGNSIGN:
        return &LMSFilterImpl::update_signsign;

      default:
        return &LMSFilterImpl::update;
      }
    }
  };

  template<typename DataType_>
  LMSFilter<DataType_>::LMSFilter(std::size_t size)
  :Parent(2, 1), impl(new LMSFilterImpl(size)), mode(Mode::NORMAL), global_size(size)
  {
    input_delay = size + 1;
  }

  template<typename DataType_>
  LMSFilter<DataType_>::~LMSFilter()
  {
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_size(std::size_t size)
  {
    if(size == 0)
    {
      throw std::out_of_range("Size must be strictly positive");
    }

    input_delay = size+1;
    this->global_size = size;
  }

  template<typename DataType_>
  std::size_t LMSFilter<DataType_>::get_size() const
  {
    return global_size;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_memory(double memory)
  {
    if (memory >= 1)
    {
      throw std::out_of_range("Memory must be less than 1");
    }
    if (memory <= 0)
    {
      throw std::out_of_range("Memory must be strictly positive");
    }

    impl->alpha = memory;
  }

  template<typename DataType_>
  double LMSFilter<DataType_>::get_memory() const
  {
    return impl->alpha;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_mu(double mu)
  {
    if (mu >= 1)
    {
      throw std::out_of_range("Mu must be less than 1");
    }
    if (mu <= 0)
    {
      throw std::out_of_range("Mu must be strictly positive");
    }

    impl->mu = mu;
  }

  template<typename DataType_>
  double LMSFilter<DataType_>::get_mu() const
  {
    return impl->mu;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::set_mode(Mode mode)
  {
    this->mode = mode;
  }

  template<typename DataType_>
  typename LMSFilter<DataType_>::Mode LMSFilter<DataType_>::get_mode() const
  {
    return mode;
  }

  template<typename DataType_>
  void LMSFilter<DataType_>::process_impl(std::size_t size) const
  {
    const DataType* ATK_RESTRICT input = converted_inputs[0];
    const DataType* ATK_RESTRICT ref = converted_inputs[1];
    DataType* ATK_RESTRICT output = outputs[0];

    auto update_function = impl->select(mode);

    for(std::size_t i = 0; i < size; ++i)
    {
      typename LMSFilterImpl::xType x(input - global_size + i, global_size, 1);
      output[i] = impl->w.conjugate().dot(x);

      (impl.get()->*update_function)(x, TypeTraits<DataType>::conj(ref[i] - output[i]));
    }
  }

  template<typename DataType_>
  const DataType_* LMSFilter<DataType_>::get_w() const
  {
    return impl->w.data();
  }

  template class LMSFilter<float>;
  template class LMSFilter<double>;
  template class LMSFilter<std::complex<float>>;
  template class LMSFilter<std::complex<double>>;
}
<|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*/

#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__

#include "cvconfig.h"

#include "opencv2/core/core.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/core/internal.hpp"

#include <assert.h>
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_TEGRA_OPTIMIZATION
#include "opencv2/core/core_tegra.hpp"
#else
#define GET_OPTIMIZED(func) (func)
#endif

namespace cv
{

// -128.f ... 255.f
extern const float g_8x32fTab[];
#define CV_8TO32F(x)  cv::g_8x32fTab[(x)+128]

extern const ushort g_8x16uSqrTab[];
#define CV_SQR_8U(x)  cv::g_8x16uSqrTab[(x)+255]

extern const char* g_HersheyGlyphs[];

extern const uchar g_Saturate8u[];
#define CV_FAST_CAST_8U(t)   (assert(-256 <= (t) && (t) <= 512), cv::g_Saturate8u[(t)+256])
#define CV_MIN_8U(a,b)       ((a) - CV_FAST_CAST_8U((a) - (b)))
#define CV_MAX_8U(a,b)       ((a) + CV_FAST_CAST_8U((b) - (a)))

#if defined WIN32 || defined _WIN32
void deleteThreadAllocData();
void deleteThreadRNGData();
#endif

template<typename T1, typename T2=T1, typename T3=T1> struct OpAdd
{
    typedef T1 type1;
    typedef T2 type2;
    typedef T3 rtype;
    T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a + b); }
};

template<typename T1, typename T2=T1, typename T3=T1> struct OpSub
{
    typedef T1 type1;
    typedef T2 type2;
    typedef T3 rtype;
    T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a - b); }
};

template<typename T1, typename T2=T1, typename T3=T1> struct OpRSub
{
    typedef T1 type1;
    typedef T2 type2;
    typedef T3 rtype;
    T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(b - a); }
};

template<typename T> struct OpMin
{
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator ()(const T a, const T b) const { return std::min(a, b); }
};

template<typename T> struct OpMax
{
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator ()(const T a, const T b) const { return std::max(a, b); }
};

inline Size getContinuousSize( const Mat& m1, int widthScale=1 )
{
    CV_Assert(m1.dims <= 2);
    return m1.isContinuous() ? Size(m1.cols*m1.rows*widthScale, 1) :
        Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2, int widthScale=1 )
{
    CV_Assert(m1.dims <= 2 && m1.size() == m2.size());
    return (m1.flags & m2.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2,
                               const Mat& m3, int widthScale=1 )
{
    CV_Assert(m1.dims <= 2 && m1.size() == m2.size() && m1.size() == m3.size());
    return (m1.flags & m2.flags & m3.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2,
                               const Mat& m3, const Mat& m4,
                               int widthScale=1 )
{
    CV_Assert(m1.dims <= 2 && m1.size() == m2.size() && m1.size() == m3.size() && m1.size() == m4.size());
    return (m1.flags & m2.flags & m3.flags & m4.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2,
                               const Mat& m3, const Mat& m4,
                               const Mat& m5, int widthScale=1 )
{
    CV_Assert(m1.dims <= 2 && m1.size() == m2.size() && m1.size() == m3.size() && m1.size() == m4.size() && m1.size() == m5.size());
    return (m1.flags & m2.flags & m3.flags & m4.flags & m5.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

struct NoVec
{
    size_t operator()(const void*, const void*, void*, size_t) const { return 0; }
};

extern volatile bool USE_SSE2;
extern volatile bool USE_SSE4_2;
extern volatile bool USE_AVX;

enum { BLOCK_SIZE = 1024 };

#ifdef HAVE_IPP
static inline IppiSize ippiSize(int width, int height) { IppiSize sz = { width, height}; return sz; }
static inline IppiSize ippiSize(Size _sz)              { IppiSize sz = { _sz.width, _sz.height}; return sz; }
#endif

#if defined HAVE_IPP && (IPP_VERSION_MAJOR >= 7)
#define ARITHM_USE_IPP 1
#define IF_IPP(then_call, else_call) then_call
#else
#define ARITHM_USE_IPP 0
#define IF_IPP(then_call, else_call) else_call
#endif

inline bool checkScalar(const Mat& sc, int atype, int sckind, int akind)
{
    if( sc.dims > 2 || (sc.cols != 1 && sc.rows != 1) || !sc.isContinuous() )
        return false;
    int cn = CV_MAT_CN(atype);
    if( akind == _InputArray::MATX && sckind != _InputArray::MATX )
        return false;
    return sc.size() == Size(1, 1) || sc.size() == Size(1, cn) || sc.size() == Size(cn, 1) ||
           (sc.size() == Size(1, 4) && sc.type() == CV_64F && cn <= 4);
}

void convertAndUnrollScalar( const Mat& sc, int buftype, uchar* scbuf, size_t blocksize );

}

#endif /*_CXCORE_INTERNAL_H_*/
<commit_msg>Revert "fixed bug #3319"<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*/

#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__

#include "cvconfig.h"

#include "opencv2/core/core.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/core/internal.hpp"

#include <assert.h>
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_TEGRA_OPTIMIZATION
#include "opencv2/core/core_tegra.hpp"
#else
#define GET_OPTIMIZED(func) (func)
#endif

namespace cv
{

// -128.f ... 255.f
extern const float g_8x32fTab[];
#define CV_8TO32F(x)  cv::g_8x32fTab[(x)+128]

extern const ushort g_8x16uSqrTab[];
#define CV_SQR_8U(x)  cv::g_8x16uSqrTab[(x)+255]

extern const char* g_HersheyGlyphs[];

extern const uchar g_Saturate8u[];
#define CV_FAST_CAST_8U(t)   (assert(-256 <= (t) && (t) <= 512), cv::g_Saturate8u[(t)+256])
#define CV_MIN_8U(a,b)       ((a) - CV_FAST_CAST_8U((a) - (b)))
#define CV_MAX_8U(a,b)       ((a) + CV_FAST_CAST_8U((b) - (a)))

#if defined WIN32 || defined _WIN32
void deleteThreadAllocData();
void deleteThreadRNGData();
#endif

template<typename T1, typename T2=T1, typename T3=T1> struct OpAdd
{
    typedef T1 type1;
    typedef T2 type2;
    typedef T3 rtype;
    T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a + b); }
};

template<typename T1, typename T2=T1, typename T3=T1> struct OpSub
{
    typedef T1 type1;
    typedef T2 type2;
    typedef T3 rtype;
    T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a - b); }
};

template<typename T1, typename T2=T1, typename T3=T1> struct OpRSub
{
    typedef T1 type1;
    typedef T2 type2;
    typedef T3 rtype;
    T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(b - a); }
};

template<typename T> struct OpMin
{
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator ()(const T a, const T b) const { return std::min(a, b); }
};

template<typename T> struct OpMax
{
    typedef T type1;
    typedef T type2;
    typedef T rtype;
    T operator ()(const T a, const T b) const { return std::max(a, b); }
};

inline Size getContinuousSize( const Mat& m1, int widthScale=1 )
{
    return m1.isContinuous() ? Size(m1.cols*m1.rows*widthScale, 1) :
        Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2, int widthScale=1 )
{
    return (m1.flags & m2.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2,
                               const Mat& m3, int widthScale=1 )
{
    return (m1.flags & m2.flags & m3.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2,
                               const Mat& m3, const Mat& m4,
                               int widthScale=1 )
{
    return (m1.flags & m2.flags & m3.flags & m4.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

inline Size getContinuousSize( const Mat& m1, const Mat& m2,
                               const Mat& m3, const Mat& m4,
                               const Mat& m5, int widthScale=1 )
{
    return (m1.flags & m2.flags & m3.flags & m4.flags & m5.flags & Mat::CONTINUOUS_FLAG) != 0 ?
        Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows);
}

struct NoVec
{
    size_t operator()(const void*, const void*, void*, size_t) const { return 0; }
};

extern volatile bool USE_SSE2;
extern volatile bool USE_SSE4_2;
extern volatile bool USE_AVX;

enum { BLOCK_SIZE = 1024 };

#ifdef HAVE_IPP
static inline IppiSize ippiSize(int width, int height) { IppiSize sz = { width, height}; return sz; }
static inline IppiSize ippiSize(Size _sz)              { IppiSize sz = { _sz.width, _sz.height}; return sz; }
#endif

#if defined HAVE_IPP && (IPP_VERSION_MAJOR >= 7)
#define ARITHM_USE_IPP 1
#define IF_IPP(then_call, else_call) then_call
#else
#define ARITHM_USE_IPP 0
#define IF_IPP(then_call, else_call) else_call
#endif

inline bool checkScalar(const Mat& sc, int atype, int sckind, int akind)
{
    if( sc.dims > 2 || (sc.cols != 1 && sc.rows != 1) || !sc.isContinuous() )
        return false;
    int cn = CV_MAT_CN(atype);
    if( akind == _InputArray::MATX && sckind != _InputArray::MATX )
        return false;
    return sc.size() == Size(1, 1) || sc.size() == Size(1, cn) || sc.size() == Size(cn, 1) ||
           (sc.size() == Size(1, 4) && sc.type() == CV_64F && cn <= 4);
}

void convertAndUnrollScalar( const Mat& sc, int buftype, uchar* scbuf, size_t blocksize );

}

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


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 tdzl2003.
** Contact: https://github.com/tdzl2003/luaqt
**
** This file is part of the LuaQt Toolkit source.
**
** This file is licensed at BSD New license.
**
** NOTICE:
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.**
**
** read COPYRIGHT.md for more informations.
**
****************************************************************************/

#pragma once

#include <lua.hpp>

// Utility functions
inline void luaL_regfuncs(lua_State*L, luaL_Reg* reg, size_t count)
{
	for (size_t i =0; i < count; ++i)
	{
		lua_pushcfunction(L, reg[i].func);
		lua_setfield(L, -2, reg[i].name);
	}
}

#define luaL_newlib(l, m)  lua_createtable(l, 0, sizeof(m)/sizeof(m[0]) - 1); luaL_regfuncs(l, m, sizeof(m)/sizeof(m[0]) - 1)

namespace LuaQt{
	void saveGlobalState(lua_State *L);
	lua_State* getGlobalState(lua_State *L);
}

// Weak ref functions
namespace LuaQt{
	int weakref(lua_State *L);
	void getweakref(lua_State *L, int id);
	void weakunref(lua_State *L, int id);
}

// Object life-cycle functions
class QObject;
namespace LuaQt{
	bool isObject(lua_State *L, int idx, const char* className);
	void* checkObject(lua_State *L, int idx, const char* className);

	void PushObject(lua_State *L, QObject* obj);
	void InitAndPushObject(lua_State *L, QObject* obj, void* ptr, const char* className);

	void InitGCer(lua_State *L);
}

// Meta functions:
namespace LuaQt{
	int General_index(lua_State *L);
	int General_newindex(lua_State *L);
}

// Argument helper functions&macros
namespace LuaQt
{
	template <typename T>
	class ArgHelper
	{
	public:
		static bool CheckArg(lua_State *L, int idx);
		static T GetArg(lua_State *L, int idx);
		static void pushRetVal(lua_State*L, const T& val);
		static void pushRetVal(lua_State*L, T&& val);
	};

	void StartArgRefFrame(lua_State *L);
	void EndArgRefFrame(lua_State *L);

	void* allocArgRef(lua_State *L, size_t size);
}

#define CHECK_ARG_COUNT(c) if (lua_gettop(L) != c) { break; }
#define CHECK_ARG(t, i) if (!LuaQt::ArgHelper<t>::CheckArg(L, i)) { break;}
#define GET_ARG(t, i, n) t n = LuaQt::ArgHelper<t>::GetArg(L, i)

#define CHECK_METHOD_ARG_COUNT(c) if (lua_gettop(L) != c+1) { break; }
#define CHECK_METHOD_ARG(t, i) if (!LuaQt::ArgHelper<t>::CheckArg(L, i+1)) { break;}
#define GET_METHOD_ARG(t, i, n) t n = LuaQt::ArgHelper<t>::GetArg(L, i+1)

#define START_ARGREF_FRAME() LuaQt::StartArgRefFrame(L)
#define END_ARGREF_FRAME() LuaQt::EndArgRefFrame(L)
#define PUSH_RET_VAL(t, v) LuaQt::ArgHelper<t>::pushRetVal(L, v)
<commit_msg>add STR() macro and remove_ref class<commit_after>/****************************************************************************
**
** Copyright (C) 2013 tdzl2003.
** Contact: https://github.com/tdzl2003/luaqt
**
** This file is part of the LuaQt Toolkit source.
**
** This file is licensed at BSD New license.
**
** NOTICE:
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
** INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
** CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
** ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.**
**
** read COPYRIGHT.md for more informations.
**
****************************************************************************/

#pragma once

#include <lua.hpp>

// Utility functions
inline void luaL_regfuncs(lua_State*L, luaL_Reg* reg, size_t count)
{
	for (size_t i =0; i < count; ++i)
	{
		lua_pushcfunction(L, reg[i].func);
		lua_setfield(L, -2, reg[i].name);
	}
}

#define luaL_newlib(l, m)  lua_createtable(l, 0, sizeof(m)/sizeof(m[0]) - 1); luaL_regfuncs(l, m, sizeof(m)/sizeof(m[0]) - 1)
#define STR(x) #x

namespace LuaQt{
	void saveGlobalState(lua_State *L);
	lua_State* getGlobalState(lua_State *L);
}

// Weak ref functions
namespace LuaQt{
	int weakref(lua_State *L);
	void getweakref(lua_State *L, int id);
	void weakunref(lua_State *L, int id);
}

// Object life-cycle functions
class QObject;
namespace LuaQt{
	bool isObject(lua_State *L, int idx, const char* className);
	void* checkObject(lua_State *L, int idx, const char* className);

	void PushObject(lua_State *L, QObject* obj);
	void InitAndPushObject(lua_State *L, QObject* obj, void* ptr, const char* className);

	void InitGCer(lua_State *L);
}

// Meta functions:
namespace LuaQt{
	int General_index(lua_State *L);
	int General_newindex(lua_State *L);
}

// Argument helper functions&macros
namespace LuaQt
{
	template <typename T>
	class ArgHelper
	{
	public:
		static bool CheckArg(lua_State *L, int idx);
		static T GetArg(lua_State *L, int idx);
		static void pushRetVal(lua_State*L, const T& val);
		static void pushRetVal(lua_State*L, T&& val);
	};

	void StartArgRefFrame(lua_State *L);
	void EndArgRefFrame(lua_State *L);

	void* allocArgRef(lua_State *L, size_t size);

	template <typename T>
	class remove_ref
	{
	public:
		typedef T type;
	};

	template <typename T>
	class remove_ref<T&>
	{
	public:
		typedef T type;
	};

	template <typename T>
	class remove_ref<const T&>
	{
	public:
		typedef T type;
	};

	template <typename T>
	class remove_ref<T&&>
	{
	public:
		typedef T type;
	};
}

#define CHECK_ARG_COUNT(c) if (lua_gettop(L) != c) { break; }
#define CHECK_ARG(t, i) if (!LuaQt::ArgHelper<LuaQt::remove_ref<t>::type>::CheckArg(L, i)) { break;}
#define GET_ARG(t, i, n) LuaQt::remove_ref<t>::type n = LuaQt::ArgHelper<LuaQt::remove_ref<t>::type>::GetArg(L, i)

#define CHECK_METHOD_ARG_COUNT(c) if (lua_gettop(L) != c+1) { break; }
#define CHECK_METHOD_ARG(t, i) if (!LuaQt::ArgHelper<LuaQt::remove_ref<t>::type>::CheckArg(L, i+1)) { break;}
#define GET_METHOD_ARG(t, i, n) LuaQt::remove_ref<t>::type n = LuaQt::ArgHelper<LuaQt::remove_ref<t>::type>::GetArg(L, i+1)

#define START_ARGREF_FRAME() LuaQt::StartArgRefFrame(L)
#define END_ARGREF_FRAME() LuaQt::EndArgRefFrame(L)
#define PUSH_RET_VAL(t, v) LuaQt::ArgHelper<t>::pushRetVal(L, v)
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993-2010 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// ServerControl.cpp : Server shutdown and ban file control
//

#include <string>
#include <fstream>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "bzfsAPI.h"
#include "plugin_utils.h"

BZ_GET_PLUGIN_VERSION

using namespace std;

enum action { join , part };

class ServerControl : public bz_EventHandler
{
public:
  ServerControl() {};
  virtual ~ServerControl() {};
  virtual void process( bz_EventData *eventData );
  int loadConfig(const char *cmdLine);
private:
  void countPlayers( action act, bz_PlayerJoinPartEventData *data );
  void checkShutdown( void );
  void checkBanChanges( void );
  void checkMasterBanChanges( void );
  void fileAccessTime(const std::string filename, time_t *mtime);
  string banFilename;
  string masterBanFilename;
  string resetServerOnceFilename;
  string resetServerAlwaysFilename;
  string banReloadMessage;
  string masterBanReloadMessage;
  time_t banFileAccessTime;
  time_t masterBanFileAccessTime;
  int numPlayers;
  int numObservers;
  bool serverActive;
  bool ignoreObservers;
};

ServerControl serverControlHandler;

BZF_PLUGIN_CALL int bz_Load ( const char* cmdLine)
{
  if (serverControlHandler.loadConfig(cmdLine) < 0) return -1;

  bz_registerEvent(bz_ePlayerJoinEvent, &serverControlHandler);
  bz_registerEvent(bz_ePlayerPartEvent, &serverControlHandler);
  bz_registerEvent(bz_eTickEvent, &serverControlHandler);
  bz_setMaxWaitTime( 3.0 );
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload ( void )
{
  bz_removeEvent(bz_ePlayerJoinEvent, &serverControlHandler);
  bz_removeEvent(bz_ePlayerPartEvent, &serverControlHandler);
  bz_removeEvent(bz_eTickEvent, &serverControlHandler);
  return 0;
}

int ServerControl::loadConfig(const char *cmdLine)
{
  PluginConfig config = PluginConfig(cmdLine);
  string section = "ServerControl";

  if (config.errors) return -1;

  serverActive = false;
  countPlayers( join , NULL );

  /*
   * Set up options from the configuration file
   */
  banFilename = config.item(section, "BanFile");
  masterBanFilename = config.item(section, "MasterBanFile");
  resetServerOnceFilename = config.item(section, "ResetServerOnceFile");
  resetServerAlwaysFilename = config.item(section, "ResetServerAlwaysFile");
  banReloadMessage = config.item(section, "BanReloadMessage");
  masterBanReloadMessage = config.item(section, "MasterBanReloadMessage");
  ignoreObservers = (config.item(section, "IgnoreObservers") != "");

  /*
   * Report settings
   */
  // Ban file
  if (banFilename == "")
    bz_debugMessagef(1, "ServerControl - No banfile checks - no BanFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Monitoring ban file: %s", banFilename.c_str());
  // Ban reload message
  if (banReloadMessage == "")
    bz_debugMessagef(1, "ServerControl - No BanReloadMessage notification");
  else
    bz_debugMessagef(1, "ServerControl - BanReloadMessage: %s", banReloadMessage.c_str());
  // Masterban file
  if (masterBanFilename == "")
    bz_debugMessagef(1, "ServerControl - No masterban file checks - no MasterbanFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Monitoring master ban file: %s", masterBanFilename.c_str());
  // Master Ban reload message
  if (masterBanReloadMessage == "")
    bz_debugMessagef(1, "ServerControl - No MasterBanReloadMessage notification");
  else
    bz_debugMessagef(1, "ServerControl - MasterBanReloadMessage: %s", masterBanReloadMessage.c_str());
  // Reset Server Once file
  if (resetServerOnceFilename == "")
    bz_debugMessagef(1, "ServerControl - No ResetServerOnceFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Using ResetServerOnceFile: %s", resetServerOnceFilename.c_str());
  // Reset Server Always file
  if (resetServerAlwaysFilename == "")
    bz_debugMessagef(1, "ServerControl - No ResetServerAlwaysFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Using ResetServerAlwaysFile: %s", resetServerAlwaysFilename.c_str());

  // Ignore Observers
  if (ignoreObservers)
    bz_debugMessage(1, "ServerControl - Ignoring Observers for server restarts");
  else
    bz_debugMessage(1, "ServerControl - Server must be empty for server restarts");

  /* Set the initial ban file access times */
  if (masterBanFilename != "")
    fileAccessTime(masterBanFilename, &masterBanFileAccessTime);
  if (banFilename != "")
    fileAccessTime(banFilename, &banFileAccessTime);

  return 0;
}

void ServerControl::fileAccessTime(const std::string filename, time_t *mtime)
{
  struct stat buf;

  if (stat(filename.c_str(), &buf) == 0) {
    *mtime = buf.st_mtime;
  } else {
    *mtime = 0;
    bz_debugMessagef(0, "ServerControl - Can't stat the banfile %s",
		     filename.c_str());
  }
}

void ServerControl::checkShutdown( void ) {
  // Check for server shutdown
  //
  // We shutdown the server in the following cases:
  //   The server has no players and
  //     the reset server once file exists OR
  //     the reset server always file exists and someone was on the server
  //
  if ((numPlayers <= 0) || (ignoreObservers && (numPlayers - numObservers) <= 0)) { // No players
    if (resetServerOnceFilename != "") {
      std::ifstream resetOnce( resetServerOnceFilename.c_str() );
      if (resetOnce) { // Reset server once exists
	resetOnce.close();
	remove( resetServerOnceFilename.c_str() );
	bz_debugMessagef(2, "ServerControl - Reset Server Once - SHUTDOWN");
	bz_shutdown();
      } else if (resetServerAlwaysFilename != "" && serverActive) {
	// Server was active - some non-observer player connected
	std::ifstream resetAlways( resetServerAlwaysFilename.c_str() );
	if (resetAlways) { // Reset server always exists
	  resetAlways.close();
	  bz_debugMessagef(2, "ServerControl - Reset Server Always - SHUTDOWN");
	  bz_shutdown();
	}
      }
    }
  }
}

void ServerControl::process( bz_EventData *eventData )
{
  ostringstream msg;
  bz_PlayerJoinPartEventData *data = (bz_PlayerJoinPartEventData *) eventData;

  if (eventData) {
    switch (eventData->eventType) {
      case bz_eTickEvent:
	checkShutdown();
	if (banFilename != "" )
	  checkBanChanges();
	if (masterBanFilename != "")
	  checkMasterBanChanges();
	break;
      case bz_ePlayerJoinEvent:
	if (data->team >= eRogueTeam &&
	    data->team <= eHunterTeam &&
	    data->callsign != "")  {
	  serverActive = true;
	}
	countPlayers( join , data );
	break;
      case bz_ePlayerPartEvent:
	countPlayers( part , data );
	checkShutdown();
	break;
      default :
	break;
    }
  }
}

void ServerControl::countPlayers(action act , bz_PlayerJoinPartEventData *data)
{
  bzAPIIntList *playerList = bz_newIntList();
  bz_PlayerRecord *player;
  ostringstream msg;
  string str;
  int numLines = 0;
  int numObs = 0;

  bz_getPlayerIndexList( playerList );

  for ( unsigned int i = 0; i < playerList->size(); i++ ) {
    player = bz_getPlayerByIndex( playerList->get(i));
    if (player) {
      if (act == join || (data && (player->playerID != data->playerID) &&
			  (player->callsign != ""))) {
	if (player->callsign != "") {
	  if (player->team == eObservers)
	    numObs++;
	  numLines++;
	}
      }
      bz_freePlayerRecord( player );
    }
  }
  numPlayers = numLines;
  numObservers = numObs;
  bz_debugMessagef(2, "serverControl - %d total players, %d observers", numPlayers, numObservers);
  bz_deleteIntList(playerList);
}

void ServerControl::checkBanChanges( void )
{
  time_t mtime;
  fileAccessTime(banFilename, &mtime);

  if (mtime != banFileAccessTime) {
    banFileAccessTime = mtime;
    bz_debugMessagef(1, "serverControl - ban file changed - reloading...");
    bz_reloadLocalBans();
    bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, banReloadMessage.c_str());
  }
}

void ServerControl::checkMasterBanChanges( void )
{
  time_t mtime;
  fileAccessTime(masterBanFilename, &mtime);
  if (mtime != masterBanFileAccessTime) {
    masterBanFileAccessTime = mtime;
    bz_debugMessagef(1, "serverControl: master ban file changed - reloading...");
    bz_reloadMasterBans();
    bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, masterBanReloadMessage.c_str());
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Only report ban file access errors once<commit_after>/* bzflag
 * Copyright (c) 1993-2010 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// ServerControl.cpp : Server shutdown and ban file control
//

#include <string>
#include <fstream>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "bzfsAPI.h"
#include "plugin_utils.h"

BZ_GET_PLUGIN_VERSION

using namespace std;

enum action { join , part };

class ServerControl : public bz_EventHandler
{
public:
  ServerControl() {};
  virtual ~ServerControl() {};
  virtual void process( bz_EventData *eventData );
  int loadConfig(const char *cmdLine);
private:
  void countPlayers( action act, bz_PlayerJoinPartEventData *data );
  void checkShutdown( void );
  void checkBanChanges( void );
  void checkMasterBanChanges( void );
  void fileAccessTime(const std::string filename, time_t *mtime, bool *error);
  string banFilename;
  string masterBanFilename;
  string resetServerOnceFilename;
  string resetServerAlwaysFilename;
  string banReloadMessage;
  string masterBanReloadMessage;
  time_t banFileAccessTime;
  bool banFileErrorLogged;
  time_t masterBanFileAccessTime;
  bool masterBanErrorLogged;
  int numPlayers;
  int numObservers;
  bool serverActive;
  bool ignoreObservers;
};

ServerControl serverControlHandler;

BZF_PLUGIN_CALL int bz_Load ( const char* cmdLine)
{
  if (serverControlHandler.loadConfig(cmdLine) < 0) return -1;

  bz_registerEvent(bz_ePlayerJoinEvent, &serverControlHandler);
  bz_registerEvent(bz_ePlayerPartEvent, &serverControlHandler);
  bz_registerEvent(bz_eTickEvent, &serverControlHandler);
  bz_setMaxWaitTime( 3.0 );
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload ( void )
{
  bz_removeEvent(bz_ePlayerJoinEvent, &serverControlHandler);
  bz_removeEvent(bz_ePlayerPartEvent, &serverControlHandler);
  bz_removeEvent(bz_eTickEvent, &serverControlHandler);
  return 0;
}

int ServerControl::loadConfig(const char *cmdLine)
{
  PluginConfig config = PluginConfig(cmdLine);
  string section = "ServerControl";

  if (config.errors) return -1;

  serverActive = false;
  countPlayers( join , NULL );

  /*
   * Set up options from the configuration file
   */
  banFilename = config.item(section, "BanFile");
  masterBanFilename = config.item(section, "MasterBanFile");
  resetServerOnceFilename = config.item(section, "ResetServerOnceFile");
  resetServerAlwaysFilename = config.item(section, "ResetServerAlwaysFile");
  banReloadMessage = config.item(section, "BanReloadMessage");
  masterBanReloadMessage = config.item(section, "MasterBanReloadMessage");
  ignoreObservers = (config.item(section, "IgnoreObservers") != "");

  /*
   * Report settings
   */
  // Ban file
  if (banFilename == "")
    bz_debugMessagef(1, "ServerControl - No banfile checks - no BanFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Monitoring ban file: %s", banFilename.c_str());
  // Ban reload message
  if (banReloadMessage == "")
    bz_debugMessagef(1, "ServerControl - No BanReloadMessage notification");
  else
    bz_debugMessagef(1, "ServerControl - BanReloadMessage: %s", banReloadMessage.c_str());
  // Masterban file
  if (masterBanFilename == "")
    bz_debugMessagef(1, "ServerControl - No masterban file checks - no MasterbanFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Monitoring master ban file: %s", masterBanFilename.c_str());
  // Master Ban reload message
  if (masterBanReloadMessage == "")
    bz_debugMessagef(1, "ServerControl - No MasterBanReloadMessage notification");
  else
    bz_debugMessagef(1, "ServerControl - MasterBanReloadMessage: %s", masterBanReloadMessage.c_str());
  // Reset Server Once file
  if (resetServerOnceFilename == "")
    bz_debugMessagef(1, "ServerControl - No ResetServerOnceFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Using ResetServerOnceFile: %s", resetServerOnceFilename.c_str());
  // Reset Server Always file
  if (resetServerAlwaysFilename == "")
    bz_debugMessagef(1, "ServerControl - No ResetServerAlwaysFile specified");
  else
    bz_debugMessagef(1, "ServerControl - Using ResetServerAlwaysFile: %s", resetServerAlwaysFilename.c_str());

  // Ignore Observers
  if (ignoreObservers)
    bz_debugMessage(1, "ServerControl - Ignoring Observers for server restarts");
  else
    bz_debugMessage(1, "ServerControl - Server must be empty for server restarts");

  /* Set the initial ban file access times */
  masterBanErrorLogged = false;
  banFileErrorLogged = false;
  if (masterBanFilename != "")
    fileAccessTime(masterBanFilename, &masterBanFileAccessTime, &masterBanErrorLogged);
  if (banFilename != "")
    fileAccessTime(banFilename, &banFileAccessTime, &banFileErrorLogged);

  return 0;
}

void ServerControl::fileAccessTime(const std::string filename, time_t *mtime, bool *error)
{
  struct stat buf;

  if (stat(filename.c_str(), &buf) == 0) {
    *mtime = buf.st_mtime;
    *error = false;
  } else {
    *mtime = 0;
    if (!*error) {
      bz_debugMessagef(0, "ServerControl - Can't stat the banfile %s",
		       filename.c_str());
      *error = true;
    }
  }
}

void ServerControl::checkShutdown( void ) {
  // Check for server shutdown
  //
  // We shutdown the server in the following cases:
  //   The server has no players and
  //     the reset server once file exists OR
  //     the reset server always file exists and someone was on the server
  //
  if ((numPlayers <= 0) || (ignoreObservers && (numPlayers - numObservers) <= 0)) { // No players
    if (resetServerOnceFilename != "") {
      std::ifstream resetOnce( resetServerOnceFilename.c_str() );
      if (resetOnce) { // Reset server once exists
	resetOnce.close();
	remove( resetServerOnceFilename.c_str() );
	bz_debugMessagef(2, "ServerControl - Reset Server Once - SHUTDOWN");
	bz_shutdown();
      } else if (resetServerAlwaysFilename != "" && serverActive) {
	// Server was active - some non-observer player connected
	std::ifstream resetAlways( resetServerAlwaysFilename.c_str() );
	if (resetAlways) { // Reset server always exists
	  resetAlways.close();
	  bz_debugMessagef(2, "ServerControl - Reset Server Always - SHUTDOWN");
	  bz_shutdown();
	}
      }
    }
  }
}

void ServerControl::process( bz_EventData *eventData )
{
  ostringstream msg;
  bz_PlayerJoinPartEventData *data = (bz_PlayerJoinPartEventData *) eventData;

  if (eventData) {
    switch (eventData->eventType) {
      case bz_eTickEvent:
	checkShutdown();
	if (banFilename != "" )
	  checkBanChanges();
	if (masterBanFilename != "")
	  checkMasterBanChanges();
	break;
      case bz_ePlayerJoinEvent:
	if (data->team >= eRogueTeam &&
	    data->team <= eHunterTeam &&
	    data->callsign != "")  {
	  serverActive = true;
	}
	countPlayers( join , data );
	break;
      case bz_ePlayerPartEvent:
	countPlayers( part , data );
	checkShutdown();
	break;
      default :
	break;
    }
  }
}

void ServerControl::countPlayers(action act , bz_PlayerJoinPartEventData *data)
{
  bzAPIIntList *playerList = bz_newIntList();
  bz_PlayerRecord *player;
  ostringstream msg;
  string str;
  int numLines = 0;
  int numObs = 0;

  bz_getPlayerIndexList( playerList );

  for ( unsigned int i = 0; i < playerList->size(); i++ ) {
    player = bz_getPlayerByIndex( playerList->get(i));
    if (player) {
      if (act == join || (data && (player->playerID != data->playerID) &&
			  (player->callsign != ""))) {
	if (player->callsign != "") {
	  if (player->team == eObservers)
	    numObs++;
	  numLines++;
	}
      }
      bz_freePlayerRecord( player );
    }
  }
  numPlayers = numLines;
  numObservers = numObs;
  bz_debugMessagef(2, "serverControl - %d total players, %d observers", numPlayers, numObservers);
  bz_deleteIntList(playerList);
}

void ServerControl::checkBanChanges( void )
{
  time_t mtime;
  fileAccessTime(banFilename, &mtime, &banFileErrorLogged);

  if (mtime != banFileAccessTime) {
    banFileAccessTime = mtime;
    bz_debugMessagef(1, "serverControl - ban file changed - reloading...");
    bz_reloadLocalBans();
    bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, banReloadMessage.c_str());
  }
}

void ServerControl::checkMasterBanChanges( void )
{
  time_t mtime;
  fileAccessTime(masterBanFilename, &mtime, &masterBanErrorLogged);
  if (mtime != masterBanFileAccessTime) {
    masterBanFileAccessTime = mtime;
    bz_debugMessagef(1, "serverControl: master ban file changed - reloading...");
    bz_reloadMasterBans();
    bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, masterBanReloadMessage.c_str());
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before><commit_msg>net: replicate r62288 in DnsRRResolver<commit_after><|endoftext|>


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

#include "net/base/net_util.h"

#include <sys/types.h>

#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"

#if !defined(OS_ANDROID)
#include <ifaddrs.h>
#endif

namespace net {

bool FileURLToFilePath(const GURL& url, FilePath* path) {
  *path = FilePath();
  std::string& file_path_str = const_cast<std::string&>(path->value());
  file_path_str.clear();

  if (!url.is_valid())
    return false;

  // Firefox seems to ignore the "host" of a file url if there is one. That is,
  // file://foo/bar.txt maps to /bar.txt.
  // TODO(dhg): This should probably take into account UNCs which could
  // include a hostname other than localhost or blank
  std::string old_path = url.path();

  if (old_path.empty())
    return false;

  // GURL stores strings as percent-encoded 8-bit, this will undo if possible.
  old_path = UnescapeURLComponent(old_path,
      UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);

  // Collapse multiple path slashes into a single path slash.
  std::string new_path;
  do {
    new_path = old_path;
    ReplaceSubstringsAfterOffset(&new_path, 0, "//", "/");
    old_path.swap(new_path);
  } while (new_path != old_path);

  file_path_str.assign(old_path);

  return !file_path_str.empty();
}

bool GetNetworkList(NetworkInterfaceList* networks) {
#if defined(OS_ANDROID)
  // TODO: Android API doesn't support ifaddrs. This method was only used by
  // P2PMessage. Consider to implement it until really needed. The possible
  // approach is implementing the similar feature by
  // java.net.NetworkInterface through JNI.
  NOTIMPLEMENTED();
  return false;
#else
  // getifaddrs() may require IO operations.
  base::ThreadRestrictions::AssertIOAllowed();

  ifaddrs *ifaddr;
  if (getifaddrs(&ifaddr) < 0) {
    PLOG(ERROR) << "getifaddrs";
    return false;
  }

  for (ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
    if (!ifa->ifa_addr)
      continue; // Interface has no IP addresses, so skip it.
    int family = ifa->ifa_addr->sa_family;
    if (family == AF_INET || family == AF_INET6) {
      IPEndPoint address;
      std::string name = ifa->ifa_name;
      if (address.FromSockAddr(ifa->ifa_addr,
                               sizeof(ifa->ifa_addr)) &&
          name.substr(0, 2) != "lo") {
        networks->push_back(NetworkInterface(name, address.address()));
      }
    }
  }

  freeifaddrs(ifaddr);

  return true;
#endif
}

}  // namespace net
<commit_msg>Cleanup GetNetworkList.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/net_util.h"

#include <sys/types.h>

#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"

#if !defined(OS_ANDROID)
#include <ifaddrs.h>
#endif
#include <net/if.h>
#include <netinet/in.h>

namespace net {

bool FileURLToFilePath(const GURL& url, FilePath* path) {
  *path = FilePath();
  std::string& file_path_str = const_cast<std::string&>(path->value());
  file_path_str.clear();

  if (!url.is_valid())
    return false;

  // Firefox seems to ignore the "host" of a file url if there is one. That is,
  // file://foo/bar.txt maps to /bar.txt.
  // TODO(dhg): This should probably take into account UNCs which could
  // include a hostname other than localhost or blank
  std::string old_path = url.path();

  if (old_path.empty())
    return false;

  // GURL stores strings as percent-encoded 8-bit, this will undo if possible.
  old_path = UnescapeURLComponent(old_path,
      UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);

  // Collapse multiple path slashes into a single path slash.
  std::string new_path;
  do {
    new_path = old_path;
    ReplaceSubstringsAfterOffset(&new_path, 0, "//", "/");
    old_path.swap(new_path);
  } while (new_path != old_path);

  file_path_str.assign(old_path);

  return !file_path_str.empty();
}

bool GetNetworkList(NetworkInterfaceList* networks) {
#if defined(OS_ANDROID)
  // TODO: Android API doesn't support ifaddrs. This method was only used by
  // P2PMessage. Consider to implement it until really needed. The possible
  // approach is implementing the similar feature by
  // java.net.NetworkInterface through JNI.
  NOTIMPLEMENTED();
  return false;
#else
  // getifaddrs() may require IO operations.
  base::ThreadRestrictions::AssertIOAllowed();

  ifaddrs *interfaces;
  if (getifaddrs(&interfaces) < 0) {
    PLOG(ERROR) << "getifaddrs";
    return false;
  }

  // Enumerate the addresses assigned to network interfaces which are up.
  for (ifaddrs *interface = interfaces;
       interface != NULL;
       interface = interface->ifa_next) {
    // Skip loopback interfaces, and ones which are down.
    if (!(IFF_UP & interface->ifa_flags))
      continue;
    if (IFF_LOOPBACK & interface->ifa_flags)
      continue;
    // Skip interfaces with no address configured.
    struct sockaddr* addr = interface->ifa_addr;
    if (!addr)
      continue;
    // Skip loopback addresses configured on non-loopback interfaces.
    int addr_size = 0;
    if (addr->sa_family == AF_INET6) {
      struct sockaddr_in6* addr_in6 =
          reinterpret_cast<struct sockaddr_in6*>(addr);
      struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
      addr_size = sizeof(*addr_in6);
      if (IN6_IS_ADDR_LOOPBACK(sin6_addr))
        continue;
    } else if (addr->sa_family == AF_INET) {
      struct sockaddr_in* addr_in =
          reinterpret_cast<struct sockaddr_in*>(addr);
      addr_size = sizeof(*addr_in);
      if (addr_in->sin_addr.s_addr == INADDR_LOOPBACK)
        continue;
    } else {
      // Skip non-IP addresses.
      continue;
    }
    IPEndPoint address;
    std::string name = interface->ifa_name;
    if (address.FromSockAddr(addr, addr_size)) {
      networks->push_back(NetworkInterface(name, address.address()));
    }
  }

  freeifaddrs(interfaces);

  return true;
#endif
}

}  // namespace net
<|endoftext|>


<commit_before>// point2point.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace  std;

int main()
{

	system("pause");
    return 0;
}

<commit_msg>pointer to pointer and address of pointer<commit_after>// point2point.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace  std;

int main()
{
	int var = 123;
	cout << "var = " << var << endl;

	int * ptrvar = &var; //    var
	cout << "*ptrvar = " << *ptrvar << endl;
	cout << "address of ptrvar ( ptrvar ) = " << ptrvar << endl;

	int **ptr_ptrvar = &ptrvar; //   var
	cout << "**ptr_ptrvar = " << ** ptr_ptrvar << endl;
	cout << "address of ptr_ptrvar ( ptr_ptrvar ) = " << ptr_ptrvar << endl;

	system("pause");
    return 0;
}

<|endoftext|>


<commit_before>#include <stan/math/prim/functor.hpp>
#include <gtest/gtest.h>

TEST(MathMetaPrim, OperandsAndPartials) {
  using stan::math::operands_and_partials;

  operands_and_partials<double> o1(1.0);
  operands_and_partials<double, double, double, double> o2(2.0, 3.0, 4.0, 5.0);

  // TODO(Sean): Learn why it's size 6
  EXPECT_GT(sizeof(&o2), sizeof(o2));

  EXPECT_FLOAT_EQ(27.1, o1.build(27.1));
}
<commit_msg>update prim ops and partials test<commit_after>#include <stan/math/prim/functor.hpp>
#include <gtest/gtest.h>

TEST(MathMetaPrim, OperandsAndPartials) {
  using stan::math::operands_and_partials;

  operands_and_partials<double> o1(1.0);
  operands_and_partials<double, double, double, double> o2(2.0, 3.0, 4.0, 5.0);

  // This is size 10 because of the two empty broadcast arrays in each edge
  EXPECT_EQ(10, sizeof(o2));

  EXPECT_FLOAT_EQ(27.1, o1.build(27.1));
}
<|endoftext|>


<commit_before><commit_msg>Update a WARNING with a bug URL.<commit_after><|endoftext|>


<commit_before>#include "party.h"

std::shared_ptr<Party> cache_fetch_party(uint32_t charId) {
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};
  Core::PartyMembersTable partyMembersTable{};

  auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from(
    partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id))
                  .where(partyMembersTable.memberId == charId));

  if (res.empty()) {
    return {};
  }
  auto& result = res.front();

  Party party;
  party.id = result.id;
  party.name = result.name;
  party.leader = result.leaderId;
  party.options = result.options;
  party.level = result.level;
  party.last_got_item_index = result.lastGotItemIndex;
  party.last_got_zuly_index = result.lastGotZulyIndex;
  party.last_got_etc_index = result.lastGotEtcIndex;

  // now we fetch all party members
  auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable)
                   .where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc()));

  if (res.empty()) {
    return {};
  }

  for (const auto& r : res2) {
    party.members.push_back(r.memberId);
  }

  return std::make_shared<Party>(party);
}

void cache_create_party(std::shared_ptr<Party> party) {
  if (!party) return;

  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::insert_into(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index));
}

void cache_write_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::update(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index)
       .where(partyTable.id == party->id));
}

void cache_write_party_members(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyMembersTable partyMembersTable{};

  conn(sqlpp::remove_from(partyMembersTable).where(partyMembersTable.id == party->id));
  auto insert = sqlpp::insert_into(partyMembersTable).columns(partyMembersTable.id, partyMembersTable.memberId);
  for (auto m : party-> members) {
    insert.values.add(partyMembersTable.id = party->id, partyMembersTable.memberId = static_cast<int>(m));
  }
  conn(insert);
}

void cache_remove_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::remove_from(partyTable).where(partyTable.id == party->id));
}
<commit_msg>Update party.cpp<commit_after>#include "party.h"
#include "ccharserver.h"

std::shared_ptr<Party> cache_fetch_party(uint32_t charId) {
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};
  Core::PartyMembersTable partyMembersTable{};

  auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from(
    partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id))
                  .where(partyMembersTable.memberId == charId));

  if (res.empty()) {
    return {};
  }
  auto& result = res.front();

  Party party;
  party.id = result.id;
  party.name = result.name;
  party.leader = result.leaderId;
  party.options = result.options;
  party.level = result.level;
  party.last_got_item_index = result.lastGotItemIndex;
  party.last_got_zuly_index = result.lastGotZulyIndex;
  party.last_got_etc_index = result.lastGotEtcIndex;

  // now we fetch all party members
  auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable)
                   .where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc()));

  if (res.empty()) {
    return {};
  }

  for (const auto& r : res2) {
    party.members.push_back(r.memberId);
  }

  return std::make_shared<Party>(party);
}

void cache_create_party(std::shared_ptr<Party> party) {
  if (!party) return;

  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::insert_into(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index));
}

void cache_write_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::update(partyTable)
       .set(partyTable.name = party->name,
       partyTable.leaderId = party->leader,
       partyTable.options = party->options,
       partyTable.level = party->level,
       partyTable.lastGotItemIndex = party->last_got_item_index,
       partyTable.lastGotEtcIndex = party->last_got_etc_index,
       partyTable.lastGotZulyIndex = party->last_got_zuly_index)
       .where(partyTable.id == party->id));
}

void cache_write_party_members(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyMembersTable partyMembersTable{};

  conn(sqlpp::remove_from(partyMembersTable).where(partyMembersTable.id == party->id));
  auto insert = sqlpp::insert_into(partyMembersTable).columns(partyMembersTable.id, partyMembersTable.memberId);
  for (auto m : party-> members) {
    insert.values.add(partyMembersTable.id = party->id, partyMembersTable.memberId = static_cast<int>(m));
  }
  conn(insert);
}

void cache_remove_party(std::shared_ptr<Party> party) {
  if (!party) return;
  auto conn = Core::connectionPool.getConnection<Core::Osirose>();
  Core::PartyTable partyTable{};

  conn(sqlpp::remove_from(partyTable).where(partyTable.id == party->id));
}

void party_request(const RoseCommon::Party::CliPartyReq& packet, CCharServer& server, uint32_t charId) {
}
<|endoftext|>


<commit_before>//============================================================================
// Name        : UDPReader.cpp
// Author      : Rodolfo Lam
// Version     :
// Copyright   : (C) 2016 Rodolfo Lam. All Rights Reserved.
// Description : Get one DATA-type package and display its contents.
//============================================================================

#include "Graphics/Screen.h"
#include "Network/MessageParser.h"
#include "Util/Math/Vec2D.h"

#include <array>
#include <iostream>
#include <istream>
#include <sstream>
#include <unordered_map>

#include <Poco/ByteOrder.h>
#include <Poco/Exception.h>
#include <Poco/Net/DatagramSocket.h>
#include <Poco/Net/SocketAddress.h>

using Poco::ByteOrder;

bool waitforEscKey();
void tempFullscreen(RL::Graphics::Screen& scr);

int main(int argc, char** argv) {
    al_init();
    al_install_keyboard();

    RL::Graphics::Screen screen;
    screen.toggleFullscreenMode();

    Poco::Net::SocketAddress sa(Poco::Net::IPAddress(), 49003);
    Poco::Net::DatagramSocket dgs;
    dgs.setBlocking(false);
    try {
        dgs.bind(sa, false);
    } catch (const Poco::Exception &e) {
        std::cerr
                << "FATAL ERROR: Is the application already running? Port could not be opened. Details: "
                << e.message() << std::endl;
        return EXIT_FAILURE;
    }

    std::array<Poco::UInt8, RL::Network::NETMESSAGE_SIZE> buffer;
    buffer.fill(0);

    std::unordered_map<RL::Network::DataTypesEnum, std::array<float, 8>,
            RL::Network::DataTypesEnumHash> parsedData;
    parsedData.reserve(46);

    for (auto const &ref : RL::Network::Data_Index) {
        std::array<float, 8> ar;
        parsedData.emplace(std::make_pair(ref.second, std::move(ar)));
    }

    RL::Network::MessageParser parser;

    bool exit = false;

    while (exit != true) {
        Poco::Net::SocketAddress sender;
        int n;

        try {
            n = dgs.receiveFrom(buffer.data(), RL::Network::NETMESSAGE_SIZE,
                    sender);
        } catch (Poco::TimeoutException &e) {
            std::cerr << "[" << al_get_time() << "] " << "Timeout, no data received" << std::endl;
        }

        parser.ParsePacket(parsedData, buffer, n);
        bool success = parser.LastPacketParseCorrect();

        std::stringstream debText;
        debText << "Last Packet time: " << al_get_time() << " | Status: "
                << success << " | Size: " << n;

        screen.processCommands(RL::Math::Vec2D<float>(), debText.str());

        screen.flipScreen(); // Actually, this might be better placed at the end.

        tempFullscreen(screen);
        exit = waitforEscKey();
    }

    return EXIT_SUCCESS;

}

void tempFullscreen(RL::Graphics::Screen& scr) {
    ALLEGRO_KEYBOARD_STATE state;
        al_get_keyboard_state(&state);

        if(al_key_down(&state, ALLEGRO_KEY_F)) {
            scr.toggleFullscreenMode();
        }
}

bool waitforEscKey() {
    ALLEGRO_KEYBOARD_STATE state;
    al_get_keyboard_state(&state);

    if(&state == nullptr) {
        return false;
    }

    return al_key_down(&state, ALLEGRO_KEY_ESCAPE);
}
<commit_msg>References are never null<commit_after>//============================================================================
// Name        : UDPReader.cpp
// Author      : Rodolfo Lam
// Version     :
// Copyright   : (C) 2016 Rodolfo Lam. All Rights Reserved.
// Description : Get one DATA-type package and display its contents.
//============================================================================

#include "Graphics/Screen.h"
#include "Network/MessageParser.h"
#include "Util/Math/Vec2D.h"

#include <array>
#include <iostream>
#include <istream>
#include <sstream>
#include <unordered_map>

#include <Poco/ByteOrder.h>
#include <Poco/Exception.h>
#include <Poco/Net/DatagramSocket.h>
#include <Poco/Net/SocketAddress.h>

using Poco::ByteOrder;

bool waitforEscKey();
void tempFullscreen(RL::Graphics::Screen& scr);

int main(int argc, char** argv) {
    al_init();
    al_install_keyboard();

    RL::Graphics::Screen screen;
    screen.toggleFullscreenMode();

    Poco::Net::SocketAddress sa(Poco::Net::IPAddress(), 49003);
    Poco::Net::DatagramSocket dgs;
    dgs.setBlocking(false);
    try {
        dgs.bind(sa, false);
    } catch (const Poco::Exception &e) {
        std::cerr
                << "FATAL ERROR: Is the application already running? Port could not be opened. Details: "
                << e.message() << std::endl;
        return EXIT_FAILURE;
    }

    std::array<Poco::UInt8, RL::Network::NETMESSAGE_SIZE> buffer;
    buffer.fill(0);

    std::unordered_map<RL::Network::DataTypesEnum, std::array<float, 8>,
            RL::Network::DataTypesEnumHash> parsedData;
    parsedData.reserve(46);

    for (auto const &ref : RL::Network::Data_Index) {
        std::array<float, 8> ar;
        parsedData.emplace(std::make_pair(ref.second, std::move(ar)));
    }

    RL::Network::MessageParser parser;

    bool exit = false;

    while (exit != true) {
        Poco::Net::SocketAddress sender;
        int n;

        try {
            n = dgs.receiveFrom(buffer.data(), RL::Network::NETMESSAGE_SIZE,
                    sender);
        } catch (Poco::TimeoutException &e) {
            std::cerr << "[" << al_get_time() << "] " << "Timeout, no data received" << std::endl;
        }

        parser.ParsePacket(parsedData, buffer, n);
        bool success = parser.LastPacketParseCorrect();

        std::stringstream debText;
        debText << "Last Packet time: " << al_get_time() << " | Status: "
                << success << " | Size: " << n;

        screen.processCommands(RL::Math::Vec2D<float>(), debText.str());

        screen.flipScreen(); // Actually, this might be better placed at the end.

        tempFullscreen(screen);
        exit = waitforEscKey();
    }

    return EXIT_SUCCESS;

}

void tempFullscreen(RL::Graphics::Screen& scr) {
    ALLEGRO_KEYBOARD_STATE state;
        al_get_keyboard_state(&state);

        if(al_key_down(&state, ALLEGRO_KEY_F)) {
            scr.toggleFullscreenMode();
        }
}

bool waitforEscKey() {
    ALLEGRO_KEYBOARD_STATE state;
    al_get_keyboard_state(&state);

    return al_key_down(&state, ALLEGRO_KEY_ESCAPE);
}
<|endoftext|>


<commit_before><commit_msg>489 - Hangman Judge<commit_after><|endoftext|>