blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16f33322d3be747f23ab6e08092ed68d146f7e03 | 393320d4dc9463ae7047390e4afe6f3e25fd70b9 | /tek2/C++/cpp_nanotekspice/sources/interfaces/IComponent.hpp | aafe94cd37a8c1c8fcb7c0c1f50ccf492a5ad826 | [] | no_license | Lime5005/epitech-1 | d1c4f3739716173c8083ea4e6a04260d6dc92775 | cb25df1fa5d540624b9e7fd58de6e458cd5cc250 | refs/heads/master | 2023-02-09T07:38:57.850357 | 2019-10-14T15:03:44 | 2019-10-14T15:03:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | hpp | /*
** IComponent.hpp for cpp_nanotekspice in /home/rubysh/Work/Repositories/Epitech/SecondYear/CPE/cpp_nanotekspice/sources/interfaces/IComponent.hpp
**
** Made by Anas Buyumad
** Login <anas.buyumad@epitech.eu>
**
** Started on Fri Jan 27 20:15:48 2017 Anas Buyumad
** Last update Fri Jan 27 20:15:49 2017 Anas Buyumad
*/
#ifndef CPP_NANOTEKSPICE_ICOMPONENT_HPP
# define CPP_NANOTEKSPICE_ICOMPONENT_HPP
#include <cstddef>
#include <vector>
namespace nts
{
enum Tristate
{
UNDEFINED = (-true),
TRUE = true,
FALSE = false
};
class IComponent
{
public:
/// Compute value of the precised pin
virtual nts::Tristate Compute(size_t pin_num_this = 1) = 0;
/// Useful to link IComponent together
virtual void SetLink(size_t pin_num_this, nts::IComponent &component, size_t pin_num_target) = 0;
///// Print on terminal the name of the component and
//// the state of every pin of the current component
/// The output won’t be tested, but it may help you
// as a trace.
virtual void Dump(void) const = 0;
virtual ~IComponent(void) { }
};
}
#endif //CPP_NANOTEKSPICE_ICOMPONENT_HPP
| [
"gauthier.cler@epitech.eu"
] | gauthier.cler@epitech.eu |
8a2249ac4c6e123f7ac68960575fd44ca52d15ba | d7a8148bf140233ac5a131f43ae84ffde2d6e7ac | /CastlePrizeWheelV17Audio/CastlePrizeWheelV17Audio.ino | 350d86e53f079245f111355140e5e8fa119789aa | [] | no_license | isomorphic85/Castle-Prize-Wheel | 1bfa8c731713d7dc2827a926ebc843d782dc85a7 | 48d4ea55ab46080426bfe06dd2c2b849d7c1b548 | refs/heads/master | 2021-01-13T12:57:39.608818 | 2017-06-20T14:15:45 | 2017-06-20T14:15:45 | 94,898,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,908 | ino |
//The Castle Fun Center Prize Wheel V17.0
//Designed & Programmed by Mike Baier
//--Objective- Create a "prize wheel"
//utilizing lights and audio to randomly generate winning
//zones within an area to award a prize.
//wheel is activated with a button press
//A Random LED is choosen as the winner, LED flashes, Audio plays
#include "Adafruit_WS2801.h"
#include <Adafruit_NeoPixel.h>
#include "Wire.h"
#include "Adafruit_LiquidCrystal.h"
#include "SPI.h"
// Connect via i2c, default address #0 (A0-A2 not jumpered)
Adafruit_LiquidCrystal lcd(0);
#include <avr/power.h>
#include <Adafruit_Soundboard.h>
//#include <Adafruit_NeoPixel.h>
#define NUMBER_OF_FLASHES 10
#define FLASH_RATE 400
#define BUTTON_PIN 8 // Digital IO pin connected to the button. This will be
// driven with a pull-up resistor so the switch should
// pull the pin to ground momentarily. On a high -> low
// transition the button press logic will execute.
#define BUTTONPIXEL_PIN 5 //Digital IO pin connected to button pixels
#define PIXEL_PIN 6 // Digital IO pin connected to the NeoPixels.
#define PIXEL_COUNT 24 //Neopixel group A count
#define PIXEL_COUNTB 16 //Button Neopixel group Count
#define BRIGHTNESS 10 // Set Brightness of all Pixels
#define BUTTONBRIGHTNESS 100 // Set brightness of button pixels
uint8_t dataPin = 9; // Yellow wire on Adafruit Pixels
uint8_t clockPin = 10; // Green wire on Adafruit Pixels
int Audio1 = 36;
int Audio2 = 46;
int Audio3 = 44;
int Audio4 = 42;
int Audio5 = 40;
int Audio6 = 48;
int Audio7 = 38;
int Audio8 = 34;
int Audio9 = 32;
int Audio10= 30;
// Parameter 1 = number of pixels in strip, neopixel stick has 8
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_RGBW Pixels are wired for RGBW bitstream
// NEO_GRB Pixels are wired for GRB bitstream, correct for neopixel stick
// NEO_KHZ400 400 KHz bitstream (e.g. FLORA pixels)
// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip), correct for neopixel stick
//Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, NEO_GRBW + NEO_KHZ800);
//Adafruit_NeoPixel stripb = Adafruit_NeoPixel(PIXEL_COUNTB, BUTTONPIXEL_PIN, NEO_GRBW + NEO_KHZ800);
Adafruit_WS2801 strip = Adafruit_WS2801(25, dataPin, clockPin );
Adafruit_NeoPixel stripb = Adafruit_NeoPixel(PIXEL_COUNTB, BUTTONPIXEL_PIN, NEO_GRBW + NEO_KHZ800);
int PrizeLED = 0;
int randomledchoice;
void setup() {
Serial.begin(9600);
Serial.println("THE CASTLE PRIZE-O-MATIC VS1053 Library Test");
// set up the LCD's number of rows and columns:
lcd.begin(20, 4);
/* pinMode(Audio1, OUTPUT);
pinMode(Audio2, OUTPUT);
pinMode(Audio3, OUTPUT);
pinMode(Audio4, OUTPUT);
pinMode(Audio5, OUTPUT);
pinMode(Audio6, OUTPUT);
pinMode(Audio7, OUTPUT);
pinMode(Audio8, OUTPUT);
pinMode(Audio9, OUTPUT);
pinMode(Audio10, OUTPUT);
*/
Serial.println(" Castle Prize-O-MATIC- SYSTEM READY!");
pinMode(BUTTON_PIN, INPUT_PULLUP);
strip.begin();
strip.show();// Initialize all pixels to 'off'
stripb.setBrightness(BUTTONBRIGHTNESS);
stripb.begin();
stripb.show();
}
void loop(){
// Get current button state and handle result
if (digitalRead(BUTTON_PIN)==LOW) {
Serial.println(" Button Pressed");
playgame(); //activate the spinning lights for the game
}
else
{
Serial.println(" Returning to Attract Mode");
attractMode();
// Print a message to the LCD.
lcd.setCursor(0,0);
lcd.print("PRIZE-O-MATIC V1.0!");
lcd.setCursor(2, 1);
lcd.print("The Castle");
lcd.setCursor(4,8);
lcd.print("System Ready!");
}
}
// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
for(uint16_t i=0; i<strip.numPixels(); i++) {
strip.setPixelColor(i, c);
stripb.setPixelColor(i, c);
strip.show();
stripb.show();
delay(wait);
}
}
//Theatre-style crawling lights.
void theaterChase3(uint32_t c, uint8_t wait) {
for (int j=0; j<20; j++) { //do 20 cycles of chasing
for (int q=0; q < 3; q++) {
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, c); //turn every third pixel on
}
strip.show();
delay(wait);
for (int i=0; i < strip.numPixels(); i=i+3) {
strip.setPixelColor(i+q, 0); //turn every third pixel off
}
}
}
}
void theaterChase(uint32_t c, uint8_t wait, int randomledchoice)
{
for (int i = 0; i < randomledchoice+1; i++)
{
strip.setPixelColor(i, c);
strip.setPixelColor(i-1, 0);
strip.show();
delay(wait);
}
}
void attractMode(void)
{
colorWipe(Color(0, 255, 0), 20);
if (digitalRead(BUTTON_PIN)==LOW) {
Serial.println(" Button Pressed");
playgame();
}
//activate the spinning lights for the game
//White
colorWipe(Color(255, 0, 255), 20); // Purple
strip.show();
if (digitalRead(BUTTON_PIN)==LOW) {
Serial.println(" Button Pressed");
playgame();
}
colorWipe(stripb.Color(0, 255, 0), 20); //White
if (digitalRead(BUTTON_PIN)==LOW) {
Serial.println(" Button Pressed");
playgame();
}
colorWipe(stripb.Color(255, 0, 255), 20); // Purple
if (digitalRead(BUTTON_PIN)==LOW) {
Serial.println(" Button Pressed");
playgame();
}
stripb.show();
}
void playgame(void)
{
randomSeed(millis()); // Seed the random generator with random amount of millis()
Serial.println(" Seeding Random Generator");
lcd.clear();
lcd.setCursor(1,2);
lcd.print("WHEEL SPINNING!");
randomled();
//theaterChase(Color(127, 127, 127), 40, 25);
/*theaterChase(Color(127, 127, 127), 50, 25);
theaterChase(Color(127, 127, 127), 50, 25);
theaterChase(Color(127, 127, 127), 50, randomledchoice);
strip.show();
Serial.println(" play game sequence");
//randomled(); // get a random LED zone to indicate the prize won
lcd.clear();
*/
}
// Adds a new random led choice to the game sequence, by sampling the timer
void randomled(void)
{
randomSeed(millis()); // Seed the random generator with random amount of millis()
int randomledchoice = random(1,26); //min (included), max (exluded)\
Serial.println(" Random LED is:");
Serial.println(randomledchoice);
// We have to convert this number, 0 to 25, to convert to LED Zone/pixels
//if(randomledchoice == 0) LEDzone1();
if(randomledchoice == 1) LEDzone1();
else if(randomledchoice == 2) LEDzone2();
else if(randomledchoice == 3) LEDzone3();
else if(randomledchoice == 4) LEDzone4();
else if(randomledchoice == 5) LEDzone5();
else if(randomledchoice == 6) LEDzone6();
else if(randomledchoice == 7) LEDzone7();
else if(randomledchoice == 8) LEDzone8();
else if(randomledchoice == 9) LEDzone9();
else if(randomledchoice == 10) LEDzone10();
else if(randomledchoice == 11) LEDzone11();
else if(randomledchoice == 12) LEDzone12();
else if(randomledchoice == 13) LEDzone13();
else if(randomledchoice == 14) LEDzone14();
else if(randomledchoice == 15) LEDzone15();
else if(randomledchoice == 16) LEDzone16();
else if(randomledchoice == 17) LEDzone17();
else if(randomledchoice == 18) LEDzone18();
else if(randomledchoice == 19) LEDzone19();
else if(randomledchoice == 20) LEDzone20();
else if(randomledchoice == 21) LEDzone21();
else if(randomledchoice == 22) LEDzone22();
else if(randomledchoice == 23) LEDzone23();
else if(randomledchoice == 24) LEDzone24();
else if(randomledchoice == 25) LEDzone25();
//PrizeLED=randomledchoice;
}
void LEDzone1(void)
{
Serial.println(" LED Zone 1");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 0);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
pinMode( Audio1, INPUT );
digitalWrite( Audio1, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio1, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio1, INPUT ); // back to input mode
strip.setPixelColor(1, 0, 255, 0);
strip.setPixelColor(24, 0, 255, 0);
strip.setPixelColor(23, 0, 255, 0);
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(0, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(0, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone2(void)
{
Serial.println(" LED Zone 2");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 1);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(0, 0, 255, 0);
strip.setPixelColor(24, 0, 255, 0);
strip.setPixelColor(23, 0, 255, 0);
pinMode( Audio1, INPUT );
digitalWrite( Audio1, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio1, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio1, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(1, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(1, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone3(void)
{
Serial.println(" LED Zone 3");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 2);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
pinMode( Audio7, INPUT );
digitalWrite( Audio7, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio7, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio7, INPUT ); // back to input mode
strip.setPixelColor(3, 0, 255, 0);
strip.setPixelColor(4, 0, 255, 0);
strip.setPixelColor(5, 0, 255, 0);
pinMode( Audio1, INPUT );
digitalWrite( Audio1, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio1, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio1, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(2, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(2, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone4(void)
{
Serial.println(" LED Zone 4");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 3);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
pinMode( Audio7, INPUT );
digitalWrite( Audio7, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio7, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio7, INPUT ); // back to input mode
strip.setPixelColor(2, 0, 255, 0);
strip.setPixelColor(4, 0, 255, 0);
strip.setPixelColor(5, 0, 255, 0);
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(3, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(3, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone5(void)
{
Serial.println(" LED Zone 5");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 4);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
pinMode( Audio7, INPUT );
digitalWrite( Audio7, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio7, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio7, INPUT ); // back to input mode
strip.setPixelColor(2, 0, 255, 0);
strip.setPixelColor(3, 0, 255, 0);
strip.setPixelColor(5, 0, 255, 0);
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(4, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(4, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone6(void)
{
Serial.println(" LED Zone 6");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 5);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
pinMode( Audio7, INPUT );
digitalWrite( Audio7, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio7, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio7, INPUT ); // back to input mode
strip.setPixelColor(2, 0, 255, 0);
strip.setPixelColor(3, 0, 255, 0);
strip.setPixelColor(4, 0, 255, 0);
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(5, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(5, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone7(void)
{
Serial.println(" LED Zone 7");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 6);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
pinMode( Audio2, INPUT );
digitalWrite( Audio2, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio2, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio2, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(6, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(6, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone8(void)
{
Serial.println(" LED Zone 8");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 7);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(8, 0, 255, 0);
strip.setPixelColor(9, 0, 255, 0);
strip.setPixelColor(10, 0, 255, 0);
pinMode( Audio3, INPUT );
digitalWrite( Audio3, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio3, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio3, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(7, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(7, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone9(void)
{
Serial.println(" LED Zone ");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 8);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(7, 0, 255, 0);
strip.setPixelColor(9, 0, 255, 0);
strip.setPixelColor(10, 0, 255, 0);
pinMode( Audio3, INPUT );
digitalWrite( Audio3, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio3, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio3, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(8, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(8, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone10(void)
{
Serial.println(" LED Zone 10");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 9);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(7, 0, 255, 0);
strip.setPixelColor(8, 0, 255, 0);
strip.setPixelColor(10, 0, 255, 0);
pinMode( Audio3, INPUT );
digitalWrite( Audio3, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio3, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio3, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(9, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(9, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone11(void)
{
Serial.println(" LED Zone 11");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 10);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(7, 0, 255, 0);
strip.setPixelColor(8, 0, 255, 0);
strip.setPixelColor(9, 0, 255, 0);
pinMode( Audio3, INPUT );
digitalWrite( Audio3, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio3, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio3, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(10, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(10, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone12(void)
{
Serial.println(" LED Zone 12");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 11);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(12, 0, 255, 0);
strip.setPixelColor(13, 0, 255, 0);
strip.setPixelColor(14, 0, 255, 0);
pinMode( Audio4, INPUT );
digitalWrite( Audio4, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio4, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio4, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(11, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(11, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone13(void)
{
Serial.println(" LED Zone 13");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 12);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(11, 0, 255, 0);
strip.setPixelColor(13, 0, 255, 0);
strip.setPixelColor(14, 0, 255, 0);
pinMode( Audio4, INPUT );
digitalWrite( Audio4, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio4, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio4, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(12, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(12, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone14(void)
{
Serial.println(" LED Zone 14");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 13);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(11, 0, 255, 0);
strip.setPixelColor(12, 0, 255, 0);
strip.setPixelColor(14, 0, 255, 0);
pinMode( Audio4, INPUT );
digitalWrite( Audio4, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio4, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio4, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(13, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(13, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone15(void)
{
Serial.println(" LED Zone 15");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 14);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(11, 0, 255, 0);
strip.setPixelColor(12, 0, 255, 0);
strip.setPixelColor(13, 0, 255, 0);
pinMode( Audio4, INPUT );
digitalWrite( Audio4, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio4, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio4, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(14, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(14, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone16(void)
{
Serial.println(" LED Zone 16");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 15);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(16, 0, 255, 0);
strip.setPixelColor(17, 0, 255, 0);
strip.setPixelColor(18, 0, 255, 0);
pinMode( Audio5, INPUT );
digitalWrite( Audio5, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio5, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio5, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(15, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(15, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone17(void)
{
Serial.println(" LED Zone 17");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 16);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(15, 0, 255, 0);
strip.setPixelColor(17, 0, 255, 0);
strip.setPixelColor(18, 0, 255, 0);
pinMode( Audio5, INPUT );
digitalWrite( Audio5, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio5, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio5, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(16, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(16, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone18(void)
{
Serial.println(" LED Zone 18");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 17);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(15, 0, 255, 0);
strip.setPixelColor(16, 0, 255, 0);
strip.setPixelColor(18, 0, 255, 0);
pinMode( Audio5, INPUT );
digitalWrite( Audio5, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio5, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio5, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(17, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(17, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone19(void)
{
Serial.println(" LED Zone 19");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 18);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(15, 0, 255, 0);
strip.setPixelColor(16, 0, 255, 0);
strip.setPixelColor(17, 0, 255, 0);
pinMode( Audio5, INPUT );
digitalWrite( Audio5, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio5, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio5, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(18, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(18, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone20(void)
{
Serial.println(" LED Zone 20");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 19);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(20, 0, 255, 0);
strip.setPixelColor(21, 0, 255, 0);
strip.setPixelColor(22, 0, 255, 0);
pinMode( Audio6, INPUT );
digitalWrite( Audio6, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio6, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio6, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(19, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(19, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone21(void)
{
Serial.println(" LED Zone 21");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 20);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(19, 0, 255, 0);
strip.setPixelColor(21, 0, 255, 0);
strip.setPixelColor(22, 0, 255, 0);
pinMode( Audio6, INPUT );
digitalWrite( Audio6, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio6, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio6, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(20, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(20, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone22(void)
{
Serial.println(" LED Zone 22");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 21);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(19, 0, 255, 0);
strip.setPixelColor(20, 0, 255, 0);
strip.setPixelColor(22, 0, 255, 0);
pinMode( Audio6, INPUT );
digitalWrite( Audio6, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio6, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio6, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(21, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(21, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone23(void)
{
Serial.println(" LED Zone 23");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 22);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(19, 0, 255, 0);
strip.setPixelColor(20, 0, 255, 0);
strip.setPixelColor(21, 0, 255, 0);
pinMode( Audio6, INPUT );
digitalWrite( Audio6, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio6, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio6, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(22, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(22, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone24(void)
{
Serial.println(" LED Zone 24");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 23);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(24, 0, 255, 0);
strip.setPixelColor(0, 0, 255, 0);
strip.setPixelColor(1, 0, 255, 0);
pinMode( Audio1, INPUT );
digitalWrite( Audio1, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio1, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio1, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(23, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(23, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
void LEDzone25(void)
{
Serial.println(" LED Zone 25");
pinMode( Audio9, INPUT );
digitalWrite( Audio9, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio9, OUTPUT ); // now pull the FX pin low for real
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 26);
theaterChase(Color(127, 127, 127), 50, 24);
pinMode( Audio9, INPUT ); // back to input mode
delay(20);
strip.setPixelColor(23, 0, 255, 0);
strip.setPixelColor(0, 0, 255, 0);
strip.setPixelColor(1, 0, 255, 0);
pinMode( Audio1, INPUT );
digitalWrite( Audio1, LOW ); // legal even if it doesn't seem to do anything
pinMode( Audio1, OUTPUT ); // now pull the FX pin low for real
delay( 125 ); // wait for 125ms
pinMode( Audio1, INPUT ); // back to input mode
for (int i=0; i<NUMBER_OF_FLASHES; i++) {
strip.setPixelColor(24, 255, 255, 255);
strip.show();
delay(FLASH_RATE);
strip.setPixelColor(24, 0, 0, 0);
strip.show();
delay(FLASH_RATE);
}
}
//**********************************************************************************************
void rainbow(uint8_t wait) {
int i, j;
for (j=0; j < 256; j++) { // 3 cycles of all 256 colors in the wheel
for (i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, Wheel( (i + j) % 255));
}
strip.show(); // write all the pixels out
delay(wait);
}
}
// Create a 24 bit color value from R,G,B for WS2801
uint32_t Color(byte r, byte g, byte b)
{
uint32_t c;
c = r;
c <<= 8;
c |= g;
c <<= 8;
c |= b;
return c;
}
//Input a value 0 to 255 to get a color value.
//The colours are a transition r - g -b - back to r
uint32_t Wheel(byte WheelPos)
{
if (WheelPos < 85) {
return Color(WheelPos * 3, 255 - WheelPos * 3, 0);
} else if (WheelPos < 170) {
WheelPos -= 85;
return Color(255 - WheelPos * 3, 0, WheelPos * 3);
} else {
WheelPos -= 170;
return Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
ef9cafb2aae02d4458cb88f7dc8daecaba90e113 | b3bbb8210f7bd4cb1211a34be2b3a524d52f473e | /lr2/laba_2_Dimova/KS.h | bd8472e694332473b45b80db9d476423604e495a | [] | no_license | DimovaAlexandra/Dimova_Sem3 | 54ed4ee808082d7943c633b7f4c84920c221ba09 | 6980e942e3a46de91b50327d2a4010f0443d483c | refs/heads/master | 2023-04-19T10:49:45.762895 | 2021-04-27T16:03:14 | 2021-04-27T16:03:14 | 295,130,530 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,774 | h | #pragma once
#include <string>
#include <vector>
class KS
{
static unsigned int IDks;
unsigned int id; // Идентификатор
int effect; // Эффективность
public:
std::string name; // Название
int N; // Количество цехов
int Ninwork; // Количсевто цехов в работе
/*static KS createKS(); // Создание компрессорной станции
friend void printKS(const KS& ks); // Вывод информации о компрессорной станции
friend void editKS(KS& ks); // Изменение цехов в работе*/
friend std::istream& operator >> (std::istream& in, KS& ks); // Создание компрессорной станции
friend std::ostream& operator << (std::ostream& out, const KS& ks); // Вывод информации о компрессорной станции
void editKS(); // Изменение цехов в работe
void savefileKS(std::ofstream& fout); // Сохранение информации о компрессорной станции
void inputfileKS(std::ifstream& fin); // Считывание инфы о компрессорной станции
/* static KS inputfileKS(std::ifstream& fin); // Считывание информации о компрессорной станции
friend KS& selectKS(vector<KS>& Zavod); // Выбор компрессорной станции
friend void deleteKS(vector<KS>& Zavod); // Удаление компрессорной станции
friend bool SearchKSByName(const KS& ks, std::string parametr); // Поиск по названию
friend bool SearchKSByNinwork(const KS& ks, double parametr); // поиск не работающих цехов по % */
};
| [
"70602965+Kai-Lee-Hyuga@users.noreply.github.com"
] | 70602965+Kai-Lee-Hyuga@users.noreply.github.com |
e3b2166daca3735b695a07603916312ff49bcddb | 9b5deee6d2c13ac0913ea80894e28e63bb9f4abf | /demos/tutorial/sequences_in_depth/example_overflow.cpp | 926fe68c8635b095ac95bf61501b11b3339f880e | [
"BSD-3-Clause"
] | permissive | rrahn/seqan | a33bd6f8f2d61a768beaf4b4b977d32bf81c84f6 | 9d65353b7f131ba38f815970c8ee2ec542a18c1e | refs/heads/master | 2023-01-20T22:46:15.290624 | 2016-01-11T17:08:07 | 2016-01-11T17:08:07 | 14,363,387 | 2 | 2 | NOASSERTION | 2018-10-02T09:20:55 | 2013-11-13T12:31:03 | C++ | UTF-8 | C++ | false | false | 454 | cpp | #include <seqan/stream.h>
using namespace seqan;
int main()
{
//![example]
String<Dna> dnaSeq;
// Sets the capacity of dnaSeq to 5.
resize(dnaSeq, 4, Exact());
// Only "TATA" is assigned to dnaSeq, since dnaSeq is limited to 4.
assign(dnaSeq, "TATAGGGG", Limit());
std::cout << dnaSeq << std::endl;
// Use the default expansion strategy.
append(dnaSeq, "GCGCGC");
std::cout << dnaSeq << std::endl;
//![example]
return 0;
} | [
"enrico.siragusa@fu-berlin.de"
] | enrico.siragusa@fu-berlin.de |
0ee32733ebb03f86f648df4227aab08ee3bfbcee | 0cff93d44b1938fec56f5473994831fbeeaee3b8 | /EstructurasNoLineales/Treap/allinone.cpp | 5fdbc968a3068c5f4295e9a5a0521a6a7bedecc2 | [] | no_license | HMBL98/Competitive-Programming-Problems | e8cffd332b8825b0be4bce4adca4a57991aa6304 | e04182a78026fb2a50002dfe3a26cd3b4c468dbc | refs/heads/master | 2020-03-23T11:02:07.650153 | 2018-07-18T19:06:28 | 2018-07-18T19:06:28 | 141,478,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,070 | cpp | #include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define mod ( ( ((n) % (k)) + (k) ) % (k))
#define forn(i,a,b) for(int i = a; i < b; i++)
#define forr(i,a,b) for(int i = a; i >= b; i--)
typedef long long int ll;
typedef long double ld;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
struct Treap{
int x,y,cnt;
Treap *l,*r;
Treap(ll x) : x(x), y(rand()), l(r = 0), cnt(1){}
};
ll cnt(Treap *t){
return t ? t->cnt : 0;
}
void updatecnt(Treap *t){
if(t) t->cnt = 1 + cnt(t->l) + cnt(t->r);
}
void split(Treap *t, Treap *&l, Treap *&r, ll x){
if(!t){l = r = 0; return;}
if(x <= t->x) split(t->l,l,t->l,x), r = t;
else split(t->r,t->r,r,x), l = t;
updatecnt(t);
}
Treap *merge(Treap *l, Treap *r){
if(!l) return r;
if(!r) return l;
if(l->y > r->y){
l->r = merge(l->r,r);
updatecnt(l);
return l;
}else{
r->l = merge(l,r->l);
updatecnt(r);
return r;
}
}
void insert(Treap *&t, Treap *n){
if(!t) t = n;
else if(n->y > t->y) split(t,n->l,n->r,n->x), t = n;
else insert(n->x < t->x ? t->l : t->r,n);
updatecnt(t);
}
void erase(Treap *&t,ll x){
if(t && t->x == x){
Treap *tmp = merge(t->l,t->r);
delete t;
t = tmp;
}else if(t){
erase(x < t->x ? t->l : t->r, x);
}
updatecnt(t);
}
ll binSearch(Treap *t,ll x){
if(!t) return 0;
if(t->x > x) return binSearch(t->l,x);
return cnt(t->l)+1+binSearch(t->r,x);
}
ll kth(Treap *t,ll k){
if(!t) return -1;
if(k == cnt(t->l)+1) return t->x;
if(cnt(t->l) >= k) return kth(t->l,k);
return kth(t->r,k-cnt(t->l)-1);
}
Treap *t = 0;
ll opc,val;
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
while(1){
cin >> opc;
if(opc == 1){
cin >> val;
if(!t)t = new Treap(val);
else insert(t,new Treap(val));
}else if(opc == 2){
cin >> val;
erase(t,val);
}else if(opc == 3){
cin >> val;
ll bin = binSearch(t,val);
if(kth(t,bin) == val)cout << bin << "\n";
else cout << "-1\n";
}else if(opc == 4){
cin >> val;
cout << kth(t,val) << "\n";
}else break;
}
return 0;
}
| [
"hugomichelbl@gmail.com"
] | hugomichelbl@gmail.com |
784a1b3ae808cd243f3859e543a9f0912eaa5563 | 46e1796795eadd2f2cb7aa2d570594ae7c288885 | /csci40/lec02/doubleDivision.cpp | ce50df030705363d6a359ad7eede1f9d35dda694 | [] | no_license | lawtonsclass/f20-code-from-class | 1afb7f7a6d230f6af9e368f13e4df8634d86a011 | 34db321491455044a14d029fff11ea81309f6792 | refs/heads/master | 2023-01-20T04:57:11.353707 | 2020-11-27T03:59:53 | 2020-11-27T03:59:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | cpp | #include <iomanip> // for setprecision
#include <iostream>
using namespace std;
int main() {
// integer divsion happens when both sides of the / are ints
double d = 1 / 2;
cout << "d: " << d << endl;
// solution: make at least one side a double
d = 1.0 / 2;
cout << "d: " << d << endl;
int x = 1;
int y = 2;
// to convert an expression from one type to another, use:
// static_cast<type_you_want>(exp)
d = x / static_cast<double>(y);
cout << "d: " << d << endl;
// Printing doubles:
// /////////////////////////////
double d2 = 1.0;
cout << "d2: " << d2 << endl;
// to force the decimal place to be shown, pass std::fixed to cout
cout << fixed; // this doesn't print anything. When cout sees fixed, it knows
// to start printing the decimal place for doubles
cout << "d2: " << d2 << endl;
// to force the number of decimal place to be what you want, you can
// add setprecision(2). This rounds the output, but does not change
// any variables
// std::setprecision lives in the <iomanip> library
cout << setprecision(2); // tells cout that for all future doubles, print
// after rounding to 2 decimal places
cout << "d2: " << d2 << endl;
double d3 = 1.5555;
cout << "d3: " << d3 << endl;
cout << setprecision(5);
cout << "d3: " << d3 << endl;
return 0;
}
| [
"lawtonnichols@gmail.com"
] | lawtonnichols@gmail.com |
f75a8c6d6670685d350751eb0b26c369f9b948d6 | 5a984c354434ae6a39d5722527f35fad37f3b14a | /Src/Application/DeviceComponent/SlotCard/CExtCard8VF.cpp | 6bd923954cd699f5ebede408c60e4d2de6597626 | [] | no_license | Gloriacnb/ISAP100-EMUX10 | f5085aba97cb1e6474c2916fba17755c7f781e4f | ded4b79e0b2741bf765ed68139ae8a45eaef44d7 | refs/heads/master | 2021-03-27T12:36:05.720627 | 2017-12-01T07:07:37 | 2017-12-01T07:07:37 | 112,694,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,269 | cpp | /*
* CExtCard8VF.cpp
*
* Created on: 2012-12-26
* Author: Administrator
*/
#include "CExtCard8VF.h"
#include "Chip8VFLogic.h"
#include "Pcm821054.h"
#include "CIsap100HardwareDesc.h"
#include "CVFPortA.h"
#include <string.h>
#include "UID.h"
#include <stdio.h>
#include "Task_define.h"
__task void T_MT_Wave(void* card );
CExtCard8VF::~CExtCard8VF() {
// TODO Auto-generated destructor stub
os_tsk_delete(TaskMtWave);
for( int i = 0; i < portNumber; i++ ) {
delete vf[i];
}
}
CExtCard8VF::CExtCard8VF(uint8 slot, std::string& name) : CBaseCard(name, slot) {
// slotNumber = slot;
EZ_FLASH_DATA_T storeInfo = {
Data_Part(slot+1),
sizeof(configData),
(uint32)&configData };
stroer.setInfo(storeInfo);
if( !stroer.ReadData() ) {
//restore default data
RestoreDefaultConfig();
}
Init821054(getSn());
InitExt8VFChip(slot, &configData);
// for( int i = 0; i < portNumber; i++ ) {
// ST_Time_Slot info = {slot+1, CIsap100HardwareDesc::slot_stbus_map[slot], CIsap100HardwareDesc::VF_port_channel_Map[i]};
// uint32 uid = UID::makeUID(&info);
//
// vf[i] = new CVFPortA(uid, i, &configData.port[i],&configData.group[i/4], &stroer);
// }
TaskMtWave = os_tsk_create_ex(T_MT_Wave, P_MT, this);
}
void CExtCard8VF::RestoreDefaultConfig(void) {
memset( &configData, 0, sizeof(configData));
for( int i = 0; i < portNumber; i++ ) {
configData.port[i].enable = 1;
configData.port[i].rcv_gain = 48;
configData.port[i].snd_gain = 29;
}
}
int CExtCard8VF::getNextVersionIndex(uint8 sn) {
if( sn >= ext8VFVersionSize ) {
return -1;
}
return sn+1;
}
int CExtCard8VF::getVersion(uint8 id, STVersion& ver) {
switch( id ) {
case ext8VFVersionPCB:
strcpy(ver.ucpVerName, "Ext8VFPCBVersion");
ver.uiVerNum = 16;
return 1;
case ext8VFVersionChip:
strcpy(ver.ucpVerName, "Ext8VFChipVersion");
ver.uiVerNum = get8VFVersion(getSn());
if( ver.uiVerNum < 16 ) {
ver.uiVerNum = 16;
}
return 1;
}
return -1;
}
__task void T_MT_Wave(void* card ) {
CExtCard8VF* vfcard = (CExtCard8VF*)card;
while( 1 ) {
os_dly_wait(5);
for (int i = 0; i < vfcard->portNumber; ++i) {
vfcard->vf[i]->process2100HZ();
}
}
}
| [
"momo_nono@163.com"
] | momo_nono@163.com |
9b25ec1d5ea331164deffa1dc1ecddbb181d8009 | b627928aa4c7c82559d63f6a1d60782c41b7e0b6 | /world_data/proj4/proj-6.3.2/test/unit/test_c_api.cpp | b53223d7284d6efb355e3126a889586a46443c68 | [
"LicenseRef-scancode-us-govt-public-domain",
"MIT"
] | permissive | oscarmb94/bta | 8cc6b1f33d10183cee698f3a4fd8ecde0b2cb45a | 96c5bc31b1ecd17b31002f2f1db446a304fb0b3e | refs/heads/master | 2022-11-26T08:00:44.777024 | 2020-08-06T16:45:29 | 2020-08-06T16:45:29 | 279,734,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172,496 | cpp | /******************************************************************************
*
* Project: PROJ
* Purpose: Test ISO19111:2019 implementation
* Author: Even Rouault <even dot rouault at spatialys dot com>
*
******************************************************************************
* Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "gtest_include.h"
#include <cstdio>
#include <limits>
#include "proj.h"
#include "proj_constants.h"
#include "proj_experimental.h"
#include "proj/common.hpp"
#include "proj/coordinateoperation.hpp"
#include "proj/coordinatesystem.hpp"
#include "proj/crs.hpp"
#include "proj/datum.hpp"
#include "proj/io.hpp"
#include "proj/metadata.hpp"
#include "proj/util.hpp"
#include <sqlite3.h>
using namespace osgeo::proj::common;
using namespace osgeo::proj::crs;
using namespace osgeo::proj::cs;
using namespace osgeo::proj::datum;
using namespace osgeo::proj::io;
using namespace osgeo::proj::metadata;
using namespace osgeo::proj::operation;
using namespace osgeo::proj::util;
namespace {
class CApi : public ::testing::Test {
static void DummyLogFunction(void *, int, const char *) {}
protected:
void SetUp() override {
m_ctxt = proj_context_create();
proj_log_func(m_ctxt, nullptr, DummyLogFunction);
}
void TearDown() override {
if (m_ctxt)
proj_context_destroy(m_ctxt);
}
static BoundCRSNNPtr createBoundCRS() {
return BoundCRS::create(
GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326,
Transformation::create(
PropertyMap(), GeographicCRS::EPSG_4807,
GeographicCRS::EPSG_4326, nullptr, PropertyMap(),
{OperationParameter::create(
PropertyMap().set(IdentifiedObject::NAME_KEY, "foo"))},
{ParameterValue::create(
Measure(1.0, UnitOfMeasure::SCALE_UNITY))},
{}));
}
static ProjectedCRSNNPtr createProjectedCRS() {
PropertyMap propertiesCRS;
propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG")
.set(Identifier::CODE_KEY, 32631)
.set(IdentifiedObject::NAME_KEY, "WGS 84 / UTM zone 31N");
return ProjectedCRS::create(
propertiesCRS, GeographicCRS::EPSG_4326,
Conversion::createUTM(PropertyMap(), 31, true),
CartesianCS::createEastingNorthing(UnitOfMeasure::METRE));
}
static VerticalCRSNNPtr createVerticalCRS() {
PropertyMap propertiesVDatum;
propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG")
.set(Identifier::CODE_KEY, 5101)
.set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn");
auto vdatum = VerticalReferenceFrame::create(propertiesVDatum);
PropertyMap propertiesCRS;
propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG")
.set(Identifier::CODE_KEY, 5701)
.set(IdentifiedObject::NAME_KEY, "ODN height");
return VerticalCRS::create(
propertiesCRS, vdatum,
VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE));
}
static CompoundCRSNNPtr createCompoundCRS() {
PropertyMap properties;
properties.set(Identifier::CODESPACE_KEY, "codespace")
.set(Identifier::CODE_KEY, "code")
.set(IdentifiedObject::NAME_KEY, "horizontal + vertical");
return CompoundCRS::create(
properties,
std::vector<CRSNNPtr>{createProjectedCRS(), createVerticalCRS()});
}
PJ_CONTEXT *m_ctxt = nullptr;
struct ObjectKeeper {
PJ *m_obj = nullptr;
explicit ObjectKeeper(PJ *obj) : m_obj(obj) {}
~ObjectKeeper() { proj_destroy(m_obj); }
ObjectKeeper(const ObjectKeeper &) = delete;
ObjectKeeper &operator=(const ObjectKeeper &) = delete;
};
struct ContextKeeper {
PJ_OPERATION_FACTORY_CONTEXT *m_op_ctxt = nullptr;
explicit ContextKeeper(PJ_OPERATION_FACTORY_CONTEXT *op_ctxt)
: m_op_ctxt(op_ctxt) {}
~ContextKeeper() { proj_operation_factory_context_destroy(m_op_ctxt); }
ContextKeeper(const ContextKeeper &) = delete;
ContextKeeper &operator=(const ContextKeeper &) = delete;
};
struct ObjListKeeper {
PJ_OBJ_LIST *m_res = nullptr;
explicit ObjListKeeper(PJ_OBJ_LIST *res) : m_res(res) {}
~ObjListKeeper() { proj_list_destroy(m_res); }
ObjListKeeper(const ObjListKeeper &) = delete;
ObjListKeeper &operator=(const ObjListKeeper &) = delete;
};
};
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create) {
proj_destroy(nullptr);
EXPECT_EQ(proj_create(m_ctxt, "invalid"), nullptr);
{
auto obj =
proj_create(m_ctxt, GeographicCRS::EPSG_4326
->exportToWKT(WKTFormatter::create().get())
.c_str());
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
// Check that functions that operate on 'non-C++' PJ don't crash
PJ_COORD coord;
coord.xyzt.x = 0;
coord.xyzt.y = 0;
coord.xyzt.z = 0;
coord.xyzt.t = 0;
EXPECT_EQ(proj_trans(obj, PJ_FWD, coord).xyzt.x,
std::numeric_limits<double>::infinity());
EXPECT_EQ(proj_geod(obj, coord, coord).xyzt.x,
std::numeric_limits<double>::infinity());
EXPECT_EQ(proj_lp_dist(obj, coord, coord),
std::numeric_limits<double>::infinity());
auto info = proj_pj_info(obj);
EXPECT_EQ(info.id, nullptr);
ASSERT_NE(info.description, nullptr);
EXPECT_EQ(info.description, std::string("WGS 84"));
ASSERT_NE(info.definition, nullptr);
EXPECT_EQ(info.definition, std::string(""));
}
{
auto obj = proj_create(m_ctxt, "EPSG:4326");
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_from_wkt) {
{
EXPECT_EQ(
proj_create_from_wkt(m_ctxt, "invalid", nullptr, nullptr, nullptr),
nullptr);
}
{
PROJ_STRING_LIST warningList = nullptr;
PROJ_STRING_LIST errorList = nullptr;
EXPECT_EQ(proj_create_from_wkt(m_ctxt, "invalid", nullptr, &warningList,
&errorList),
nullptr);
EXPECT_EQ(warningList, nullptr);
proj_string_list_destroy(warningList);
EXPECT_NE(errorList, nullptr);
proj_string_list_destroy(errorList);
}
{
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
}
{
auto obj = proj_create_from_wkt(
m_ctxt,
"GEOGCS[\"WGS 84\",\n"
" DATUM[\"WGS_1984\",\n"
" SPHEROID[\"WGS 84\",6378137,298.257223563,\"unused\"]],\n"
" PRIMEM[\"Greenwich\",0],\n"
" UNIT[\"degree\",0.0174532925199433]]",
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
}
{
PROJ_STRING_LIST warningList = nullptr;
PROJ_STRING_LIST errorList = nullptr;
auto obj = proj_create_from_wkt(
m_ctxt,
"GEOGCS[\"WGS 84\",\n"
" DATUM[\"WGS_1984\",\n"
" SPHEROID[\"WGS 84\",6378137,298.257223563,\"unused\"]],\n"
" PRIMEM[\"Greenwich\",0],\n"
" UNIT[\"degree\",0.0174532925199433]]",
nullptr, &warningList, &errorList);
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
EXPECT_EQ(warningList, nullptr);
proj_string_list_destroy(warningList);
EXPECT_NE(errorList, nullptr);
proj_string_list_destroy(errorList);
}
{
PROJ_STRING_LIST warningList = nullptr;
PROJ_STRING_LIST errorList = nullptr;
const char *const options[] = {"STRICT=NO", nullptr};
auto obj = proj_create_from_wkt(
m_ctxt,
"GEOGCS[\"WGS 84\",\n"
" DATUM[\"WGS_1984\",\n"
" SPHEROID[\"WGS 84\",6378137,298.257223563,\"unused\"]],\n"
" PRIMEM[\"Greenwich\",0],\n"
" UNIT[\"degree\",0.0174532925199433]]",
options, &warningList, &errorList);
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
EXPECT_EQ(warningList, nullptr);
proj_string_list_destroy(warningList);
EXPECT_NE(errorList, nullptr);
proj_string_list_destroy(errorList);
}
{
PROJ_STRING_LIST warningList = nullptr;
PROJ_STRING_LIST errorList = nullptr;
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, &warningList, &errorList);
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
EXPECT_EQ(warningList, nullptr);
EXPECT_EQ(errorList, nullptr);
}
// Warnings: missing projection parameters
{
PROJ_STRING_LIST warningList = nullptr;
PROJ_STRING_LIST errorList = nullptr;
auto obj = proj_create_from_wkt(
m_ctxt, "PROJCS[\"test\",\n"
" GEOGCS[\"WGS 84\",\n"
" DATUM[\"WGS_1984\",\n"
" SPHEROID[\"WGS 84\",6378137,298.257223563]],\n"
" PRIMEM[\"Greenwich\",0],\n"
" UNIT[\"degree\",0.0174532925199433]],\n"
" PROJECTION[\"Transverse_Mercator\"],\n"
" PARAMETER[\"latitude_of_origin\",31],\n"
" UNIT[\"metre\",1]]",
nullptr, &warningList, &errorList);
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
EXPECT_NE(warningList, nullptr);
proj_string_list_destroy(warningList);
EXPECT_EQ(errorList, nullptr);
proj_string_list_destroy(errorList);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, "PROJCS[\"test\",\n"
" GEOGCS[\"WGS 84\",\n"
" DATUM[\"WGS_1984\",\n"
" SPHEROID[\"WGS 84\",6378137,298.257223563]],\n"
" PRIMEM[\"Greenwich\",0],\n"
" UNIT[\"degree\",0.0174532925199433]],\n"
" PROJECTION[\"Transverse_Mercator\"],\n"
" PARAMETER[\"latitude_of_origin\",31],\n"
" UNIT[\"metre\",1]]",
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
EXPECT_NE(obj, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_as_wkt) {
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
{
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2019, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("GEOGCRS[") == 0) << wkt;
}
{
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2019_SIMPLIFIED, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("GEOGCRS[") == 0) << wkt;
EXPECT_TRUE(std::string(wkt).find("ANGULARUNIT[") == std::string::npos)
<< wkt;
}
{
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2015, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("GEODCRS[") == 0) << wkt;
}
{
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2015_SIMPLIFIED, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("GEODCRS[") == 0) << wkt;
EXPECT_TRUE(std::string(wkt).find("ANGULARUNIT[") == std::string::npos)
<< wkt;
}
{
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("GEOGCS[\"WGS 84\"") == 0) << wkt;
}
{
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_ESRI, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("GEOGCS[\"GCS_WGS_1984\"") == 0)
<< wkt;
}
// MULTILINE=NO
{
const char *const options[] = {"MULTILINE=NO", nullptr};
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("\n") == std::string::npos) << wkt;
}
// INDENTATION_WIDTH=2
{
const char *const options[] = {"INDENTATION_WIDTH=2", nullptr};
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("\n DATUM") != std::string::npos)
<< wkt;
}
// OUTPUT_AXIS=NO
{
const char *const options[] = {"OUTPUT_AXIS=NO", nullptr};
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("AXIS") == std::string::npos) << wkt;
}
// OUTPUT_AXIS=AUTO
{
const char *const options[] = {"OUTPUT_AXIS=AUTO", nullptr};
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("AXIS") == std::string::npos) << wkt;
}
// OUTPUT_AXIS=YES
{
const char *const options[] = {"OUTPUT_AXIS=YES", nullptr};
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("AXIS") != std::string::npos) << wkt;
}
auto crs4979 = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4979->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper_crs4979(crs4979);
ASSERT_NE(crs4979, nullptr);
// STRICT=NO
{
EXPECT_EQ(proj_as_wkt(m_ctxt, crs4979, PJ_WKT1_GDAL, nullptr), nullptr);
const char *const options[] = {"STRICT=NO", nullptr};
auto wkt = proj_as_wkt(m_ctxt, crs4979, PJ_WKT1_GDAL, options);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("GEOGCS[\"WGS 84\"") == 0) << wkt;
}
// unsupported option
{
const char *const options[] = {"unsupported=yes", nullptr};
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2019, options);
EXPECT_EQ(wkt, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_as_wkt_check_db_use) {
auto obj = proj_create_from_wkt(
m_ctxt, "GEOGCS[\"AGD66\",DATUM[\"Australian_Geodetic_Datum_1966\","
"SPHEROID[\"Australian National Spheroid\",6378160,298.25]],"
"PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]]",
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_ESRI, nullptr);
EXPECT_EQ(std::string(wkt),
"GEOGCS[\"GCS_Australian_1966\",DATUM[\"D_Australian_1966\","
"SPHEROID[\"Australian\",6378160.0,298.25]],"
"PRIMEM[\"Greenwich\",0.0],"
"UNIT[\"Degree\",0.0174532925199433]]");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_as_wkt_incompatible_WKT1) {
auto wkt = createBoundCRS()->exportToWKT(WKTFormatter::create().get());
auto obj =
proj_create_from_wkt(m_ctxt, wkt.c_str(), nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr) << wkt;
auto wkt1_GDAL = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, nullptr);
ASSERT_EQ(wkt1_GDAL, nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_as_proj_string) {
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
{
auto proj_5 = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_5, nullptr);
ASSERT_NE(proj_5, nullptr);
EXPECT_EQ(std::string(proj_5),
"+proj=longlat +datum=WGS84 +no_defs +type=crs");
}
{
auto proj_4 = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_4, nullptr);
ASSERT_NE(proj_4, nullptr);
EXPECT_EQ(std::string(proj_4),
"+proj=longlat +datum=WGS84 +no_defs +type=crs");
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_as_proj_string_incompatible_WKT1) {
auto obj = proj_create_from_wkt(
m_ctxt,
createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto str = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_5, nullptr);
ASSERT_EQ(str, nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_as_proj_string_approx_tmerc_option_yes) {
auto obj = proj_create(m_ctxt, "+proj=tmerc +type=crs");
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
const char *options[] = {"USE_APPROX_TMERC=YES", nullptr};
auto str = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_4, options);
ASSERT_NE(str, nullptr);
EXPECT_EQ(str,
std::string("+proj=tmerc +approx +lat_0=0 +lon_0=0 +k=1 +x_0=0 "
"+y_0=0 +datum=WGS84 +units=m +no_defs +type=crs"));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_create_bound_crs_to_WGS84) {
auto crs = proj_create_from_database(m_ctxt, "EPSG", "3844",
PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
auto res = proj_crs_create_bound_crs_to_WGS84(m_ctxt, crs, nullptr);
ObjectKeeper keeper_res(res);
ASSERT_NE(res, nullptr);
auto proj_4 = proj_as_proj_string(m_ctxt, res, PJ_PROJ_4, nullptr);
ASSERT_NE(proj_4, nullptr);
EXPECT_EQ(std::string(proj_4),
"+proj=sterea +lat_0=46 +lon_0=25 +k=0.99975 +x_0=500000 "
"+y_0=500000 +ellps=krass "
"+towgs84=2.329,-147.042,-92.08,-0.309,0.325,0.497,5.69 "
"+units=m +no_defs +type=crs");
auto base_crs = proj_get_source_crs(m_ctxt, res);
ObjectKeeper keeper_base_crs(base_crs);
ASSERT_NE(base_crs, nullptr);
auto hub_crs = proj_get_target_crs(m_ctxt, res);
ObjectKeeper keeper_hub_crs(hub_crs);
ASSERT_NE(hub_crs, nullptr);
auto transf = proj_crs_get_coordoperation(m_ctxt, res);
ObjectKeeper keeper_transf(transf);
ASSERT_NE(transf, nullptr);
std::vector<double> values(7, 0);
EXPECT_TRUE(proj_coordoperation_get_towgs84_values(m_ctxt, transf,
values.data(), 7, true));
auto expected = std::vector<double>{2.329, -147.042, -92.08, -0.309,
0.325, 0.497, 5.69};
EXPECT_EQ(values, expected);
auto res2 = proj_crs_create_bound_crs(m_ctxt, base_crs, hub_crs, transf);
ObjectKeeper keeper_res2(res2);
ASSERT_NE(res2, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(res, res2, PJ_COMP_STRICT));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_create_bound_crs_to_WGS84_on_invalid_type) {
auto wkt = createProjectedCRS()->derivingConversion()->exportToWKT(
WKTFormatter::create().get());
auto obj =
proj_create_from_wkt(m_ctxt, wkt.c_str(), nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr) << wkt;
auto res = proj_crs_create_bound_crs_to_WGS84(m_ctxt, obj, nullptr);
ASSERT_EQ(res, nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_name) {
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto name = proj_get_name(obj);
ASSERT_TRUE(name != nullptr);
EXPECT_EQ(name, std::string("WGS 84"));
EXPECT_EQ(name, proj_get_name(obj));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_id_auth_name) {
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto auth = proj_get_id_auth_name(obj, 0);
ASSERT_TRUE(auth != nullptr);
EXPECT_EQ(auth, std::string("EPSG"));
EXPECT_EQ(auth, proj_get_id_auth_name(obj, 0));
EXPECT_EQ(proj_get_id_auth_name(obj, -1), nullptr);
EXPECT_EQ(proj_get_id_auth_name(obj, 1), nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_id_code) {
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto code = proj_get_id_code(obj, 0);
ASSERT_TRUE(code != nullptr);
EXPECT_EQ(code, std::string("4326"));
EXPECT_EQ(code, proj_get_id_code(obj, 0));
EXPECT_EQ(proj_get_id_code(obj, -1), nullptr);
EXPECT_EQ(proj_get_id_code(obj, 1), nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_type) {
{
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEOGRAPHIC_2D_CRS);
}
{
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4979->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEOGRAPHIC_3D_CRS);
}
{
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4978->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEOCENTRIC_CRS);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, GeographicCRS::EPSG_4326->datum()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEODETIC_REFERENCE_FRAME);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, GeographicCRS::EPSG_4326->ellipsoid()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_ELLIPSOID);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, createProjectedCRS()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_PROJECTED_CRS);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, createVerticalCRS()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_VERTICAL_CRS);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, createVerticalCRS()
->datum()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_VERTICAL_REFERENCE_FRAME);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, createProjectedCRS()
->derivingConversion()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_CONVERSION);
}
{
auto obj = proj_create_from_wkt(
m_ctxt,
createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_BOUND_CRS);
}
{
auto obj = proj_create_from_wkt(
m_ctxt, createBoundCRS()
->transformation()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_get_type(obj), PJ_TYPE_TRANSFORMATION);
}
{
auto obj = proj_create_from_wkt(m_ctxt, "AUTHORITY[\"EPSG\", 4326]",
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_EQ(obj, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_from_database) {
{
auto crs = proj_create_from_database(m_ctxt, "EPSG", "-1",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_EQ(crs, nullptr);
}
{
auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
EXPECT_TRUE(proj_is_crs(crs));
EXPECT_FALSE(proj_is_deprecated(crs));
EXPECT_EQ(proj_get_type(crs), PJ_TYPE_GEOGRAPHIC_2D_CRS);
const char *code = proj_get_id_code(crs, 0);
ASSERT_NE(code, nullptr);
EXPECT_EQ(std::string(code), "4326");
}
{
auto crs = proj_create_from_database(m_ctxt, "EPSG", "6871",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
EXPECT_TRUE(proj_is_crs(crs));
EXPECT_EQ(proj_get_type(crs), PJ_TYPE_COMPOUND_CRS);
}
{
auto ellipsoid = proj_create_from_database(
m_ctxt, "EPSG", "7030", PJ_CATEGORY_ELLIPSOID, false, nullptr);
ASSERT_NE(ellipsoid, nullptr);
ObjectKeeper keeper(ellipsoid);
EXPECT_EQ(proj_get_type(ellipsoid), PJ_TYPE_ELLIPSOID);
}
{
auto pm = proj_create_from_database(
m_ctxt, "EPSG", "8903", PJ_CATEGORY_PRIME_MERIDIAN, false, nullptr);
ASSERT_NE(pm, nullptr);
ObjectKeeper keeper(pm);
EXPECT_EQ(proj_get_type(pm), PJ_TYPE_PRIME_MERIDIAN);
}
{
auto datum = proj_create_from_database(
m_ctxt, "EPSG", "6326", PJ_CATEGORY_DATUM, false, nullptr);
ASSERT_NE(datum, nullptr);
ObjectKeeper keeper(datum);
EXPECT_EQ(proj_get_type(datum), PJ_TYPE_GEODETIC_REFERENCE_FRAME);
}
{
auto op = proj_create_from_database(m_ctxt, "EPSG", "16031",
PJ_CATEGORY_COORDINATE_OPERATION,
false, nullptr);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper(op);
EXPECT_EQ(proj_get_type(op), PJ_TYPE_CONVERSION);
auto info = proj_pj_info(op);
EXPECT_NE(info.id, nullptr);
EXPECT_EQ(info.id, std::string("utm"));
ASSERT_NE(info.description, nullptr);
EXPECT_EQ(info.description, std::string("UTM zone 31N"));
ASSERT_NE(info.definition, nullptr);
EXPECT_EQ(info.definition, std::string("proj=utm zone=31 ellps=GRS80"));
EXPECT_EQ(info.accuracy, 0);
}
{
auto op = proj_create_from_database(m_ctxt, "EPSG", "1024",
PJ_CATEGORY_COORDINATE_OPERATION,
false, nullptr);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper(op);
EXPECT_EQ(proj_get_type(op), PJ_TYPE_TRANSFORMATION);
auto info = proj_pj_info(op);
EXPECT_NE(info.id, nullptr);
EXPECT_EQ(info.id, std::string("pipeline"));
ASSERT_NE(info.description, nullptr);
EXPECT_EQ(info.description, std::string("MGI to ETRS89 (4)"));
ASSERT_NE(info.definition, nullptr);
EXPECT_EQ(
info.definition,
std::string("proj=pipeline step proj=axisswap "
"order=2,1 step proj=unitconvert xy_in=deg xy_out=rad "
"step proj=push v_3 "
"step proj=cart ellps=bessel step proj=helmert "
"x=601.705 y=84.263 z=485.227 rx=-4.7354 ry=-1.3145 "
"rz=-5.393 s=-2.3887 convention=coordinate_frame "
"step inv proj=cart ellps=GRS80 "
"step proj=pop v_3 "
"step proj=unitconvert xy_in=rad xy_out=deg "
"step proj=axisswap order=2,1"));
EXPECT_EQ(info.accuracy, 1);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs) {
auto crs = proj_create_from_wkt(
m_ctxt,
createProjectedCRS()
->exportToWKT(
WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get())
.c_str(),
nullptr, nullptr, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
EXPECT_TRUE(proj_is_crs(crs));
auto geodCRS = proj_crs_get_geodetic_crs(m_ctxt, crs);
ASSERT_NE(geodCRS, nullptr);
ObjectKeeper keeper_geogCRS(geodCRS);
EXPECT_TRUE(proj_is_crs(geodCRS));
auto geogCRS_name = proj_get_name(geodCRS);
ASSERT_TRUE(geogCRS_name != nullptr);
EXPECT_EQ(geogCRS_name, std::string("WGS 84"));
auto h_datum = proj_crs_get_horizontal_datum(m_ctxt, crs);
ASSERT_NE(h_datum, nullptr);
ObjectKeeper keeper_h_datum(h_datum);
auto datum = proj_crs_get_datum(m_ctxt, crs);
ASSERT_NE(datum, nullptr);
ObjectKeeper keeper_datum(datum);
EXPECT_TRUE(proj_is_equivalent_to(h_datum, datum, PJ_COMP_STRICT));
auto datum_name = proj_get_name(datum);
ASSERT_TRUE(datum_name != nullptr);
EXPECT_EQ(datum_name, std::string("World Geodetic System 1984"));
auto ellipsoid = proj_get_ellipsoid(m_ctxt, crs);
ASSERT_NE(ellipsoid, nullptr);
ObjectKeeper keeper_ellipsoid(ellipsoid);
auto ellipsoid_name = proj_get_name(ellipsoid);
ASSERT_TRUE(ellipsoid_name != nullptr);
EXPECT_EQ(ellipsoid_name, std::string("WGS 84"));
auto ellipsoid_from_datum = proj_get_ellipsoid(m_ctxt, datum);
ASSERT_NE(ellipsoid_from_datum, nullptr);
ObjectKeeper keeper_ellipsoid_from_datum(ellipsoid_from_datum);
EXPECT_EQ(proj_get_ellipsoid(m_ctxt, ellipsoid), nullptr);
EXPECT_FALSE(proj_is_crs(ellipsoid));
double a;
double b;
int b_is_computed;
double rf;
EXPECT_TRUE(proj_ellipsoid_get_parameters(m_ctxt, ellipsoid, nullptr,
nullptr, nullptr, nullptr));
EXPECT_TRUE(proj_ellipsoid_get_parameters(m_ctxt, ellipsoid, &a, &b,
&b_is_computed, &rf));
EXPECT_FALSE(proj_ellipsoid_get_parameters(m_ctxt, crs, &a, &b,
&b_is_computed, &rf));
EXPECT_EQ(a, 6378137);
EXPECT_NEAR(b, 6356752.31424518, 1e-9);
EXPECT_EQ(b_is_computed, 1);
EXPECT_EQ(rf, 298.257223563);
auto id = proj_get_id_code(ellipsoid, 0);
ASSERT_TRUE(id != nullptr);
EXPECT_EQ(id, std::string("7030"));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_prime_meridian) {
auto crs = proj_create_from_wkt(
m_ctxt,
createProjectedCRS()
->exportToWKT(
WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get())
.c_str(),
nullptr, nullptr, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
auto pm = proj_get_prime_meridian(m_ctxt, crs);
ASSERT_NE(pm, nullptr);
ObjectKeeper keeper_pm(pm);
auto pm_name = proj_get_name(pm);
ASSERT_TRUE(pm_name != nullptr);
EXPECT_EQ(pm_name, std::string("Greenwich"));
EXPECT_EQ(proj_get_prime_meridian(m_ctxt, pm), nullptr);
EXPECT_TRUE(proj_prime_meridian_get_parameters(m_ctxt, pm, nullptr, nullptr,
nullptr));
double longitude = -1;
double longitude_unit = 0;
const char *longitude_unit_name = nullptr;
EXPECT_TRUE(proj_prime_meridian_get_parameters(
m_ctxt, pm, &longitude, &longitude_unit, &longitude_unit_name));
EXPECT_EQ(longitude, 0);
EXPECT_NEAR(longitude_unit, UnitOfMeasure::DEGREE.conversionToSI(), 1e-10);
ASSERT_TRUE(longitude_unit_name != nullptr);
EXPECT_EQ(longitude_unit_name, std::string("degree"));
auto datum = proj_crs_get_horizontal_datum(m_ctxt, crs);
ASSERT_NE(datum, nullptr);
ObjectKeeper keeper_datum(datum);
auto pm_from_datum = proj_get_prime_meridian(m_ctxt, datum);
ASSERT_NE(pm_from_datum, nullptr);
ObjectKeeper keeper_pm_from_datum(pm_from_datum);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_compound) {
auto crs = proj_create_from_wkt(
m_ctxt,
createCompoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
EXPECT_EQ(proj_get_type(crs), PJ_TYPE_COMPOUND_CRS);
EXPECT_EQ(proj_crs_get_sub_crs(m_ctxt, crs, -1), nullptr);
EXPECT_EQ(proj_crs_get_sub_crs(m_ctxt, crs, 2), nullptr);
auto subcrs_horiz = proj_crs_get_sub_crs(m_ctxt, crs, 0);
ASSERT_NE(subcrs_horiz, nullptr);
ObjectKeeper keeper_subcrs_horiz(subcrs_horiz);
EXPECT_EQ(proj_get_type(subcrs_horiz), PJ_TYPE_PROJECTED_CRS);
EXPECT_EQ(proj_crs_get_sub_crs(m_ctxt, subcrs_horiz, 0), nullptr);
auto subcrs_vertical = proj_crs_get_sub_crs(m_ctxt, crs, 1);
ASSERT_NE(subcrs_vertical, nullptr);
ObjectKeeper keeper_subcrs_vertical(subcrs_vertical);
EXPECT_EQ(proj_get_type(subcrs_vertical), PJ_TYPE_VERTICAL_CRS);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_source_target_crs_bound_crs) {
auto crs = proj_create_from_wkt(
m_ctxt,
createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
auto sourceCRS = proj_get_source_crs(m_ctxt, crs);
ASSERT_NE(sourceCRS, nullptr);
ObjectKeeper keeper_sourceCRS(sourceCRS);
EXPECT_EQ(std::string(proj_get_name(sourceCRS)), "NTF (Paris)");
auto targetCRS = proj_get_target_crs(m_ctxt, crs);
ASSERT_NE(targetCRS, nullptr);
ObjectKeeper keeper_targetCRS(targetCRS);
EXPECT_EQ(std::string(proj_get_name(targetCRS)), "WGS 84");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_source_target_crs_transformation) {
auto obj = proj_create_from_wkt(
m_ctxt, createBoundCRS()
->transformation()
->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ASSERT_NE(obj, nullptr);
ObjectKeeper keeper(obj);
auto sourceCRS = proj_get_source_crs(m_ctxt, obj);
ASSERT_NE(sourceCRS, nullptr);
ObjectKeeper keeper_sourceCRS(sourceCRS);
EXPECT_EQ(std::string(proj_get_name(sourceCRS)), "NTF (Paris)");
auto targetCRS = proj_get_target_crs(m_ctxt, obj);
ASSERT_NE(targetCRS, nullptr);
ObjectKeeper keeper_targetCRS(targetCRS);
EXPECT_EQ(std::string(proj_get_name(targetCRS)), "WGS 84");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_source_crs_of_projected_crs) {
auto crs = proj_create_from_wkt(
m_ctxt,
createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
auto sourceCRS = proj_get_source_crs(m_ctxt, crs);
ASSERT_NE(sourceCRS, nullptr);
ObjectKeeper keeper_sourceCRS(sourceCRS);
EXPECT_EQ(std::string(proj_get_name(sourceCRS)), "WGS 84");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_source_target_crs_conversion_without_crs) {
auto obj = proj_create_from_database(m_ctxt, "EPSG", "16031",
PJ_CATEGORY_COORDINATE_OPERATION,
false, nullptr);
ASSERT_NE(obj, nullptr);
ObjectKeeper keeper(obj);
auto sourceCRS = proj_get_source_crs(m_ctxt, obj);
ASSERT_EQ(sourceCRS, nullptr);
auto targetCRS = proj_get_target_crs(m_ctxt, obj);
ASSERT_EQ(targetCRS, nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_source_target_crs_invalid_object) {
auto obj = proj_create_from_wkt(
m_ctxt, "ELLIPSOID[\"WGS 84\",6378137,298.257223563]", nullptr, nullptr,
nullptr);
ASSERT_NE(obj, nullptr);
ObjectKeeper keeper(obj);
auto sourceCRS = proj_get_source_crs(m_ctxt, obj);
ASSERT_EQ(sourceCRS, nullptr);
auto targetCRS = proj_get_target_crs(m_ctxt, obj);
ASSERT_EQ(targetCRS, nullptr);
}
// ---------------------------------------------------------------------------
struct ListFreer {
PROJ_STRING_LIST list;
ListFreer(PROJ_STRING_LIST ptrIn) : list(ptrIn) {}
~ListFreer() { proj_string_list_destroy(list); }
ListFreer(const ListFreer &) = delete;
ListFreer &operator=(const ListFreer &) = delete;
};
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_authorities_from_database) {
auto list = proj_get_authorities_from_database(m_ctxt);
ListFreer feer(list);
ASSERT_NE(list, nullptr);
ASSERT_TRUE(list[0] != nullptr);
EXPECT_EQ(list[0], std::string("EPSG"));
ASSERT_TRUE(list[1] != nullptr);
EXPECT_EQ(list[1], std::string("ESRI"));
ASSERT_TRUE(list[2] != nullptr);
EXPECT_EQ(list[2], std::string("IGNF"));
ASSERT_TRUE(list[3] != nullptr);
EXPECT_EQ(list[3], std::string("OGC"));
ASSERT_TRUE(list[4] != nullptr);
EXPECT_EQ(list[4], std::string("PROJ"));
EXPECT_EQ(list[5], nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_codes_from_database) {
auto listTypes =
std::vector<PJ_TYPE>{PJ_TYPE_ELLIPSOID,
PJ_TYPE_PRIME_MERIDIAN,
PJ_TYPE_GEODETIC_REFERENCE_FRAME,
PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME,
PJ_TYPE_VERTICAL_REFERENCE_FRAME,
PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME,
PJ_TYPE_DATUM_ENSEMBLE,
PJ_TYPE_CRS,
PJ_TYPE_GEODETIC_CRS,
PJ_TYPE_GEOCENTRIC_CRS,
PJ_TYPE_GEOGRAPHIC_CRS,
PJ_TYPE_GEOGRAPHIC_2D_CRS,
PJ_TYPE_GEOGRAPHIC_3D_CRS,
PJ_TYPE_VERTICAL_CRS,
PJ_TYPE_PROJECTED_CRS,
PJ_TYPE_COMPOUND_CRS,
PJ_TYPE_TEMPORAL_CRS,
PJ_TYPE_BOUND_CRS,
PJ_TYPE_OTHER_CRS,
PJ_TYPE_CONVERSION,
PJ_TYPE_TRANSFORMATION,
PJ_TYPE_CONCATENATED_OPERATION,
PJ_TYPE_OTHER_COORDINATE_OPERATION,
PJ_TYPE_UNKNOWN};
for (const auto &type : listTypes) {
auto list = proj_get_codes_from_database(m_ctxt, "EPSG", type, true);
ListFreer feer(list);
if (type == PJ_TYPE_TEMPORAL_CRS || type == PJ_TYPE_BOUND_CRS ||
type == PJ_TYPE_UNKNOWN) {
EXPECT_EQ(list, nullptr) << type;
} else {
ASSERT_NE(list, nullptr) << type;
ASSERT_NE(list[0], nullptr) << type;
}
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, conversion) {
auto crs = proj_create_from_database(m_ctxt, "EPSG", "32631",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
// invalid object type
EXPECT_FALSE(proj_coordoperation_get_method_info(m_ctxt, crs, nullptr,
nullptr, nullptr));
{
auto conv = proj_crs_get_coordoperation(m_ctxt, crs);
ASSERT_NE(conv, nullptr);
ObjectKeeper keeper_conv(conv);
ASSERT_EQ(proj_crs_get_coordoperation(m_ctxt, conv), nullptr);
}
auto conv = proj_crs_get_coordoperation(m_ctxt, crs);
ASSERT_NE(conv, nullptr);
ObjectKeeper keeper_conv(conv);
EXPECT_TRUE(proj_coordoperation_get_method_info(m_ctxt, conv, nullptr,
nullptr, nullptr));
const char *methodName = nullptr;
const char *methodAuthorityName = nullptr;
const char *methodCode = nullptr;
EXPECT_TRUE(proj_coordoperation_get_method_info(
m_ctxt, conv, &methodName, &methodAuthorityName, &methodCode));
ASSERT_NE(methodName, nullptr);
ASSERT_NE(methodAuthorityName, nullptr);
ASSERT_NE(methodCode, nullptr);
EXPECT_EQ(methodName, std::string("Transverse Mercator"));
EXPECT_EQ(methodAuthorityName, std::string("EPSG"));
EXPECT_EQ(methodCode, std::string("9807"));
EXPECT_EQ(proj_coordoperation_get_param_count(m_ctxt, conv), 5);
EXPECT_EQ(proj_coordoperation_get_param_index(m_ctxt, conv, "foo"), -1);
EXPECT_EQ(
proj_coordoperation_get_param_index(m_ctxt, conv, "False easting"), 3);
EXPECT_FALSE(proj_coordoperation_get_param(
m_ctxt, conv, -1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr));
EXPECT_FALSE(proj_coordoperation_get_param(
m_ctxt, conv, 5, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr));
const char *name = nullptr;
const char *nameAuthorityName = nullptr;
const char *nameCode = nullptr;
double value = 0;
const char *valueString = nullptr;
double valueUnitConvFactor = 0;
const char *valueUnitName = nullptr;
const char *unitAuthName = nullptr;
const char *unitCode = nullptr;
const char *unitCategory = nullptr;
EXPECT_TRUE(proj_coordoperation_get_param(
m_ctxt, conv, 3, &name, &nameAuthorityName, &nameCode, &value,
&valueString, &valueUnitConvFactor, &valueUnitName, &unitAuthName,
&unitCode, &unitCategory));
ASSERT_NE(name, nullptr);
ASSERT_NE(nameAuthorityName, nullptr);
ASSERT_NE(nameCode, nullptr);
EXPECT_EQ(valueString, nullptr);
ASSERT_NE(valueUnitName, nullptr);
ASSERT_NE(unitAuthName, nullptr);
ASSERT_NE(unitCategory, nullptr);
ASSERT_NE(unitCategory, nullptr);
EXPECT_EQ(name, std::string("False easting"));
EXPECT_EQ(nameAuthorityName, std::string("EPSG"));
EXPECT_EQ(nameCode, std::string("8806"));
EXPECT_EQ(value, 500000.0);
EXPECT_EQ(valueUnitConvFactor, 1.0);
EXPECT_EQ(valueUnitName, std::string("metre"));
EXPECT_EQ(unitAuthName, std::string("EPSG"));
EXPECT_EQ(unitCode, std::string("9001"));
EXPECT_EQ(unitCategory, std::string("linear"));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, transformation_from_boundCRS) {
auto crs = proj_create_from_wkt(
m_ctxt,
createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
auto transf = proj_crs_get_coordoperation(m_ctxt, crs);
ASSERT_NE(transf, nullptr);
ObjectKeeper keeper_transf(transf);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_coordoperation_get_grid_used) {
auto op = proj_create_from_database(m_ctxt, "EPSG", "1312",
PJ_CATEGORY_COORDINATE_OPERATION, true,
nullptr);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper(op);
EXPECT_EQ(proj_coordoperation_get_grid_used_count(m_ctxt, op), 1);
const char *shortName = nullptr;
const char *fullName = nullptr;
const char *packageName = nullptr;
const char *url = nullptr;
int directDownload = 0;
int openLicense = 0;
int available = 0;
EXPECT_EQ(proj_coordoperation_get_grid_used(m_ctxt, op, -1, nullptr,
nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr),
0);
EXPECT_EQ(proj_coordoperation_get_grid_used(m_ctxt, op, 1, nullptr, nullptr,
nullptr, nullptr, nullptr,
nullptr, nullptr),
0);
EXPECT_EQ(proj_coordoperation_get_grid_used(
m_ctxt, op, 0, &shortName, &fullName, &packageName, &url,
&directDownload, &openLicense, &available),
1);
ASSERT_NE(shortName, nullptr);
ASSERT_NE(fullName, nullptr);
ASSERT_NE(packageName, nullptr);
ASSERT_NE(url, nullptr);
EXPECT_EQ(shortName, std::string("ntv1_can.dat"));
// EXPECT_EQ(fullName, std::string(""));
EXPECT_EQ(packageName, std::string("proj-datumgrid"));
EXPECT_TRUE(std::string(url).find(
"https://download.osgeo.org/proj/proj-datumgrid-") == 0)
<< std::string(url);
EXPECT_EQ(directDownload, 1);
EXPECT_EQ(openLicense, 1);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_coordoperation_is_instantiable) {
auto op = proj_create_from_database(m_ctxt, "EPSG", "1671",
PJ_CATEGORY_COORDINATE_OPERATION, true,
nullptr);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper(op);
EXPECT_EQ(proj_coordoperation_is_instantiable(m_ctxt, op), 1);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_operations) {
auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr);
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
auto source_crs = proj_create_from_database(
m_ctxt, "EPSG", "4267", PJ_CATEGORY_CRS, false, nullptr); // NAD27
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
auto target_crs = proj_create_from_database(
m_ctxt, "EPSG", "4269", PJ_CATEGORY_CRS, false, nullptr); // NAD83
ASSERT_NE(target_crs, nullptr);
ObjectKeeper keeper_target_crs(target_crs);
proj_operation_factory_context_set_spatial_criterion(
m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION);
proj_operation_factory_context_set_grid_availability_use(
m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 10);
EXPECT_EQ(proj_list_get(m_ctxt, res, -1), nullptr);
EXPECT_EQ(proj_list_get(m_ctxt, res, proj_list_get_count(res)), nullptr);
auto op = proj_list_get(m_ctxt, res, 0);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper_op(op);
EXPECT_FALSE(proj_coordoperation_has_ballpark_transformation(m_ctxt, op));
EXPECT_EQ(proj_get_name(op), std::string("NAD27 to NAD83 (3)"));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_operations_discard_superseded) {
auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr);
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
auto source_crs = proj_create_from_database(
m_ctxt, "EPSG", "4203", PJ_CATEGORY_CRS, false, nullptr); // AGD84
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
auto target_crs = proj_create_from_database(
m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84
ASSERT_NE(target_crs, nullptr);
ObjectKeeper keeper_target_crs(target_crs);
proj_operation_factory_context_set_spatial_criterion(
m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION);
proj_operation_factory_context_set_grid_availability_use(
m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED);
proj_operation_factory_context_set_discard_superseded(m_ctxt, ctxt, true);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 2);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_operations_dont_discard_superseded) {
auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr);
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
auto source_crs = proj_create_from_database(
m_ctxt, "EPSG", "4203", PJ_CATEGORY_CRS, false, nullptr); // AGD84
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
auto target_crs = proj_create_from_database(
m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84
ASSERT_NE(target_crs, nullptr);
ObjectKeeper keeper_target_crs(target_crs);
proj_operation_factory_context_set_spatial_criterion(
m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION);
proj_operation_factory_context_set_grid_availability_use(
m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED);
proj_operation_factory_context_set_discard_superseded(m_ctxt, ctxt, false);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 5);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_operations_with_pivot) {
auto source_crs = proj_create_from_database(
m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
auto target_crs = proj_create_from_database(
m_ctxt, "EPSG", "6668", PJ_CATEGORY_CRS, false, nullptr); // JGD2011
ASSERT_NE(target_crs, nullptr);
ObjectKeeper keeper_target_crs(target_crs);
// There is no direct transformations between both
// Default behaviour: allow any pivot
{
auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr);
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 1);
auto op = proj_list_get(m_ctxt, res, 0);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper_op(op);
EXPECT_EQ(
proj_get_name(op),
std::string(
"Inverse of JGD2000 to WGS 84 (1) + JGD2000 to JGD2011 (2)"));
}
// Disallow pivots
{
auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr);
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
proj_operation_factory_context_set_allow_use_intermediate_crs(
m_ctxt, ctxt, PROJ_INTERMEDIATE_CRS_USE_NEVER);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 1);
auto op = proj_list_get(m_ctxt, res, 0);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper_op(op);
EXPECT_EQ(
proj_get_name(op),
std::string("Ballpark geographic offset from WGS 84 to JGD2011"));
}
// Restrict pivot to Tokyo CRS
{
auto ctxt = proj_create_operation_factory_context(m_ctxt, "EPSG");
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
const char *pivots[] = {"EPSG", "4301", nullptr};
proj_operation_factory_context_set_allowed_intermediate_crs(
m_ctxt, ctxt, pivots);
proj_operation_factory_context_set_spatial_criterion(
m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION);
proj_operation_factory_context_set_grid_availability_use(
m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 7);
auto op = proj_list_get(m_ctxt, res, 0);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper_op(op);
EXPECT_EQ(
proj_get_name(op),
std::string(
"Inverse of Tokyo to WGS 84 (108) + Tokyo to JGD2011 (2)"));
}
// Restrict pivot to JGD2000
{
auto ctxt = proj_create_operation_factory_context(m_ctxt, "any");
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
const char *pivots[] = {"EPSG", "4612", nullptr};
proj_operation_factory_context_set_allowed_intermediate_crs(
m_ctxt, ctxt, pivots);
proj_operation_factory_context_set_spatial_criterion(
m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION);
proj_operation_factory_context_set_grid_availability_use(
m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED);
proj_operation_factory_context_set_allow_use_intermediate_crs(
m_ctxt, ctxt, PROJ_INTERMEDIATE_CRS_USE_ALWAYS);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
// includes results from ESRI
EXPECT_EQ(proj_list_get_count(res), 4);
auto op = proj_list_get(m_ctxt, res, 0);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper_op(op);
EXPECT_EQ(
proj_get_name(op),
std::string(
"Inverse of JGD2000 to WGS 84 (1) + JGD2000 to JGD2011 (2)"));
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_context_set_database_path_null) {
EXPECT_TRUE(
proj_context_set_database_path(m_ctxt, nullptr, nullptr, nullptr));
auto source_crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false,
nullptr); // WGS84
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_context_set_database_path_main_memory_one_aux) {
auto c_path = proj_context_get_database_path(m_ctxt);
ASSERT_TRUE(c_path != nullptr);
std::string path(c_path);
const char *aux_db_list[] = {path.c_str(), nullptr};
// This is super exotic and a miracle that it works. :memory: as the
// main DB is empty. The real stuff is in the aux_db_list. No view
// is created in the ':memory:' internal DB, but as there's only one
// aux DB its tables and views can be directly queried...
// If that breaks at some point, that wouldn't be a big issue.
// Keeping that one as I had a hard time figuring out why it worked !
// The real thing is tested by the C++
// factory::attachExtraDatabases_auxiliary
EXPECT_TRUE(proj_context_set_database_path(m_ctxt, ":memory:", aux_db_list,
nullptr));
auto source_crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false,
nullptr); // WGS84
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_context_set_database_path_error_1) {
EXPECT_FALSE(proj_context_set_database_path(m_ctxt, "i_do_not_exist.db",
nullptr, nullptr));
// We will eventually re-open on the default DB
auto source_crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false,
nullptr); // WGS84
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_context_set_database_path_error_2) {
const char *aux_db_list[] = {"i_do_not_exist.db", nullptr};
EXPECT_FALSE(
proj_context_set_database_path(m_ctxt, nullptr, aux_db_list, nullptr));
// We will eventually re-open on the default DB
auto source_crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false,
nullptr); // WGS84
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_context_guess_wkt_dialect) {
EXPECT_EQ(proj_context_guess_wkt_dialect(nullptr, "LOCAL_CS[\"foo\"]"),
PJ_GUESSED_WKT1_GDAL);
EXPECT_EQ(proj_context_guess_wkt_dialect(
nullptr,
"GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_"
"1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],"
"UNIT[\"Degree\",0.0174532925199433]]"),
PJ_GUESSED_WKT1_ESRI);
EXPECT_EQ(proj_context_guess_wkt_dialect(
nullptr,
"GEOGCRS[\"WGS 84\",\n"
" DATUM[\"World Geodetic System 1984\",\n"
" ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n"
" CS[ellipsoidal,2],\n"
" AXIS[\"geodetic latitude (Lat)\",north],\n"
" AXIS[\"geodetic longitude (Lon)\",east],\n"
" UNIT[\"degree\",0.0174532925199433]]"),
PJ_GUESSED_WKT2_2019);
EXPECT_EQ(proj_context_guess_wkt_dialect(
nullptr,
"GEODCRS[\"WGS 84\",\n"
" DATUM[\"World Geodetic System 1984\",\n"
" ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n"
" CS[ellipsoidal,2],\n"
" AXIS[\"geodetic latitude (Lat)\",north],\n"
" AXIS[\"geodetic longitude (Lon)\",east],\n"
" UNIT[\"degree\",0.0174532925199433]]"),
PJ_GUESSED_WKT2_2015);
EXPECT_EQ(proj_context_guess_wkt_dialect(nullptr, "foo"),
PJ_GUESSED_NOT_WKT);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_from_name) {
/*
PJ_OBJ_LIST PROJ_DLL *proj_create_from_name(
PJ_CONTEXT *ctx,
const char *auth_name,
const char *searchedName,
const PJ_TYPE* types,
size_t typesCount,
int approximateMatch,
size_t limitResultCount,
const char* const *options); */
{
auto res = proj_create_from_name(m_ctxt, nullptr, "WGS 84", nullptr, 0,
false, 0, nullptr);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 4);
}
{
auto res = proj_create_from_name(m_ctxt, "xx", "WGS 84", nullptr, 0,
false, 0, nullptr);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 0);
}
{
const PJ_TYPE types[] = {PJ_TYPE_GEODETIC_CRS, PJ_TYPE_PROJECTED_CRS};
auto res = proj_create_from_name(m_ctxt, nullptr, "WGS 84", types, 2,
true, 10, nullptr);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 10);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_identify) {
auto obj = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4807->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
{
auto res = proj_identify(m_ctxt, obj, nullptr, nullptr, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 1);
}
{
int *confidence = nullptr;
auto res = proj_identify(m_ctxt, obj, "EPSG", nullptr, &confidence);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 1);
EXPECT_EQ(confidence[0], 100);
proj_int_list_destroy(confidence);
}
{
auto objEllps = proj_create_from_wkt(
m_ctxt,
Ellipsoid::GRS1980->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeperEllps(objEllps);
ASSERT_NE(objEllps, nullptr);
auto res = proj_identify(m_ctxt, objEllps, nullptr, nullptr, nullptr);
ObjListKeeper keeper_res(res);
EXPECT_EQ(res, nullptr);
}
{
auto obj2 = proj_create(
m_ctxt, "+proj=longlat +datum=WGS84 +no_defs +type=crs");
ObjectKeeper keeper2(obj2);
ASSERT_NE(obj2, nullptr);
int *confidence = nullptr;
auto res = proj_identify(m_ctxt, obj2, nullptr, nullptr, &confidence);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 4);
proj_int_list_destroy(confidence);
}
{
auto obj2 = proj_create_from_database(m_ctxt, "IGNF", "ETRS89UTM28",
PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper2(obj2);
ASSERT_NE(obj2, nullptr);
int *confidence = nullptr;
auto res = proj_identify(m_ctxt, obj2, "EPSG", nullptr, &confidence);
ObjListKeeper keeper_res(res);
EXPECT_EQ(proj_list_get_count(res), 1);
auto gotCRS = proj_list_get(m_ctxt, res, 0);
ASSERT_NE(gotCRS, nullptr);
ObjectKeeper keeper_gotCRS(gotCRS);
auto auth = proj_get_id_auth_name(gotCRS, 0);
ASSERT_TRUE(auth != nullptr);
EXPECT_EQ(auth, std::string("EPSG"));
auto code = proj_get_id_code(gotCRS, 0);
ASSERT_TRUE(code != nullptr);
EXPECT_EQ(code, std::string("25828"));
EXPECT_EQ(confidence[0], 70);
proj_int_list_destroy(confidence);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_area_of_use) {
{
auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
EXPECT_TRUE(proj_get_area_of_use(m_ctxt, crs, nullptr, nullptr, nullptr,
nullptr, nullptr));
const char *name = nullptr;
double w;
double s;
double e;
double n;
EXPECT_TRUE(proj_get_area_of_use(m_ctxt, crs, &w, &s, &e, &n, &name));
EXPECT_EQ(w, -180);
EXPECT_EQ(s, -90);
EXPECT_EQ(e, 180);
EXPECT_EQ(n, 90);
ASSERT_TRUE(name != nullptr);
EXPECT_EQ(std::string(name), "World");
}
{
auto obj = proj_create(m_ctxt, "+proj=longlat +type=crs");
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_FALSE(proj_get_area_of_use(m_ctxt, obj, nullptr, nullptr,
nullptr, nullptr, nullptr));
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_coordoperation_get_accuracy) {
{
auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
EXPECT_EQ(proj_coordoperation_get_accuracy(m_ctxt, crs), -1.0);
}
{
auto obj = proj_create_from_database(m_ctxt, "EPSG", "1170",
PJ_CATEGORY_COORDINATE_OPERATION,
false, nullptr);
ASSERT_NE(obj, nullptr);
ObjectKeeper keeper(obj);
EXPECT_EQ(proj_coordoperation_get_accuracy(m_ctxt, obj), 16.0);
}
{
auto obj = proj_create(m_ctxt, "+proj=helmert");
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
EXPECT_EQ(proj_coordoperation_get_accuracy(m_ctxt, obj), -1.0);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_geographic_crs) {
auto cs = proj_create_ellipsoidal_2D_cs(
m_ctxt, PJ_ELLPS2D_LATITUDE_LONGITUDE, nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
{
auto obj = proj_create_geographic_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto objRef =
proj_create(m_ctxt, GeographicCRS::EPSG_4326
->exportToWKT(WKTFormatter::create().get())
.c_str());
ObjectKeeper keeperobjRef(objRef);
EXPECT_NE(objRef, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT));
auto datum = proj_crs_get_datum(m_ctxt, obj);
ObjectKeeper keeper_datum(datum);
ASSERT_NE(datum, nullptr);
auto obj2 =
proj_create_geographic_crs_from_datum(m_ctxt, "WGS 84", datum, cs);
ObjectKeeper keeperObj(obj2);
ASSERT_NE(obj2, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(obj, obj2, PJ_COMP_STRICT));
}
{
auto obj =
proj_create_geographic_crs(m_ctxt, nullptr, nullptr, nullptr, 1.0,
0.0, nullptr, 0.0, nullptr, 0.0, cs);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
}
// Datum with GDAL_WKT1 spelling: special case of WGS_1984
{
auto obj = proj_create_geographic_crs(
m_ctxt, "WGS 84", "WGS_1984", "WGS 84", 6378137, 298.257223563,
"Greenwich", 0.0, "Degree", 0.0174532925199433, cs);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto objRef =
proj_create(m_ctxt, GeographicCRS::EPSG_4326
->exportToWKT(WKTFormatter::create().get())
.c_str());
ObjectKeeper keeperobjRef(objRef);
EXPECT_NE(objRef, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT));
}
// Datum with GDAL_WKT1 spelling: database query
{
auto obj = proj_create_geographic_crs(
m_ctxt, "NAD83", "North_American_Datum_1983", "GRS 1980", 6378137,
298.257222101, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto objRef =
proj_create(m_ctxt, GeographicCRS::EPSG_4269
->exportToWKT(WKTFormatter::create().get())
.c_str());
ObjectKeeper keeperobjRef(objRef);
EXPECT_NE(objRef, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT));
}
// Datum with GDAL_WKT1 spelling: database query in alias_name table
{
auto crs = proj_create_geographic_crs(
m_ctxt, "S-JTSK (Ferro)",
"System_Jednotne_Trigonometricke_Site_Katastralni_Ferro",
"Bessel 1841", 6377397.155, 299.1528128, "Ferro",
-17.66666666666667, "Degree", 0.0174532925199433, cs);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
auto datum = proj_crs_get_datum(m_ctxt, crs);
ASSERT_NE(datum, nullptr);
ObjectKeeper keeper_datum(datum);
auto datum_name = proj_get_name(datum);
ASSERT_TRUE(datum_name != nullptr);
EXPECT_EQ(datum_name,
std::string("System of the Unified Trigonometrical Cadastral "
"Network (Ferro)"));
}
// WKT1 with (deprecated)
{
auto crs = proj_create_geographic_crs(
m_ctxt, "SAD69 (deprecated)", "South_American_Datum_1969",
"GRS 1967", 6378160, 298.247167427, "Greenwich", 0, "Degree",
0.0174532925199433, cs);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
auto name = proj_get_name(crs);
ASSERT_TRUE(name != nullptr);
EXPECT_EQ(name, std::string("SAD69"));
EXPECT_TRUE(proj_is_deprecated(crs));
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_geocentric_crs) {
{
auto obj = proj_create_geocentric_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433,
"Metre", 1.0);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto objRef =
proj_create(m_ctxt, GeographicCRS::EPSG_4978
->exportToWKT(WKTFormatter::create().get())
.c_str());
ObjectKeeper keeperobjRef(objRef);
EXPECT_NE(objRef, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT));
auto datum = proj_crs_get_datum(m_ctxt, obj);
ObjectKeeper keeper_datum(datum);
ASSERT_NE(datum, nullptr);
auto obj2 = proj_create_geocentric_crs_from_datum(m_ctxt, "WGS 84",
datum, "Metre", 1.0);
ObjectKeeper keeperObj(obj2);
ASSERT_NE(obj2, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(obj, obj2, PJ_COMP_STRICT));
}
{
auto obj = proj_create_geocentric_crs(m_ctxt, nullptr, nullptr, nullptr,
1.0, 0.0, nullptr, 0.0, nullptr,
0.0, nullptr, 0.0);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, check_coord_op_obj_can_be_used_with_proj_trans) {
{
auto projCRS = proj_create_conversion_utm(m_ctxt, 31, true);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
PJ_COORD coord;
coord.xyzt.x = proj_torad(3.0);
coord.xyzt.y = 0;
coord.xyzt.z = 0;
coord.xyzt.t = 0;
EXPECT_NEAR(proj_trans(projCRS, PJ_FWD, coord).xyzt.x, 500000.0, 1e-9);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_projections) {
/* BEGIN: Generated by scripts/create_c_api_projections.py*/
{
auto projCRS = proj_create_conversion_utm(m_ctxt, 0, 0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_transverse_mercator(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_gauss_schreiber_transverse_mercator(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_transverse_mercator_south_oriented(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_two_point_equidistant(
m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_tunisia_mapping_grid(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_albers_equal_area(
m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_lambert_conic_conformal_1sp(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_lambert_conic_conformal_2sp(
m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_lambert_conic_conformal_2sp_michigan(
m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433,
"Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_lambert_conic_conformal_2sp_belgium(
m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_azimuthal_equidistant(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_guam_projection(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_bonne(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_lambert_cylindrical_equal_area_spherical(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_lambert_cylindrical_equal_area(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_cassini_soldner(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_equidistant_conic(
m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_eckert_i(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_eckert_ii(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_eckert_iii(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_eckert_iv(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_eckert_v(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_eckert_vi(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_equidistant_cylindrical(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_equidistant_cylindrical_spherical(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_gall(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_goode_homolosine(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_interrupted_goode_homolosine(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_geostationary_satellite_sweep_x(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_geostationary_satellite_sweep_y(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_gnomonic(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_hotine_oblique_mercator_variant_a(
m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_hotine_oblique_mercator_variant_b(
m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_hotine_oblique_mercator_two_point_natural_origin(
m_ctxt, 0, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433,
"Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_laborde_oblique_mercator(
m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_international_map_world_polyconic(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_krovak_north_oriented(
m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_krovak(m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree",
0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_lambert_azimuthal_equal_area(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_miller_cylindrical(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_mercator_variant_a(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_mercator_variant_b(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS =
proj_create_conversion_popular_visualisation_pseudo_mercator(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_mollweide(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_new_zealand_mapping_grid(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_oblique_stereographic(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_orthographic(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_american_polyconic(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_polar_stereographic_variant_a(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_polar_stereographic_variant_b(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_robinson(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_sinusoidal(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_stereographic(
m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_van_der_grinten(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_wagner_i(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_wagner_ii(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_wagner_iii(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_wagner_iv(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_wagner_v(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_wagner_vi(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_wagner_vii(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_quadrilateralized_spherical_cube(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_spherical_cross_track_height(
m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_equal_earth(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_vertical_perspective(
m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
{
auto projCRS = proj_create_conversion_pole_rotation_grib_convention(
m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
/* END: Generated by scripts/create_c_api_projections.py*/
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_cs_get_axis_info) {
{
auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(crs, nullptr);
ObjectKeeper keeper(crs);
auto cs = proj_crs_get_coordinate_system(m_ctxt, crs);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
EXPECT_EQ(proj_cs_get_type(m_ctxt, cs), PJ_CS_TYPE_ELLIPSOIDAL);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 2);
EXPECT_FALSE(proj_cs_get_axis_info(m_ctxt, cs, -1, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr));
EXPECT_FALSE(proj_cs_get_axis_info(m_ctxt, cs, 2, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr));
EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr));
const char *name = nullptr;
const char *abbrev = nullptr;
const char *direction = nullptr;
double unitConvFactor = 0.0;
const char *unitName = nullptr;
const char *unitAuthority = nullptr;
const char *unitCode = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(
m_ctxt, cs, 0, &name, &abbrev, &direction, &unitConvFactor,
&unitName, &unitAuthority, &unitCode));
ASSERT_NE(name, nullptr);
ASSERT_NE(abbrev, nullptr);
ASSERT_NE(direction, nullptr);
ASSERT_NE(unitName, nullptr);
ASSERT_NE(unitAuthority, nullptr);
ASSERT_NE(unitCode, nullptr);
EXPECT_EQ(std::string(name), "Geodetic latitude");
EXPECT_EQ(std::string(abbrev), "Lat");
EXPECT_EQ(std::string(direction), "north");
EXPECT_EQ(unitConvFactor, 0.017453292519943295) << unitConvFactor;
EXPECT_EQ(std::string(unitName), "degree");
EXPECT_EQ(std::string(unitAuthority), "EPSG");
EXPECT_EQ(std::string(unitCode), "9122");
}
// Non CRS object
{
auto obj = proj_create_from_database(m_ctxt, "EPSG", "1170",
PJ_CATEGORY_COORDINATE_OPERATION,
false, nullptr);
ASSERT_NE(obj, nullptr);
ObjectKeeper keeper(obj);
EXPECT_EQ(proj_crs_get_coordinate_system(m_ctxt, obj), nullptr);
EXPECT_EQ(proj_cs_get_type(m_ctxt, obj), PJ_CS_TYPE_UNKNOWN);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, obj), -1);
EXPECT_FALSE(proj_cs_get_axis_info(m_ctxt, obj, 0, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr,
nullptr));
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_context_get_database_metadata) {
EXPECT_TRUE(proj_context_get_database_metadata(m_ctxt, "IGNF.VERSION") !=
nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_clone) {
auto obj = proj_create(m_ctxt, "+proj=longlat");
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto clone = proj_clone(m_ctxt, obj);
ObjectKeeper keeperClone(clone);
ASSERT_NE(clone, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(obj, clone, PJ_COMP_STRICT));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_alter_geodetic_crs) {
auto projCRS = proj_create_from_wkt(
m_ctxt,
createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(projCRS);
ASSERT_NE(projCRS, nullptr);
auto newGeodCRS = proj_create(m_ctxt, "+proj=longlat +type=crs");
ObjectKeeper keeper_newGeodCRS(newGeodCRS);
ASSERT_NE(newGeodCRS, nullptr);
auto geodCRS = proj_crs_get_geodetic_crs(m_ctxt, projCRS);
ObjectKeeper keeper_geodCRS(geodCRS);
ASSERT_NE(geodCRS, nullptr);
auto geodCRSAltered =
proj_crs_alter_geodetic_crs(m_ctxt, geodCRS, newGeodCRS);
ObjectKeeper keeper_geodCRSAltered(geodCRSAltered);
ASSERT_NE(geodCRSAltered, nullptr);
EXPECT_TRUE(
proj_is_equivalent_to(geodCRSAltered, newGeodCRS, PJ_COMP_STRICT));
{
auto projCRSAltered =
proj_crs_alter_geodetic_crs(m_ctxt, projCRS, newGeodCRS);
ObjectKeeper keeper_projCRSAltered(projCRSAltered);
ASSERT_NE(projCRSAltered, nullptr);
EXPECT_EQ(proj_get_type(projCRSAltered), PJ_TYPE_PROJECTED_CRS);
auto projCRSAltered_geodCRS =
proj_crs_get_geodetic_crs(m_ctxt, projCRSAltered);
ObjectKeeper keeper_projCRSAltered_geodCRS(projCRSAltered_geodCRS);
ASSERT_NE(projCRSAltered_geodCRS, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(projCRSAltered_geodCRS, newGeodCRS,
PJ_COMP_STRICT));
}
// Check that proj_crs_alter_geodetic_crs preserves deprecation flag
{
auto projCRSDeprecated =
proj_alter_name(m_ctxt, projCRS, "new name (deprecated)");
ObjectKeeper keeper_projCRSDeprecated(projCRSDeprecated);
ASSERT_NE(projCRSDeprecated, nullptr);
auto projCRSAltered =
proj_crs_alter_geodetic_crs(m_ctxt, projCRSDeprecated, newGeodCRS);
ObjectKeeper keeper_projCRSAltered(projCRSAltered);
ASSERT_NE(projCRSAltered, nullptr);
EXPECT_EQ(proj_get_name(projCRSAltered), std::string("new name"));
EXPECT_TRUE(proj_is_deprecated(projCRSAltered));
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_alter_cs_angular_unit) {
auto crs = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
{
auto alteredCRS = proj_crs_alter_cs_angular_unit(m_ctxt, crs, "my unit",
2, nullptr, nullptr);
ObjectKeeper keeper_alteredCRS(alteredCRS);
ASSERT_NE(alteredCRS, nullptr);
auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
double unitConvFactor = 0.0;
const char *unitName = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr,
nullptr, &unitConvFactor, &unitName,
nullptr, nullptr));
ASSERT_NE(unitName, nullptr);
EXPECT_EQ(unitConvFactor, 2) << unitConvFactor;
EXPECT_EQ(std::string(unitName), "my unit");
}
{
auto alteredCRS = proj_crs_alter_cs_angular_unit(
m_ctxt, crs, "my unit", 2, "my auth", "my code");
ObjectKeeper keeper_alteredCRS(alteredCRS);
ASSERT_NE(alteredCRS, nullptr);
auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
double unitConvFactor = 0.0;
const char *unitName = nullptr;
const char *unitAuthName = nullptr;
const char *unitCode = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr,
nullptr, &unitConvFactor, &unitName,
&unitAuthName, &unitCode));
ASSERT_NE(unitName, nullptr);
EXPECT_EQ(unitConvFactor, 2) << unitConvFactor;
EXPECT_EQ(std::string(unitName), "my unit");
ASSERT_NE(unitAuthName, nullptr);
EXPECT_EQ(std::string(unitAuthName), "my auth");
ASSERT_NE(unitCode, nullptr);
EXPECT_EQ(std::string(unitCode), "my code");
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_alter_cs_linear_unit) {
auto crs = proj_create_from_wkt(
m_ctxt,
createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
{
auto alteredCRS = proj_crs_alter_cs_linear_unit(m_ctxt, crs, "my unit",
2, nullptr, nullptr);
ObjectKeeper keeper_alteredCRS(alteredCRS);
ASSERT_NE(alteredCRS, nullptr);
auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
double unitConvFactor = 0.0;
const char *unitName = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr,
nullptr, &unitConvFactor, &unitName,
nullptr, nullptr));
ASSERT_NE(unitName, nullptr);
EXPECT_EQ(unitConvFactor, 2) << unitConvFactor;
EXPECT_EQ(std::string(unitName), "my unit");
}
{
auto alteredCRS = proj_crs_alter_cs_linear_unit(
m_ctxt, crs, "my unit", 2, "my auth", "my code");
ObjectKeeper keeper_alteredCRS(alteredCRS);
ASSERT_NE(alteredCRS, nullptr);
auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
double unitConvFactor = 0.0;
const char *unitName = nullptr;
const char *unitAuthName = nullptr;
const char *unitCode = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr,
nullptr, &unitConvFactor, &unitName,
&unitAuthName, &unitCode));
ASSERT_NE(unitName, nullptr);
EXPECT_EQ(unitConvFactor, 2) << unitConvFactor;
EXPECT_EQ(std::string(unitName), "my unit");
ASSERT_NE(unitAuthName, nullptr);
EXPECT_EQ(std::string(unitAuthName), "my auth");
ASSERT_NE(unitCode, nullptr);
EXPECT_EQ(std::string(unitCode), "my code");
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_alter_parameters_linear_unit) {
auto crs = proj_create_from_wkt(
m_ctxt,
createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
{
auto alteredCRS = proj_crs_alter_parameters_linear_unit(
m_ctxt, crs, "my unit", 2, nullptr, nullptr, false);
ObjectKeeper keeper_alteredCRS(alteredCRS);
ASSERT_NE(alteredCRS, nullptr);
auto wkt = proj_as_wkt(m_ctxt, alteredCRS, PJ_WKT2_2019, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("500000") != std::string::npos)
<< wkt;
EXPECT_TRUE(std::string(wkt).find("\"my unit\",2") != std::string::npos)
<< wkt;
}
{
auto alteredCRS = proj_crs_alter_parameters_linear_unit(
m_ctxt, crs, "my unit", 2, nullptr, nullptr, true);
ObjectKeeper keeper_alteredCRS(alteredCRS);
ASSERT_NE(alteredCRS, nullptr);
auto wkt = proj_as_wkt(m_ctxt, alteredCRS, PJ_WKT2_2019, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_TRUE(std::string(wkt).find("250000") != std::string::npos)
<< wkt;
EXPECT_TRUE(std::string(wkt).find("\"my unit\",2") != std::string::npos)
<< wkt;
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_engineering_crs) {
auto crs = proj_create_engineering_crs(m_ctxt, "name");
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
auto wkt = proj_as_wkt(m_ctxt, crs, PJ_WKT1_GDAL, nullptr);
ASSERT_NE(wkt, nullptr);
EXPECT_EQ(std::string(wkt), "LOCAL_CS[\"name\",\n"
" UNIT[\"metre\",1,\n"
" AUTHORITY[\"EPSG\",\"9001\"]],\n"
" AXIS[\"Easting\",EAST],\n"
" AXIS[\"Northing\",NORTH]]")
<< wkt;
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_alter_name) {
auto cs = proj_create_ellipsoidal_2D_cs(
m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
auto obj = proj_create_geographic_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
{
auto alteredObj = proj_alter_name(m_ctxt, obj, "new name");
ObjectKeeper keeper_alteredObj(alteredObj);
ASSERT_NE(alteredObj, nullptr);
EXPECT_EQ(std::string(proj_get_name(alteredObj)), "new name");
EXPECT_FALSE(proj_is_deprecated(alteredObj));
}
{
auto alteredObj = proj_alter_name(m_ctxt, obj, "new name (deprecated)");
ObjectKeeper keeper_alteredObj(alteredObj);
ASSERT_NE(alteredObj, nullptr);
EXPECT_EQ(std::string(proj_get_name(alteredObj)), "new name");
EXPECT_TRUE(proj_is_deprecated(alteredObj));
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_alter_id) {
auto cs = proj_create_ellipsoidal_2D_cs(
m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
auto obj = proj_create_geographic_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs);
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
auto alteredObj = proj_alter_id(m_ctxt, obj, "auth", "code");
ObjectKeeper keeper_alteredObj(alteredObj);
ASSERT_NE(alteredObj, nullptr);
EXPECT_EQ(std::string(proj_get_id_auth_name(alteredObj, 0)), "auth");
EXPECT_EQ(std::string(proj_get_id_code(alteredObj, 0)), "code");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_projected_crs) {
PJ_PARAM_DESCRIPTION param;
param.name = "param name";
param.auth_name = nullptr;
param.code = nullptr;
param.value = 0.99;
param.unit_name = nullptr;
param.unit_conv_factor = 1.0;
param.unit_type = PJ_UT_SCALE;
auto conv = proj_create_conversion(m_ctxt, "conv", "conv auth", "conv code",
"method", "method auth", "method code",
1, ¶m);
ObjectKeeper keeper_conv(conv);
ASSERT_NE(conv, nullptr);
auto geog_cs = proj_create_ellipsoidal_2D_cs(
m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0);
ObjectKeeper keeper_geog_cs(geog_cs);
ASSERT_NE(geog_cs, nullptr);
auto geogCRS = proj_create_geographic_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs);
ObjectKeeper keeper_geogCRS(geogCRS);
ASSERT_NE(geogCRS, nullptr);
auto cs = proj_create_cartesian_2D_cs(m_ctxt, PJ_CART2D_EASTING_NORTHING,
nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
auto projCRS =
proj_create_projected_crs(m_ctxt, "my CRS", geogCRS, conv, cs);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_transformation) {
PJ_PARAM_DESCRIPTION param;
param.name = "param name";
param.auth_name = nullptr;
param.code = nullptr;
param.value = 0.99;
param.unit_name = nullptr;
param.unit_conv_factor = 1.0;
param.unit_type = PJ_UT_SCALE;
auto geog_cs = proj_create_ellipsoidal_2D_cs(
m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0);
ObjectKeeper keeper_geog_cs(geog_cs);
ASSERT_NE(geog_cs, nullptr);
auto source_crs = proj_create_geographic_crs(
m_ctxt, "Source CRS", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs);
ObjectKeeper keeper_source_crs(source_crs);
ASSERT_NE(source_crs, nullptr);
auto target_crs = proj_create_geographic_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs);
ObjectKeeper keeper_target_crs(target_crs);
ASSERT_NE(target_crs, nullptr);
auto interp_crs = proj_create_geographic_crs(
m_ctxt, "Interpolation CRS", "World Geodetic System 1984", "WGS 84",
6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433,
geog_cs);
ObjectKeeper keeper_interp_crs(interp_crs);
ASSERT_NE(interp_crs, nullptr);
{
auto transf = proj_create_transformation(
m_ctxt, "transf", "transf auth", "transf code", source_crs,
target_crs, interp_crs, "method", "method auth", "method code", 1,
¶m, 0);
ObjectKeeper keeper_transf(transf);
ASSERT_NE(transf, nullptr);
EXPECT_EQ(proj_coordoperation_get_param_count(m_ctxt, transf), 1);
auto got_source_crs = proj_get_source_crs(m_ctxt, transf);
ObjectKeeper keeper_got_source_crs(got_source_crs);
ASSERT_NE(got_source_crs, nullptr);
EXPECT_TRUE(
proj_is_equivalent_to(source_crs, got_source_crs, PJ_COMP_STRICT));
auto got_target_crs = proj_get_target_crs(m_ctxt, transf);
ObjectKeeper keeper_got_target_crs(got_target_crs);
ASSERT_NE(got_target_crs, nullptr);
EXPECT_TRUE(
proj_is_equivalent_to(target_crs, got_target_crs, PJ_COMP_STRICT));
}
{
auto transf = proj_create_transformation(
m_ctxt, "transf", "transf auth", "transf code", source_crs,
target_crs, nullptr, "method", "method auth", "method code", 1,
¶m, -1);
ObjectKeeper keeper_transf(transf);
ASSERT_NE(transf, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_compound_crs) {
auto horiz_cs = proj_create_ellipsoidal_2D_cs(
m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0);
ObjectKeeper keeper_horiz_cs(horiz_cs);
ASSERT_NE(horiz_cs, nullptr);
auto horiz_crs = proj_create_geographic_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433,
horiz_cs);
ObjectKeeper keeper_horiz_crs(horiz_crs);
ASSERT_NE(horiz_crs, nullptr);
auto vert_crs = proj_create_vertical_crs(m_ctxt, "myVertCRS", "myVertDatum",
nullptr, 0.0);
ObjectKeeper keeper_vert_crs(vert_crs);
ASSERT_NE(vert_crs, nullptr);
EXPECT_EQ(proj_get_name(vert_crs), std::string("myVertCRS"));
auto compound_crs =
proj_create_compound_crs(m_ctxt, "myCompoundCRS", horiz_crs, vert_crs);
ObjectKeeper keeper_compound_crss(compound_crs);
ASSERT_NE(compound_crs, nullptr);
EXPECT_EQ(proj_get_name(compound_crs), std::string("myCompoundCRS"));
auto subcrs_horiz = proj_crs_get_sub_crs(m_ctxt, compound_crs, 0);
ASSERT_NE(subcrs_horiz, nullptr);
ObjectKeeper keeper_subcrs_horiz(subcrs_horiz);
EXPECT_TRUE(proj_is_equivalent_to(subcrs_horiz, horiz_crs, PJ_COMP_STRICT));
auto subcrs_vert = proj_crs_get_sub_crs(m_ctxt, compound_crs, 1);
ASSERT_NE(subcrs_vert, nullptr);
ObjectKeeper keeper_subcrs_vert(subcrs_vert);
EXPECT_TRUE(proj_is_equivalent_to(subcrs_vert, vert_crs, PJ_COMP_STRICT));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_convert_conversion_to_other_method) {
{
auto geog_cs = proj_create_ellipsoidal_2D_cs(
m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0);
ObjectKeeper keeper_geog_cs(geog_cs);
ASSERT_NE(geog_cs, nullptr);
auto geogCRS = proj_create_geographic_crs(
m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137,
298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433,
geog_cs);
ObjectKeeper keeper_geogCRS(geogCRS);
ASSERT_NE(geogCRS, nullptr);
auto cs = proj_create_cartesian_2D_cs(
m_ctxt, PJ_CART2D_EASTING_NORTHING, nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
auto conv = proj_create_conversion_mercator_variant_a(
m_ctxt, 0, 1, 0.99, 2, 3, "Degree", 0.0174532925199433, "Metre",
1.0);
ObjectKeeper keeper_conv(conv);
ASSERT_NE(conv, nullptr);
auto projCRS =
proj_create_projected_crs(m_ctxt, "my CRS", geogCRS, conv, cs);
ObjectKeeper keeper_projCRS(projCRS);
ASSERT_NE(projCRS, nullptr);
// Wrong object type
EXPECT_EQ(
proj_convert_conversion_to_other_method(
m_ctxt, projCRS, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, nullptr),
nullptr);
auto conv_in_proj = proj_crs_get_coordoperation(m_ctxt, projCRS);
ObjectKeeper keeper_conv_in_proj(conv_in_proj);
ASSERT_NE(conv_in_proj, nullptr);
// 3rd and 4th argument both 0/null
EXPECT_EQ(proj_convert_conversion_to_other_method(m_ctxt, conv_in_proj,
0, nullptr),
nullptr);
auto new_conv = proj_convert_conversion_to_other_method(
m_ctxt, conv_in_proj, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, nullptr);
ObjectKeeper keeper_new_conv(new_conv);
ASSERT_NE(new_conv, nullptr);
EXPECT_FALSE(
proj_is_equivalent_to(new_conv, conv_in_proj, PJ_COMP_STRICT));
EXPECT_TRUE(
proj_is_equivalent_to(new_conv, conv_in_proj, PJ_COMP_EQUIVALENT));
auto new_conv_from_name = proj_convert_conversion_to_other_method(
m_ctxt, conv_in_proj, 0, EPSG_NAME_METHOD_MERCATOR_VARIANT_B);
ObjectKeeper keeper_new_conv_from_name(new_conv_from_name);
ASSERT_NE(new_conv_from_name, nullptr);
EXPECT_TRUE(proj_is_equivalent_to(new_conv, new_conv_from_name,
PJ_COMP_STRICT));
auto new_conv_back = proj_convert_conversion_to_other_method(
m_ctxt, conv_in_proj, 0, EPSG_NAME_METHOD_MERCATOR_VARIANT_A);
ObjectKeeper keeper_new_conv_back(new_conv_back);
ASSERT_NE(new_conv_back, nullptr);
EXPECT_TRUE(
proj_is_equivalent_to(conv_in_proj, new_conv_back, PJ_COMP_STRICT));
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_non_deprecated) {
auto crs = proj_create_from_database(m_ctxt, "EPSG", "4226",
PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
auto list = proj_get_non_deprecated(m_ctxt, crs);
ASSERT_NE(list, nullptr);
ObjListKeeper keeper_list(list);
EXPECT_EQ(proj_list_get_count(list), 2);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_query_geodetic_crs_from_datum) {
{
auto list = proj_query_geodetic_crs_from_datum(m_ctxt, nullptr, "EPSG",
"6326", nullptr);
ASSERT_NE(list, nullptr);
ObjListKeeper keeper_list(list);
EXPECT_GE(proj_list_get_count(list), 3);
}
{
auto list = proj_query_geodetic_crs_from_datum(m_ctxt, "EPSG", "EPSG",
"6326", "geographic 2D");
ASSERT_NE(list, nullptr);
ObjListKeeper keeper_list(list);
EXPECT_EQ(proj_list_get_count(list), 1);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_uom_get_info_from_database) {
{
EXPECT_FALSE(proj_uom_get_info_from_database(
m_ctxt, "auth", "code", nullptr, nullptr, nullptr));
}
{
EXPECT_TRUE(proj_uom_get_info_from_database(m_ctxt, "EPSG", "9001",
nullptr, nullptr, nullptr));
}
{
const char *name = nullptr;
double conv_factor = 0.0;
const char *category = nullptr;
EXPECT_TRUE(proj_uom_get_info_from_database(
m_ctxt, "EPSG", "9001", &name, &conv_factor, &category));
ASSERT_NE(name, nullptr);
ASSERT_NE(category, nullptr);
EXPECT_EQ(std::string(name), "metre");
EXPECT_EQ(conv_factor, 1.0);
EXPECT_EQ(std::string(category), "linear");
}
{
const char *name = nullptr;
double conv_factor = 0.0;
const char *category = nullptr;
EXPECT_TRUE(proj_uom_get_info_from_database(
m_ctxt, "EPSG", "9102", &name, &conv_factor, &category));
ASSERT_NE(name, nullptr);
ASSERT_NE(category, nullptr);
EXPECT_EQ(std::string(name), "degree");
EXPECT_NEAR(conv_factor, UnitOfMeasure::DEGREE.conversionToSI(), 1e-10);
EXPECT_EQ(std::string(category), "angular");
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_grid_get_info_from_database) {
{
EXPECT_FALSE(proj_grid_get_info_from_database(m_ctxt, "xxx", nullptr,
nullptr, nullptr, nullptr,
nullptr, nullptr));
}
{
EXPECT_TRUE(proj_grid_get_info_from_database(
m_ctxt, "GDA94_GDA2020_conformal.gsb", nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr));
}
{
const char *name = nullptr;
const char *package_name = nullptr;
const char *url = nullptr;
int direct_download = 0;
int open_license = 0;
int available = 0;
EXPECT_TRUE(proj_grid_get_info_from_database(
m_ctxt, "GDA94_GDA2020_conformal.gsb", &name, &package_name, &url,
&direct_download, &open_license, &available));
ASSERT_NE(name, nullptr);
ASSERT_NE(package_name, nullptr);
ASSERT_NE(url, nullptr);
EXPECT_EQ(direct_download, 1);
EXPECT_EQ(open_license, 1);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_cartesian_2D_cs) {
{
auto cs = proj_create_cartesian_2D_cs(
m_ctxt, PJ_CART2D_EASTING_NORTHING, nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
}
{
auto cs = proj_create_cartesian_2D_cs(
m_ctxt, PJ_CART2D_NORTHING_EASTING, nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
}
{
auto cs = proj_create_cartesian_2D_cs(
m_ctxt, PJ_CART2D_NORTH_POLE_EASTING_SOUTH_NORTHING_SOUTH, nullptr,
0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
}
{
auto cs = proj_create_cartesian_2D_cs(
m_ctxt, PJ_CART2D_SOUTH_POLE_EASTING_NORTH_NORTHING_NORTH, nullptr,
0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
}
{
auto cs = proj_create_cartesian_2D_cs(
m_ctxt, PJ_CART2D_WESTING_SOUTHING, nullptr, 0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_crs_info_list_from_database) {
{ proj_crs_info_list_destroy(nullptr); }
{ proj_get_crs_list_parameters_destroy(nullptr); }
// All null parameters
{
auto list = proj_get_crs_info_list_from_database(nullptr, nullptr,
nullptr, nullptr);
ASSERT_NE(list, nullptr);
ASSERT_NE(list[0], nullptr);
EXPECT_NE(list[0]->auth_name, nullptr);
EXPECT_NE(list[0]->code, nullptr);
EXPECT_NE(list[0]->name, nullptr);
proj_crs_info_list_destroy(list);
}
// Default parameters
{
int result_count = 0;
auto params = proj_get_crs_list_parameters_create();
auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params,
&result_count);
proj_get_crs_list_parameters_destroy(params);
ASSERT_NE(list, nullptr);
EXPECT_GT(result_count, 1);
EXPECT_EQ(list[result_count], nullptr);
bool found4326 = false;
bool found4978 = false;
bool found4979 = false;
bool found32631 = false;
bool found3855 = false;
bool found3901 = false;
for (int i = 0; i < result_count; i++) {
auto code = std::string(list[i]->code);
if (code == "4326") {
found4326 = true;
EXPECT_EQ(std::string(list[i]->auth_name), "EPSG");
EXPECT_EQ(std::string(list[i]->name), "WGS 84");
EXPECT_EQ(list[i]->type, PJ_TYPE_GEOGRAPHIC_2D_CRS);
EXPECT_EQ(list[i]->deprecated, 0);
EXPECT_EQ(list[i]->bbox_valid, 1);
EXPECT_EQ(list[i]->west_lon_degree, -180.0);
EXPECT_EQ(list[i]->south_lat_degree, -90.0);
EXPECT_EQ(list[i]->east_lon_degree, 180.0);
EXPECT_EQ(list[i]->north_lat_degree, 90.0);
EXPECT_EQ(std::string(list[i]->area_name), "World");
EXPECT_EQ(list[i]->projection_method_name, nullptr);
} else if (code == "4978") {
found4978 = true;
EXPECT_EQ(list[i]->type, PJ_TYPE_GEOCENTRIC_CRS);
} else if (code == "4979") {
found4979 = true;
EXPECT_EQ(list[i]->type, PJ_TYPE_GEOGRAPHIC_3D_CRS);
} else if (code == "32631") {
found32631 = true;
EXPECT_EQ(list[i]->type, PJ_TYPE_PROJECTED_CRS);
EXPECT_EQ(std::string(list[i]->projection_method_name),
"Transverse Mercator");
} else if (code == "3855") {
found3855 = true;
EXPECT_EQ(list[i]->type, PJ_TYPE_VERTICAL_CRS);
} else if (code == "3901") {
found3901 = true;
EXPECT_EQ(list[i]->type, PJ_TYPE_COMPOUND_CRS);
}
EXPECT_EQ(list[i]->deprecated, 0);
}
EXPECT_TRUE(found4326);
EXPECT_TRUE(found4978);
EXPECT_TRUE(found4979);
EXPECT_TRUE(found32631);
EXPECT_TRUE(found3855);
EXPECT_TRUE(found3901);
proj_crs_info_list_destroy(list);
}
// Filter on only geodetic crs
{
int result_count = 0;
auto params = proj_get_crs_list_parameters_create();
params->typesCount = 1;
auto type = PJ_TYPE_GEODETIC_CRS;
params->types = &type;
auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params,
&result_count);
bool foundGeog2D = false;
bool foundGeog3D = false;
bool foundGeocentric = false;
for (int i = 0; i < result_count; i++) {
foundGeog2D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS;
foundGeog3D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS;
foundGeocentric |= list[i]->type == PJ_TYPE_GEOCENTRIC_CRS;
EXPECT_TRUE(list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS ||
list[i]->type == PJ_TYPE_GEOCENTRIC_CRS);
}
EXPECT_TRUE(foundGeog2D);
EXPECT_TRUE(foundGeog3D);
EXPECT_TRUE(foundGeocentric);
proj_get_crs_list_parameters_destroy(params);
proj_crs_info_list_destroy(list);
}
// Filter on only geographic crs
{
int result_count = 0;
auto params = proj_get_crs_list_parameters_create();
params->typesCount = 1;
auto type = PJ_TYPE_GEOGRAPHIC_CRS;
params->types = &type;
auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params,
&result_count);
bool foundGeog2D = false;
bool foundGeog3D = false;
for (int i = 0; i < result_count; i++) {
foundGeog2D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS;
foundGeog3D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS;
EXPECT_TRUE(list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS);
}
EXPECT_TRUE(foundGeog2D);
EXPECT_TRUE(foundGeog3D);
proj_get_crs_list_parameters_destroy(params);
proj_crs_info_list_destroy(list);
}
// Filter on only geographic 2D crs and projected CRS
{
int result_count = 0;
auto params = proj_get_crs_list_parameters_create();
params->typesCount = 2;
const PJ_TYPE types[] = {PJ_TYPE_GEOGRAPHIC_2D_CRS,
PJ_TYPE_PROJECTED_CRS};
params->types = types;
auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params,
&result_count);
bool foundGeog2D = false;
bool foundProjected = false;
for (int i = 0; i < result_count; i++) {
foundGeog2D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS;
foundProjected |= list[i]->type == PJ_TYPE_PROJECTED_CRS;
EXPECT_TRUE(list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS ||
list[i]->type == PJ_TYPE_PROJECTED_CRS);
}
EXPECT_TRUE(foundGeog2D);
EXPECT_TRUE(foundProjected);
proj_get_crs_list_parameters_destroy(params);
proj_crs_info_list_destroy(list);
}
// Filter on bbox (inclusion)
{
int result_count = 0;
auto params = proj_get_crs_list_parameters_create();
params->bbox_valid = 1;
params->west_lon_degree = 2;
params->south_lat_degree = 49;
params->east_lon_degree = 2.1;
params->north_lat_degree = 49.1;
params->typesCount = 1;
auto type = PJ_TYPE_PROJECTED_CRS;
params->types = &type;
auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params,
&result_count);
ASSERT_NE(list, nullptr);
EXPECT_GT(result_count, 1);
for (int i = 0; i < result_count; i++) {
if (list[i]->west_lon_degree < list[i]->east_lon_degree) {
EXPECT_LE(list[i]->west_lon_degree, params->west_lon_degree);
EXPECT_GE(list[i]->east_lon_degree, params->east_lon_degree);
}
EXPECT_LE(list[i]->south_lat_degree, params->south_lat_degree);
EXPECT_GE(list[i]->north_lat_degree, params->north_lat_degree);
}
proj_get_crs_list_parameters_destroy(params);
proj_crs_info_list_destroy(list);
}
// Filter on bbox (intersection)
{
int result_count = 0;
auto params = proj_get_crs_list_parameters_create();
params->bbox_valid = 1;
params->west_lon_degree = 2;
params->south_lat_degree = 49;
params->east_lon_degree = 2.1;
params->north_lat_degree = 49.1;
params->crs_area_of_use_contains_bbox = 0;
params->typesCount = 1;
auto type = PJ_TYPE_PROJECTED_CRS;
params->types = &type;
auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params,
&result_count);
ASSERT_NE(list, nullptr);
EXPECT_GT(result_count, 1);
for (int i = 0; i < result_count; i++) {
if (list[i]->west_lon_degree < list[i]->east_lon_degree) {
EXPECT_LE(list[i]->west_lon_degree, params->west_lon_degree);
EXPECT_GE(list[i]->east_lon_degree, params->east_lon_degree);
}
EXPECT_LE(list[i]->south_lat_degree, params->north_lat_degree);
EXPECT_GE(list[i]->north_lat_degree, params->south_lat_degree);
}
proj_get_crs_list_parameters_destroy(params);
proj_crs_info_list_destroy(list);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_normalize_for_visualization) {
{
auto P = proj_create(m_ctxt, "+proj=utm +zone=31 +ellps=WGS84");
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P);
ObjectKeeper keeper_Pnormalized(Pnormalized);
EXPECT_EQ(Pnormalized, nullptr);
}
auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4326", "EPSG:32631", nullptr);
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P);
ObjectKeeper keeper_Pnormalized(Pnormalized);
ASSERT_NE(Pnormalized, nullptr);
auto projstr = proj_as_proj_string(m_ctxt, Pnormalized, PJ_PROJ_5, nullptr);
ASSERT_NE(projstr, nullptr);
EXPECT_EQ(std::string(projstr),
"+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad "
"+step +proj=utm +zone=31 +ellps=WGS84");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_normalize_for_visualization_with_alternatives) {
auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4326", "EPSG:3003", nullptr);
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P);
ObjectKeeper keeper_Pnormalized(Pnormalized);
ASSERT_NE(Pnormalized, nullptr);
{
PJ_COORD c;
// Approximately Roma
c.lpz.lam = 12.5;
c.lpz.phi = 42;
c.lpz.z = 0;
c = proj_trans(Pnormalized, PJ_FWD, c);
EXPECT_NEAR(c.xy.x, 1789912.46264783037, 1e-8);
EXPECT_NEAR(c.xy.y, 4655716.25402576849, 1e-8);
auto projstr = proj_pj_info(Pnormalized).definition;
ASSERT_NE(projstr, nullptr);
EXPECT_EQ(std::string(projstr),
"proj=pipeline step proj=unitconvert xy_in=deg xy_out=rad "
"step proj=push v_3 step proj=cart ellps=WGS84 "
"step inv proj=helmert x=-104.1 y=-49.1 z=-9.9 rx=0.971 "
"ry=-2.917 rz=0.714 s=-11.68 convention=position_vector "
"step inv proj=cart ellps=intl step proj=pop v_3 "
"step proj=tmerc lat_0=0 lon_0=9 k=0.9996 x_0=1500000 "
"y_0=0 ellps=intl");
}
{
PJ_COORD c;
// Approximately Roma
c.xyz.x = 1789912.46264783037;
c.xyz.y = 4655716.25402576849;
c.xyz.z = 0;
c = proj_trans(Pnormalized, PJ_INV, c);
EXPECT_NEAR(c.lp.lam, 12.5, 1e-8);
EXPECT_NEAR(c.lp.phi, 42, 1e-8);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_normalize_for_visualization_with_alternatives_reverse) {
auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:3003", "EPSG:4326", nullptr);
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P);
ObjectKeeper keeper_Pnormalized(Pnormalized);
ASSERT_NE(Pnormalized, nullptr);
PJ_COORD c;
// Approximately Roma
c.xyz.x = 1789912.46264783037;
c.xyz.y = 4655716.25402576849;
c.xyz.z = 0;
c = proj_trans(Pnormalized, PJ_FWD, c);
EXPECT_NEAR(c.lp.lam, 12.5, 1e-8);
EXPECT_NEAR(c.lp.phi, 42, 1e-8);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_normalize_for_visualization_on_crs) {
auto P = proj_create(m_ctxt, "EPSG:4326");
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P);
ObjectKeeper keeper_Pnormalized(Pnormalized);
ASSERT_NE(Pnormalized, nullptr);
EXPECT_EQ(proj_get_id_code(Pnormalized, 0), nullptr);
auto cs = proj_crs_get_coordinate_system(m_ctxt, Pnormalized);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
const char *name = nullptr;
ASSERT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, &name, nullptr, nullptr,
nullptr, nullptr, nullptr, nullptr));
ASSERT_NE(name, nullptr);
EXPECT_EQ(std::string(name), "Geodetic longitude");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_coordoperation_create_inverse) {
auto P = proj_create(
m_ctxt, "+proj=pipeline +step +proj=axisswap +order=2,1 +step "
"+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push "
"+v_3 +step +proj=cart +ellps=evrst30 +step +proj=helmert "
"+x=293 +y=836 +z=318 +rx=0.5 +ry=1.6 +rz=-2.8 +s=2.1 "
"+convention=position_vector +step +inv +proj=cart "
"+ellps=WGS84 +step +proj=pop +v_3 +step +proj=unitconvert "
"+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1");
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pinversed = proj_coordoperation_create_inverse(m_ctxt, P);
ObjectKeeper keeper_Pinversed(Pinversed);
ASSERT_NE(Pinversed, nullptr);
auto projstr = proj_as_proj_string(m_ctxt, Pinversed, PJ_PROJ_5, nullptr);
ASSERT_NE(projstr, nullptr);
EXPECT_EQ(std::string(projstr),
"+proj=pipeline +step +proj=axisswap +order=2,1 +step "
"+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 "
"+step +proj=cart +ellps=WGS84 +step +inv +proj=helmert +x=293 "
"+y=836 +z=318 +rx=0.5 +ry=1.6 +rz=-2.8 +s=2.1 "
"+convention=position_vector +step +inv +proj=cart "
"+ellps=evrst30 +step +proj=pop +v_3 +step +proj=unitconvert "
"+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_remarks) {
auto co = proj_create_from_database(m_ctxt, "EPSG", "8048",
PJ_CATEGORY_COORDINATE_OPERATION, false,
nullptr);
ObjectKeeper keeper(co);
ASSERT_NE(co, nullptr);
auto remarks = proj_get_remarks(co);
ASSERT_NE(remarks, nullptr);
EXPECT_TRUE(std::string(remarks).find(
"Scale difference in ppb where 1/billion = 1E-9.") == 0)
<< remarks;
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_get_scope) {
{
auto co = proj_create_from_database(m_ctxt, "EPSG", "8048",
PJ_CATEGORY_COORDINATE_OPERATION,
false, nullptr);
ObjectKeeper keeper(co);
ASSERT_NE(co, nullptr);
auto scope = proj_get_scope(co);
ASSERT_NE(scope, nullptr);
EXPECT_EQ(scope,
std::string("Conformal transformation of GDA94 coordinates "
"that have been derived through GNSS CORS."));
}
{
auto P = proj_create(m_ctxt, "+proj=noop");
ObjectKeeper keeper(P);
ASSERT_NE(P, nullptr);
auto scope = proj_get_scope(P);
ASSERT_EQ(scope, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_concatoperation_get_step) {
// Test on a non concatenated operation
{
auto co = proj_create_from_database(m_ctxt, "EPSG", "8048",
PJ_CATEGORY_COORDINATE_OPERATION,
false, nullptr);
ObjectKeeper keeper(co);
ASSERT_NE(co, nullptr);
ASSERT_NE(proj_get_type(co), PJ_TYPE_CONCATENATED_OPERATION);
ASSERT_EQ(proj_concatoperation_get_step_count(m_ctxt, co), 0);
ASSERT_EQ(proj_concatoperation_get_step(m_ctxt, co, 0), nullptr);
}
// Test on a concatenated operation
{
auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr);
ASSERT_NE(ctxt, nullptr);
ContextKeeper keeper_ctxt(ctxt);
// GDA94 / MGA zone 56
auto source_crs = proj_create_from_database(
m_ctxt, "EPSG", "28356", PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(source_crs, nullptr);
ObjectKeeper keeper_source_crs(source_crs);
// GDA2020 / MGA zone 56
auto target_crs = proj_create_from_database(
m_ctxt, "EPSG", "7856", PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(target_crs, nullptr);
ObjectKeeper keeper_target_crs(target_crs);
proj_operation_factory_context_set_spatial_criterion(
m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION);
proj_operation_factory_context_set_grid_availability_use(
m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED);
auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt);
ASSERT_NE(res, nullptr);
ObjListKeeper keeper_res(res);
ASSERT_GT(proj_list_get_count(res), 0);
auto op = proj_list_get(m_ctxt, res, 0);
ASSERT_NE(op, nullptr);
ObjectKeeper keeper_op(op);
ASSERT_EQ(proj_get_type(op), PJ_TYPE_CONCATENATED_OPERATION);
ASSERT_EQ(proj_concatoperation_get_step_count(m_ctxt, op), 3);
EXPECT_EQ(proj_concatoperation_get_step(m_ctxt, op, -1), nullptr);
EXPECT_EQ(proj_concatoperation_get_step(m_ctxt, op, 3), nullptr);
auto step = proj_concatoperation_get_step(m_ctxt, op, 1);
ASSERT_NE(step, nullptr);
ObjectKeeper keeper_step(step);
const char *scope = proj_get_scope(step);
EXPECT_NE(scope, nullptr);
EXPECT_NE(std::string(scope), std::string());
const char *remarks = proj_get_remarks(step);
EXPECT_NE(remarks, nullptr);
EXPECT_NE(std::string(remarks), std::string());
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_as_projjson) {
auto obj = proj_create(
m_ctxt,
Ellipsoid::WGS84->exportToJSON(JSONFormatter::create().get()).c_str());
ObjectKeeper keeper(obj);
ASSERT_NE(obj, nullptr);
{
auto projjson = proj_as_projjson(m_ctxt, obj, nullptr);
ASSERT_NE(projjson, nullptr);
EXPECT_EQ(std::string(projjson),
"{\n"
" \"$schema\": "
"\"https://proj.org/schemas/v0.2/projjson.schema.json\",\n"
" \"type\": \"Ellipsoid\",\n"
" \"name\": \"WGS 84\",\n"
" \"semi_major_axis\": 6378137,\n"
" \"inverse_flattening\": 298.257223563,\n"
" \"id\": {\n"
" \"authority\": \"EPSG\",\n"
" \"code\": 7030\n"
" }\n"
"}");
}
{
const char *const options[] = {"INDENTATION_WIDTH=4", "SCHEMA=",
nullptr};
auto projjson = proj_as_projjson(m_ctxt, obj, options);
ASSERT_NE(projjson, nullptr);
EXPECT_EQ(std::string(projjson),
"{\n"
" \"type\": \"Ellipsoid\",\n"
" \"name\": \"WGS 84\",\n"
" \"semi_major_axis\": 6378137,\n"
" \"inverse_flattening\": 298.257223563,\n"
" \"id\": {\n"
" \"authority\": \"EPSG\",\n"
" \"code\": 7030\n"
" }\n"
"}");
}
{
const char *const options[] = {"MULTILINE=NO", "SCHEMA=", nullptr};
auto projjson = proj_as_projjson(m_ctxt, obj, options);
ASSERT_NE(projjson, nullptr);
EXPECT_EQ(std::string(projjson),
"{\"type\":\"Ellipsoid\",\"name\":\"WGS 84\","
"\"semi_major_axis\":6378137,"
"\"inverse_flattening\":298.257223563,"
"\"id\":{\"authority\":\"EPSG\",\"code\":7030}}");
}
}
// ---------------------------------------------------------------------------
struct Fixture_proj_context_set_autoclose_database : public CApi {
void test(bool autoclose) {
proj_context_set_autoclose_database(m_ctxt, autoclose);
auto c_path = proj_context_get_database_path(m_ctxt);
ASSERT_TRUE(c_path != nullptr);
std::string path(c_path);
FILE *f = fopen(path.c_str(), "rb");
ASSERT_NE(f, nullptr);
fseek(f, 0, SEEK_END);
auto length = ftell(f);
std::string content;
content.resize(static_cast<size_t>(length));
fseek(f, 0, SEEK_SET);
auto read_bytes = fread(&content[0], 1, content.size(), f);
ASSERT_EQ(read_bytes, content.size());
fclose(f);
const char *tempdir = getenv("TEMP");
if (!tempdir) {
tempdir = getenv("TMP");
}
if (!tempdir) {
tempdir = "/tmp";
}
std::string tmp_filename(
std::string(tempdir) +
"/test_proj_context_set_autoclose_database.db");
f = fopen(tmp_filename.c_str(), "wb");
if (!f) {
std::cerr << "Cannot create " << tmp_filename << std::endl;
return;
}
fwrite(content.data(), 1, content.size(), f);
fclose(f);
{
sqlite3 *db = nullptr;
sqlite3_open_v2(tmp_filename.c_str(), &db, SQLITE_OPEN_READWRITE,
nullptr);
ASSERT_NE(db, nullptr);
ASSERT_TRUE(sqlite3_exec(db, "UPDATE geodetic_crs SET name = 'foo' "
"WHERE auth_name = 'EPSG' and code = "
"'4326'",
nullptr, nullptr, nullptr) == SQLITE_OK);
sqlite3_close(db);
}
EXPECT_TRUE(proj_context_set_database_path(m_ctxt, tmp_filename.c_str(),
nullptr, nullptr));
{
auto crs = proj_create_from_database(
m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
EXPECT_EQ(proj_get_name(crs), std::string("foo"));
}
{
sqlite3 *db = nullptr;
sqlite3_open_v2(tmp_filename.c_str(), &db, SQLITE_OPEN_READWRITE,
nullptr);
ASSERT_NE(db, nullptr);
ASSERT_TRUE(sqlite3_exec(db, "UPDATE geodetic_crs SET name = 'bar' "
"WHERE auth_name = 'EPSG' and code = "
"'4326'",
nullptr, nullptr, nullptr) == SQLITE_OK);
sqlite3_close(db);
}
{
auto crs = proj_create_from_database(
m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper(crs);
ASSERT_NE(crs, nullptr);
EXPECT_EQ(proj_get_name(crs),
std::string(autoclose ? "bar" : "foo"));
}
if (!autoclose) {
proj_context_destroy(m_ctxt);
m_ctxt = nullptr;
}
std::remove(tmp_filename.c_str());
}
};
TEST_F(Fixture_proj_context_set_autoclose_database,
proj_context_set_autoclose_database_true) {
test(true);
}
TEST_F(Fixture_proj_context_set_autoclose_database,
proj_context_set_autoclose_database_false) {
test(false);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_crs_to_crs_from_pj) {
auto src = proj_create(m_ctxt, "EPSG:4326");
ObjectKeeper keeper_src(src);
ASSERT_NE(src, nullptr);
auto dst = proj_create(m_ctxt, "EPSG:32631");
ObjectKeeper keeper_dst(dst);
ASSERT_NE(dst, nullptr);
auto P = proj_create_crs_to_crs_from_pj(m_ctxt, src, dst, nullptr, nullptr);
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P);
ObjectKeeper keeper_Pnormalized(Pnormalized);
ASSERT_NE(Pnormalized, nullptr);
auto projstr = proj_as_proj_string(m_ctxt, Pnormalized, PJ_PROJ_5, nullptr);
ASSERT_NE(projstr, nullptr);
EXPECT_EQ(std::string(projstr),
"+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad "
"+step +proj=utm +zone=31 +ellps=WGS84");
}
// ---------------------------------------------------------------------------
static void
check_axis_is_latitude(PJ_CONTEXT *ctx, PJ *cs, int axis_number,
const char *unit_name = "degree",
double unit_conv_factor = 0.017453292519943295,
const char *auth = "EPSG", const char *code = "9122") {
const char *name = nullptr;
const char *abbrev = nullptr;
const char *direction = nullptr;
double unitConvFactor = 0.0;
const char *unitName = nullptr;
const char *unitAuthority = nullptr;
const char *unitCode = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(ctx, cs, axis_number, &name, &abbrev,
&direction, &unitConvFactor, &unitName,
&unitAuthority, &unitCode));
ASSERT_NE(name, nullptr);
ASSERT_NE(abbrev, nullptr);
ASSERT_NE(direction, nullptr);
ASSERT_NE(unitName, nullptr);
if (auth) {
ASSERT_NE(unitAuthority, nullptr);
ASSERT_NE(unitCode, nullptr);
}
EXPECT_EQ(std::string(name), "Latitude");
EXPECT_EQ(std::string(abbrev), "lat");
EXPECT_EQ(std::string(direction), "north");
EXPECT_EQ(unitConvFactor, unit_conv_factor) << unitConvFactor;
EXPECT_EQ(std::string(unitName), unit_name);
if (auth) {
EXPECT_EQ(std::string(unitAuthority), auth);
EXPECT_EQ(std::string(unitCode), code);
}
}
// ---------------------------------------------------------------------------
static void
check_axis_is_longitude(PJ_CONTEXT *ctx, PJ *cs, int axis_number,
const char *unit_name = "degree",
double unit_conv_factor = 0.017453292519943295,
const char *auth = "EPSG", const char *code = "9122") {
const char *name = nullptr;
const char *abbrev = nullptr;
const char *direction = nullptr;
double unitConvFactor = 0.0;
const char *unitName = nullptr;
const char *unitAuthority = nullptr;
const char *unitCode = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(ctx, cs, axis_number, &name, &abbrev,
&direction, &unitConvFactor, &unitName,
&unitAuthority, &unitCode));
ASSERT_NE(name, nullptr);
ASSERT_NE(abbrev, nullptr);
ASSERT_NE(direction, nullptr);
ASSERT_NE(unitName, nullptr);
if (auth) {
ASSERT_NE(unitAuthority, nullptr);
ASSERT_NE(unitCode, nullptr);
}
EXPECT_EQ(std::string(name), "Longitude");
EXPECT_EQ(std::string(abbrev), "lon");
EXPECT_EQ(std::string(direction), "east");
EXPECT_EQ(unitConvFactor, unit_conv_factor) << unitConvFactor;
EXPECT_EQ(std::string(unitName), unit_name);
if (auth) {
EXPECT_EQ(std::string(unitAuthority), auth);
EXPECT_EQ(std::string(unitCode), code);
}
}
// ---------------------------------------------------------------------------
static void check_axis_is_height(PJ_CONTEXT *ctx, PJ *cs, int axis_number,
const char *unit_name = "metre",
double unit_conv_factor = 1,
const char *auth = "EPSG",
const char *code = "9001") {
const char *name = nullptr;
const char *abbrev = nullptr;
const char *direction = nullptr;
double unitConvFactor = 0.0;
const char *unitName = nullptr;
const char *unitAuthority = nullptr;
const char *unitCode = nullptr;
EXPECT_TRUE(proj_cs_get_axis_info(ctx, cs, axis_number, &name, &abbrev,
&direction, &unitConvFactor, &unitName,
&unitAuthority, &unitCode));
ASSERT_NE(name, nullptr);
ASSERT_NE(abbrev, nullptr);
ASSERT_NE(direction, nullptr);
ASSERT_NE(unitName, nullptr);
if (auth) {
ASSERT_NE(unitAuthority, nullptr);
ASSERT_NE(unitCode, nullptr);
}
EXPECT_EQ(std::string(name), "Ellipsoidal height");
EXPECT_EQ(std::string(abbrev), "h");
EXPECT_EQ(std::string(direction), "up");
EXPECT_EQ(unitConvFactor, unit_conv_factor) << unitConvFactor;
EXPECT_EQ(std::string(unitName), unit_name);
if (auth) {
EXPECT_EQ(std::string(unitAuthority), auth);
EXPECT_EQ(std::string(unitCode), code);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_ellipsoidal_3D_cs) {
{
auto cs = proj_create_ellipsoidal_3D_cs(
m_ctxt, PJ_ELLPS3D_LATITUDE_LONGITUDE_HEIGHT, nullptr, 0, nullptr,
0);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
EXPECT_EQ(proj_cs_get_type(m_ctxt, cs), PJ_CS_TYPE_ELLIPSOIDAL);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3);
check_axis_is_latitude(m_ctxt, cs, 0);
check_axis_is_longitude(m_ctxt, cs, 1);
check_axis_is_height(m_ctxt, cs, 2);
}
{
auto cs = proj_create_ellipsoidal_3D_cs(
m_ctxt, PJ_ELLPS3D_LONGITUDE_LATITUDE_HEIGHT, "foo", 0.5, "bar",
0.6);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
EXPECT_EQ(proj_cs_get_type(m_ctxt, cs), PJ_CS_TYPE_ELLIPSOIDAL);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3);
check_axis_is_longitude(m_ctxt, cs, 0, "foo", 0.5, nullptr, nullptr);
check_axis_is_latitude(m_ctxt, cs, 1, "foo", 0.5, nullptr, nullptr);
check_axis_is_height(m_ctxt, cs, 2, "bar", 0.6, nullptr, nullptr);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_promote_to_3D) {
auto crs2D =
proj_create(m_ctxt, GeographicCRS::EPSG_4326
->exportToWKT(WKTFormatter::create().get())
.c_str());
ObjectKeeper keeper_crs2D(crs2D);
EXPECT_NE(crs2D, nullptr);
auto crs3D = proj_crs_promote_to_3D(m_ctxt, nullptr, crs2D);
ObjectKeeper keeper_crs3D(crs3D);
EXPECT_NE(crs3D, nullptr);
auto cs = proj_crs_get_coordinate_system(m_ctxt, crs3D);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3);
auto code = proj_get_id_code(crs3D, 0);
ASSERT_TRUE(code != nullptr);
EXPECT_EQ(code, std::string("4979"));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_demote_to_2D) {
auto crs3D =
proj_create(m_ctxt, GeographicCRS::EPSG_4979
->exportToWKT(WKTFormatter::create().get())
.c_str());
ObjectKeeper keeper_crs3D(crs3D);
EXPECT_NE(crs3D, nullptr);
auto crs2D = proj_crs_demote_to_2D(m_ctxt, nullptr, crs3D);
ObjectKeeper keeper_crs2D(crs2D);
EXPECT_NE(crs2D, nullptr);
auto cs = proj_crs_get_coordinate_system(m_ctxt, crs2D);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 2);
auto code = proj_get_id_code(crs2D, 0);
ASSERT_TRUE(code != nullptr);
EXPECT_EQ(code, std::string("4326"));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_create_projected_3D_crs_from_2D) {
auto projCRS = proj_create_from_database(m_ctxt, "EPSG", "32631",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(projCRS, nullptr);
ObjectKeeper keeper_projCRS(projCRS);
{
auto geog3DCRS = proj_create_from_database(
m_ctxt, "EPSG", "4979", PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(geog3DCRS, nullptr);
ObjectKeeper keeper_geog3DCRS(geog3DCRS);
auto crs3D = proj_crs_create_projected_3D_crs_from_2D(
m_ctxt, nullptr, projCRS, geog3DCRS);
ObjectKeeper keeper_crs3D(crs3D);
EXPECT_NE(crs3D, nullptr);
EXPECT_EQ(proj_get_type(crs3D), PJ_TYPE_PROJECTED_CRS);
EXPECT_EQ(std::string(proj_get_name(crs3D)),
std::string(proj_get_name(projCRS)));
auto cs = proj_crs_get_coordinate_system(m_ctxt, crs3D);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3);
}
{
auto crs3D = proj_crs_create_projected_3D_crs_from_2D(m_ctxt, nullptr,
projCRS, nullptr);
ObjectKeeper keeper_crs3D(crs3D);
EXPECT_NE(crs3D, nullptr);
EXPECT_EQ(proj_get_type(crs3D), PJ_TYPE_PROJECTED_CRS);
EXPECT_EQ(std::string(proj_get_name(crs3D)),
std::string(proj_get_name(projCRS)));
auto cs = proj_crs_get_coordinate_system(m_ctxt, crs3D);
ASSERT_NE(cs, nullptr);
ObjectKeeper keeperCs(cs);
EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3);
}
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_crs_create_bound_vertical_crs) {
auto vert_crs = proj_create_vertical_crs(m_ctxt, "myVertCRS", "myVertDatum",
nullptr, 0.0);
ObjectKeeper keeper_vert_crs(vert_crs);
ASSERT_NE(vert_crs, nullptr);
auto crs4979 = proj_create_from_wkt(
m_ctxt,
GeographicCRS::EPSG_4979->exportToWKT(WKTFormatter::create().get())
.c_str(),
nullptr, nullptr, nullptr);
ObjectKeeper keeper_crs4979(crs4979);
ASSERT_NE(crs4979, nullptr);
auto bound_crs = proj_crs_create_bound_vertical_crs(m_ctxt, vert_crs,
crs4979, "foo.gtx");
ObjectKeeper keeper_bound_crs(bound_crs);
ASSERT_NE(bound_crs, nullptr);
auto projCRS = proj_create_from_database(m_ctxt, "EPSG", "32631",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(projCRS, nullptr);
ObjectKeeper keeper_projCRS(projCRS);
auto compound_crs =
proj_create_compound_crs(m_ctxt, "myCompoundCRS", projCRS, bound_crs);
ObjectKeeper keeper_compound_crss(compound_crs);
ASSERT_NE(compound_crs, nullptr);
auto proj_4 = proj_as_proj_string(m_ctxt, compound_crs, PJ_PROJ_4, nullptr);
ASSERT_NE(proj_4, nullptr);
EXPECT_EQ(std::string(proj_4),
"+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=foo.gtx "
"+vunits=m +no_defs +type=crs");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_crs_to_crs_with_only_ballpark_transformations) {
// ETRS89 / UTM zone 31N + EGM96 height to WGS 84 (G1762)
auto P =
proj_create_crs_to_crs(m_ctxt, "EPSG:25831+5773", "EPSG:7665", nullptr);
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P);
ObjectKeeper keeper_Pnormalized(Pnormalized);
ASSERT_NE(Pnormalized, nullptr);
PJ_COORD coord;
coord.xyzt.x = 500000;
coord.xyzt.y = 4500000;
coord.xyzt.z = 0;
coord.xyzt.t = 0;
coord = proj_trans(Pnormalized, PJ_FWD, coord);
EXPECT_NEAR(coord.xyzt.x, 3.0, 1e-9);
EXPECT_NEAR(coord.xyzt.y, 40.65085651660555, 1e-9);
if (coord.xyzt.z != 0) {
// z will depend if the egm96_15.gtx grid is there or not
EXPECT_NEAR(coord.xyzt.z, 47.04784081844435, 1e-3);
}
}
// ---------------------------------------------------------------------------
TEST_F(
CApi,
proj_create_crs_to_crs_from_custom_compound_crs_with_NAD83_2011_and_geoidgrid_ref_against_WGS84_to_WGS84_G1762) {
if (strcmp(proj_grid_info("egm96_15.gtx").format, "missing") == 0) {
return; // use GTEST_SKIP() if we upgrade gtest
}
PJ *P;
PJ *inCrsH = proj_create_from_database(m_ctxt, "EPSG", "6340",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(inCrsH, nullptr);
PJ *inDummyCrs = proj_create_vertical_crs(m_ctxt, "VerticalDummyCrs",
"DummyDatum", "metre", 1.0);
ASSERT_NE(inDummyCrs, nullptr);
auto crs4979 = proj_create_from_database(m_ctxt, "EPSG", "4979",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(crs4979, nullptr);
PJ *inCrsV = proj_crs_create_bound_vertical_crs(m_ctxt, inDummyCrs, crs4979,
"egm96_15.gtx");
ASSERT_NE(inCrsV, nullptr);
proj_destroy(inDummyCrs);
proj_destroy(crs4979);
PJ *inCompound =
proj_create_compound_crs(m_ctxt, "Compound", inCrsH, inCrsV);
ASSERT_NE(inCompound, nullptr);
proj_destroy(inCrsH);
proj_destroy(inCrsV);
PJ *outCrs = proj_create(m_ctxt, "EPSG:7665");
ASSERT_NE(outCrs, nullptr);
// In this particular case, PROJ computes a transformation from NAD83(2011)
// (EPSG:6318) to WGS84 (EPSG:4979) for the initial horizontal adjustment
// before the geoidgrids application. There are 6 candidate transformations
// for that in subzones of the US and one last no-op tranformation flagged
// as ballpark. That one used to be eliminated because by
// proj_create_crs_to_crs() because there were non Ballpark transformations
// available. This resulted thus in an error when transforming outside of
// those few subzones.
P = proj_create_crs_to_crs_from_pj(m_ctxt, inCompound, outCrs, nullptr,
nullptr);
ASSERT_NE(P, nullptr);
proj_destroy(inCompound);
proj_destroy(outCrs);
PJ_COORD in_coord;
in_coord.xyzt.x = 350499.911;
in_coord.xyzt.y = 3884807.956;
in_coord.xyzt.z = 150.072;
in_coord.xyzt.t = 2010;
PJ_COORD outcoord = proj_trans(P, PJ_FWD, in_coord);
proj_destroy(P);
EXPECT_NEAR(outcoord.xyzt.x, 35.09499307271, 1e-9);
EXPECT_NEAR(outcoord.xyzt.y, -118.64014868921, 1e-9);
EXPECT_NEAR(outcoord.xyzt.z, 118.059, 1e-3);
}
// ---------------------------------------------------------------------------
TEST_F(
CApi,
proj_create_crs_to_crs_from_custom_compound_crs_with_NAD83_2011_and_geoidgrid_ref_against_NAD83_2011_to_WGS84_G1762) {
if (strcmp(proj_grid_info("egm96_15.gtx").format, "missing") == 0) {
return; // use GTEST_SKIP() if we upgrade gtest
}
PJ *P;
// NAD83(2011) 2D
PJ *inCrsH = proj_create_from_database(m_ctxt, "EPSG", "6318",
PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(inCrsH, nullptr);
PJ *inDummyCrs = proj_create_vertical_crs(m_ctxt, "VerticalDummyCrs",
"DummyDatum", "metre", 1.0);
ASSERT_NE(inDummyCrs, nullptr);
// NAD83(2011) 3D
PJ *inGeog3DCRS = proj_create_from_database(
m_ctxt, "EPSG", "6319", PJ_CATEGORY_CRS, false, nullptr);
ASSERT_NE(inCrsH, nullptr);
// Note: this is actually a bad example since we tell here that egm96_15.gtx
// is referenced against NAD83(2011)
PJ *inCrsV = proj_crs_create_bound_vertical_crs(
m_ctxt, inDummyCrs, inGeog3DCRS, "egm96_15.gtx");
ASSERT_NE(inCrsV, nullptr);
proj_destroy(inDummyCrs);
proj_destroy(inGeog3DCRS);
PJ *inCompound =
proj_create_compound_crs(m_ctxt, "Compound", inCrsH, inCrsV);
ASSERT_NE(inCompound, nullptr);
proj_destroy(inCrsH);
proj_destroy(inCrsV);
// WGS84 (G1762)
PJ *outCrs = proj_create(m_ctxt, "EPSG:7665");
ASSERT_NE(outCrs, nullptr);
P = proj_create_crs_to_crs_from_pj(m_ctxt, inCompound, outCrs, nullptr,
nullptr);
ASSERT_NE(P, nullptr);
proj_destroy(inCompound);
proj_destroy(outCrs);
PJ_COORD in_coord;
in_coord.xyzt.x = 35;
in_coord.xyzt.y = -118;
in_coord.xyzt.z = 0;
in_coord.xyzt.t = 2010;
PJ_COORD outcoord = proj_trans(P, PJ_FWD, in_coord);
proj_destroy(P);
EXPECT_NEAR(outcoord.xyzt.x, 35.000003665064803, 1e-9);
EXPECT_NEAR(outcoord.xyzt.y, -118.00001414221214, 1e-9);
EXPECT_NEAR(outcoord.xyzt.z, -32.5823, 1e-3);
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_vertical_crs_ex) {
// NAD83(2011) / UTM zone 11N
auto horiz_crs = proj_create_from_database(m_ctxt, "EPSG", "6340",
PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper_horiz_crs(horiz_crs);
ASSERT_NE(horiz_crs, nullptr);
auto vert_crs = proj_create_vertical_crs_ex(
m_ctxt, "myVertCRS (ftUS)", "myVertDatum", nullptr, nullptr,
"US survey foot", 0.304800609601219, "PROJ @foo.gtx", nullptr, nullptr,
nullptr, nullptr);
ObjectKeeper keeper_vert_crs(vert_crs);
ASSERT_NE(vert_crs, nullptr);
auto compound =
proj_create_compound_crs(m_ctxt, "Compound", horiz_crs, vert_crs);
ObjectKeeper keeper_compound(compound);
ASSERT_NE(compound, nullptr);
// NAD83(2011) 3D
PJ *geog_crs = proj_create(m_ctxt, "EPSG:6319");
ObjectKeeper keeper_geog_crs(geog_crs);
ASSERT_NE(geog_crs, nullptr);
auto P = proj_create_crs_to_crs_from_pj(m_ctxt, compound, geog_crs, nullptr,
nullptr);
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto name = proj_get_name(P);
ASSERT_TRUE(name != nullptr);
EXPECT_EQ(name,
std::string("Inverse of UTM zone 11N + "
"Transformation from myVertCRS (ftUS) to myVertCRS + "
"Transformation from myVertCRS to NAD83(2011)"));
auto proj_5 = proj_as_proj_string(m_ctxt, P, PJ_PROJ_5, nullptr);
ASSERT_NE(proj_5, nullptr);
EXPECT_EQ(std::string(proj_5),
"+proj=pipeline "
"+step +inv +proj=utm +zone=11 +ellps=GRS80 "
"+step +proj=unitconvert +z_in=us-ft +z_out=m "
"+step +proj=vgridshift +grids=@foo.gtx +multiplier=1 "
"+step +proj=unitconvert +xy_in=rad +xy_out=deg "
"+step +proj=axisswap +order=2,1");
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_vertical_crs_ex_with_geog_crs) {
// NAD83(2011) / UTM zone 11N
auto horiz_crs = proj_create_from_database(m_ctxt, "EPSG", "6340",
PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper_horiz_crs(horiz_crs);
ASSERT_NE(horiz_crs, nullptr);
// WGS84
PJ *wgs84 = proj_create(m_ctxt, "EPSG:4979");
ObjectKeeper keeper_wgs84(wgs84);
ASSERT_NE(wgs84, nullptr);
auto vert_crs = proj_create_vertical_crs_ex(
m_ctxt, "myVertCRS", "myVertDatum", nullptr, nullptr, "US survey foot",
0.304800609601219, "PROJ @foo.gtx", nullptr, nullptr, wgs84, nullptr);
ObjectKeeper keeper_vert_crs(vert_crs);
ASSERT_NE(vert_crs, nullptr);
auto compound =
proj_create_compound_crs(m_ctxt, "Compound", horiz_crs, vert_crs);
ObjectKeeper keeper_compound(compound);
ASSERT_NE(compound, nullptr);
// NAD83(2011) 3D
PJ *geog_crs = proj_create(m_ctxt, "EPSG:6319");
ObjectKeeper keeper_geog_crs(geog_crs);
ASSERT_NE(geog_crs, nullptr);
auto P = proj_create_crs_to_crs_from_pj(m_ctxt, compound, geog_crs, nullptr,
nullptr);
ObjectKeeper keeper_P(P);
ASSERT_NE(P, nullptr);
auto name = proj_get_name(P);
ASSERT_TRUE(name != nullptr);
EXPECT_EQ(
name,
std::string("Inverse of UTM zone 11N + "
"Ballpark geographic offset from NAD83(2011) to WGS 84 + "
"Transformation from myVertCRS to myVertCRS (metre) + "
"Transformation from myVertCRS (metre) to WGS 84 + "
"Ballpark geographic offset from WGS 84 to NAD83(2011)"));
auto proj_5 = proj_as_proj_string(m_ctxt, P, PJ_PROJ_5, nullptr);
ASSERT_NE(proj_5, nullptr);
EXPECT_EQ(std::string(proj_5),
"+proj=pipeline "
"+step +inv +proj=utm +zone=11 +ellps=GRS80 "
"+step +proj=unitconvert +z_in=us-ft +z_out=m "
"+step +proj=vgridshift +grids=@foo.gtx +multiplier=1 "
"+step +proj=unitconvert +xy_in=rad +xy_out=deg "
"+step +proj=axisswap +order=2,1");
// Check that we get the same results after an export of compoundCRS to
// PROJJSON and a re-import from it.
auto projjson = proj_as_projjson(m_ctxt, compound, nullptr);
ASSERT_NE(projjson, nullptr);
auto compound_from_projjson = proj_create(m_ctxt, projjson);
ObjectKeeper keeper_compound_from_projjson(compound_from_projjson);
ASSERT_NE(compound_from_projjson, nullptr);
auto P2 = proj_create_crs_to_crs_from_pj(m_ctxt, compound_from_projjson,
geog_crs, nullptr, nullptr);
ObjectKeeper keeper_P2(P2);
ASSERT_NE(P2, nullptr);
auto name_bis = proj_get_name(P2);
ASSERT_TRUE(name_bis != nullptr);
EXPECT_EQ(std::string(name_bis), std::string(name));
auto proj_5_bis = proj_as_proj_string(m_ctxt, P2, PJ_PROJ_5, nullptr);
ASSERT_NE(proj_5_bis, nullptr);
EXPECT_EQ(std::string(proj_5_bis), std::string(proj_5));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_create_derived_geographic_crs) {
PJ *crs_4326 = proj_create(m_ctxt, "EPSG:4326");
ObjectKeeper keeper_crs_4326(crs_4326);
ASSERT_NE(crs_4326, nullptr);
PJ *conversion = proj_create_conversion_pole_rotation_grib_convention(
m_ctxt, 2, 3, 4, "Degree", 0.0174532925199433);
ObjectKeeper keeper_conversion(conversion);
ASSERT_NE(conversion, nullptr);
PJ *cs = proj_crs_get_coordinate_system(m_ctxt, crs_4326);
ObjectKeeper keeper_cs(cs);
ASSERT_NE(cs, nullptr);
ASSERT_EQ(
proj_create_derived_geographic_crs(m_ctxt, "my rotated CRS",
conversion, // wrong type of object
conversion, cs),
nullptr);
ASSERT_EQ(
proj_create_derived_geographic_crs(m_ctxt, "my rotated CRS", crs_4326,
crs_4326, // wrong type of object
cs),
nullptr);
ASSERT_EQ(proj_create_derived_geographic_crs(
m_ctxt, "my rotated CRS", crs_4326, conversion,
conversion // wrong type of object
),
nullptr);
PJ *derived_crs = proj_create_derived_geographic_crs(
m_ctxt, "my rotated CRS", crs_4326, conversion, cs);
ObjectKeeper keeper_derived_crs(derived_crs);
ASSERT_NE(derived_crs, nullptr);
EXPECT_FALSE(proj_is_derived_crs(m_ctxt, crs_4326));
EXPECT_TRUE(proj_is_derived_crs(m_ctxt, derived_crs));
auto wkt = proj_as_wkt(m_ctxt, derived_crs, PJ_WKT2_2019, nullptr);
const char *expected_wkt =
"GEOGCRS[\"my rotated CRS\",\n"
" BASEGEOGCRS[\"WGS 84\",\n"
" DATUM[\"World Geodetic System 1984\",\n"
" ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n"
" LENGTHUNIT[\"metre\",1]]],\n"
" PRIMEM[\"Greenwich\",0,\n"
" ANGLEUNIT[\"degree\",0.0174532925199433]]],\n"
" DERIVINGCONVERSION[\"Pole rotation (GRIB convention)\",\n"
" METHOD[\"Pole rotation (GRIB convention)\"],\n"
" PARAMETER[\"Latitude of the southern pole (GRIB "
"convention)\",2,\n"
" ANGLEUNIT[\"degree\",0.0174532925199433,\n"
" ID[\"EPSG\",9122]]],\n"
" PARAMETER[\"Longitude of the southern pole (GRIB "
"convention)\",3,\n"
" ANGLEUNIT[\"degree\",0.0174532925199433,\n"
" ID[\"EPSG\",9122]]],\n"
" PARAMETER[\"Axis rotation (GRIB convention)\",4,\n"
" ANGLEUNIT[\"degree\",0.0174532925199433,\n"
" ID[\"EPSG\",9122]]]],\n"
" CS[ellipsoidal,2],\n"
" AXIS[\"geodetic latitude (Lat)\",north,\n"
" ORDER[1],\n"
" ANGLEUNIT[\"degree\",0.0174532925199433,\n"
" ID[\"EPSG\",9122]]],\n"
" AXIS[\"geodetic longitude (Lon)\",east,\n"
" ORDER[2],\n"
" ANGLEUNIT[\"degree\",0.0174532925199433,\n"
" ID[\"EPSG\",9122]]]]";
ASSERT_NE(wkt, nullptr);
EXPECT_EQ(wkt, std::string(expected_wkt));
auto proj_5 = proj_as_proj_string(m_ctxt, derived_crs, PJ_PROJ_5, nullptr);
ASSERT_NE(proj_5, nullptr);
EXPECT_EQ(proj_5, std::string("+proj=ob_tran +o_proj=longlat +o_lon_p=-4 "
"+o_lat_p=-2 +lon_0=3 +datum=WGS84 +no_defs "
"+type=crs"));
}
// ---------------------------------------------------------------------------
TEST_F(CApi, proj_is_equivalent_to_with_ctx) {
auto from_epsg = proj_create_from_database(m_ctxt, "EPSG", "7844",
PJ_CATEGORY_CRS, false, nullptr);
ObjectKeeper keeper_from_epsg(from_epsg);
ASSERT_NE(from_epsg, nullptr);
auto wkt = "GEOGCRS[\"GDA2020\",\n"
" DATUM[\"GDA2020\",\n"
" ELLIPSOID[\"GRS_1980\",6378137,298.257222101,\n"
" LENGTHUNIT[\"metre\",1]]],\n"
" PRIMEM[\"Greenwich\",0,\n"
" ANGLEUNIT[\"Degree\",0.0174532925199433]],\n"
" CS[ellipsoidal,2],\n"
" AXIS[\"geodetic latitude (Lat)\",north,\n"
" ORDER[1],\n"
" ANGLEUNIT[\"degree\",0.0174532925199433]],\n"
" AXIS[\"geodetic longitude (Lon)\",east,\n"
" ORDER[2],\n"
" ANGLEUNIT[\"degree\",0.0174532925199433]]]";
auto from_wkt =
proj_create_from_wkt(m_ctxt, wkt, nullptr, nullptr, nullptr);
ObjectKeeper keeper_from_wkt(from_wkt);
EXPECT_NE(from_wkt, nullptr);
EXPECT_TRUE(proj_is_equivalent_to_with_ctx(m_ctxt, from_epsg, from_wkt,
PJ_COMP_EQUIVALENT));
}
} // namespace
| [
"oscarmb94@hotmail.es"
] | oscarmb94@hotmail.es |
84fd01986a9d5202d06c64740906b1d451720714 | 132dbb86bd06fdadc99d32fb13d03c4d215f262d | /ArithmeticProgressions.cpp | e97790bda847c689163d02266c4e4ec4b8c513fc | [] | no_license | bossbobster/USACO-Training | 90d481c2241aa50d467d3acadfd2cf80264dc087 | 4689499a24844f39e385a06d49c1c602277fc0e6 | refs/heads/master | 2023-02-20T00:31:45.689765 | 2023-02-05T09:30:02 | 2023-02-05T09:30:02 | 204,623,891 | 12 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,874 | cpp | /*
PROB: ariprog
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <bitset>
using namespace std;
ifstream fin("ariprog.in");
ofstream fout("ariprog.out");
bitset<125000> bisquares;
int sequences[10000][2] ;
void calculateBisquares(int num)
{
for(int i = 0; i <= num; i ++)
{
for(int j = i; j <= num; j ++)
{
bisquares[(i * i) + (j * j)] = true;
}
}
}
bool cpr(int n1[2], int n2[2])
{
if(n1[1] == n2[1])
return n1[0] < n2[0];
return n1[1] < n2[1];
}
int main()
{
int n, m, seqCnt = 0;
bool sol = true;
fin >> n >> m;
calculateBisquares(m);
for(int j = 1; j <= (m * m + m * m) / (n - 1); j ++)
{
for(int i = 0; i <= m * m + m * m; i ++)
{
if(!bisquares[i])
continue;
if(i + (n - 1) * j > m * m + m * m)
break;
sol = true;
for(int k = 1; k <= n - 1; k ++)
{
if(!bisquares[i + j * k])
{
sol = false;
break;
}
}
if(sol)
{
sequences[seqCnt][0] = i;
sequences[seqCnt][1] = j;
seqCnt ++;
}
}
}
if(!seqCnt)
fout << "NONE" << endl;
else
{
for(int i = 0; i < seqCnt; i ++)
fout << sequences[i][0] << " " << sequences[i][1] << endl;
}
}
/*
Executing...
Test 1: TEST OK [0.004 secs, 1360 KB]
Test 2: TEST OK [0.004 secs, 1388 KB]
Test 3: TEST OK [0.004 secs, 1412 KB]
Test 4: TEST OK [0.004 secs, 1320 KB]
Test 5: TEST OK [0.018 secs, 1408 KB]
Test 6: TEST OK [0.137 secs, 1392 KB]
Test 7: TEST OK [1.680 secs, 1400 KB]
Test 8: TEST OK [3.840 secs, 1376 KB]
Test 9: TEST OK [3.367 secs, 1392 KB]
*/
| [
"noreply@github.com"
] | noreply@github.com |
6613355fd8262412cffa90cb605f1ab7eac86f37 | fd5b9e74d18ce162d8fb582cf7ee1c601929d7ad | /1789.cpp | c53f3a5e008e01b72399df66a909244d7e493d41 | [] | no_license | parkhaeseon/boj | 811b04a532456fb12ee6092090d692b883469a15 | 2b4cf6bea412b8f17480a2872b2db811374a70c2 | refs/heads/master | 2022-02-21T10:30:52.773309 | 2019-10-01T04:51:18 | 2019-10-01T04:51:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 588 | cpp | #include <iostream>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;
int main(void)
{
long long N = 0;
scanf("%lld", &N);
long long i = 1;
while (1)
{
long long left = (i*i) / 2 - i / 2 + 2 * i;
long long right = (i + 1)*(i + 1) / 2 - (i + 1) / 2 + 2 * (i + 1);
if (left < N && N <= right) break;
if (left >= N)
{
--i;
break;
}
++i;
}
printf("%lld\n", i + 1);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
89aa736166628e4441f7a6224ba66011a4bbfb48 | 9cf7c69cd3259fb43396df40d8e91a4254ad8d4b | /Polimorfismo/Mago.h | 08fc706e5fbb1893bdbe1b2d67c955c7f877cec9 | [] | no_license | UnitecProgra3/EjerciciosEnClaseDragon | 17e48bf67263203015f165174104ff68faad95d9 | f69454e11689cf1eef44f670f4c2231fe0e87547 | refs/heads/master | 2016-08-12T10:41:50.814417 | 2016-02-18T00:17:36 | 2016-02-18T00:17:36 | 50,446,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | h | #ifndef MAGO_H
#define MAGO_H
#include "Personaje.h"
class Mago : public Personaje
{
public:
Mago();
virtual ~Mago();
void atacar();
protected:
private:
};
#endif // MAGO_H
| [
"ahmed.hn.43@gmail.com"
] | ahmed.hn.43@gmail.com |
14f09665f3ea66203a9f55ce16f05848dc8ffac9 | 348e80a3b8c0c0a16fc36ef2d1034eac06da97aa | /PeraProcessDesigner/PeraProcessDesigner/CxBCGPSplitterWnd.cpp | 0611174039754ba83c05e9aa059f4057f4dd0b25 | [] | no_license | wyrover/WorkPlatForm | 0e2c9127ccb6828857532eb11f96be3efc061fe9 | f14a8cdd2bc3772ea4bd37a0381f5f8305a0a2c2 | refs/heads/master | 2021-01-16T21:16:13.672343 | 2016-01-17T08:59:01 | 2016-01-17T08:59:01 | 62,207,103 | 0 | 1 | null | 2016-06-29T07:56:29 | 2016-06-29T07:56:28 | null | GB18030 | C++ | false | false | 5,014 | cpp | // CxBCGPSplitterWnd.cpp : 实现文件
//
#include "stdafx.h"
#include "CxBCGPSplitterWnd.h"
static enum HitTestValue
{
noHit = 0,
vSplitterBox = 1,
hSplitterBox = 2,
bothSplitterBox = 3, // just for keyboard
vSplitterBar1 = 101,
vSplitterBar15 = 115,
hSplitterBar1 = 201,
hSplitterBar15 = 215,
splitterIntersection1 = 301,
splitterIntersection225 = 525
};
// CCxBCGPSplitterWnd
BEGIN_MESSAGE_MAP(CCxBCGPSplitterWnd, CBCGPSplitterWnd)
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()
IMPLEMENT_DYNAMIC(CCxBCGPSplitterWnd, CBCGPSplitterWnd)
CCxBCGPSplitterWnd::CCxBCGPSplitterWnd()
{
m_cxSplitter = 7; //must >=4 ,拖动时拖动条的宽度
m_cySplitter = 4;
}
CCxBCGPSplitterWnd::~CCxBCGPSplitterWnd()
{
}
void CCxBCGPSplitterWnd::RecalcLayout()
{
CBCGPSplitterWnd::RecalcLayout();
CRect rcView;
CWnd* pWnd = GetDlgItem(IdFromRowCol(0,0));
pWnd->GetWindowRect(&rcView);
ScreenToClient(&rcView);
rcView.DeflateRect(-2, 0, 1, -2);
pWnd->MoveWindow(rcView);
pWnd = GetDlgItem(IdFromRowCol(0,1));
pWnd->GetWindowRect(&rcView);
ScreenToClient(&rcView);
rcView.DeflateRect(-2, 0, -2, -2);
pWnd->MoveWindow(rcView);
}
void CCxBCGPSplitterWnd::StartTracking( int ht )
{
//Splitter 不能有 WS_CLIPCHILDREN 属性
ModifyStyle(WS_CLIPCHILDREN, 0);
CBCGPSplitterWnd::StartTracking(ht);
}
void CCxBCGPSplitterWnd::StopTracking( BOOL bAccept )
{
CBCGPSplitterWnd::StopTracking(bAccept);
ModifyStyle(0, WS_CLIPCHILDREN);
}
void CCxBCGPSplitterWnd::OnMouseMove(UINT /*nFlags*/, CPoint pt)
{
if (GetCapture() != this)
StopTracking(FALSE);
if (m_bTracking)
{
// move tracker to current cursor position
pt.Offset(m_ptTrackOffset); // pt is the upper right of hit detect
// limit the point to the valid split range
if (pt.y < m_rectLimit.top)
pt.y = m_rectLimit.top;
else if (pt.y > m_rectLimit.bottom)
pt.y = m_rectLimit.bottom;
if (pt.x < m_rectLimit.left)
pt.x = m_rectLimit.left;
else if (pt.x > m_rectLimit.right)
pt.x = m_rectLimit.right;
if (m_htTrack == vSplitterBox ||
m_htTrack >= vSplitterBar1 && m_htTrack <= vSplitterBar15)
{
if (m_rectTracker.top != pt.y)
{
OnInvertTracker(m_rectTracker);
m_rectTracker.OffsetRect(0, pt.y - m_rectTracker.top);
OnInvertTracker(m_rectTracker);
}
}
else if (m_htTrack == hSplitterBox ||
m_htTrack >= hSplitterBar1 && m_htTrack <= hSplitterBar15)
{
if (m_rectTracker.left != pt.x)
{
OnInvertTracker(m_rectTracker);
m_rectTracker.OffsetRect(pt.x - m_rectTracker.left, 0);
OnInvertTracker(m_rectTracker);
}
}
else if (m_htTrack == bothSplitterBox ||
(m_htTrack >= splitterIntersection1 &&
m_htTrack <= splitterIntersection225))
{
if (m_rectTracker.top != pt.y)
{
OnInvertTracker(m_rectTracker);
m_rectTracker.OffsetRect(0, pt.y - m_rectTracker.top);
OnInvertTracker(m_rectTracker);
}
if (m_rectTracker2.left != pt.x)
{
OnInvertTracker(m_rectTracker2);
m_rectTracker2.OffsetRect(pt.x - m_rectTracker2.left, 0);
OnInvertTracker(m_rectTracker2);
}
}
}
else
{
// simply hit-test and set appropriate cursor
int ht = HitTest(pt);
SetSplitCursor(ht);
}
}
void CCxBCGPSplitterWnd::GetHitRect(int ht, CRect& rectHit)
{
ASSERT_VALID(this);
CRect rectClient;
GetClientRect(&rectClient);
rectClient.InflateRect(-m_cxBorder, -m_cyBorder);
int cx = rectClient.Width();
int cy = rectClient.Height();
int x = rectClient.top;
int y = rectClient.left;
// hit rectangle does not include border
// m_rectLimit will be limited to valid tracking rect
// m_ptTrackOffset will be set to appropriate tracking offset
m_ptTrackOffset.x = 0;
m_ptTrackOffset.y = 0;
if (ht == vSplitterBox)
{
cy = m_cySplitter - (2*m_cyBorder - 1);
m_ptTrackOffset.y = -(cy / 2);
ASSERT(m_pRowInfo[0].nCurSize > 0);
m_rectLimit.bottom -= cy;
}
else if (ht == hSplitterBox)
{
cx = m_cxSplitter - (2*m_cxBorder - 1);
m_ptTrackOffset.x = -(cx / 2);
ASSERT(m_pColInfo[0].nCurSize > 0);
m_rectLimit.right -= cx;
}
else if (ht >= vSplitterBar1 && ht <= vSplitterBar15)
{
cy = m_cySplitter - (2*m_cyBorder - 1);
m_ptTrackOffset.y = -(cy / 2);
int row;
for (row = 0; row < ht - vSplitterBar1; row++)
y += m_pRowInfo[row].nCurSize + m_cySplitterGap;
m_rectLimit.top = y;
y += m_pRowInfo[row].nCurSize + m_cyBorderShare + 1;
m_rectLimit.bottom -= cy;
}
else if (ht >= hSplitterBar1 && ht <= hSplitterBar15)
{
cx = m_cxSplitter - (2*m_cxBorder - 1);
m_ptTrackOffset.x = -(cx / 2);
int col;
for (col = 0; col < ht - hSplitterBar1; col++)
x += m_pColInfo[col].nCurSize + m_cxSplitterGap;
m_rectLimit.left = x;
x += m_pColInfo[col].nCurSize + m_cxBorderShare + 1;
m_rectLimit.right -= cx;
}
else
{
TRACE(traceAppMsg, 0, "Error: GetHitRect(%d): Not Found!\n", ht);
ASSERT(FALSE);
}
rectHit.right = (rectHit.left = x) + cx;
rectHit.bottom = (rectHit.top = y) + cy;
}
| [
"cugxiangzhenwei@sina.cn"
] | cugxiangzhenwei@sina.cn |
5c5381d221d20ded2ad610de5792b11ea538d23b | f6f0f87647e23507dca538760ab70e26415b8313 | /6.5.0/msvc2022_64/include/QtCore/6.5.0/QtCore/private/qatomicscopedvaluerollback_p.h | a201bbfed943e54c5b1c637674253e8d15c76dd3 | [] | no_license | stenzek/duckstation-ext-qt-minimal | a942c62adc5654c03d90731a8266dc711546b268 | e5c412efffa3926f7a4d5bf0ae0333e1d6784f30 | refs/heads/master | 2023-08-17T16:50:21.478373 | 2023-08-15T14:53:43 | 2023-08-15T14:53:43 | 233,179,313 | 3 | 1 | null | 2021-11-16T15:34:28 | 2020-01-11T05:05:34 | C++ | UTF-8 | C++ | false | false | 3,501 | h | // Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QATOMICSCOPEDVALUEROLLBACK_P_H
#define QATOMICSCOPEDVALUEROLLBACK_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of qapplication_*.cpp, qwidget*.cpp and qfiledialog.cpp. This header
// file may change from version to version without notice, or even be removed.
//
// We mean it.
//
#include <QtCore/qglobal.h>
#include <QtCore/qatomic.h>
#include <atomic>
QT_BEGIN_NAMESPACE
template <typename T>
class [[nodiscard]] QAtomicScopedValueRollback
{
std::atomic<T> &m_atomic;
T m_value;
std::memory_order m_mo;
Q_DISABLE_COPY_MOVE(QAtomicScopedValueRollback)
constexpr std::memory_order store_part(std::memory_order mo) noexcept
{
switch (mo) {
case std::memory_order_relaxed:
case std::memory_order_consume:
case std::memory_order_acquire: return std::memory_order_relaxed;
case std::memory_order_release:
case std::memory_order_acq_rel: return std::memory_order_release;
case std::memory_order_seq_cst: return std::memory_order_seq_cst;
}
// GCC 8.x does not tread __builtin_unreachable() as constexpr
#if !defined(Q_CC_GNU_ONLY) || (Q_CC_GNU >= 900)
// NOLINTNEXTLINE(qt-use-unreachable-return): Triggers on Clang, breaking GCC 8
Q_UNREACHABLE();
#endif
return std::memory_order_seq_cst;
}
public:
//
// std::atomic:
//
explicit constexpr
QAtomicScopedValueRollback(std::atomic<T> &var,
std::memory_order mo = std::memory_order_seq_cst)
: m_atomic(var), m_value(var.load(mo)), m_mo(mo) {}
explicit constexpr
QAtomicScopedValueRollback(std::atomic<T> &var, T value,
std::memory_order mo = std::memory_order_seq_cst)
: m_atomic(var), m_value(var.exchange(value, mo)), m_mo(mo) {}
//
// Q(Basic)AtomicInteger:
//
explicit constexpr
QAtomicScopedValueRollback(QBasicAtomicInteger<T> &var,
std::memory_order mo = std::memory_order_seq_cst)
: QAtomicScopedValueRollback(var._q_value, mo) {}
explicit constexpr
QAtomicScopedValueRollback(QBasicAtomicInteger<T> &var, T value,
std::memory_order mo = std::memory_order_seq_cst)
: QAtomicScopedValueRollback(var._q_value, value, mo) {}
//
// Q(Basic)AtomicPointer:
//
explicit constexpr
QAtomicScopedValueRollback(QBasicAtomicPointer<std::remove_pointer_t<T>> &var,
std::memory_order mo = std::memory_order_seq_cst)
: QAtomicScopedValueRollback(var._q_value, mo) {}
explicit constexpr
QAtomicScopedValueRollback(QBasicAtomicPointer<std::remove_pointer_t<T>> &var, T value,
std::memory_order mo = std::memory_order_seq_cst)
: QAtomicScopedValueRollback(var._q_value, value, mo) {}
#if __cpp_constexpr >= 201907L
constexpr
#endif
~QAtomicScopedValueRollback()
{
m_atomic.store(m_value, store_part(m_mo));
}
constexpr void commit()
{
m_value = m_atomic.load(m_mo);
}
};
QT_END_NAMESPACE
#endif // QATOMICASCOPEDVALUEROLLBACK_P_H
| [
"stenzek@gmail.com"
] | stenzek@gmail.com |
3f0d69a59fad91094027cacfbebb2adedcaea487 | 6035fe3136d967bc02ef3a4e8556142028fa13e2 | /pc/key_pair.cpp | d01a5750b924c09e7d3acd6044fc0929ddbb28f2 | [
"Apache-2.0"
] | permissive | rtilder/pyth-client | 331993c17e4f9310643ba71022a10b67b67ff456 | aaf33e1dd13c7c945f1545dd5b207646cba034d3 | refs/heads/main | 2023-08-12T13:29:47.373341 | 2021-10-13T00:01:12 | 2021-10-13T17:55:48 | 401,839,554 | 0 | 0 | Apache-2.0 | 2021-08-31T20:49:06 | 2021-08-31T20:49:06 | null | UTF-8 | C++ | false | false | 5,398 | cpp | #include "key_pair.hpp"
#include "jtree.hpp"
#include "mem_map.hpp"
#include "misc.hpp"
#include <openssl/evp.h>
#define PC_SYMBOL_SPACES 0x2020202020202020
using namespace pc;
hash::hash()
{
}
hash::hash( const hash& obj )
{
*this = obj;
}
hash& hash::operator=( const hash& obj )
{
i_[0] = obj.i_[0];
i_[1] = obj.i_[1];
i_[2] = obj.i_[2];
i_[3] = obj.i_[3];
return *this;
}
bool hash::operator==( const hash& obj) const
{
return i_[0] == obj.i_[0] &&
i_[1] == obj.i_[1] &&
i_[2] == obj.i_[2] &&
i_[3] == obj.i_[3];
}
bool hash::operator!=( const hash& obj) const
{
return i_[0] != obj.i_[0] ||
i_[1] != obj.i_[1] ||
i_[2] != obj.i_[2] ||
i_[3] != obj.i_[3];
}
void hash::zero()
{
i_[0] = i_[1] = i_[2] = i_[3] = 0UL;
}
bool hash::init_from_file( const std::string& file )
{
mem_map mp;
mp.set_file( file );
if ( !mp.init() ) {
return false;
}
pc::dec_base58( (const uint8_t*)mp.data(), mp.size(), pk_ );
return true;
}
bool hash::init_from_text( const std::string& buf )
{
pc::dec_base58( (const uint8_t*)buf.c_str(), buf.length(), pk_ );
return true;
}
bool hash::init_from_text( str buf )
{
pc::dec_base58( (const uint8_t*)buf.str_, buf.len_, pk_ );
return true;
}
void hash::init_from_buf( const uint8_t *pk )
{
__builtin_memcpy( pk_, pk, len );
}
int hash::enc_base58( uint8_t *buf, uint32_t buflen ) const
{
return pc::enc_base58( pk_, len, buf, buflen );
}
int hash::enc_base58( std::string& res ) const
{
char buf[64];
int n = enc_base58( (uint8_t*)buf, 64 );
res.assign( buf, n );
return n;
}
int hash::dec_base58( const uint8_t *buf, uint32_t buflen )
{
return pc::dec_base58( buf, buflen, pk_ );
}
pub_key::pub_key()
{
}
pub_key::pub_key( const pub_key& obj )
: hash( obj )
{
}
pub_key::pub_key( const key_pair& kp )
{
kp.get_pub_key( *this );
}
pub_key& pub_key::operator=( const pub_key& pk )
{
return (pub_key&)hash::operator=( pk );
}
void key_pair::gen()
{
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL);
EVP_PKEY_keygen_init(pctx);
EVP_PKEY_keygen(pctx, &pkey);
EVP_PKEY_CTX_free(pctx);
size_t len[] = { pub_key::len };
EVP_PKEY_get_raw_private_key( pkey, pk_, len );
EVP_PKEY_get_raw_public_key( pkey, &pk_[pub_key::len], len );
EVP_PKEY_free( pkey );
}
void key_pair::zero()
{
__builtin_memset( pk_, 0, len );
}
bool key_pair::init_from_file( const std::string& file )
{
mem_map mp;
mp.set_file( file );
if ( !mp.init() ) {
return false;
}
return init_from_json( mp.data(), mp.size() );
}
bool key_pair::init_from_json( const std::string& buf )
{
return init_from_json( buf.c_str(), buf.length() );
}
bool key_pair::init_from_json( const char *buf, size_t len )
{
jtree jt;
jt.parse( buf, len );
uint8_t *pk = pk_;
for( uint32_t it = jt.get_first(1); it; it = jt.get_next( it ) ) {
*pk++ = (uint8_t)jt.get_uint( it );
}
return key_pair::len == (size_t)(pk - pk_);
}
void key_pair::get_pub_key( pub_key& pk ) const
{
pk.init_from_buf( &pk_[pub_key::len] );
}
key_cache::key_cache()
: ptr_( nullptr )
{
}
key_cache::~key_cache()
{
if ( ptr_ ) {
EVP_PKEY_free( (EVP_PKEY*)ptr_ );
ptr_ = nullptr;
}
}
void key_cache::set( const key_pair& pk )
{
EVP_PKEY *pkey = EVP_PKEY_new_raw_private_key(
EVP_PKEY_ED25519, NULL, pk.data(), pub_key::len );
ptr_ = (void*)pkey;
}
void *key_cache::get() const
{
return ptr_;
}
void signature::init_from_buf( const uint8_t *buf )
{
__builtin_memcpy( sig_, buf, len );
}
bool signature::init_from_text( const std::string& buf )
{
pc::dec_base58( (const uint8_t*)buf.c_str(), buf.length(), sig_ );
return true;
}
int signature::enc_base58( uint8_t *buf, uint32_t buflen )
{
return pc::enc_base58( sig_, len, buf, buflen );
}
int signature::enc_base58( std::string& res )
{
char buf[256];
int n = enc_base58( (uint8_t*)buf, 256 );
res.assign( buf, n );
return n;
}
bool signature::sign(
const uint8_t* msg, uint32_t msg_len, const key_pair& kp )
{
EVP_PKEY *pkey = EVP_PKEY_new_raw_private_key( EVP_PKEY_ED25519,
NULL, kp.data(), pub_key::len );
if ( !pkey ) {
return false;
}
EVP_MD_CTX *mctx = EVP_MD_CTX_new();
int rc = EVP_DigestSignInit( mctx, NULL, NULL, NULL, pkey );
if ( rc ) {
size_t sig_len[1] = { len };
rc = EVP_DigestSign( mctx, sig_, sig_len, msg, msg_len );
}
EVP_MD_CTX_free( mctx );
EVP_PKEY_free( pkey );
return rc != 0;
}
bool signature::sign(
const uint8_t* msg, uint32_t msg_len, const key_cache& kp )
{
EVP_PKEY *pkey = (EVP_PKEY*)kp.get();
if ( !pkey ) {
return false;
}
EVP_MD_CTX *mctx = EVP_MD_CTX_new();
int rc = EVP_DigestSignInit( mctx, NULL, NULL, NULL, pkey );
if ( rc ) {
size_t sig_len[1] = { len };
rc = EVP_DigestSign( mctx, sig_, sig_len, msg, msg_len );
}
EVP_MD_CTX_free( mctx );
return rc != 0;
}
bool signature::verify(
const uint8_t* msg, uint32_t msg_len, const pub_key& pk )
{
EVP_PKEY *pkey = EVP_PKEY_new_raw_public_key( EVP_PKEY_ED25519,
NULL, pk.data(), pub_key::len );
if ( !pkey ) {
return false;
}
EVP_MD_CTX *mctx = EVP_MD_CTX_new();
int rc = EVP_DigestSignInit( mctx, NULL, NULL, NULL, pkey );
if ( rc ) {
rc = EVP_DigestVerify( mctx, sig_, len, msg, msg_len );
}
EVP_MD_CTX_free( mctx );
EVP_PKEY_free( pkey );
return rc != 0;
}
| [
"richardbrooks2000@gmail.com"
] | richardbrooks2000@gmail.com |
885b9312141a0b3e5b6889bd4d56d04792c514e8 | 8401945119f7344ae672a49a29f178e66c12dd09 | /Display.h | 6f408f351e85c16d6e37ae17e04b5872ec0bdcf2 | [] | no_license | the-rich-piana/modern-opengl | 83631fb69f5419503545d4ac4b58056efe6a9f41 | d7b82ebfccf82f9c2ca511e9a14d897907531155 | refs/heads/master | 2020-09-03T01:31:13.453516 | 2019-11-03T19:13:48 | 2019-11-03T19:13:48 | 219,351,696 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | h | #pragma once
#include <string>
#include <SDL2/SDL.h>
class Display
{
public:
Display(int width, int height, const std::string& title);
void Clear(float r, float g, float b, float a);
void Update();
bool IsClosed();
void SwapBuffers();
virtual ~Display();
protected:
private:
void operator=(const Display& display) {}
Display(const Display& display) {}
SDL_Window* m_window;
SDL_GLContext m_glContext;
bool isClosed;
};
| [
"noreply@github.com"
] | noreply@github.com |
95926a9b50a31d895b45c157902fb8c439f90803 | 1359bb193ce7ec547ae07862c207b6b68d7d8d8e | /Matrix/Spiral Matrix II.cpp | afe8bdafc5b4a063f3883d173e043dd7439f236f | [] | no_license | yukta22/leetcode | f13f6d96c0e7254651de55ce9ab54ca5f5992e6b | 8d1352415146adf7cb8963e6c80c78111c89dc4f | refs/heads/main | 2023-08-14T11:01:48.541234 | 2021-09-28T09:36:45 | 2021-09-28T09:36:45 | 328,369,449 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,100 | cpp | // https://leetcode.com/problems/spiral-matrix-ii/
// Time Comp : O(n2) , Space : O(1)
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>>ans(n,vector<int>(n));
if(n == 0)return ans;
int r1 = 0 , r2 = n-1;
int c1 = 0 , c2 = n-1;
int j = 1;
while(r1 <= r2 && c1 <= c2){
for(int i = c1 ; i <= c2 ; i++){
ans[r1][i] = j;
j++;
}
for(int i = r1+1 ; i <= r2 ; i++){
ans[i][c2] = j;
j++;
}
if(r1 < r2 && c1 < c2){
for(int i = c2-1 ; i >= c1 ; i--){
ans[r2][i] = j;
j++;
}
for(int i = r2-1 ; i > r1 ; i--){
ans[i][c1] = j;
j++;
}
}
r1++;
r2--;
c1++;
c2--;
}
return ans;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
8a4d4e2953b0f108217b12354cc27d9c34ecc0f4 | c2506bdb7d3be4a1ad4e9f4b75a8da39812c2bd3 | /Building_Biolofical_Assembly/Functions.h | 8787d28dae850736a8727f58e7c62cee8c33fb96 | [] | no_license | NoraRo/Building-Biological-Assembly | a3c9db3923146d53fe277c2264d3b8cca371442f | 58b4a923410b0b056e7c0d69370ccda940ab1881 | refs/heads/master | 2021-04-26T23:14:56.189231 | 2018-03-17T21:20:11 | 2018-03-17T21:20:11 | 123,955,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,368 | h | #pragma once
#include<vector>
#include<iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
void lgg_crystal(vector<double>& cell,
vector<double>& cells,
vector<vector<double>>& deor,
vector<vector<double>>& orth,
vector<vector<double>>& deors,
vector<vector<double>>& orths);
double determinanet(vector<vector<double>> &A, double EP);
vector<vector<double>> transpose(vector<vector<double>>& A);
double distancE(const vector<double>& v, int size);
double angle(vector<double>& v1, vector<double>& v2);
double dotproduct(vector<double>& v1, vector<double>& v2);
//This function checks if this atom is HA or not according to this paper
//Metals in protein structures: a review of their principal features by Harding 2010
//http://dx.doi.org/10.1080/0889311X.2010.485616
bool is_HA(string str);
//This function takes file handle and extracts all HAs.
// returns list of strings of HAs and writes them on a separete file
vector<string> extract_HAs(istream& in, string ha_file);
//Searching for the min and max values of X, Y and Z coordinates
vector<double> range_XYZ(istream& in, string out_f);
//Matrix multiplication
vector<double> vec_multi_matrix(vector<vector<double>> m, vector<double> vec);
vector<vector<double>> identity_vec(int size);
double** identity_i(int size);
vector<vector<double>> identity_i_vec(int size);
| [
"nora.abdelhameed@gmail.com"
] | nora.abdelhameed@gmail.com |
ce9e7ae7d0fd137ed4a8ba7756d67cd39e587c6e | 877bad5999a3eeab5d6d20b5b69a273b730c5fd8 | /TestKhoaLuan/DirectShowTVSample/Chapter-8/DVDPlayer2/DVDPlayer2.cpp | 35ebe2a3705c3d1664cf286ec2cd46f818f2c327 | [] | no_license | eaglezhao/tracnghiemweb | ebdca23cb820769303d27204156a2999b8381e03 | aaae7bb7b9393a8000d395c1d98dcfc389e3c4ed | refs/heads/master | 2021-01-10T12:26:27.694468 | 2010-10-06T01:15:35 | 2010-10-06T01:15:35 | 45,880,587 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,477 | cpp | // DVDPlayer2.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "resource.h"
#include <dshow.h>
HINSTANCE hInst;
IDvdGraphBuilder *m_pIDvdGB;
IDvdControl2 *m_pIDvdC2;
IMediaControl *m_pIMC;
IGraphBuilder* m_pGraph;
LRESULT CALLBACK CmdWnd(HWND, UINT, WPARAM, LPARAM);
void InitDVD()
{
CoInitialize (NULL);
// Create an instance of the DVD Graph Builder object.
HRESULT hr;
hr = CoCreateInstance(CLSID_DvdGraphBuilder,
NULL,
CLSCTX_INPROC_SERVER,
IID_IDvdGraphBuilder,
(void**)&m_pIDvdGB);
// Build the DVD filter graph.
AM_DVD_RENDERSTATUS buildStatus;
m_pIDvdGB->RenderDvdVideoVolume(NULL, AM_DVD_HWDEC_PREFER , &buildStatus);
m_pIDvdGB->GetDvdInterface(IID_IDvdControl2, (void**)&m_pIDvdC2);
// Get a pointer to the filter graph manager.
m_pIDvdGB->GetFiltergraph(&m_pGraph) ;
m_pGraph->QueryInterface(IID_IMediaControl, (void**)&m_pIMC);
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, NULL, (DLGPROC)CmdWnd);
return 0;
}
// Mesage handler for about box.
LRESULT CALLBACK CmdWnd(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
InitDVD ();
return TRUE;
case WM_DESTROY:
DestroyWindow (hDlg);
//EndDialog (hDlg, NULL);
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_PLAY:
m_pIMC->Run ();
break;
case IDC_STOP:
m_pIMC->Stop();
break;
case IDC_PAUSE:
m_pIMC->Pause ();
break;
case IDC_RESUME:
m_pIMC->Run ();
break;
case IDC_NEXT:
m_pIDvdC2->PlayNextChapter(DVD_CMD_FLAG_None, NULL);
break;
case IDC_PREV:
// m_pIDvdC2->PlayPreviousChapter(DVD_CMD_FLAG_None, NULL);
break;
case IDC_REWIND:
m_pIDvdC2->PlayBackwards(8.0, DVD_CMD_FLAG_None, NULL);
break;
case IDC_FF:
m_pIDvdC2->PlayForwards(8.0, DVD_CMD_FLAG_None, NULL);
break;
case IDC_ROOTMENU:
m_pIDvdC2->ShowMenu(DVD_MENU_Root, DVD_CMD_FLAG_Flush, NULL);
break;
}
break;
}
return FALSE;
}
| [
"nCoreNiceIT@gmail.com"
] | nCoreNiceIT@gmail.com |
2fcec5d2135600ea7e960048ced9f582734d595f | 77c4ca9b33e007daecfc4318537d7babea5dde84 | /tensorflow/python/lib/io/file_io_wrapper.cc | 6a5399c0db1ea8d8d3c7190b234b49b90be067d7 | [
"Apache-2.0"
] | permissive | RJ722/tensorflow | 308eede8e911e2b6a6930fef3e24a493ab9a2a61 | 6c935289da11da738f2eaed18644082f3a6938d6 | refs/heads/master | 2020-12-20T16:51:12.767583 | 2020-01-25T06:46:50 | 2020-01-25T06:51:20 | 236,138,137 | 2 | 3 | Apache-2.0 | 2020-01-25T07:12:41 | 2020-01-25T07:12:40 | null | UTF-8 | C++ | false | false | 8,796 | cc | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <string>
#include <vector>
#include "include/pybind11/pybind11.h"
#include "include/pybind11/stl.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/buffered_inputstream.h"
#include "tensorflow/core/lib/io/random_inputstream.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_statistics.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/stringpiece.h"
#include "tensorflow/core/platform/tstring.h"
#include "tensorflow/python/lib/core/pybind11_absl.h"
#include "tensorflow/python/lib/core/pybind11_status.h"
namespace {
namespace py = pybind11;
PYBIND11_MODULE(_pywrap_file_io, m) {
m.def("FileExists", [](const std::string& filename) {
tensorflow::Status status;
{
py::gil_scoped_release release;
status = tensorflow::Env::Default()->FileExists(filename);
}
tensorflow::MaybeRaiseRegisteredFromStatus(status);
});
m.def("DeleteFile", [](const std::string& filename) {
tensorflow::MaybeRaiseRegisteredFromStatus(
tensorflow::Env::Default()->DeleteFile(filename));
});
m.def("ReadFileToString", [](const std::string& filename) {
std::string data;
const auto status =
ReadFileToString(tensorflow::Env::Default(), filename, &data);
tensorflow::MaybeRaiseRegisteredFromStatus(status);
return py::bytes(data);
});
m.def("WriteStringToFile",
[](const std::string& filename, tensorflow::StringPiece data) {
return WriteStringToFile(tensorflow::Env::Default(), filename, data);
});
m.def("GetChildren", [](const std::string& dirname) {
std::vector<std::string> results;
const auto status =
tensorflow::Env::Default()->GetChildren(dirname, &results);
tensorflow::MaybeRaiseRegisteredFromStatus(status);
return results;
});
m.def("GetMatchingFiles", [](const std::string& pattern) {
std::vector<std::string> results;
const auto status =
tensorflow::Env::Default()->GetMatchingPaths(pattern, &results);
tensorflow::MaybeRaiseRegisteredFromStatus(status);
return results;
});
m.def("CreateDir", [](const std::string& dirname) {
const auto status = tensorflow::Env::Default()->CreateDir(dirname);
if (tensorflow::errors::IsAlreadyExists(status)) {
return;
}
tensorflow::MaybeRaiseRegisteredFromStatus(status);
});
m.def("RecursivelyCreateDir", [](const std::string& dirname) {
tensorflow::MaybeRaiseRegisteredFromStatus(
tensorflow::Env::Default()->RecursivelyCreateDir(dirname));
});
m.def("CopyFile",
[](const std::string& src, const std::string& target, bool overwrite) {
auto* env = tensorflow::Env::Default();
tensorflow::Status status;
if (!overwrite && env->FileExists(target).ok()) {
status = tensorflow::errors::AlreadyExists("file already exists");
} else {
status = env->CopyFile(src, target);
}
tensorflow::MaybeRaiseRegisteredFromStatus(status);
});
m.def("RenameFile",
[](const std::string& src, const std::string& target, bool overwrite) {
auto* env = tensorflow::Env::Default();
tensorflow::Status status;
if (!overwrite && env->FileExists(target).ok()) {
status = tensorflow::errors::AlreadyExists("file already exists");
} else {
status = env->RenameFile(src, target);
}
tensorflow::MaybeRaiseRegisteredFromStatus(status);
});
m.def("DeleteRecursively", [](const std::string& dirname) {
tensorflow::int64 undeleted_files;
tensorflow::int64 undeleted_dirs;
auto status = tensorflow::Env::Default()->DeleteRecursively(
dirname, &undeleted_files, &undeleted_dirs);
if (status.ok() && (undeleted_files > 0 || undeleted_dirs > 0)) {
status =
tensorflow::errors::PermissionDenied("could not fully delete dir");
}
tensorflow::MaybeRaiseRegisteredFromStatus(status);
});
m.def("IsDirectory", [](const std::string& dirname) {
const auto status = tensorflow::Env::Default()->IsDirectory(dirname);
// FAILED_PRECONDITION response means path exists but isn't a dir.
if (tensorflow::errors::IsFailedPrecondition(status)) {
return false;
}
tensorflow::MaybeRaiseRegisteredFromStatus(status);
return true;
});
py::class_<tensorflow::FileStatistics>(m, "FileStatistics")
.def_readonly("length", &tensorflow::FileStatistics::length)
.def_readonly("mtime_nsec", &tensorflow::FileStatistics::mtime_nsec)
.def_readonly("is_directory", &tensorflow::FileStatistics::is_directory);
m.def("Stat", [](const std::string& filename) {
std::unique_ptr<tensorflow::FileStatistics> self(
new tensorflow::FileStatistics);
const auto status = tensorflow::Env::Default()->Stat(filename, self.get());
tensorflow::MaybeRaiseRegisteredFromStatus(status);
return self.release();
});
using tensorflow::WritableFile;
py::class_<WritableFile>(m, "WritableFile")
.def(py::init([](const std::string& filename, const std::string& mode) {
auto* env = tensorflow::Env::Default();
std::unique_ptr<WritableFile> self;
const auto status = mode.find("a") == std::string::npos
? env->NewWritableFile(filename, &self)
: env->NewAppendableFile(filename, &self);
tensorflow::MaybeRaiseRegisteredFromStatus(status);
return self.release();
}))
.def("append",
[](WritableFile* self, tensorflow::StringPiece data) {
tensorflow::MaybeRaiseRegisteredFromStatus(self->Append(data));
})
// TODO(slebedev): Make WritableFile::Tell const and change self
// to be a reference.
.def("tell",
[](WritableFile* self) {
tensorflow::int64 pos = -1;
const auto status = self->Tell(&pos);
tensorflow::MaybeRaiseRegisteredFromStatus(status);
return pos;
})
.def("flush",
[](WritableFile* self) {
tensorflow::MaybeRaiseRegisteredFromStatus(self->Flush());
})
.def("close", [](WritableFile* self) {
tensorflow::MaybeRaiseRegisteredFromStatus(self->Close());
});
using tensorflow::io::BufferedInputStream;
py::class_<BufferedInputStream>(m, "BufferedInputStream")
.def(py::init([](const std::string& filename, size_t buffer_size) {
std::unique_ptr<tensorflow::RandomAccessFile> file;
const auto status =
tensorflow::Env::Default()->NewRandomAccessFile(filename, &file);
tensorflow::MaybeRaiseRegisteredFromStatus(status);
std::unique_ptr<tensorflow::io::RandomAccessInputStream> input_stream(
new tensorflow::io::RandomAccessInputStream(file.release(),
/*owns_file=*/true));
return new BufferedInputStream(input_stream.release(), buffer_size,
/*owns_input_stream=*/true);
}))
.def("read",
[](BufferedInputStream* self, tensorflow::int64 bytes_to_read) {
tensorflow::tstring result;
const auto status = self->ReadNBytes(bytes_to_read, &result);
if (!status.ok() && !tensorflow::errors::IsOutOfRange(status)) {
result.clear();
tensorflow::MaybeRaiseRegisteredFromStatus(status);
}
return py::bytes(result);
})
.def("readline",
[](BufferedInputStream* self) {
return py::bytes(self->ReadLineAsString());
})
.def("seek",
[](BufferedInputStream* self, tensorflow::int64 pos) {
tensorflow::MaybeRaiseRegisteredFromStatus(self->Seek(pos));
})
.def("tell", [](BufferedInputStream* self) { return self->Tell(); });
}
} // namespace
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
86fd960aa7b5eb437b773b1a98835099711e59d0 | 962460d7c1577527107edb77ccf36a4d38d58ccd | /00xxx/UVA - 481.cpp | 610a71e3374b5163041dab209921363d1e063ce9 | [] | no_license | axuy312/UVa | 60170fba534b8378021fbf3a118b7387eb426aba | 5dc657253a9fae84959378765d6e7c98b332acf6 | refs/heads/main | 2023-01-05T05:38:28.092606 | 2020-10-26T16:05:18 | 2020-10-26T16:05:18 | 307,424,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
int value,sum=0;
vector<int>tail;
vector<int>index;
vector<int>values;
cin >> value;
tail.push_back(value);
values.push_back(value);
index.push_back(0);
while (cin >> value)
{
values.push_back(value);
if (tail[0] > value)
{
tail[0] = value;
index.push_back(0);
}
else if (tail.back() < value)
{
tail.push_back(value);
index.push_back(tail.size() - 1);
}
else
{
int ci, low = 0, high = tail.size() - 1, mid;
while (high - low > 1)
{
mid = (low + high) / 2;
if (tail[mid] >= value)
{
high = mid;
}
else
{
low = mid;
}
}
tail[high] = value;
index.push_back(high);
}
/*for (int i = 0; i < tail.size(); i++)
{
cout << tail[i] << " ";
}
cout << "\n";*/
}
vector<int>res;
cout << tail.size() << "\n-\n";
for (int i = index.size() - 1,s = tail.size() - 1; i >= 0 && s >= 0; i--)
{
if (index[i] == s)
{
res.push_back(values[i]);
s--;
}
}
for (int i = res.size() - 1; i >= 0; i--)
{
cout << res[i] << "\n";
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
a8271c669d3953a7fcbd9e217d873693ad143b43 | 27881023eb624a31698751776967135565fa93bd | /CodeCarteDeFormation/_07_automaton/_07_automaton.ino | 12ed433e530d69a3fc599eae71338efba81d50ce | [] | no_license | LaurentCabaret/IncFall2013 | 90e35220ab918ba17957ab54748f5d5f78f7514f | 0d54e5877d86401a453de5f29db592a94a353ddb | refs/heads/master | 2020-05-04T14:36:33.301283 | 2014-03-10T12:31:22 | 2014-03-10T12:31:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,979 | ino | /************************************************************************
* Electronics tutorials for INC courses : 07 - Automaton *
* *
* This program demonstrates the use of an automaton to control *
* everything easily. *
* *
* Copyright : (c) 2013 Xavier Lagorce <Xavier.Lagorce@crans.org> *
************************************************************************/
// States of the control automaton
typedef enum {
state_idle,
state_set_color,
state_enter_config,
state_config_red,
state_config_blue,
state_config_green,
} control_state;
//**** Global variables used for global parameters
// Inputs :
int poten = A0; // Potentiometer
int sw = 2; // User button
// Ouputs :
int led_ind = 13; // Arduino LED
int led_blue = 9; // RGB LEDs
int led_green = 10; // "
int led_red = 11; // "
// Shared variables
boolean alive_state = false;
volatile boolean button_pressed = false; // These variables need to be volatile
volatile boolean button_released = false; // to be changed in the interrupt handle
control_state state;
int red_int = 255;
int blue_int = 255;
int green_int = 255;
// Program parameters
unsigned long control_period = 100;
unsigned long config_press_time = 2000;
unsigned long alive_period = 500;
#define DEBOUNCE_TIME 10
// Interrupts handle
void button_interrupt_handle() {
// This function is called whenever the button changes state it should be as quick as possible.
static unsigned long last_event = 0;
// Detect button pressed == falling edge on the pin
if (millis() - last_event > DEBOUNCE_TIME && digitalRead(sw) == LOW) {
button_pressed = true;
} else {
if (millis() - last_event > DEBOUNCE_TIME) {
// Detect button released == rising edge on the pin
button_released = true;
}
}
last_event = millis();
}
// This function is called one time when the arduino starts
void setup() {
// Set output pins as outputs
pinMode(led_ind, OUTPUT);
pinMode(led_blue, OUTPUT);
pinMode(led_green, OUTPUT);
pinMode(led_red, OUTPUT);
// Set default values for outputs (all LEDs OFF)
digitalWrite(led_ind, LOW);
digitalWrite(led_blue, HIGH);
digitalWrite(led_red, HIGH);
digitalWrite(led_green, HIGH);
// Attach handles to interrupt sources
attachInterrupt(0, button_interrupt_handle, CHANGE);
// Open the serial link at 115200 bps
Serial.begin(115200);
// Be polite
Serial.println("Hello, I'm waking up... and you ?");
// Set initial state
state = state_set_color;
}
// This function is called continuously when the arduino runs
void loop() {
i_m_alive_loop();
control_loop();
}
// Simple task to indicate that the code is not stuck somewhere
void i_m_alive_loop() {
// This static variable will keep its value between different calls to this function
// but like all local variables won't be accessible from the outside of this function.
static unsigned long last_time = 0;
// Get the number of milliseconds ellapsed since the start of the arduino
unsigned long cur_time = millis();
// Only do something if a sufficient amount of time has passed by
// (and don't block the program to wait if not)
if (cur_time - last_time > alive_period) {
// Things to do periodically
if (alive_state) {
digitalWrite(led_ind, HIGH);
} else {
digitalWrite(led_ind, LOW);
}
alive_state = !alive_state;
// Keep track of the last time the task was executed
last_time = cur_time;
}
}
// Main task
void control_loop() {
// This static variable will keep its value between different calls to this function
// but like all local variables won't be accessible from the outside of this function.
static unsigned long last_time = 0;
// Get the number of milliseconds ellapsed since the start of the arduino
unsigned long cur_time = millis();
// To keep track of timings
static unsigned long btn_pressed_at;
// Only do something if a sufficient amount of time has passed by
// (and don't block the program to wait if not)
if (cur_time - last_time > control_period) {
switch(state) {
case state_idle:
// If the button is pressed, keep note of the current
// time and wait for the release
if (button_pressed) {
state = state_enter_config;
button_pressed = false;
button_released = false;
btn_pressed_at = cur_time;
} else {
// Ack a previous release
if (button_released) {
button_released = false;
}
}
break;
case state_set_color:
// Set correct LED color and go to idle state
analogWrite(led_red, red_int);
analogWrite(led_blue, blue_int);
analogWrite(led_green, green_int);
state = state_idle;
break;
case state_enter_config:
// Go to config mode if the button stayed pressed for long enough
if (cur_time - btn_pressed_at >= config_press_time) {
// Stop every LED before going to config mode
analogWrite(led_red, 255);
analogWrite(led_blue, 255);
analogWrite(led_green, 255);
state = state_config_red;
alive_period = 100;
} else {
if (button_released) {
state = state_idle;
button_released = false;
}
}
break;
case state_config_red:
// Set the red intensity according to the potentiometer
red_int = 255-((long)analogRead(poten))*255/710;
analogWrite(led_red, red_int);
// Go to next config if the button is pressed
if (button_pressed) {
button_pressed = false;
analogWrite(led_red, 255);
state = state_config_blue;
}
break;
case state_config_blue:
// Set the blue intensity according to the potentiometer
blue_int = 255-((long)analogRead(poten))*255/710;
analogWrite(led_blue, blue_int);
// Go to next config if the button is pressed
if (button_pressed) {
button_pressed = false;
analogWrite(led_blue, 255);
state = state_config_green;
}
break;
case state_config_green:
// Set the green intensity according to the potentiometer
green_int = 255-((long)analogRead(poten))*255/710;
analogWrite(led_green, green_int);
// Exit config mode if button is pressed
if (button_pressed) {
button_pressed = false;
analogWrite(led_green, 255);
state = state_set_color;
alive_period = 500;
}
break;
default:
state = state_set_color;
break;
}
last_time = cur_time;
}
}
| [
"Xavier.Lagorce@crans.org"
] | Xavier.Lagorce@crans.org |
24bdaed1ac07ce4675f782044f0fa43ea5fba254 | e9c56da7a05a6fdeed9b1282eed20577e64c9df6 | /src/models/acoustics/acoustics.hpp | 6b0c262599665ddb9ba2b6be8e7b44636cbaaf0c | [] | no_license | pezzus/conslaw2d | 940a0a4c6bb8eedcf851fb8faedab622d13aac89 | be3b022bb9c18fc9e1be525757255645e3976dc6 | refs/heads/master | 2020-11-27T19:06:54.174668 | 2019-12-22T15:06:33 | 2019-12-22T15:06:33 | 229,571,822 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,908 | hpp | #ifndef ACOUSTICS_HPP
#define ACOUSTICS_HPP
// Modello equazioni Acustica
#include <cstddef>
// Libreria EIGEN per l'Algebra
#include <Eigen/Core>
#include <cmath>
// Dimensione dello spazio di stato
// [p, u, v]
#define DIMENSION 3
namespace ConservationLaw2D {
namespace Model {
/*! \class LinearAcoustics
\brief Modello per le equazioni dell'acustica lineari */
template <typename T>
class LinearAcoustics {
public:
// Defininzioni vettori
// Vettore per la soluzione
/*! \brief Tipo di dato reale, per esempio \c float o \c double */
typedef T real_t;
/*! \brief Tipo per i vettori contenenti la soluzione */
typedef Eigen::Matrix<T, DIMENSION, 1> SolType;
/*! \brief Tipo per le matrici contenenti il flusso \f$ m \times 2 \f$ */
typedef Eigen::Matrix<T, DIMENSION, 2> FluxType;
/*! \brief Costruttore del modello
\param[in] rho0 Densità del gas nello stato non perturbato
\param[in] K0 Modulo di elasticità lineare */
LinearAcoustics( real_t rho0, real_t K0 )
:rho0_(rho0), K0_(K0), c0_(sqrt(K0_/rho0_)), Z0_(c0_*rho0_) {}
// Accesso ai dati
/*! \brief Restituisce l'impedenza del mezzo \f$ Z_0 \f$ */
real_t Z(void) { return Z0_; }
/*! \brief Restituisce la velocità del suono nel mezzo \f$ c_0 \f$ */
real_t C(void) { return c0_; }
// Flusso in direzione normale
/*! \brief Restituisce il flusso esatto */
inline FluxType Flux( const SolType& q ) const {
FluxType Flux = FluxType::Zero();
// F(q)
Flux(0,0) = K0_ * q[1];
Flux(1,0) = q[0]/rho0_;
Flux(2,0) = 0.0;
// G(q)
Flux(0,1) = K0_ * q[2];
Flux(1,1) = 0.0;
Flux(2,1) = q[0]/rho0_;
return Flux;
}
// Variabili primitive <-> Variabili conservate
/*! \brief Restituisce la soluzione nelle variabili conservate \f$ (p,u,v) \f$ */
inline SolType PrimitiveToConservative( const SolType& w ) const {
return w;
}
/*! \brief Restituisce la soluzione nelle variabili primitive \f$ (p,u,v) \f$ */
inline SolType ConservativeToPrimitive( const SolType& q ) const {
return q;
}
// Controlla se lo stato e' consistente
/*! \brief Controlla se lo stato è consistente */
inline bool ConsistentState( const SolType& q ) const {
// Pressione positiva?
return true;
}
// Massimo autovalore
/*! \brief Restituisce il massimo autovalore */
inline real_t MaxLambda( const SolType& q ) {
return c0_;
}
// Autovalori
/*! \brief Restituisce gli autovalori del flusso esatto */
inline SolType EigenValues( const SolType& q, const real_t nx, const real_t ny ) const {
SolType Eig = SolType::Zero();
Eig[0] = - c0_;
Eig[1] = 0.0;
Eig[2] = + c0_;
return Eig;
}
private:
real_t rho0_, K0_, c0_, Z0_;
};
}
}
#endif
| [
"simone@pezzu.it"
] | simone@pezzu.it |
bdadbd7629158f022e3ece7187be7379cd701eff | ae7509586f6c1c4e3353d4db41f521d43e4d76ef | /mowei_msgs/include/setLinearActuatorLockResponse.h | 3e95dfadc14ac83de9a966a823562d39ab5fa77c | [] | no_license | lg609/mowei_agv | a99de47dd5eef4d21d7745b0a6c17dd568ebe269 | d38c930c66e769fa874bc67b458b1d1abf8b2c59 | refs/heads/master | 2020-03-22T05:37:23.276890 | 2018-07-03T12:18:49 | 2018-07-03T12:18:49 | 139,579,350 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,410 | h | // Generated by gencpp from file mowei_msgs/setLinearActuatorLockResponse.msg
// DO NOT EDIT!
#ifndef MOWEI_MSGS_MESSAGE_SETLINEARACTUATORLOCKRESPONSE_H
#define MOWEI_MSGS_MESSAGE_SETLINEARACTUATORLOCKRESPONSE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace mowei_msgs
{
template <class ContainerAllocator>
struct setLinearActuatorLockResponse_
{
typedef setLinearActuatorLockResponse_<ContainerAllocator> Type;
setLinearActuatorLockResponse_()
: success(0) {
}
setLinearActuatorLockResponse_(const ContainerAllocator& _alloc)
: success(0) {
(void)_alloc;
}
typedef int8_t _success_type;
_success_type success;
typedef boost::shared_ptr< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> const> ConstPtr;
}; // struct setLinearActuatorLockResponse_
typedef ::mowei_msgs::setLinearActuatorLockResponse_<std::allocator<void> > setLinearActuatorLockResponse;
typedef boost::shared_ptr< ::mowei_msgs::setLinearActuatorLockResponse > setLinearActuatorLockResponsePtr;
typedef boost::shared_ptr< ::mowei_msgs::setLinearActuatorLockResponse const> setLinearActuatorLockResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace mowei_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
{
static const char* value()
{
return "0b13460cb14006d3852674b4c614f25f";
}
static const char* value(const ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x0b13460cb14006d3ULL;
static const uint64_t static_value2 = 0x852674b4c614f25fULL;
};
template<class ContainerAllocator>
struct DataType< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
{
static const char* value()
{
return "mowei_msgs/setLinearActuatorLockResponse";
}
static const char* value(const ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
{
static const char* value()
{
return "int8 success\n\
\n\
";
}
static const char* value(const ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.success);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct setLinearActuatorLockResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::mowei_msgs::setLinearActuatorLockResponse_<ContainerAllocator>& v)
{
s << indent << "success: ";
Printer<int8_t>::stream(s, indent + " ", v.success);
}
};
} // namespace message_operations
} // namespace ros
#endif // MOWEI_MSGS_MESSAGE_SETLINEARACTUATORLOCKRESPONSE_H
| [
"407939195@qq.com"
] | 407939195@qq.com |
a53ba4cb49bd0ca1c4a37aaa91d6178c7f04ac08 | 00948a19e63549ddfdea1f6e5ac55ffcfeb7c1b3 | /apps/bidirectional/NonlinearWeightedAStar.h | 6de340023c0987a1d4e406af71e6a971b1db2bb4 | [
"MIT"
] | permissive | Voleco/bdexplain | 6aa310cc9f4c11025d967e4c89aa9673053a708c | 5e610155ad4cc0e9024d73497a8c88e33801e833 | refs/heads/master | 2021-07-04T09:06:10.217994 | 2019-04-04T13:04:53 | 2019-04-04T13:04:53 | 147,047,793 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,721 | h |
#ifndef NonlinearWeightedAStar_h
#define NonlinearWeightedAStar_h
#include "AStarOpenClosed.h"
#include <cmath>
const double n_weight = 1.5;
const double n_PI = 3.1415927;
const double additive_bound_K = 10;
template <class state>
struct PureHCompare {
//f = h
bool operator()(const AStarOpenClosedData<state> &i1, const AStarOpenClosedData<state> &i2) const
{
double f1, f2;
f1 = i1.h ;
f2 = i2.h;
if (fequal(f1, f2))
{
return (fless(i1.g, i2.g));
}
return (fgreater(f1, f2));
}
};
inline double quadraticEquationRoot(double a, double b, double c)
{
double delta = b*b - 4*a*c;
double x = (-b + sqrt(delta)) / (2 * a);
return x;
}
inline double cubicEquationRoot(double a, double b, double c, double d)
{
double P = 36 * a*b*c - 8 * b*b*b - 108 * a*a*d;
double Q = 12 * a*c - 4 * b*b;
double delta = P*P + Q*Q*Q;
double x = (-2 * b + cbrt(P + sqrt(delta)) + cbrt(P - sqrt(delta))) / (6 * a);
return x;
}
//curve below y + wx above y + x
template <class state>
struct QuadraticCompare1 {
//f = g + (2w-1)h + sqrt(g^2 + h^2 -2gh + 4wgh)
bool operator()(const AStarOpenClosedData<state> &i1, const AStarOpenClosedData<state> &i2) const
{
double f1, f2;
f1 = i1.g + (2 * n_weight - 1)*i1.h + sqrt(i1.g*i1.g + i1.h*i1.h - 2 * i1.g*i1.h + 4 * n_weight*i1.g*i1.h);
f2 = i2.g + (2 * n_weight - 1)*i2.h + sqrt(i2.g*i2.g + i2.h*i2.h - 2 * i2.g*i2.h + 4 * n_weight*i2.g*i2.h);
if (fequal(f1, f2))
{
return (fless(i1.g, i2.g));
}
return (fgreater(f1, f2));
}
};
//curve above y + wx below y + x
template <class state>
struct QuadraticCompare2 {
//f = g + h + sqrt(g^2 + h^2 + 2gh + 4w(w-1)h^2)
bool operator()(const AStarOpenClosedData<state> &i1, const AStarOpenClosedData<state> &i2) const
{
double f1, f2;
f1 = i1.g + i1.h + sqrt(i1.g*i1.g + i1.h*i1.h + 2 * i1.g*i1.h + 4 * n_weight*(n_weight - 1)*i1.h*i1.h);
f2 = i2.g + i2.h + sqrt(i2.g*i2.g + i2.h*i2.h + 2 * i2.g*i2.h + 4 * n_weight*(n_weight - 1)*i2.h*i2.h);
if (fequal(f1, f2))
{
return (fless(i1.g, i2.g));
}
return (fgreater(f1, f2));
}
};
template <class state>
struct RickCompare {
//f = g + h if h==0
//f = g + h + K otherwise
bool operator()(const AStarOpenClosedData<state> &i1, const AStarOpenClosedData<state> &i2) const
{
double f1, f2;
if (i1.h == 0)
f1 = i1.g;
else
f1 = i1.g + i1.h + additive_bound_K;
if (i2.h == 0)
f2 = i2.g;
else
f2 = i2.g + i2.h + additive_bound_K;
if (fequal(f1, f2))
{
return (fless(i1.g, i2.g));
}
return (fgreater(f1, f2));
}
};
template <class state>
struct RickCompare2 {
//h_i : h of start
//f = g + h + K*min(h , h_i) / h_i
//RickCompare2(hi):h_i(hi){ printf("h_i: %d\n", h_i); }
bool operator()(const AStarOpenClosedData<state> &i1, const AStarOpenClosedData<state> &i2) const
{
double f1, f2;
double minh1, minh2;
if (i1.h < h_i)
minh1 = i1.h;
else
minh1 = h_i;
if (i2.h < h_i)
minh2 = i2.h;
else
minh2 = h_i;
f1 = i1.g + i1.h + additive_bound_K *minh1/h_i;
f2 = i2.g + i2.h + additive_bound_K*minh2/h_i;
if (fequal(f1, f2))
{
return (fless(i1.g, i2.g));
}
return (fgreater(f1, f2));
}
double h_i;
};
template <class state>
struct LinearCompare {
//f = g + h -K + sqrt( (g+h-K)^2 + 4hK)
bool operator()(const AStarOpenClosedData<state> &i1, const AStarOpenClosedData<state> &i2) const
{
double f1, f2;
double b1 = i1.g + i1.h - additive_bound_K;
double b2 = i2.g + i2.h - additive_bound_K;
f1 = b1+ sqrt(b1*b1 + 4 * i1.h*additive_bound_K);
f2 = b2 + sqrt(b2*b2 + 4 * i2.h*additive_bound_K);
if (fequal(f1, f2))
{
return (fless(i1.g, i2.g));
}
return (fgreater(f1, f2));
}
};
#endif /* NonlinearWeightedAStar_h */
| [
"chenjingwei1991@gmail.com"
] | chenjingwei1991@gmail.com |
140a64a45e8884cf1b8f67f4f7f201c438c3d496 | 07a60d7281d7256250a290e3f5eb0aa89c742f1d | /8.08/8.08/8.08.cpp | 685db6c53d4c75ecf35a574478b8e0d3d79660f4 | [] | no_license | Ahmed12-sys/Deitel-C--How-to-Program--Nineth-Edition | cd6450a6ee1fc15e0748773ff0835acbe9ce8771 | 26e47ad612f47a9ad265525294500bed95e3ffd0 | refs/heads/master | 2020-07-26T02:41:04.552571 | 2019-09-15T20:41:28 | 2019-09-15T20:41:28 | 208,506,550 | 0 | 0 | null | null | null | null | WINDOWS-1258 | C++ | false | false | 1,858 | cpp | // 8.08.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#define SIZE 5
int main()
{ //a
unsigned int values[SIZE] = { 2 ,4,6,8,10 };
//b
unsigned int* vPtr;
//c
for (int i = 0; i < SIZE; i++) {
std::cout << values[i];
}
//d
vPtr = values;//vptr=&(values[0])
//e Use a for statement to display the elements of built-in array values using pointer/offset
//notation.
for (int i = 0; i < SIZE; i++) {
std::cout << *(vPtr+i);
}
//f use a for statement to display the elements of built-in array values using pointer/offset
//notation with the built - in array’s name as the pointer.
for (int i = 0; i < SIZE; i++) {
std::cout << *(values + i);
}
//g Use a for statement to display the elements of built-in array values by subscripting the
/*pointer to the built - in array.*/
for (int i = 0; i < SIZE; i++) {
std::cout << vPtr[i];
}
//h Refer to the fifth element of values:
//array subscript notation
//values[4];
//pointer/offset notation with the built-in array name’s as the pointer
//*(values+4);
//pointer subscript notation
//vPtr[3];
// pointer / offset notation.
//*(vPtr + 4);
std::cout << "Hello World!\n";
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| [
"mkforeinger@yandex.com"
] | mkforeinger@yandex.com |
3edb6d12d2e9b5dba7a57300b12bf8644edfcbb2 | 4aa2780eafd965b50d62cbeab7b8e1ce040aa309 | /Programs/Consecutive Subsequence.cpp | 55a178eabba121430fa54ce16acf97d3f1704f5e | [] | no_license | ayush5148/Coding-break-outs | 05c2aa2a8187eb588c809b7543a5deb97431e625 | 52e1daedb55b39c6a212d70ca357fd46e1704890 | refs/heads/master | 2021-04-14T00:11:59.705831 | 2020-03-22T17:50:25 | 2020-03-22T17:50:25 | 249,197,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,059 | cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
typedef pair<int , int> pp;
#define X first
#define Y second
typedef long long int ll;
#define debug(x) cout<<#x<<" :: "<<x<<"\n";
#define debug2(x,y) cout<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\n";
#define debug3(x,y,z) cout<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\t"<<#z<<" :: "<<z<<"\n";
#define fastIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
const int N = 1e6+1;
ll a[N], dp[N];
vector<int> v[N];
map <ll,ll> mapp;
int main() {
fastIO;
ll n,mmax = -1, idx = 1 ;
cin>>n;
for (int i=1; i<=n; i++){
cin>>a[i];
}
for (int i=1; i<=n; i++) {
dp[i] = mapp[a[i]-1]+1;
mapp[a[i]] = max (mapp[a[i]], dp[i]);
if (dp[i] > mmax)
idx= i;
mmax = max (mmax, dp[i]);
}
cout << mmax << endl;
int ele = a[idx] - mmax +1;
// debug(ele);
for (int i=1; i<=n; i++) {
if (a[i] == ele) {
cout << i<<" ";
ele++;
}
}
}
| [
"aygarg@amazon.com"
] | aygarg@amazon.com |
5c2051fac2a105a71b3b25703190fb5d8fb509e2 | 0a70cf01bf16fc0cd1a696e08f657739eb4fd87c | /cf/368D2/e.cpp | 7bf590c8dea67003ec5bd4bf10d06a6d188eec85 | [] | no_license | erjiaqing/my_solutions | ca63b664cb6f7ecb7d756a70666fdf3be6dc06b3 | 87bf90af4aca2853f30a7c341fe747d499728ba3 | refs/heads/master | 2022-09-05T17:45:19.902071 | 2022-08-13T02:18:30 | 2022-08-13T02:18:30 | 20,209,446 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 2,548 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
const int maxq = 2000 + 5, maxop = 1000000 + 5;
struct op{
int o, x1;
}oper[maxop];
long long colorsum[maxq][maxq];
long long bit[maxq];
int state[maxq];
vector<pair<pii, int> > query;
vector<pair<pii, int> > chain[maxq];
inline int lb(int x) {return x & -x;}
long long get(int x)
{
long long ret = 0;
for (; x; x -= lb(x)) ret += bit[x];
return ret;
}
void upd(int x, int v) {for (; x < maxq; x += lb(x)) bit[x] += v;}
int main()
{
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= k; i++)
{
int len;
scanf("%d", &len);
for (int j = 0; j < len; j++)
{
int x, y, w;
scanf("%d%d%d", &x, &y, &w);
chain[i].push_back(make_pair(pii(x, y), w));
}
sort(chain[i].begin(), chain[i].end());
}
int q;
char operat[15];
scanf("%d", &q);
int qid = 0;
for (int i = 0; i < q; i++)
{
scanf("%s", operat);
if (operat[0] == 'A')
{
oper[i].o = 0;
oper[i].x1 = ++qid;
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
query.push_back(make_pair(pii(x2, y2), qid));
query.push_back(make_pair(pii(x1 - 1, y1 - 1), qid));
query.push_back(make_pair(pii(x2, y1 - 1), -qid));
query.push_back(make_pair(pii(x1 - 1, y2), -qid));
} else
{
oper[i].o = 1;
scanf("%d", &oper[i].x1);
}
}
sort(query.begin(), query.end());
int qrys = query.size();
for (int i = 1; i <= k; i++)
{
int qh1 = 0, qh2 = 0;
int len = chain[i].size();
memset(bit, 0, sizeof bit);
// cerr << "COLOR " << i << endl;
while (qh1 < len || qh2 < qrys)
{
if (qh2 == qrys) break;
if (qh1 < len && chain[i][qh1].first.first <= query[qh2].first.first)
{
// fprintf(stderr, "POS (%d,%d) WEIGHT %d\n", chain[i][qh1].first.first, chain[i][qh1].first.second, chain[i][qh1].second);
upd(chain[i][qh1].first.second, chain[i][qh1].second);
qh1++;
} else
{
long long res = get(query[qh2].first.second);
int pos = abs(query[qh2].second);
int sgn = (pos == query[qh2].second ? 1 : -1);
// fprintf(stderr, "QRY (%d,%d) sgn %c res %lld qry %d\n", query[qh2].first.first, query[qh2].first.second, sgn == 1 ? '+' : '-', res, pos);
colorsum[pos][i] += sgn * res;
qh2++;
}
}
}
for (int i = 0; i < q; i++)
{
if (oper[i].o == 0)
{
long long ans = 0;
int qry = oper[i].x1;
// cerr << "QID = " << qry << endl;
for (int j = 1; j <= k; j++)
if (!state[j])
ans += colorsum[qry][j];
printf("%lld\n", ans);
} else
state[oper[i].x1] ^= 1;
}
return 0;
}
| [
"gs199704@gmail.com"
] | gs199704@gmail.com |
b246d831711592193367cdcffd15a25d678d09e2 | 887691d6f226d58253dd9d235339e354734199e5 | /fluidic-control-board/arduino-auto-alternate/fluidic_control_alternate.ino | 7d68418e2f8b43b81900d87b238f304818d97b24 | [] | no_license | mLabOSU/soft-snake-locomotion | 9ee22aefe30444285068dc5d08f158f330a87ed5 | 3c4d44ae72cc91d42dd1ae0bbee40fc2802d93d0 | refs/heads/master | 2020-06-10T19:53:12.329307 | 2017-09-01T17:40:02 | 2017-09-01T17:40:02 | 75,891,819 | 0 | 1 | null | 2017-08-11T22:51:50 | 2016-12-08T01:41:48 | Python | UTF-8 | C++ | false | false | 3,036 | ino | int prescaler = 256; // set this to match whatever prescaler value you set in CS registers below
// intialize values for the PWM duty cycle set by pots
float potDC1 = 0;
float potDC2 = 0;
float potDC3 = 0;
float potDC4 = 0;
void setup() {
Serial.begin(9600);
// input pins for valve switches
pinMode(50, INPUT);
pinMode(51, INPUT);
pinMode(52, INPUT);
pinMode(53, INPUT);
// output pins for valve PWM
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
int eightOnes = 255; // this is 11111111 in binary
TCCR3A &= ~eightOnes; // this operation (AND plus NOT), set the eight bits in TCCR registers to 0
TCCR3B &= ~eightOnes;
TCCR4A &= ~eightOnes;
TCCR4B &= ~eightOnes;
// set waveform generation to frequency and phase correct, non-inverting PWM output
TCCR3A = _BV(COM3A1);
TCCR3B = _BV(WGM33) | _BV(CS32);
TCCR4A = _BV(COM4A1) | _BV(COM4B1) | _BV(COM4C1);
TCCR4B = _BV(WGM43) | _BV(CS42);
}
void pPWM(float pwmfreq, float pwmDC1, float pwmDC2, float pwmDC3, float pwmDC4) {
// set PWM frequency by adjusting ICR (top of triangle waveform)
ICR3 = F_CPU / (prescaler * pwmfreq * 2);
ICR4 = F_CPU / (prescaler * pwmfreq * 2);
// set duty cycles
OCR3A = (ICR4) * (pwmDC1 * 0.01);
OCR4A = 0;
OCR4B = (ICR4) * (pwmDC3 * 0.01);
OCR4C = 0;
delay(2000);
OCR3A = 0;
OCR4A = (ICR4) * (pwmDC2 * 0.01);
OCR4B = 0;
OCR4C = (ICR4) * (pwmDC4 * 0.01);
delay(2000);
}
void loop() {
potDC1 = 0; potDC2 = 0; potDC3 = 0; potDC4 = 0;
// if statement for manual switch override
if (digitalRead(50) == LOW) {
potDC1 = analogRead(A1)*100.0/1024.0; // scale values from pot to 0 to 100, which gets used for duty cycle percentage
}
if (digitalRead(51) == LOW) { potDC2 = analogRead(A2)*100.0/1024.0; }
if (digitalRead(52) == LOW) { potDC3 = analogRead(A3)*100.0/1024.0; }
if (digitalRead(53) == LOW) { potDC4 = analogRead(A4)*100.0/1024.0; }
float potPWMfq = analogRead(A7)*100.0/1024.0; // scale values from pot to 0 to 100, which gets used for frequency (Hz)
potPWMfq = round(potPWMfq/5)*5+1; //1 to 91 Hz in increments of 5 (rounding helps to deal with noisy pot)
// update PWM output based on the above values from pots
pPWM(potPWMfq,potDC1,potDC2,potDC3,potDC4);
// transfer function for sensor Honeywell ASDXRRX100PGAA5 (100 psi, 5V, A-calibration)
// Vout = 0.8*Vsupply/(Pmax - Pmin)*(Papplied - Pmin) + 0.1*Vsupply
// Rearrange to get: Papplied = (Vout/Vsupply - 0.1)*(Pmax - Pmin)/0.8 + Pmin;
// read output voltages from sensors and convert to pressure reading in PSI
float P1 = (analogRead(A8)/1024.0 - 0.1)*100.0/0.8;
float P2 = (analogRead(A9)/1024.0 - 0.1)*100.0/0.8;
float P3 = (analogRead(A10)/1024.0 - 0.1)*100.0/0.8;
float P4 = (analogRead(A11)/1024.0 - 0.1)*100.0/0.8;
// print pressure readings
Serial.print(P1); Serial.print("\t");
Serial.print(P2); Serial.print("\t");
Serial.print(P3); Serial.print("\t");
Serial.print(P4); Serial.print("\n");
delay(200);
}
| [
"crpatte2@asu.edu"
] | crpatte2@asu.edu |
35a18ee3b898b1503346a07581bfbeedfd09a591 | abe6619c046259cb3710c96e8de9e0e37b2d8938 | /src/gameEngine/actor/items/weapon.cpp | 7d52d75a95a1c7c668aa163b502cb53750f13223 | [] | no_license | dabaldassi/castor | c67673420af03de2bfa2ef6ae701ce8396d0a888 | 6631ed93dfb78e30b17e40496e8cdc7829530c96 | refs/heads/master | 2020-03-29T12:03:49.466428 | 2019-11-03T01:17:29 | 2019-11-03T01:17:29 | 149,883,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | cpp | #include "weapon.h"
using actor::Weapon;
void Weapon::effect(actor::Actor *actor)
{
if(_effectfct2.size() != 0) Actor::effect(actor);
else actor->takeDamage(_damage);
}
void Weapon::effect()
{
if(_effectfct.size() != 0) Actor::effect();
}
void Weapon::set(float damage, float distance)
{
_damage = damage;
_distance = distance;
}
| [
"david.baldassin@etu.uca.fr"
] | david.baldassin@etu.uca.fr |
e1de6ac47bc9d062a9872fefbfd33886f393fbca | 3e3159d400b9456f96de0d1cba5c64a34ff8279d | /Classes/Level1Scene.h | bec9349ed9d5cb29ea8e343c577920f3060bcb44 | [] | no_license | Shaneohayda/Trench-Defence | a6a0719baee41c59ac2224a43c317f5702cf2c13 | 50f834343f7a254d8285a60afa49b3df0948868a | refs/heads/master | 2020-04-03T17:56:24.766294 | 2016-03-05T14:42:16 | 2016-03-05T14:42:16 | 51,311,592 | 0 | 0 | null | 2016-02-08T16:58:01 | 2016-02-08T16:58:01 | null | UTF-8 | C++ | false | false | 1,498 | h | #ifndef __LEVEL1_SCENE_H__
#define __LEVEL1_SCENE_H__
#include "cocos2d.h"
#include "Creep.h"
#include "WayPoint.h"
#include "Wave.h"
#include "GameHUD.h"
using namespace cocos2d;
class Level1 : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
~Level1();
virtual bool init();
// Important Variables
int currentLevel;
void addWayPoint();
void addWaves();
void FollowPath(Node *sender);
void gameLogic(float dt);
void addTarget();
virtual void update(float dt);
Wave* getCurrentWave();
Wave* getNextWave();
int count = 0;
// implement the "static create()" method manually
CREATE_FUNC(Level1);
void menuCloseCallback(cocos2d::Ref* pSender);
void setViewPointCenter(cocos2d::Point position);
// Tower
void addTower(Point pos, std::string towerType);
Point tileCoordForPosition(Point position);
bool canBuildOnTilePosition(Point pos);
Point boundLayerPos(Point newPos);
int getCount() { return count; };
void setCount(int c) { count = c; };
int getSCount() { return count; };
void setSCount(int s) { count = s; };
Point position;
GameHUD *gameHUD;
// void onEnter();
// void onExit();
private:
TMXTiledMap *_tileMap;
TMXLayer *_background;
TMXLayer *_Sources;
TMXLayer *_Quicksand;
TMXLayer *_walls;
TMXLayer *_turrets;
TMXLayer *_buildable;
Sprite *_enemyUnit1;
cocos2d::Label *scoreLabel;
GameHUD *_hud;
int _numCollected = 5;
int _scCollected = 0;
};
#endif | [
"shaneohayda@gmail.com"
] | shaneohayda@gmail.com |
23c0f9fb345a0ecb2f39b5cc388ffae519ae6dc7 | dfc32d0eacc2e9ff7e5e517fc6d569438efba25d | /src/fpsgame/server.cpp | 1f01bc4ca52545b06f11ecd7549670facfead133 | [
"BSD-3-Clause",
"Zlib",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lheckemann/sdos-test | 9f85105f60d7d537a511b4177ec883bc9d9a430d | d2bc0888d00e4263c851bf960476919ced7768bc | refs/heads/master | 2021-01-15T23:07:00.733192 | 2014-06-17T16:27:30 | 2014-06-17T16:27:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120,570 | cpp | #include "game.h"
namespace game
{
void parseoptions(vector<const char *> &args)
{
loopv(args)
#ifndef STANDALONE
if(!game::clientoption(args[i]))
#endif
if(!server::serveroption(args[i]))
conoutf(CON_ERROR, "unknown command-line option: %s", args[i]);
}
const char *gameident() { return "fps"; }
}
extern ENetAddress masteraddress;
namespace server
{
struct server_entity // server side version of "entity" type
{
int type;
int spawntime;
char spawned;
};
static const int DEATHMILLIS = 300;
struct clientinfo;
struct gameevent
{
virtual ~gameevent() {}
virtual bool flush(clientinfo *ci, int fmillis);
virtual void process(clientinfo *ci) {}
virtual bool keepable() const { return false; }
};
struct timedevent : gameevent
{
int millis;
bool flush(clientinfo *ci, int fmillis);
};
struct hitinfo
{
int target;
int lifesequence;
int rays;
float dist;
vec dir;
};
struct shotevent : timedevent
{
int id, gun;
vec from, to;
vector<hitinfo> hits;
void process(clientinfo *ci);
};
struct explodeevent : timedevent
{
int id, gun;
vector<hitinfo> hits;
bool keepable() const { return true; }
void process(clientinfo *ci);
};
struct suicideevent : gameevent
{
void process(clientinfo *ci);
};
struct pickupevent : gameevent
{
int ent;
void process(clientinfo *ci);
};
template <int N>
struct projectilestate
{
int projs[N];
int numprojs;
projectilestate() : numprojs(0) {}
void reset() { numprojs = 0; }
void add(int val)
{
if(numprojs>=N) numprojs = 0;
projs[numprojs++] = val;
}
bool remove(int val)
{
loopi(numprojs) if(projs[i]==val)
{
projs[i] = projs[--numprojs];
return true;
}
return false;
}
};
struct gamestate : fpsstate
{
vec o;
int state, editstate;
int lastdeath, deadflush, lastspawn, lifesequence;
int lastshot;
projectilestate<8> rockets, grenades;
int frags, flags, deaths, teamkills, shotdamage, damage, tokens;
int lasttimeplayed, timeplayed;
float effectiveness;
gamestate() : state(CS_DEAD), editstate(CS_DEAD), lifesequence(0) {}
bool isalive(int gamemillis)
{
return state==CS_ALIVE || (state==CS_DEAD && gamemillis - lastdeath <= DEATHMILLIS);
}
bool waitexpired(int gamemillis)
{
return gamemillis - lastshot >= gunwait;
}
void reset()
{
if(state!=CS_SPECTATOR) state = editstate = CS_DEAD;
maxhealth = 100;
rockets.reset();
grenades.reset();
timeplayed = 0;
effectiveness = 0;
frags = flags = deaths = teamkills = shotdamage = damage = tokens = 0;
lastdeath = 0;
respawn();
}
void respawn()
{
fpsstate::respawn();
o = vec(-1e10f, -1e10f, -1e10f);
deadflush = 0;
lastspawn = -1;
lastshot = 0;
tokens = 0;
}
void reassign()
{
respawn();
rockets.reset();
grenades.reset();
}
};
struct savedscore
{
uint ip;
string name;
int maxhealth, frags, flags, deaths, teamkills, shotdamage, damage;
int timeplayed;
float effectiveness;
void save(gamestate &gs)
{
maxhealth = gs.maxhealth;
frags = gs.frags;
flags = gs.flags;
deaths = gs.deaths;
teamkills = gs.teamkills;
shotdamage = gs.shotdamage;
damage = gs.damage;
timeplayed = gs.timeplayed;
effectiveness = gs.effectiveness;
}
void restore(gamestate &gs)
{
if(gs.health==gs.maxhealth) gs.health = maxhealth;
gs.maxhealth = maxhealth;
gs.frags = frags;
gs.flags = flags;
gs.deaths = deaths;
gs.teamkills = teamkills;
gs.shotdamage = shotdamage;
gs.damage = damage;
gs.timeplayed = timeplayed;
gs.effectiveness = effectiveness;
}
};
extern int gamemillis, nextexceeded;
struct clientinfo
{
int clientnum, ownernum, connectmillis, sessionid, overflow;
string name, team, mapvote;
int playermodel;
int modevote;
int privilege;
bool connected, local, timesync;
int gameoffset, lastevent, pushed, exceeded;
gamestate state;
vector<gameevent *> events;
vector<uchar> position, messages;
uchar *wsdata;
int wslen;
vector<clientinfo *> bots;
int ping, aireinit;
string clientmap;
int mapcrc;
bool warned, gameclip;
ENetPacket *getdemo, *getmap, *clipboard;
int lastclipboard, needclipboard;
int connectauth;
uint authreq;
string authname, authdesc;
void *authchallenge;
int authkickvictim;
char *authkickreason;
clientinfo() : getdemo(NULL), getmap(NULL), clipboard(NULL), authchallenge(NULL), authkickreason(NULL) { reset(); }
~clientinfo() { events.deletecontents(); cleanclipboard(); cleanauth(); }
void addevent(gameevent *e)
{
if(state.state==CS_SPECTATOR || events.length()>100) delete e;
else events.add(e);
}
enum
{
PUSHMILLIS = 3000
};
int calcpushrange()
{
ENetPeer *peer = getclientpeer(ownernum);
return PUSHMILLIS + (peer ? peer->roundTripTime + peer->roundTripTimeVariance : ENET_PEER_DEFAULT_ROUND_TRIP_TIME);
}
bool checkpushed(int millis, int range)
{
return millis >= pushed - range && millis <= pushed + range;
}
void scheduleexceeded()
{
if(state.state!=CS_ALIVE || !exceeded) return;
int range = calcpushrange();
if(!nextexceeded || exceeded + range < nextexceeded) nextexceeded = exceeded + range;
}
void setexceeded()
{
if(state.state==CS_ALIVE && !exceeded && !checkpushed(gamemillis, calcpushrange())) exceeded = gamemillis;
scheduleexceeded();
}
void setpushed()
{
pushed = max(pushed, gamemillis);
if(exceeded && checkpushed(exceeded, calcpushrange())) exceeded = 0;
}
bool checkexceeded()
{
return state.state==CS_ALIVE && exceeded && gamemillis > exceeded + calcpushrange();
}
void mapchange()
{
mapvote[0] = 0;
modevote = INT_MAX;
state.reset();
events.deletecontents();
overflow = 0;
timesync = false;
lastevent = 0;
exceeded = 0;
pushed = 0;
clientmap[0] = '\0';
mapcrc = 0;
warned = false;
gameclip = false;
}
void reassign()
{
state.reassign();
events.deletecontents();
timesync = false;
lastevent = 0;
}
void cleanclipboard(bool fullclean = true)
{
if(clipboard) { if(--clipboard->referenceCount <= 0) enet_packet_destroy(clipboard); clipboard = NULL; }
if(fullclean) lastclipboard = 0;
}
void cleanauthkick()
{
authkickvictim = -1;
DELETEA(authkickreason);
}
void cleanauth(bool full = true)
{
authreq = 0;
if(authchallenge) { freechallenge(authchallenge); authchallenge = NULL; }
if(full) cleanauthkick();
}
void reset()
{
name[0] = team[0] = 0;
playermodel = -1;
privilege = PRIV_NONE;
connected = local = false;
connectauth = 0;
position.setsize(0);
messages.setsize(0);
ping = 0;
aireinit = 0;
needclipboard = 0;
cleanclipboard();
cleanauth();
mapchange();
}
int geteventmillis(int servmillis, int clientmillis)
{
if(!timesync || (events.empty() && state.waitexpired(servmillis)))
{
timesync = true;
gameoffset = servmillis - clientmillis;
return servmillis;
}
else return gameoffset + clientmillis;
}
};
struct ban
{
int time, expire;
uint ip;
};
namespace aiman
{
extern void removeai(clientinfo *ci);
extern void clearai();
extern void checkai();
extern void reqadd(clientinfo *ci, int skill);
extern void reqdel(clientinfo *ci);
extern void setbotlimit(clientinfo *ci, int limit);
extern void setbotbalance(clientinfo *ci, bool balance);
extern void changemap();
extern void addclient(clientinfo *ci);
extern void changeteam(clientinfo *ci);
}
#define MM_MODE 0xF
#define MM_AUTOAPPROVE 0x1000
#define MM_PRIVSERV (MM_MODE | MM_AUTOAPPROVE)
#define MM_PUBSERV ((1<<MM_OPEN) | (1<<MM_VETO))
#define MM_COOPSERV (MM_AUTOAPPROVE | MM_PUBSERV | (1<<MM_LOCKED))
bool notgotitems = true; // true when map has changed and waiting for clients to send item
int gamemode = 0;
int gamemillis = 0, gamelimit = 0, nextexceeded = 0, gamespeed = 100;
bool gamepaused = false, shouldstep = true;
string smapname = "";
int interm = 0;
enet_uint32 lastsend = 0;
int mastermode = MM_OPEN, mastermask = MM_PRIVSERV;
stream *mapdata = NULL;
vector<uint> allowedips;
vector<ban> bannedips;
void addban(uint ip, int expire)
{
allowedips.removeobj(ip);
ban b;
b.time = totalmillis;
b.expire = totalmillis + expire;
b.ip = ip;
loopv(bannedips) if(bannedips[i].expire - b.expire > 0) { bannedips.insert(i, b); return; }
bannedips.add(b);
}
vector<clientinfo *> connects, clients, bots;
void kickclients(uint ip, clientinfo *actor = NULL, int priv = PRIV_NONE)
{
loopvrev(clients)
{
clientinfo &c = *clients[i];
if(c.state.aitype != AI_NONE || c.privilege >= PRIV_ADMIN || c.local) continue;
if(actor && ((c.privilege > priv && !actor->local) || c.clientnum == actor->clientnum)) continue;
if(getclientip(c.clientnum) == ip) disconnect_client(c.clientnum, DISC_KICK);
}
}
struct maprotation
{
static int exclude;
int modes;
string map;
int calcmodemask() const { return modes&(1<<NUMGAMEMODES) ? modes & ~exclude : modes; }
bool hasmode(int mode, int offset = STARTGAMEMODE) const { return (calcmodemask() & (1 << (mode-offset))) != 0; }
int findmode(int mode) const
{
if(!hasmode(mode)) loopi(NUMGAMEMODES) if(hasmode(i, 0)) return i+STARTGAMEMODE;
return mode;
}
bool match(int reqmode, const char *reqmap) const
{
return hasmode(reqmode) && (!map[0] || !reqmap[0] || !strcmp(map, reqmap));
}
bool includes(const maprotation &rot) const
{
return rot.modes == modes ? rot.map[0] && !map[0] : (rot.modes & modes) == rot.modes;
}
};
int maprotation::exclude = 0;
vector<maprotation> maprotations;
int curmaprotation = 0;
VAR(lockmaprotation, 0, 0, 2);
void maprotationreset()
{
maprotations.setsize(0);
curmaprotation = 0;
maprotation::exclude = 0;
}
void nextmaprotation()
{
curmaprotation++;
if(maprotations.inrange(curmaprotation) && maprotations[curmaprotation].modes) return;
do curmaprotation--;
while(maprotations.inrange(curmaprotation) && maprotations[curmaprotation].modes);
curmaprotation++;
}
int findmaprotation(int mode, const char *map)
{
for(int i = max(curmaprotation, 0); i < maprotations.length(); i++)
{
maprotation &rot = maprotations[i];
if(!rot.modes) break;
if(rot.match(mode, map)) return i;
}
int start;
for(start = max(curmaprotation, 0) - 1; start >= 0; start--) if(!maprotations[start].modes) break;
start++;
for(int i = start; i < curmaprotation; i++)
{
maprotation &rot = maprotations[i];
if(!rot.modes) break;
if(rot.match(mode, map)) return i;
}
int best = -1;
loopv(maprotations)
{
maprotation &rot = maprotations[i];
if(rot.match(mode, map) && (best < 0 || maprotations[best].includes(rot))) best = i;
}
return best;
}
bool searchmodename(const char *haystack, const char *needle)
{
if(!needle[0]) return true;
do
{
if(needle[0] != '.')
{
haystack = strchr(haystack, needle[0]);
if(!haystack) break;
haystack++;
}
const char *h = haystack, *n = needle+1;
for(; *h && *n; h++)
{
if(*h == *n) n++;
else if(*h != ' ') break;
}
if(!*n) return true;
if(*n == '.') return !*h;
} while(needle[0] != '.');
return false;
}
int genmodemask(vector<char *> &modes)
{
int modemask = 0;
loopv(modes)
{
const char *mode = modes[i];
int op = mode[0];
switch(mode[0])
{
case '*':
modemask |= 1<<NUMGAMEMODES;
loopk(NUMGAMEMODES) if(m_checknot(k+STARTGAMEMODE, M_DEMO|M_EDIT|M_LOCAL)) modemask |= 1<<k;
continue;
case '!':
mode++;
if(mode[0] != '?') break;
case '?':
mode++;
loopk(NUMGAMEMODES) if(searchmodename(gamemodes[k].name, mode))
{
if(op == '!') modemask &= ~(1<<k);
else modemask |= 1<<k;
}
continue;
}
int modenum = INT_MAX;
if(isdigit(mode[0])) modenum = atoi(mode);
else loopk(NUMGAMEMODES) if(searchmodename(gamemodes[k].name, mode)) { modenum = k+STARTGAMEMODE; break; }
if(!m_valid(modenum)) continue;
switch(op)
{
case '!': modemask &= ~(1 << (modenum - STARTGAMEMODE)); break;
default: modemask |= 1 << (modenum - STARTGAMEMODE); break;
}
}
return modemask;
}
bool addmaprotation(int modemask, const char *map)
{
if(!map[0]) loopk(NUMGAMEMODES) if(modemask&(1<<k) && !m_check(k+STARTGAMEMODE, M_EDIT)) modemask &= ~(1<<k);
if(!modemask) return false;
if(!(modemask&(1<<NUMGAMEMODES))) maprotation::exclude |= modemask;
maprotation &rot = maprotations.add();
rot.modes = modemask;
copystring(rot.map, map);
return true;
}
void addmaprotations(tagval *args, int numargs)
{
vector<char *> modes, maps;
for(int i = 0; i + 1 < numargs; i += 2)
{
explodelist(args[i].getstr(), modes);
explodelist(args[i+1].getstr(), maps);
int modemask = genmodemask(modes);
if(maps.length()) loopvj(maps) addmaprotation(modemask, maps[j]);
else addmaprotation(modemask, "");
modes.deletearrays();
maps.deletearrays();
}
if(maprotations.length() && maprotations.last().modes)
{
maprotation &rot = maprotations.add();
rot.modes = 0;
rot.map[0] = '\0';
}
}
COMMAND(maprotationreset, "");
COMMANDN(maprotation, addmaprotations, "ss2V");
struct demofile
{
string info;
uchar *data;
int len;
};
vector<demofile> demos;
bool demonextmatch = false;
stream *demotmp = NULL, *demorecord = NULL, *demoplayback = NULL;
int nextplayback = 0, demomillis = 0;
VAR(maxdemos, 0, 5, 25);
VAR(maxdemosize, 0, 16, 31);
VAR(restrictdemos, 0, 1, 1);
VAR(restrictpausegame, 0, 1, 1);
VAR(restrictgamespeed, 0, 1, 1);
SVAR(serverdesc, "");
SVAR(serverpass, "");
SVAR(adminpass, "");
VARF(publicserver, 0, 0, 2, {
switch(publicserver)
{
case 0: default: mastermask = MM_PRIVSERV; break;
case 1: mastermask = MM_PUBSERV; break;
case 2: mastermask = MM_COOPSERV; break;
}
});
SVAR(servermotd, "");
struct teamkillkick
{
int modes, limit, ban;
bool match(int mode) const
{
return (modes&(1<<(mode-STARTGAMEMODE)))!=0;
}
bool includes(const teamkillkick &tk) const
{
return tk.modes != modes && (tk.modes & modes) == tk.modes;
}
};
vector<teamkillkick> teamkillkicks;
void teamkillkickreset()
{
teamkillkicks.setsize(0);
}
void addteamkillkick(char *modestr, int *limit, int *ban)
{
vector<char *> modes;
explodelist(modestr, modes);
teamkillkick &kick = teamkillkicks.add();
kick.modes = genmodemask(modes);
kick.limit = *limit;
kick.ban = *ban > 0 ? *ban*60000 : (*ban < 0 ? 0 : 30*60000);
modes.deletearrays();
}
COMMAND(teamkillkickreset, "");
COMMANDN(teamkillkick, addteamkillkick, "sii");
struct teamkillinfo
{
uint ip;
int teamkills;
};
vector<teamkillinfo> teamkills;
bool shouldcheckteamkills = false;
void addteamkill(clientinfo *actor, clientinfo *victim, int n)
{
if(!m_timed || actor->state.aitype != AI_NONE || actor->local || actor->privilege || (victim && victim->state.aitype != AI_NONE)) return;
shouldcheckteamkills = true;
uint ip = getclientip(actor->clientnum);
loopv(teamkills) if(teamkills[i].ip == ip)
{
teamkills[i].teamkills += n;
return;
}
teamkillinfo &tk = teamkills.add();
tk.ip = ip;
tk.teamkills = n;
}
void checkteamkills()
{
teamkillkick *kick = NULL;
if(m_timed) loopv(teamkillkicks) if(teamkillkicks[i].match(gamemode) && (!kick || kick->includes(teamkillkicks[i])))
kick = &teamkillkicks[i];
if(kick) loopvrev(teamkills)
{
teamkillinfo &tk = teamkills[i];
if(tk.teamkills >= kick->limit)
{
if(kick->ban > 0) addban(tk.ip, kick->ban);
kickclients(tk.ip);
teamkills.removeunordered(i);
}
}
shouldcheckteamkills = false;
}
void *newclientinfo() { return new clientinfo; }
void deleteclientinfo(void *ci) { delete (clientinfo *)ci; }
clientinfo *getinfo(int n)
{
if(n < MAXCLIENTS) return (clientinfo *)getclientinfo(n);
n -= MAXCLIENTS;
return bots.inrange(n) ? bots[n] : NULL;
}
uint mcrc = 0;
vector<entity> ments;
vector<server_entity> sents;
vector<savedscore> scores;
int msgsizelookup(int msg)
{
static int sizetable[NUMMSG] = { -1 };
if(sizetable[0] < 0)
{
memset(sizetable, -1, sizeof(sizetable));
for(const int *p = msgsizes; *p >= 0; p += 2) sizetable[p[0]] = p[1];
}
return msg >= 0 && msg < NUMMSG ? sizetable[msg] : -1;
}
const char *modename(int n, const char *unknown)
{
if(m_valid(n)) return gamemodes[n - STARTGAMEMODE].name;
return unknown;
}
const char *mastermodename(int n, const char *unknown)
{
return (n>=MM_START && size_t(n-MM_START)<sizeof(mastermodenames)/sizeof(mastermodenames[0])) ? mastermodenames[n-MM_START] : unknown;
}
const char *privname(int type)
{
switch(type)
{
case PRIV_ADMIN: return "admin";
case PRIV_AUTH: return "auth";
case PRIV_MASTER: return "master";
default: return "unknown";
}
}
void sendservmsg(const char *s) { sendf(-1, 1, "ris", N_SERVMSG, s); }
void sendservmsgf(const char *fmt, ...)
{
defvformatstring(s, fmt, fmt);
sendf(-1, 1, "ris", N_SERVMSG, s);
}
void resetitems()
{
mcrc = 0;
ments.setsize(0);
sents.setsize(0);
//cps.reset();
}
bool serveroption(const char *arg)
{
if(arg[0]=='-') switch(arg[1])
{
case 'n': setsvar("serverdesc", &arg[2]); return true;
case 'y': setsvar("serverpass", &arg[2]); return true;
case 'p': setsvar("adminpass", &arg[2]); return true;
case 'o': setvar("publicserver", atoi(&arg[2])); return true;
}
return false;
}
void serverinit()
{
smapname[0] = '\0';
resetitems();
}
int numclients(int exclude = -1, bool nospec = true, bool noai = true, bool priv = false)
{
int n = 0;
loopv(clients)
{
clientinfo *ci = clients[i];
if(ci->clientnum!=exclude && (!nospec || ci->state.state!=CS_SPECTATOR || (priv && (ci->privilege || ci->local))) && (!noai || ci->state.aitype == AI_NONE)) n++;
}
return n;
}
bool duplicatename(clientinfo *ci, char *name)
{
if(!name) name = ci->name;
loopv(clients) if(clients[i]!=ci && !strcmp(name, clients[i]->name)) return true;
return false;
}
const char *colorname(clientinfo *ci, char *name = NULL)
{
if(!name) name = ci->name;
if(name[0] && !duplicatename(ci, name) && ci->state.aitype == AI_NONE) return name;
static string cname[3];
static int cidx = 0;
cidx = (cidx+1)%3;
formatstring(cname[cidx])(ci->state.aitype == AI_NONE ? "%s \fs\f5(%d)\fr" : "%s \fs\f5[%d]\fr", name, ci->clientnum);
return cname[cidx];
}
struct servmode
{
virtual ~servmode() {}
virtual void entergame(clientinfo *ci) {}
virtual void leavegame(clientinfo *ci, bool disconnecting = false) {}
virtual void moved(clientinfo *ci, const vec &oldpos, bool oldclip, const vec &newpos, bool newclip) {}
virtual bool canspawn(clientinfo *ci, bool connecting = false) { return true; }
virtual void spawned(clientinfo *ci) {}
virtual int fragvalue(clientinfo *victim, clientinfo *actor)
{
if(victim==actor || isteam(victim->team, actor->team)) return -1;
return 1;
}
virtual void died(clientinfo *victim, clientinfo *actor) {}
virtual bool canchangeteam(clientinfo *ci, const char *oldteam, const char *newteam) { return true; }
virtual void changeteam(clientinfo *ci, const char *oldteam, const char *newteam) {}
virtual void initclient(clientinfo *ci, packetbuf &p, bool connecting) {}
virtual void update() {}
virtual void cleanup() {}
virtual void setup() {}
virtual void newmap() {}
virtual void intermission() {}
virtual bool hidefrags() { return false; }
virtual int getteamscore(const char *team) { return 0; }
virtual void getteamscores(vector<teamscore> &scores) {}
virtual bool extinfoteam(const char *team, ucharbuf &p) { return false; }
};
#define SERVMODE 1
#include "capture.h"
#include "ctf.h"
#include "collect.h"
captureservmode capturemode;
ctfservmode ctfmode;
collectservmode collectmode;
servmode *smode = NULL;
bool canspawnitem(int type) { return !m_noitems && (type>=I_SHELLS && type<=I_QUAD && (!m_noammo || type<I_SHELLS || type>I_CARTRIDGES)); }
int spawntime(int type)
{
if(m_classicsp) return INT_MAX;
int np = numclients(-1, true, false);
np = np<3 ? 4 : (np>4 ? 2 : 3); // spawn times are dependent on number of players
int sec = 0;
switch(type)
{
case I_SHELLS:
case I_BULLETS:
case I_ROCKETS:
case I_ROUNDS:
case I_GRENADES:
case I_CARTRIDGES: sec = np*4; break;
case I_HEALTH: sec = np*5; break;
case I_GREENARMOUR: sec = 20; break;
case I_YELLOWARMOUR: sec = 30; break;
case I_BOOST: sec = 60; break;
case I_QUAD: sec = 70; break;
}
return sec*1000;
}
bool delayspawn(int type)
{
switch(type)
{
case I_GREENARMOUR:
case I_YELLOWARMOUR:
return !m_classicsp;
case I_BOOST:
case I_QUAD:
return true;
default:
return false;
}
}
bool pickup(int i, int sender) // server side item pickup, acknowledge first client that gets it
{
if((m_timed && gamemillis>=gamelimit) || !sents.inrange(i) || !sents[i].spawned) return false;
clientinfo *ci = getinfo(sender);
if(!ci || (!ci->local && !ci->state.canpickup(sents[i].type))) return false;
sents[i].spawned = false;
sents[i].spawntime = spawntime(sents[i].type);
sendf(-1, 1, "ri3", N_ITEMACC, i, sender);
ci->state.pickup(sents[i].type);
return true;
}
static hashset<teaminfo> teaminfos;
void clearteaminfo()
{
teaminfos.clear();
}
bool teamhasplayers(const char *team) { loopv(clients) if(!strcmp(clients[i]->team, team)) return true; return false; }
bool pruneteaminfo()
{
int oldteams = teaminfos.numelems;
enumerates(teaminfos, teaminfo, old,
if(!old.frags && !teamhasplayers(old.team)) teaminfos.remove(old.team);
);
return teaminfos.numelems < oldteams;
}
teaminfo *addteaminfo(const char *team)
{
teaminfo *t = teaminfos.access(team);
if(!t)
{
if(teaminfos.numelems >= MAXTEAMS && !pruneteaminfo()) return NULL;
t = &teaminfos[team];
copystring(t->team, team, sizeof(t->team));
t->frags = 0;
}
return t;
}
clientinfo *choosebestclient(float &bestrank)
{
clientinfo *best = NULL;
bestrank = -1;
loopv(clients)
{
clientinfo *ci = clients[i];
if(ci->state.timeplayed<0) continue;
float rank = ci->state.state!=CS_SPECTATOR ? ci->state.effectiveness/max(ci->state.timeplayed, 1) : -1;
if(!best || rank > bestrank) { best = ci; bestrank = rank; }
}
return best;
}
void autoteam()
{
static const char * const teamnames[2] = {"good", "evil"};
vector<clientinfo *> team[2];
float teamrank[2] = {0, 0};
for(int round = 0, remaining = clients.length(); remaining>=0; round++)
{
int first = round&1, second = (round+1)&1, selected = 0;
while(teamrank[first] <= teamrank[second])
{
float rank;
clientinfo *ci = choosebestclient(rank);
if(!ci) break;
if(smode && smode->hidefrags()) rank = 1;
else if(selected && rank<=0) break;
ci->state.timeplayed = -1;
team[first].add(ci);
if(rank>0) teamrank[first] += rank;
selected++;
if(rank<=0) break;
}
if(!selected) break;
remaining -= selected;
}
loopi(sizeof(team)/sizeof(team[0]))
{
addteaminfo(teamnames[i]);
loopvj(team[i])
{
clientinfo *ci = team[i][j];
if(!strcmp(ci->team, teamnames[i])) continue;
copystring(ci->team, teamnames[i], MAXTEAMLEN+1);
sendf(-1, 1, "riisi", N_SETTEAM, ci->clientnum, teamnames[i], -1);
}
}
}
struct teamrank
{
const char *name;
float rank;
int clients;
teamrank(const char *name) : name(name), rank(0), clients(0) {}
};
const char *chooseworstteam(const char *suggest = NULL, clientinfo *exclude = NULL)
{
teamrank teamranks[2] = { teamrank("good"), teamrank("evil") };
const int numteams = sizeof(teamranks)/sizeof(teamranks[0]);
loopv(clients)
{
clientinfo *ci = clients[i];
if(ci==exclude || ci->state.aitype!=AI_NONE || ci->state.state==CS_SPECTATOR || !ci->team[0]) continue;
ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed;
ci->state.lasttimeplayed = lastmillis;
loopj(numteams) if(!strcmp(ci->team, teamranks[j].name))
{
teamrank &ts = teamranks[j];
ts.rank += ci->state.effectiveness/max(ci->state.timeplayed, 1);
ts.clients++;
break;
}
}
teamrank *worst = &teamranks[numteams-1];
loopi(numteams-1)
{
teamrank &ts = teamranks[i];
if(smode && smode->hidefrags())
{
if(ts.clients < worst->clients || (ts.clients == worst->clients && ts.rank < worst->rank)) worst = &ts;
}
else if(ts.rank < worst->rank || (ts.rank == worst->rank && ts.clients < worst->clients)) worst = &ts;
}
return worst->name;
}
void prunedemos(int extra = 0)
{
int n = clamp(demos.length() + extra - maxdemos, 0, demos.length());
if(n <= 0) return;
loopi(n) delete[] demos[i].data;
demos.remove(0, n);
}
void adddemo()
{
if(!demotmp) return;
int len = (int)min(demotmp->size(), stream::offset((maxdemosize<<20) + 0x10000));
demofile &d = demos.add();
time_t t = time(NULL);
char *timestr = ctime(&t), *trim = timestr + strlen(timestr);
while(trim>timestr && iscubespace(*--trim)) *trim = '\0';
formatstring(d.info)("%s: %s, %s, %.2f%s", timestr, modename(gamemode), smapname, len > 1024*1024 ? len/(1024*1024.f) : len/1024.0f, len > 1024*1024 ? "MB" : "kB");
sendservmsgf("demo \"%s\" recorded", d.info);
d.data = new uchar[len];
d.len = len;
demotmp->seek(0, SEEK_SET);
demotmp->read(d.data, len);
DELETEP(demotmp);
}
void enddemorecord()
{
if(!demorecord) return;
DELETEP(demorecord);
if(!demotmp) return;
if(!maxdemos || !maxdemosize) { DELETEP(demotmp); return; }
prunedemos(1);
adddemo();
}
void writedemo(int chan, void *data, int len)
{
if(!demorecord) return;
int stamp[3] = { gamemillis, chan, len };
lilswap(stamp, 3);
demorecord->write(stamp, sizeof(stamp));
demorecord->write(data, len);
if(demorecord->rawtell() >= (maxdemosize<<20)) enddemorecord();
}
void recordpacket(int chan, void *data, int len)
{
writedemo(chan, data, len);
}
int welcomepacket(packetbuf &p, clientinfo *ci);
void sendwelcome(clientinfo *ci);
void setupdemorecord()
{
if(!m_mp(gamemode) || m_edit) return;
demotmp = opentempfile("demorecord", "w+b");
if(!demotmp) return;
stream *f = opengzfile(NULL, "wb", demotmp);
if(!f) { DELETEP(demotmp); return; }
sendservmsg("recording demo");
demorecord = f;
demoheader hdr;
memcpy(hdr.magic, DEMO_MAGIC, sizeof(hdr.magic));
hdr.version = DEMO_VERSION;
hdr.protocol = PROTOCOL_VERSION;
lilswap(&hdr.version, 2);
demorecord->write(&hdr, sizeof(demoheader));
packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE);
welcomepacket(p, NULL);
writedemo(1, p.buf, p.len);
}
void listdemos(int cn)
{
packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE);
putint(p, N_SENDDEMOLIST);
putint(p, demos.length());
loopv(demos) sendstring(demos[i].info, p);
sendpacket(cn, 1, p.finalize());
}
void cleardemos(int n)
{
if(!n)
{
loopv(demos) delete[] demos[i].data;
demos.shrink(0);
sendservmsg("cleared all demos");
}
else if(demos.inrange(n-1))
{
delete[] demos[n-1].data;
demos.remove(n-1);
sendservmsgf("cleared demo %d", n);
}
}
static void freegetmap(ENetPacket *packet)
{
loopv(clients)
{
clientinfo *ci = clients[i];
if(ci->getmap == packet) ci->getmap = NULL;
}
}
static void freegetdemo(ENetPacket *packet)
{
loopv(clients)
{
clientinfo *ci = clients[i];
if(ci->getdemo == packet) ci->getdemo = NULL;
}
}
void senddemo(clientinfo *ci, int num)
{
if(ci->getdemo) return;
if(!num) num = demos.length();
if(!demos.inrange(num-1)) return;
demofile &d = demos[num-1];
if((ci->getdemo = sendf(ci->clientnum, 2, "rim", N_SENDDEMO, d.len, d.data)))
ci->getdemo->freeCallback = freegetdemo;
}
void enddemoplayback()
{
if(!demoplayback) return;
DELETEP(demoplayback);
loopv(clients) sendf(clients[i]->clientnum, 1, "ri3", N_DEMOPLAYBACK, 0, clients[i]->clientnum);
sendservmsg("demo playback finished");
loopv(clients) sendwelcome(clients[i]);
}
void setupdemoplayback()
{
if(demoplayback) return;
demoheader hdr;
string msg;
msg[0] = '\0';
defformatstring(file)("%s.dmo", smapname);
demoplayback = opengzfile(file, "rb");
if(!demoplayback) formatstring(msg)("could not read demo \"%s\"", file);
else if(demoplayback->read(&hdr, sizeof(demoheader))!=sizeof(demoheader) || memcmp(hdr.magic, DEMO_MAGIC, sizeof(hdr.magic)))
formatstring(msg)("\"%s\" is not a demo file", file);
else
{
lilswap(&hdr.version, 2);
if(hdr.version!=DEMO_VERSION) formatstring(msg)("demo \"%s\" requires an %s version of Cube 2: Sauerbraten", file, hdr.version<DEMO_VERSION ? "older" : "newer");
else if(hdr.protocol!=PROTOCOL_VERSION) formatstring(msg)("demo \"%s\" requires an %s version of Cube 2: Sauerbraten", file, hdr.protocol<PROTOCOL_VERSION ? "older" : "newer");
}
if(msg[0])
{
DELETEP(demoplayback);
sendservmsg(msg);
return;
}
sendservmsgf("playing demo \"%s\"", file);
demomillis = 0;
sendf(-1, 1, "ri3", N_DEMOPLAYBACK, 1, -1);
if(demoplayback->read(&nextplayback, sizeof(nextplayback))!=sizeof(nextplayback))
{
enddemoplayback();
return;
}
lilswap(&nextplayback, 1);
}
void readdemo(int curtime)
{
if(!demoplayback) return;
demomillis += curtime;
while(demomillis>=nextplayback)
{
int chan, len;
if(demoplayback->read(&chan, sizeof(chan))!=sizeof(chan) ||
demoplayback->read(&len, sizeof(len))!=sizeof(len))
{
enddemoplayback();
return;
}
lilswap(&chan, 1);
lilswap(&len, 1);
ENetPacket *packet = enet_packet_create(NULL, len+1, 0);
if(!packet || demoplayback->read(packet->data+1, len)!=size_t(len))
{
if(packet) enet_packet_destroy(packet);
enddemoplayback();
return;
}
packet->data[0] = N_DEMOPACKET;
sendpacket(-1, chan, packet);
if(!packet->referenceCount) enet_packet_destroy(packet);
if(!demoplayback) break;
if(demoplayback->read(&nextplayback, sizeof(nextplayback))!=sizeof(nextplayback))
{
enddemoplayback();
return;
}
lilswap(&nextplayback, 1);
}
}
void stopdemo()
{
if(m_demo) enddemoplayback();
else enddemorecord();
}
void pausegame(bool val, clientinfo *ci = NULL)
{
if(gamepaused==val) return;
gamepaused = val;
sendf(-1, 1, "riii", N_PAUSEGAME, gamepaused ? 1 : 0, ci ? ci->clientnum : -1);
}
void checkpausegame()
{
if(!gamepaused) return;
int admins = 0;
loopv(clients) if(clients[i]->privilege >= (restrictpausegame ? PRIV_ADMIN : PRIV_MASTER) || clients[i]->local) admins++;
if(!admins) pausegame(false);
}
void forcepaused(bool paused)
{
pausegame(paused);
}
bool ispaused() { return gamepaused; }
void changegamespeed(int val, clientinfo *ci = NULL)
{
val = clamp(val, 10, 1000);
if(gamespeed==val) return;
gamespeed = val;
sendf(-1, 1, "riii", N_GAMESPEED, gamespeed, ci ? ci->clientnum : -1);
}
void forcegamespeed(int speed)
{
changegamespeed(speed);
}
int scaletime(int t) { return t*gamespeed; }
SVAR(serverauth, "");
struct userkey
{
char *name;
char *desc;
userkey() : name(NULL), desc(NULL) {}
userkey(char *name, char *desc) : name(name), desc(desc) {}
};
static inline uint hthash(const userkey &k) { return ::hthash(k.name); }
static inline bool htcmp(const userkey &x, const userkey &y) { return !strcmp(x.name, y.name) && !strcmp(x.desc, y.desc); }
struct userinfo : userkey
{
void *pubkey;
int privilege;
userinfo() : pubkey(NULL), privilege(PRIV_NONE) {}
~userinfo() { delete[] name; delete[] desc; if(pubkey) freepubkey(pubkey); }
};
hashset<userinfo> users;
void adduser(char *name, char *desc, char *pubkey, char *priv)
{
userkey key(name, desc);
userinfo &u = users[key];
if(u.pubkey) { freepubkey(u.pubkey); u.pubkey = NULL; }
if(!u.name) u.name = newstring(name);
if(!u.desc) u.desc = newstring(desc);
u.pubkey = parsepubkey(pubkey);
switch(priv[0])
{
case 'a': case 'A': u.privilege = PRIV_ADMIN; break;
case 'm': case 'M': default: u.privilege = PRIV_AUTH; break;
}
}
COMMAND(adduser, "ssss");
void clearusers()
{
users.clear();
}
COMMAND(clearusers, "");
void hashpassword(int cn, int sessionid, const char *pwd, char *result, int maxlen)
{
char buf[2*sizeof(string)];
formatstring(buf)("%d %d ", cn, sessionid);
copystring(&buf[strlen(buf)], pwd);
if(!hashstring(buf, result, maxlen)) *result = '\0';
}
bool checkpassword(clientinfo *ci, const char *wanted, const char *given)
{
string hash;
hashpassword(ci->clientnum, ci->sessionid, wanted, hash, sizeof(hash));
return !strcmp(hash, given);
}
void revokemaster(clientinfo *ci)
{
ci->privilege = PRIV_NONE;
if(ci->state.state==CS_SPECTATOR && !ci->local) aiman::removeai(ci);
}
extern void connected(clientinfo *ci);
bool setmaster(clientinfo *ci, bool val, const char *pass = "", const char *authname = NULL, const char *authdesc = NULL, int authpriv = PRIV_MASTER, bool force = false, bool trial = false)
{
if(authname && !val) return false;
const char *name = "";
if(val)
{
bool haspass = adminpass[0] && checkpassword(ci, adminpass, pass);
int wantpriv = ci->local || haspass ? PRIV_ADMIN : authpriv;
if(ci->privilege)
{
if(wantpriv <= ci->privilege) return true;
}
else if(wantpriv <= PRIV_MASTER && !force)
{
if(ci->state.state==CS_SPECTATOR)
{
sendf(ci->clientnum, 1, "ris", N_SERVMSG, "Spectators may not claim master.");
return false;
}
loopv(clients) if(ci!=clients[i] && clients[i]->privilege)
{
sendf(ci->clientnum, 1, "ris", N_SERVMSG, "Master is already claimed.");
return false;
}
if(!authname && !(mastermask&MM_AUTOAPPROVE) && !ci->privilege && !ci->local)
{
sendf(ci->clientnum, 1, "ris", N_SERVMSG, "This server requires you to use the \"/auth\" command to claim master.");
return false;
}
}
if(trial) return true;
ci->privilege = wantpriv;
name = privname(ci->privilege);
}
else
{
if(!ci->privilege) return false;
if(trial) return true;
name = privname(ci->privilege);
revokemaster(ci);
}
bool hasmaster = false;
loopv(clients) if(clients[i]->local || clients[i]->privilege >= PRIV_MASTER) hasmaster = true;
if(!hasmaster)
{
mastermode = MM_OPEN;
allowedips.shrink(0);
}
string msg;
if(val && authname)
{
if(authdesc && authdesc[0]) formatstring(msg)("%s claimed %s as '\fs\f5%s\fr' [\fs\f0%s\fr]", colorname(ci), name, authname, authdesc);
else formatstring(msg)("%s claimed %s as '\fs\f5%s\fr'", colorname(ci), name, authname);
}
else formatstring(msg)("%s %s %s", colorname(ci), val ? "claimed" : "relinquished", name);
packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE);
putint(p, N_SERVMSG);
sendstring(msg, p);
putint(p, N_CURRENTMASTER);
putint(p, mastermode);
loopv(clients) if(clients[i]->privilege >= PRIV_MASTER)
{
putint(p, clients[i]->clientnum);
putint(p, clients[i]->privilege);
}
putint(p, -1);
sendpacket(-1, 1, p.finalize());
checkpausegame();
return true;
}
bool trykick(clientinfo *ci, int victim, const char *reason = NULL, const char *authname = NULL, const char *authdesc = NULL, int authpriv = PRIV_NONE, bool trial = false)
{
int priv = ci->privilege;
if(authname)
{
if(priv >= authpriv || ci->local) authname = authdesc = NULL;
else priv = authpriv;
}
if((priv || ci->local) && ci->clientnum!=victim)
{
clientinfo *vinfo = (clientinfo *)getclientinfo(victim);
if(vinfo && vinfo->connected && (priv >= vinfo->privilege || ci->local) && vinfo->privilege < PRIV_ADMIN && !vinfo->local)
{
if(trial) return true;
string kicker;
if(authname)
{
if(authdesc && authdesc[0]) formatstring(kicker)("%s as '\fs\f5%s\fr' [\fs\f0%s\fr]", colorname(ci), authname, authdesc);
else formatstring(kicker)("%s as '\fs\f5%s\fr'", colorname(ci), authname);
}
else copystring(kicker, colorname(ci));
if(reason && reason[0]) sendservmsgf("%s kicked %s because: %s", kicker, colorname(vinfo), reason);
else sendservmsgf("%s kicked %s", kicker, colorname(vinfo));
uint ip = getclientip(victim);
addban(ip, 4*60*60000);
kickclients(ip, ci, priv);
}
}
return false;
}
savedscore *findscore(clientinfo *ci, bool insert)
{
uint ip = getclientip(ci->clientnum);
if(!ip && !ci->local) return 0;
if(!insert)
{
loopv(clients)
{
clientinfo *oi = clients[i];
if(oi->clientnum != ci->clientnum && getclientip(oi->clientnum) == ip && !strcmp(oi->name, ci->name))
{
oi->state.timeplayed += lastmillis - oi->state.lasttimeplayed;
oi->state.lasttimeplayed = lastmillis;
static savedscore curscore;
curscore.save(oi->state);
return &curscore;
}
}
}
loopv(scores)
{
savedscore &sc = scores[i];
if(sc.ip == ip && !strcmp(sc.name, ci->name)) return ≻
}
if(!insert) return 0;
savedscore &sc = scores.add();
sc.ip = ip;
copystring(sc.name, ci->name);
return ≻
}
void savescore(clientinfo *ci)
{
savedscore *sc = findscore(ci, true);
if(sc) sc->save(ci->state);
}
static struct msgfilter
{
uchar msgmask[NUMMSG];
msgfilter(int msg, ...)
{
memset(msgmask, 0, sizeof(msgmask));
va_list msgs;
va_start(msgs, msg);
for(uchar val = 1; msg < NUMMSG; msg = va_arg(msgs, int))
{
if(msg < 0) val = uchar(-msg);
else msgmask[msg] = val;
}
va_end(msgs);
}
uchar operator[](int msg) const { return msg >= 0 && msg < NUMMSG ? msgmask[msg] : 0; }
} msgfilter(-1, N_CONNECT, N_SERVINFO, N_INITCLIENT, N_WELCOME, N_MAPCHANGE, N_SERVMSG, N_DAMAGE, N_HITPUSH, N_SHOTFX, N_EXPLODEFX, N_DIED, N_SPAWNSTATE, N_FORCEDEATH, N_TEAMINFO, N_ITEMACC, N_ITEMSPAWN, N_TIMEUP, N_CDIS, N_CURRENTMASTER, N_PONG, N_RESUME, N_BASESCORE, N_BASEINFO, N_BASEREGEN, N_ANNOUNCE, N_SENDDEMOLIST, N_SENDDEMO, N_DEMOPLAYBACK, N_SENDMAP, N_DROPFLAG, N_SCOREFLAG, N_RETURNFLAG, N_RESETFLAG, N_INVISFLAG, N_CLIENT, N_AUTHCHAL, N_INITAI, N_EXPIRETOKENS, N_DROPTOKENS, N_STEALTOKENS, N_DEMOPACKET, -2, N_REMIP, N_NEWMAP, N_GETMAP, N_SENDMAP, N_CLIPBOARD, -3, N_EDITENT, N_EDITF, N_EDITT, N_EDITM, N_FLIP, N_COPY, N_PASTE, N_ROTATE, N_REPLACE, N_DELCUBE, N_EDITVAR, -4, N_POS, NUMMSG),
connectfilter(-1, N_CONNECT, -2, N_AUTHANS, -3, N_PING, NUMMSG);
int checktype(int type, clientinfo *ci)
{
if(ci)
{
if(!ci->connected) switch(connectfilter[type])
{
// allow only before authconnect
case 1: return !ci->connectauth ? type : -1;
// allow only during authconnect
case 2: return ci->connectauth ? type : -1;
// always allow
case 3: return type;
// never allow
default: return -1;
}
if(ci->local) return type;
}
switch(msgfilter[type])
{
// server-only messages
case 1: return ci ? -1 : type;
// only allowed in coop-edit
case 2: if(m_edit) break; return -1;
// only allowed in coop-edit, no overflow check
case 3: return m_edit ? type : -1;
// no overflow check
case 4: return type;
}
if(ci && ++ci->overflow >= 200) return -2;
return type;
}
struct worldstate
{
int uses, len;
uchar *data;
worldstate() : uses(0), len(0), data(NULL) {}
void setup(int n) { len = n; data = new uchar[n]; }
void cleanup() { DELETEA(data); len = 0; }
bool contains(const uchar *p) const { return p >= data && p < &data[len]; }
};
vector<worldstate> worldstates;
bool reliablemessages = false;
void cleanworldstate(ENetPacket *packet)
{
loopv(worldstates)
{
worldstate &ws = worldstates[i];
if(!ws.contains(packet->data)) continue;
ws.uses--;
if(ws.uses <= 0)
{
ws.cleanup();
worldstates.removeunordered(i);
}
break;
}
}
void flushclientposition(clientinfo &ci)
{
if(ci.position.empty() || (!hasnonlocalclients() && !demorecord)) return;
packetbuf p(ci.position.length(), 0);
p.put(ci.position.getbuf(), ci.position.length());
ci.position.setsize(0);
sendpacket(-1, 0, p.finalize(), ci.ownernum);
}
static void sendpositions(worldstate &ws, ucharbuf &wsbuf)
{
if(wsbuf.empty()) return;
int wslen = wsbuf.length();
recordpacket(0, wsbuf.buf, wslen);
wsbuf.put(wsbuf.buf, wslen);
loopv(clients)
{
clientinfo &ci = *clients[i];
if(ci.state.aitype != AI_NONE) continue;
uchar *data = wsbuf.buf;
int size = wslen;
if(ci.wsdata >= wsbuf.buf) { data = ci.wsdata + ci.wslen; size -= ci.wslen; }
if(size <= 0) continue;
ENetPacket *packet = enet_packet_create(data, size, ENET_PACKET_FLAG_NO_ALLOCATE);
sendpacket(ci.clientnum, 0, packet);
if(packet->referenceCount) { ws.uses++; packet->freeCallback = cleanworldstate; }
else enet_packet_destroy(packet);
}
wsbuf.offset(wsbuf.length());
}
static inline void addposition(worldstate &ws, ucharbuf &wsbuf, int mtu, clientinfo &bi, clientinfo &ci)
{
if(bi.position.empty()) return;
if(wsbuf.length() + bi.position.length() > mtu) sendpositions(ws, wsbuf);
int offset = wsbuf.length();
wsbuf.put(bi.position.getbuf(), bi.position.length());
bi.position.setsize(0);
int len = wsbuf.length() - offset;
if(ci.wsdata < wsbuf.buf) { ci.wsdata = &wsbuf.buf[offset]; ci.wslen = len; }
else ci.wslen += len;
}
static void sendmessages(worldstate &ws, ucharbuf &wsbuf)
{
if(wsbuf.empty()) return;
int wslen = wsbuf.length();
recordpacket(1, wsbuf.buf, wslen);
wsbuf.put(wsbuf.buf, wslen);
loopv(clients)
{
clientinfo &ci = *clients[i];
if(ci.state.aitype != AI_NONE) continue;
uchar *data = wsbuf.buf;
int size = wslen;
if(ci.wsdata >= wsbuf.buf) { data = ci.wsdata + ci.wslen; size -= ci.wslen; }
if(size <= 0) continue;
ENetPacket *packet = enet_packet_create(data, size, (reliablemessages ? ENET_PACKET_FLAG_RELIABLE : 0) | ENET_PACKET_FLAG_NO_ALLOCATE);
sendpacket(ci.clientnum, 1, packet);
if(packet->referenceCount) { ws.uses++; packet->freeCallback = cleanworldstate; }
else enet_packet_destroy(packet);
}
wsbuf.offset(wsbuf.length());
}
static inline void addmessages(worldstate &ws, ucharbuf &wsbuf, int mtu, clientinfo &bi, clientinfo &ci)
{
if(bi.messages.empty()) return;
if(wsbuf.length() + 10 + bi.messages.length() > mtu) sendmessages(ws, wsbuf);
int offset = wsbuf.length();
putint(wsbuf, N_CLIENT);
putint(wsbuf, bi.clientnum);
putuint(wsbuf, bi.messages.length());
wsbuf.put(bi.messages.getbuf(), bi.messages.length());
bi.messages.setsize(0);
int len = wsbuf.length() - offset;
if(ci.wsdata < wsbuf.buf) { ci.wsdata = &wsbuf.buf[offset]; ci.wslen = len; }
else ci.wslen += len;
}
bool buildworldstate()
{
int wsmax = 0;
loopv(clients)
{
clientinfo &ci = *clients[i];
ci.overflow = 0;
ci.wsdata = NULL;
wsmax += ci.position.length();
if(ci.messages.length()) wsmax += 10 + ci.messages.length();
}
if(wsmax <= 0)
{
reliablemessages = false;
return false;
}
worldstate &ws = worldstates.add();
ws.setup(2*wsmax);
int mtu = getservermtu() - 100;
if(mtu <= 0) mtu = ws.len;
ucharbuf wsbuf(ws.data, ws.len);
loopv(clients)
{
clientinfo &ci = *clients[i];
if(ci.state.aitype != AI_NONE) continue;
addposition(ws, wsbuf, mtu, ci, ci);
loopvj(ci.bots) addposition(ws, wsbuf, mtu, *ci.bots[j], ci);
}
sendpositions(ws, wsbuf);
loopv(clients)
{
clientinfo &ci = *clients[i];
if(ci.state.aitype != AI_NONE) continue;
addmessages(ws, wsbuf, mtu, ci, ci);
loopvj(ci.bots) addmessages(ws, wsbuf, mtu, *ci.bots[j], ci);
}
sendmessages(ws, wsbuf);
reliablemessages = false;
if(ws.uses) return true;
ws.cleanup();
worldstates.drop();
return false;
}
bool sendpackets(bool force)
{
if(clients.empty() || (!hasnonlocalclients() && !demorecord)) return false;
enet_uint32 curtime = enet_time_get()-lastsend;
if(curtime<33 && !force) return false;
bool flush = buildworldstate();
lastsend += curtime - (curtime%33);
return flush;
}
template<class T>
void sendstate(gamestate &gs, T &p)
{
putint(p, gs.lifesequence);
putint(p, gs.health);
putint(p, gs.maxhealth);
putint(p, gs.armour);
putint(p, gs.armourtype);
putint(p, gs.gunselect);
loopi(GUN_PISTOL-GUN_SG+1) putint(p, gs.ammo[GUN_SG+i]);
}
void spawnstate(clientinfo *ci)
{
gamestate &gs = ci->state;
gs.spawnstate(gamemode);
gs.lifesequence = (gs.lifesequence + 1)&0x7F;
}
void sendspawn(clientinfo *ci)
{
gamestate &gs = ci->state;
spawnstate(ci);
sendf(ci->ownernum, 1, "rii7v", N_SPAWNSTATE, ci->clientnum, gs.lifesequence,
gs.health, gs.maxhealth,
gs.armour, gs.armourtype,
gs.gunselect, GUN_PISTOL-GUN_SG+1, &gs.ammo[GUN_SG]);
gs.lastspawn = gamemillis;
}
void sendwelcome(clientinfo *ci)
{
packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE);
int chan = welcomepacket(p, ci);
sendpacket(ci->clientnum, chan, p.finalize());
}
void putinitclient(clientinfo *ci, packetbuf &p)
{
if(ci->state.aitype != AI_NONE)
{
putint(p, N_INITAI);
putint(p, ci->clientnum);
putint(p, ci->ownernum);
putint(p, ci->state.aitype);
putint(p, ci->state.skill);
putint(p, ci->playermodel);
sendstring(ci->name, p);
sendstring(ci->team, p);
}
else
{
putint(p, N_INITCLIENT);
putint(p, ci->clientnum);
sendstring(ci->name, p);
sendstring(ci->team, p);
putint(p, ci->playermodel);
}
}
void welcomeinitclient(packetbuf &p, int exclude = -1)
{
loopv(clients)
{
clientinfo *ci = clients[i];
if(!ci->connected || ci->clientnum == exclude) continue;
putinitclient(ci, p);
}
}
bool hasmap(clientinfo *ci)
{
return (m_edit && (clients.length() > 0 || ci->local)) ||
(smapname[0] && (!m_timed || gamemillis < gamelimit || (ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || numclients(ci->clientnum, true, true, true)));
}
int welcomepacket(packetbuf &p, clientinfo *ci)
{
putint(p, N_WELCOME);
putint(p, N_MAPCHANGE);
sendstring(smapname, p);
putint(p, gamemode);
putint(p, notgotitems ? 1 : 0);
if(!ci || (m_timed && smapname[0]))
{
putint(p, N_TIMEUP);
putint(p, gamemillis < gamelimit && !interm ? max((gamelimit - gamemillis)/1000, 1) : 0);
}
if(!notgotitems)
{
putint(p, N_ITEMLIST);
loopv(sents) if(sents[i].spawned)
{
putint(p, i);
putint(p, sents[i].type);
}
putint(p, -1);
}
bool hasmaster = false;
if(mastermode != MM_OPEN)
{
putint(p, N_CURRENTMASTER);
putint(p, mastermode);
hasmaster = true;
}
loopv(clients) if(clients[i]->privilege >= PRIV_MASTER)
{
if(!hasmaster)
{
putint(p, N_CURRENTMASTER);
putint(p, mastermode);
hasmaster = true;
}
putint(p, clients[i]->clientnum);
putint(p, clients[i]->privilege);
}
if(hasmaster) putint(p, -1);
if(gamepaused)
{
putint(p, N_PAUSEGAME);
putint(p, 1);
putint(p, -1);
}
if(gamespeed != 100)
{
putint(p, N_GAMESPEED);
putint(p, gamespeed);
putint(p, -1);
}
if(m_teammode)
{
putint(p, N_TEAMINFO);
enumerates(teaminfos, teaminfo, t,
if(t.frags) { sendstring(t.team, p); putint(p, t.frags); }
);
sendstring("", p);
}
if(ci)
{
putint(p, N_SETTEAM);
putint(p, ci->clientnum);
sendstring(ci->team, p);
putint(p, -1);
}
if(ci && (m_demo || m_mp(gamemode)) && ci->state.state!=CS_SPECTATOR)
{
if(smode && !smode->canspawn(ci, true))
{
ci->state.state = CS_DEAD;
putint(p, N_FORCEDEATH);
putint(p, ci->clientnum);
sendf(-1, 1, "ri2x", N_FORCEDEATH, ci->clientnum, ci->clientnum);
}
else
{
gamestate &gs = ci->state;
spawnstate(ci);
putint(p, N_SPAWNSTATE);
putint(p, ci->clientnum);
sendstate(gs, p);
gs.lastspawn = gamemillis;
}
}
if(ci && ci->state.state==CS_SPECTATOR)
{
putint(p, N_SPECTATOR);
putint(p, ci->clientnum);
putint(p, 1);
sendf(-1, 1, "ri3x", N_SPECTATOR, ci->clientnum, 1, ci->clientnum);
}
if(!ci || clients.length()>1)
{
putint(p, N_RESUME);
loopv(clients)
{
clientinfo *oi = clients[i];
if(ci && oi->clientnum==ci->clientnum) continue;
putint(p, oi->clientnum);
putint(p, oi->state.state);
putint(p, oi->state.frags);
putint(p, oi->state.flags);
putint(p, oi->state.quadmillis);
sendstate(oi->state, p);
}
putint(p, -1);
welcomeinitclient(p, ci ? ci->clientnum : -1);
}
if(smode) smode->initclient(ci, p, true);
return 1;
}
bool restorescore(clientinfo *ci)
{
//if(ci->local) return false;
savedscore *sc = findscore(ci, false);
if(sc)
{
sc->restore(ci->state);
return true;
}
return false;
}
void sendresume(clientinfo *ci)
{
gamestate &gs = ci->state;
sendf(-1, 1, "ri3i9vi", N_RESUME, ci->clientnum,
gs.state, gs.frags, gs.flags, gs.quadmillis,
gs.lifesequence,
gs.health, gs.maxhealth,
gs.armour, gs.armourtype,
gs.gunselect, GUN_PISTOL-GUN_SG+1, &gs.ammo[GUN_SG], -1);
}
void sendinitclient(clientinfo *ci)
{
packetbuf p(MAXTRANS, ENET_PACKET_FLAG_RELIABLE);
putinitclient(ci, p);
sendpacket(-1, 1, p.finalize(), ci->clientnum);
}
void loaditems()
{
resetitems();
notgotitems = true;
if(m_edit || !loadents(smapname, ments, &mcrc))
return;
loopv(ments) if(canspawnitem(ments[i].type))
{
server_entity se = { NOTUSED, 0, false };
while(sents.length()<=i) sents.add(se);
sents[i].type = ments[i].type;
if(m_mp(gamemode) && delayspawn(sents[i].type)) sents[i].spawntime = spawntime(sents[i].type);
else sents[i].spawned = true;
}
notgotitems = false;
}
void changemap(const char *s, int mode)
{
stopdemo();
pausegame(false);
changegamespeed(100);
if(smode) smode->cleanup();
aiman::clearai();
gamemode = mode;
gamemillis = 0;
gamelimit = (m_overtime ? 15 : 10)*60000;
interm = 0;
nextexceeded = 0;
copystring(smapname, s);
loaditems();
scores.shrink(0);
shouldcheckteamkills = false;
teamkills.shrink(0);
loopv(clients)
{
clientinfo *ci = clients[i];
ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed;
}
if(!m_mp(gamemode)) kicknonlocalclients(DISC_LOCAL);
sendf(-1, 1, "risii", N_MAPCHANGE, smapname, gamemode, 1);
clearteaminfo();
if(m_teammode) autoteam();
if(m_capture) smode = &capturemode;
else if(m_ctf) smode = &ctfmode;
else if(m_collect) smode = &collectmode;
else smode = NULL;
if(m_timed && smapname[0]) sendf(-1, 1, "ri2", N_TIMEUP, gamemillis < gamelimit && !interm ? max((gamelimit - gamemillis)/1000, 1) : 0);
loopv(clients)
{
clientinfo *ci = clients[i];
ci->mapchange();
ci->state.lasttimeplayed = lastmillis;
if(m_mp(gamemode) && ci->state.state!=CS_SPECTATOR) sendspawn(ci);
}
aiman::changemap();
if(m_demo)
{
if(clients.length()) setupdemoplayback();
}
else if(demonextmatch)
{
demonextmatch = false;
setupdemorecord();
}
if(smode) smode->setup();
}
void rotatemap(bool next)
{
if(!maprotations.inrange(curmaprotation))
{
changemap("", 1);
return;
}
if(next)
{
curmaprotation = findmaprotation(gamemode, smapname);
if(curmaprotation >= 0) nextmaprotation();
else curmaprotation = smapname[0] ? max(findmaprotation(gamemode, ""), 0) : 0;
}
maprotation &rot = maprotations[curmaprotation];
changemap(rot.map, rot.findmode(gamemode));
}
struct votecount
{
char *map;
int mode, count;
votecount() {}
votecount(char *s, int n) : map(s), mode(n), count(0) {}
};
void checkvotes(bool force = false)
{
vector<votecount> votes;
int maxvotes = 0;
loopv(clients)
{
clientinfo *oi = clients[i];
if(oi->state.state==CS_SPECTATOR && !oi->privilege && !oi->local) continue;
if(oi->state.aitype!=AI_NONE) continue;
maxvotes++;
if(!m_valid(oi->modevote)) continue;
votecount *vc = NULL;
loopvj(votes) if(!strcmp(oi->mapvote, votes[j].map) && oi->modevote==votes[j].mode)
{
vc = &votes[j];
break;
}
if(!vc) vc = &votes.add(votecount(oi->mapvote, oi->modevote));
vc->count++;
}
votecount *best = NULL;
loopv(votes) if(!best || votes[i].count > best->count || (votes[i].count == best->count && rnd(2))) best = &votes[i];
if(force || (best && best->count > maxvotes/2))
{
if(demorecord) enddemorecord();
if(best && (best->count > (force ? 1 : maxvotes/2)))
{
sendservmsg(force ? "vote passed by default" : "vote passed by majority");
changemap(best->map, best->mode);
}
else rotatemap(true);
}
}
void forcemap(const char *map, int mode)
{
stopdemo();
if(!map[0] && !m_check(mode, M_EDIT))
{
int idx = findmaprotation(mode, smapname);
if(idx < 0 && smapname[0]) idx = findmaprotation(mode, "");
if(idx < 0) return;
map = maprotations[idx].map;
}
if(hasnonlocalclients()) sendservmsgf("local player forced %s on map %s", modename(mode), map[0] ? map : "[new map]");
changemap(map, mode);
}
void vote(const char *map, int reqmode, int sender)
{
clientinfo *ci = getinfo(sender);
if(!ci || (ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || (!ci->local && !m_mp(reqmode))) return;
if(!m_valid(reqmode)) return;
if(!map[0] && !m_check(reqmode, M_EDIT))
{
int idx = findmaprotation(reqmode, smapname);
if(idx < 0 && smapname[0]) idx = findmaprotation(reqmode, "");
if(idx < 0) return;
map = maprotations[idx].map;
}
if(lockmaprotation && !ci->local && ci->privilege < (lockmaprotation > 1 ? PRIV_ADMIN : PRIV_MASTER) && findmaprotation(reqmode, map) < 0)
{
sendf(sender, 1, "ris", N_SERVMSG, "This server has locked the map rotation.");
return;
}
copystring(ci->mapvote, map);
ci->modevote = reqmode;
if(ci->local || (ci->privilege && mastermode>=MM_VETO))
{
if(demorecord) enddemorecord();
if(!ci->local || hasnonlocalclients())
sendservmsgf("%s forced %s on map %s", colorname(ci), modename(ci->modevote), ci->mapvote[0] ? ci->mapvote : "[new map]");
changemap(ci->mapvote, ci->modevote);
}
else
{
sendservmsgf("%s suggests %s on map %s (select map to vote)", colorname(ci), modename(reqmode), map[0] ? map : "[new map]");
checkvotes();
}
}
void checkintermission()
{
if(gamemillis >= gamelimit && !interm)
{
sendf(-1, 1, "ri2", N_TIMEUP, 0);
if(smode) smode->intermission();
changegamespeed(100);
interm = gamemillis + 10000;
}
}
void startintermission() { gamelimit = min(gamelimit, gamemillis); checkintermission(); }
void dodamage(clientinfo *target, clientinfo *actor, int damage, int gun, const vec &hitpush = vec(0, 0, 0))
{
gamestate &ts = target->state;
ts.dodamage(damage);
if(target!=actor && !isteam(target->team, actor->team)) actor->state.damage += damage;
sendf(-1, 1, "ri6", N_DAMAGE, target->clientnum, actor->clientnum, damage, ts.armour, ts.health);
if(target==actor) target->setpushed();
else if(!hitpush.iszero())
{
ivec v = vec(hitpush).rescale(DNF);
sendf(ts.health<=0 ? -1 : target->ownernum, 1, "ri7", N_HITPUSH, target->clientnum, gun, damage, v.x, v.y, v.z);
target->setpushed();
}
if(ts.health<=0)
{
target->state.deaths++;
int fragvalue = smode ? smode->fragvalue(target, actor) : (target==actor || isteam(target->team, actor->team) ? -1 : 1);
actor->state.frags += fragvalue;
if(fragvalue>0)
{
int friends = 0, enemies = 0; // note: friends also includes the fragger
if(m_teammode) loopv(clients) if(strcmp(clients[i]->team, actor->team)) enemies++; else friends++;
else { friends = 1; enemies = clients.length()-1; }
actor->state.effectiveness += fragvalue*friends/float(max(enemies, 1));
}
teaminfo *t = m_teammode ? teaminfos.access(actor->team) : NULL;
if(t) t->frags += fragvalue;
sendf(-1, 1, "ri5", N_DIED, target->clientnum, actor->clientnum, actor->state.frags, t ? t->frags : 0);
target->position.setsize(0);
if(smode) smode->died(target, actor);
ts.state = CS_DEAD;
ts.lastdeath = gamemillis;
if(actor!=target && isteam(actor->team, target->team))
{
actor->state.teamkills++;
addteamkill(actor, target, 1);
}
ts.deadflush = ts.lastdeath + DEATHMILLIS;
// don't issue respawn yet until DEATHMILLIS has elapsed
// ts.respawn();
}
}
void suicide(clientinfo *ci)
{
gamestate &gs = ci->state;
if(gs.state!=CS_ALIVE) return;
int fragvalue = smode ? smode->fragvalue(ci, ci) : -1;
ci->state.frags += fragvalue;
ci->state.deaths++;
teaminfo *t = m_teammode ? teaminfos.access(ci->team) : NULL;
if(t) t->frags += fragvalue;
sendf(-1, 1, "ri5", N_DIED, ci->clientnum, ci->clientnum, gs.frags, t ? t->frags : 0);
ci->position.setsize(0);
if(smode) smode->died(ci, NULL);
gs.state = CS_DEAD;
gs.lastdeath = gamemillis;
gs.respawn();
}
void suicideevent::process(clientinfo *ci)
{
suicide(ci);
}
void explodeevent::process(clientinfo *ci)
{
gamestate &gs = ci->state;
switch(gun)
{
case GUN_RL:
if(!gs.rockets.remove(id)) return;
break;
case GUN_GL:
if(!gs.grenades.remove(id)) return;
break;
default:
return;
}
sendf(-1, 1, "ri4x", N_EXPLODEFX, ci->clientnum, gun, id, ci->ownernum);
loopv(hits)
{
hitinfo &h = hits[i];
clientinfo *target = getinfo(h.target);
if(!target || target->state.state!=CS_ALIVE || h.lifesequence!=target->state.lifesequence || h.dist<0 || h.dist>guns[gun].exprad) continue;
bool dup = false;
loopj(i) if(hits[j].target==h.target) { dup = true; break; }
if(dup) continue;
int damage = guns[gun].damage;
if(gs.quadmillis) damage *= 4;
damage = int(damage*(1-h.dist/EXP_DISTSCALE/guns[gun].exprad));
if(target==ci) damage /= EXP_SELFDAMDIV;
dodamage(target, ci, damage, gun, h.dir);
}
}
void shotevent::process(clientinfo *ci)
{
gamestate &gs = ci->state;
int wait = millis - gs.lastshot;
if(!gs.isalive(gamemillis) ||
wait<gs.gunwait ||
gun<GUN_FIST || gun>GUN_PISTOL ||
gs.ammo[gun]<=0 || (guns[gun].range && from.dist(to) > guns[gun].range + 1))
return;
if(gun!=GUN_FIST) gs.ammo[gun]--;
gs.lastshot = millis;
gs.gunwait = guns[gun].attackdelay;
sendf(-1, 1, "rii9x", N_SHOTFX, ci->clientnum, gun, id,
int(from.x*DMF), int(from.y*DMF), int(from.z*DMF),
int(to.x*DMF), int(to.y*DMF), int(to.z*DMF),
ci->ownernum);
gs.shotdamage += guns[gun].damage*(gs.quadmillis ? 4 : 1)*guns[gun].rays;
switch(gun)
{
case GUN_RL: gs.rockets.add(id); break;
case GUN_GL: gs.grenades.add(id); break;
default:
{
int totalrays = 0, maxrays = guns[gun].rays;
loopv(hits)
{
hitinfo &h = hits[i];
clientinfo *target = getinfo(h.target);
if(!target || target->state.state!=CS_ALIVE || h.lifesequence!=target->state.lifesequence || h.rays<1 || h.dist > guns[gun].range + 1) continue;
totalrays += h.rays;
if(totalrays>maxrays) continue;
int damage = h.rays*guns[gun].damage;
if(gs.quadmillis) damage *= 4;
dodamage(target, ci, damage, gun, h.dir);
}
break;
}
}
}
void pickupevent::process(clientinfo *ci)
{
gamestate &gs = ci->state;
if(m_mp(gamemode) && !gs.isalive(gamemillis)) return;
pickup(ent, ci->clientnum);
}
bool gameevent::flush(clientinfo *ci, int fmillis)
{
process(ci);
return true;
}
bool timedevent::flush(clientinfo *ci, int fmillis)
{
if(millis > fmillis) return false;
else if(millis >= ci->lastevent)
{
ci->lastevent = millis;
process(ci);
}
return true;
}
void clearevent(clientinfo *ci)
{
delete ci->events.remove(0);
}
void flushevents(clientinfo *ci, int millis)
{
while(ci->events.length())
{
gameevent *ev = ci->events[0];
if(ev->flush(ci, millis)) clearevent(ci);
else break;
}
}
void processevents(int curtime)
{
loopv(clients)
{
clientinfo *ci = clients[i];
if(curtime>0 && ci->state.quadmillis) ci->state.quadmillis = max(ci->state.quadmillis-curtime, 0);
flushevents(ci, gamemillis);
}
}
void cleartimedevents(clientinfo *ci)
{
int keep = 0;
loopv(ci->events)
{
if(ci->events[i]->keepable())
{
if(keep < i)
{
for(int j = keep; j < i; j++) delete ci->events[j];
ci->events.remove(keep, i - keep);
i = keep;
}
keep = i+1;
continue;
}
}
while(ci->events.length() > keep) delete ci->events.pop();
ci->timesync = false;
}
void serverupdate()
{
emulatecurtime;
if(shouldstep && !gamepaused)
{
gamemillis += curtime;
if(m_demo) readdemo(curtime);
else if(!m_timed || gamemillis < gamelimit)
{
processevents(curtime);
if(curtime)
{
loopv(sents) if(sents[i].spawntime) // spawn entities when timer reached
{
int oldtime = sents[i].spawntime;
sents[i].spawntime -= curtime;
if(sents[i].spawntime<=0)
{
sents[i].spawntime = 0;
sents[i].spawned = true;
sendf(-1, 1, "ri2", N_ITEMSPAWN, i);
}
else if(sents[i].spawntime<=10000 && oldtime>10000 && (sents[i].type==I_QUAD || sents[i].type==I_BOOST))
{
sendf(-1, 1, "ri2", N_ANNOUNCE, sents[i].type);
}
}
}
aiman::checkai();
if(smode) smode->update();
}
}
while(bannedips.length() && bannedips[0].expire-totalmillis <= 0) bannedips.remove(0);
loopv(connects) if(totalmillis-connects[i]->connectmillis>15000) disconnect_client(connects[i]->clientnum, DISC_TIMEOUT);
if(nextexceeded && gamemillis > nextexceeded && (!m_timed || gamemillis < gamelimit))
{
nextexceeded = 0;
loopvrev(clients)
{
clientinfo &c = *clients[i];
if(c.state.aitype != AI_NONE) continue;
if(c.checkexceeded()) disconnect_client(c.clientnum, DISC_MSGERR);
else c.scheduleexceeded();
}
}
if(shouldcheckteamkills) checkteamkills();
if(shouldstep && !gamepaused)
{
if(m_timed && smapname[0] && gamemillis-curtime>0) checkintermission();
if(interm > 0 && gamemillis>interm)
{
if(demorecord) enddemorecord();
interm = -1;
checkvotes(true);
}
}
shouldstep = clients.length() > 0;
}
void forcespectator(clientinfo *ci)
{
if(ci->state.state==CS_ALIVE) suicide(ci);
if(smode) smode->leavegame(ci);
ci->state.state = CS_SPECTATOR;
ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed;
if(!ci->local && (!ci->privilege || ci->warned)) aiman::removeai(ci);
sendf(-1, 1, "ri3", N_SPECTATOR, ci->clientnum, 1);
}
struct crcinfo
{
int crc, matches;
crcinfo() {}
crcinfo(int crc, int matches) : crc(crc), matches(matches) {}
static bool compare(const crcinfo &x, const crcinfo &y) { return x.matches > y.matches; }
};
VAR(modifiedmapspectator, 0, 1, 2);
void checkmaps(int req = -1)
{
if(m_edit || !smapname[0]) return;
vector<crcinfo> crcs;
int total = 0, unsent = 0, invalid = 0;
if(mcrc) crcs.add(crcinfo(mcrc, clients.length() + 1));
loopv(clients)
{
clientinfo *ci = clients[i];
if(ci->state.state==CS_SPECTATOR || ci->state.aitype != AI_NONE) continue;
total++;
if(!ci->clientmap[0])
{
if(ci->mapcrc < 0) invalid++;
else if(!ci->mapcrc) unsent++;
}
else
{
crcinfo *match = NULL;
loopvj(crcs) if(crcs[j].crc == ci->mapcrc) { match = &crcs[j]; break; }
if(!match) crcs.add(crcinfo(ci->mapcrc, 1));
else match->matches++;
}
}
if(!mcrc && total - unsent < min(total, 4)) return;
crcs.sort(crcinfo::compare);
string msg;
loopv(clients)
{
clientinfo *ci = clients[i];
if(ci->state.state==CS_SPECTATOR || ci->state.aitype != AI_NONE || ci->clientmap[0] || ci->mapcrc >= 0 || (req < 0 && ci->warned)) continue;
formatstring(msg)("%s has modified map \"%s\"", colorname(ci), smapname);
sendf(req, 1, "ris", N_SERVMSG, msg);
if(req < 0) ci->warned = true;
}
if(crcs.length() >= 2) loopv(crcs)
{
crcinfo &info = crcs[i];
if(i || info.matches <= crcs[i+1].matches) loopvj(clients)
{
clientinfo *ci = clients[j];
if(ci->state.state==CS_SPECTATOR || ci->state.aitype != AI_NONE || !ci->clientmap[0] || ci->mapcrc != info.crc || (req < 0 && ci->warned)) continue;
formatstring(msg)("%s has modified map \"%s\"", colorname(ci), smapname);
sendf(req, 1, "ris", N_SERVMSG, msg);
if(req < 0) ci->warned = true;
}
}
if(req < 0 && modifiedmapspectator && (mcrc || modifiedmapspectator > 1)) loopv(clients)
{
clientinfo *ci = clients[i];
if(!ci->local && ci->warned && ci->state.state != CS_SPECTATOR) forcespectator(ci);
}
}
bool shouldspectate(clientinfo *ci)
{
return !ci->local && ci->warned && modifiedmapspectator && (mcrc || modifiedmapspectator > 1);
}
void unspectate(clientinfo *ci)
{
if(shouldspectate(ci)) return;
ci->state.state = CS_DEAD;
ci->state.respawn();
ci->state.lasttimeplayed = lastmillis;
aiman::addclient(ci);
if(ci->clientmap[0] || ci->mapcrc) checkmaps();
sendf(-1, 1, "ri3", N_SPECTATOR, ci->clientnum, 0);
if(!hasmap(ci)) rotatemap(true);
}
void sendservinfo(clientinfo *ci)
{
sendf(ci->clientnum, 1, "ri5ss", N_SERVINFO, ci->clientnum, PROTOCOL_VERSION, ci->sessionid, serverpass[0] ? 1 : 0, serverdesc, serverauth);
}
void noclients()
{
bannedips.shrink(0);
aiman::clearai();
}
void localconnect(int n)
{
clientinfo *ci = getinfo(n);
ci->clientnum = ci->ownernum = n;
ci->connectmillis = totalmillis;
ci->sessionid = (rnd(0x1000000)*((totalmillis%10000)+1))&0xFFFFFF;
ci->local = true;
connects.add(ci);
sendservinfo(ci);
}
void localdisconnect(int n)
{
if(m_demo) enddemoplayback();
clientdisconnect(n);
}
int clientconnect(int n, uint ip)
{
clientinfo *ci = getinfo(n);
ci->clientnum = ci->ownernum = n;
ci->connectmillis = totalmillis;
ci->sessionid = (rnd(0x1000000)*((totalmillis%10000)+1))&0xFFFFFF;
connects.add(ci);
if(!m_mp(gamemode)) return DISC_LOCAL;
sendservinfo(ci);
return DISC_NONE;
}
void clientdisconnect(int n)
{
clientinfo *ci = getinfo(n);
loopv(clients) if(clients[i]->authkickvictim == ci->clientnum) clients[i]->cleanauth();
if(ci->connected)
{
if(ci->privilege) setmaster(ci, false);
if(smode) smode->leavegame(ci, true);
ci->state.timeplayed += lastmillis - ci->state.lasttimeplayed;
savescore(ci);
sendf(-1, 1, "ri2", N_CDIS, n);
clients.removeobj(ci);
aiman::removeai(ci);
if(!numclients(-1, false, true)) noclients(); // bans clear when server empties
if(ci->local) checkpausegame();
}
else connects.removeobj(ci);
}
int reserveclients() { return 3; }
struct gbaninfo
{
enet_uint32 ip, mask;
};
vector<gbaninfo> gbans;
void cleargbans()
{
gbans.shrink(0);
}
bool checkgban(uint ip)
{
loopv(gbans) if((ip & gbans[i].mask) == gbans[i].ip) return true;
return false;
}
void addgban(const char *name)
{
union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ip, mask;
ip.i = 0;
mask.i = 0;
loopi(4)
{
char *end = NULL;
int n = strtol(name, &end, 10);
if(!end) break;
if(end > name) { ip.b[i] = n; mask.b[i] = 0xFF; }
name = end;
while(*name && *name++ != '.');
}
gbaninfo &ban = gbans.add();
ban.ip = ip.i;
ban.mask = mask.i;
loopvrev(clients)
{
clientinfo *ci = clients[i];
if(ci->state.aitype != AI_NONE || ci->local || ci->privilege >= PRIV_ADMIN) continue;
if(checkgban(getclientip(ci->clientnum))) disconnect_client(ci->clientnum, DISC_IPBAN);
}
}
int allowconnect(clientinfo *ci, const char *pwd = "")
{
if(ci->local) return DISC_NONE;
if(!m_mp(gamemode)) return DISC_LOCAL;
if(serverpass[0])
{
if(!checkpassword(ci, serverpass, pwd)) return DISC_PASSWORD;
return DISC_NONE;
}
if(adminpass[0] && checkpassword(ci, adminpass, pwd)) return DISC_NONE;
if(numclients(-1, false, true)>=maxclients) return DISC_MAXCLIENTS;
uint ip = getclientip(ci->clientnum);
loopv(bannedips) if(bannedips[i].ip==ip) return DISC_IPBAN;
if(checkgban(ip)) return DISC_IPBAN;
if(mastermode>=MM_PRIVATE && allowedips.find(ip)<0) return DISC_PRIVATE;
return DISC_NONE;
}
bool allowbroadcast(int n)
{
clientinfo *ci = getinfo(n);
return ci && ci->connected;
}
clientinfo *findauth(uint id)
{
loopv(clients) if(clients[i]->authreq == id) return clients[i];
return NULL;
}
void authfailed(clientinfo *ci)
{
if(!ci) return;
ci->cleanauth();
if(ci->connectauth) disconnect_client(ci->clientnum, ci->connectauth);
}
void authfailed(uint id)
{
authfailed(findauth(id));
}
void authsucceeded(uint id)
{
clientinfo *ci = findauth(id);
if(!ci) return;
ci->cleanauth(ci->connectauth!=0);
if(ci->connectauth) connected(ci);
if(ci->authkickvictim >= 0)
{
if(setmaster(ci, true, "", ci->authname, NULL, PRIV_AUTH, false, true))
trykick(ci, ci->authkickvictim, ci->authkickreason, ci->authname, NULL, PRIV_AUTH);
ci->cleanauthkick();
}
else setmaster(ci, true, "", ci->authname, NULL, PRIV_AUTH);
}
void authchallenged(uint id, const char *val, const char *desc = "")
{
clientinfo *ci = findauth(id);
if(!ci) return;
sendf(ci->clientnum, 1, "risis", N_AUTHCHAL, desc, id, val);
}
uint nextauthreq = 0;
bool tryauth(clientinfo *ci, const char *user, const char *desc)
{
ci->cleanauth();
if(!nextauthreq) nextauthreq = 1;
ci->authreq = nextauthreq++;
filtertext(ci->authname, user, false, 100);
copystring(ci->authdesc, desc);
if(ci->authdesc[0])
{
userinfo *u = users.access(userkey(ci->authname, ci->authdesc));
if(u)
{
uint seed[3] = { ::hthash(serverauth) + detrnd(size_t(ci) + size_t(user) + size_t(desc), 0x10000), uint(totalmillis), randomMT() };
vector<char> buf;
ci->authchallenge = genchallenge(u->pubkey, seed, sizeof(seed), buf);
sendf(ci->clientnum, 1, "risis", N_AUTHCHAL, desc, ci->authreq, buf.getbuf());
}
else ci->cleanauth();
}
else if(!requestmasterf("reqauth %u %s\n", ci->authreq, ci->authname))
{
ci->cleanauth();
sendf(ci->clientnum, 1, "ris", N_SERVMSG, "not connected to authentication server");
}
if(ci->authreq) return true;
if(ci->connectauth) disconnect_client(ci->clientnum, ci->connectauth);
return false;
}
bool answerchallenge(clientinfo *ci, uint id, char *val, const char *desc)
{
if(ci->authreq != id || strcmp(ci->authdesc, desc))
{
ci->cleanauth();
return !ci->connectauth;
}
for(char *s = val; *s; s++)
{
if(!isxdigit(*s)) { *s = '\0'; break; }
}
if(desc[0])
{
if(ci->authchallenge && checkchallenge(val, ci->authchallenge))
{
userinfo *u = users.access(userkey(ci->authname, ci->authdesc));
if(u)
{
if(ci->connectauth) connected(ci);
if(ci->authkickvictim >= 0)
{
if(setmaster(ci, true, "", ci->authname, ci->authdesc, u->privilege, false, true))
trykick(ci, ci->authkickvictim, ci->authkickreason, ci->authname, ci->authdesc, u->privilege);
}
else setmaster(ci, true, "", ci->authname, ci->authdesc, u->privilege);
}
}
ci->cleanauth();
}
else if(!requestmasterf("confauth %u %s\n", id, val))
{
ci->cleanauth();
sendf(ci->clientnum, 1, "ris", N_SERVMSG, "not connected to authentication server");
}
return ci->authreq || !ci->connectauth;
}
void masterconnected()
{
}
void masterdisconnected()
{
loopvrev(clients)
{
clientinfo *ci = clients[i];
if(ci->authreq) authfailed(ci);
}
}
void processmasterinput(const char *cmd, int cmdlen, const char *args)
{
uint id;
string val;
if(sscanf(cmd, "failauth %u", &id) == 1)
authfailed(id);
else if(sscanf(cmd, "succauth %u", &id) == 1)
authsucceeded(id);
else if(sscanf(cmd, "chalauth %u %255s", &id, val) == 2)
authchallenged(id, val);
else if(!strncmp(cmd, "cleargbans", cmdlen))
cleargbans();
else if(sscanf(cmd, "addgban %100s", val) == 1)
addgban(val);
}
void receivefile(int sender, uchar *data, int len)
{
if(!m_edit || len > 4*1024*1024) return;
clientinfo *ci = getinfo(sender);
if(ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) return;
if(mapdata) DELETEP(mapdata);
if(!len) return;
mapdata = opentempfile("mapdata", "w+b");
if(!mapdata) { sendf(sender, 1, "ris", N_SERVMSG, "failed to open temporary file for map"); return; }
mapdata->write(data, len);
sendservmsgf("[%s sent a map to server, \"/getmap\" to receive it]", colorname(ci));
}
void sendclipboard(clientinfo *ci)
{
if(!ci->lastclipboard || !ci->clipboard) return;
bool flushed = false;
loopv(clients)
{
clientinfo &e = *clients[i];
if(e.clientnum != ci->clientnum && e.needclipboard - ci->lastclipboard >= 0)
{
if(!flushed) { flushserver(true); flushed = true; }
sendpacket(e.clientnum, 1, ci->clipboard);
}
}
}
void connected(clientinfo *ci)
{
if(m_demo) enddemoplayback();
if(!hasmap(ci)) rotatemap(false);
shouldstep = true;
connects.removeobj(ci);
clients.add(ci);
ci->connectauth = 0;
ci->connected = true;
ci->needclipboard = totalmillis ? totalmillis : 1;
if(mastermode>=MM_LOCKED) ci->state.state = CS_SPECTATOR;
ci->state.lasttimeplayed = lastmillis;
const char *worst = m_teammode ? chooseworstteam(NULL, ci) : NULL;
copystring(ci->team, worst ? worst : "good", MAXTEAMLEN+1);
sendwelcome(ci);
if(restorescore(ci)) sendresume(ci);
sendinitclient(ci);
aiman::addclient(ci);
if(m_demo) setupdemoplayback();
if(servermotd[0]) sendf(ci->clientnum, 1, "ris", N_SERVMSG, servermotd);
}
void parsepacket(int sender, int chan, packetbuf &p) // has to parse exactly each byte of the packet
{
if(sender<0 || p.packet->flags&ENET_PACKET_FLAG_UNSEQUENCED || chan > 2) return;
char text[MAXTRANS];
int type;
clientinfo *ci = sender>=0 ? getinfo(sender) : NULL, *cq = ci, *cm = ci;
if(ci && !ci->connected)
{
if(chan==0) return;
else if(chan!=1) { disconnect_client(sender, DISC_MSGERR); return; }
else while(p.length() < p.maxlen) switch(checktype(getint(p), ci))
{
case N_CONNECT:
{
getstring(text, p);
filtertext(text, text, false, MAXNAMELEN);
if(!text[0]) copystring(text, "unnamed");
copystring(ci->name, text, MAXNAMELEN+1);
ci->playermodel = getint(p);
string password, authdesc, authname;
getstring(password, p, sizeof(password));
getstring(authdesc, p, sizeof(authdesc));
getstring(authname, p, sizeof(authname));
int disc = allowconnect(ci, password);
if(disc)
{
if(disc == DISC_LOCAL || !serverauth[0] || strcmp(serverauth, authdesc) || !tryauth(ci, authname, authdesc))
{
disconnect_client(sender, disc);
return;
}
ci->connectauth = disc;
}
else connected(ci);
break;
}
case N_AUTHANS:
{
string desc, ans;
getstring(desc, p, sizeof(desc));
uint id = (uint)getint(p);
getstring(ans, p, sizeof(ans));
if(!answerchallenge(ci, id, ans, desc))
{
disconnect_client(sender, ci->connectauth);
return;
}
break;
}
case N_PING:
getint(p);
break;
default:
disconnect_client(sender, DISC_MSGERR);
return;
}
return;
}
else if(chan==2)
{
receivefile(sender, p.buf, p.maxlen);
return;
}
if(p.packet->flags&ENET_PACKET_FLAG_RELIABLE) reliablemessages = true;
#define QUEUE_AI clientinfo *cm = cq;
#define QUEUE_MSG { if(cm && (!cm->local || demorecord || hasnonlocalclients())) while(curmsg<p.length()) cm->messages.add(p.buf[curmsg++]); }
#define QUEUE_BUF(body) { \
if(cm && (!cm->local || demorecord || hasnonlocalclients())) \
{ \
curmsg = p.length(); \
{ body; } \
} \
}
#define QUEUE_INT(n) QUEUE_BUF(putint(cm->messages, n))
#define QUEUE_UINT(n) QUEUE_BUF(putuint(cm->messages, n))
#define QUEUE_STR(text) QUEUE_BUF(sendstring(text, cm->messages))
int curmsg;
while((curmsg = p.length()) < p.maxlen) switch(type = checktype(getint(p), ci))
{
case N_POS:
{
int pcn = getuint(p);
p.get();
uint flags = getuint(p);
clientinfo *cp = getinfo(pcn);
if(cp && pcn != sender && cp->ownernum != sender) cp = NULL;
vec pos;
loopk(3)
{
int n = p.get(); n |= p.get()<<8; if(flags&(1<<k)) { n |= p.get()<<16; if(n&0x800000) n |= -1<<24; }
pos[k] = n/DMF;
}
loopk(3) p.get();
int mag = p.get(); if(flags&(1<<3)) mag |= p.get()<<8;
int dir = p.get(); dir |= p.get()<<8;
vec vel = vec((dir%360)*RAD, (clamp(dir/360, 0, 180)-90)*RAD).mul(mag/DVELF);
if(flags&(1<<4))
{
p.get(); if(flags&(1<<5)) p.get();
if(flags&(1<<6)) loopk(2) p.get();
}
if(cp)
{
if((!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING))
{
if(!ci->local && !m_edit && max(vel.magnitude2(), (float)fabs(vel.z)) >= 180)
cp->setexceeded();
cp->position.setsize(0);
while(curmsg<p.length()) cp->position.add(p.buf[curmsg++]);
}
if(smode && cp->state.state==CS_ALIVE) smode->moved(cp, cp->state.o, cp->gameclip, pos, (flags&0x80)!=0);
cp->state.o = pos;
cp->gameclip = (flags&0x80)!=0;
}
break;
}
case N_TELEPORT:
{
int pcn = getint(p), teleport = getint(p), teledest = getint(p);
clientinfo *cp = getinfo(pcn);
if(cp && pcn != sender && cp->ownernum != sender) cp = NULL;
if(cp && (!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING))
{
flushclientposition(*cp);
sendf(-1, 0, "ri4x", N_TELEPORT, pcn, teleport, teledest, cp->ownernum);
}
break;
}
case N_JUMPPAD:
{
int pcn = getint(p), jumppad = getint(p);
clientinfo *cp = getinfo(pcn);
if(cp && pcn != sender && cp->ownernum != sender) cp = NULL;
if(cp && (!ci->local || demorecord || hasnonlocalclients()) && (cp->state.state==CS_ALIVE || cp->state.state==CS_EDITING))
{
cp->setpushed();
flushclientposition(*cp);
sendf(-1, 0, "ri3x", N_JUMPPAD, pcn, jumppad, cp->ownernum);
}
break;
}
case N_FROMAI:
{
int qcn = getint(p);
if(qcn < 0) cq = ci;
else
{
cq = getinfo(qcn);
if(cq && qcn != sender && cq->ownernum != sender) cq = NULL;
}
break;
}
case N_EDITMODE:
{
int val = getint(p);
if(!ci->local && !m_edit) break;
if(val ? ci->state.state!=CS_ALIVE && ci->state.state!=CS_DEAD : ci->state.state!=CS_EDITING) break;
if(smode)
{
if(val) smode->leavegame(ci);
else smode->entergame(ci);
}
if(val)
{
ci->state.editstate = ci->state.state;
ci->state.state = CS_EDITING;
ci->events.setsize(0);
ci->state.rockets.reset();
ci->state.grenades.reset();
}
else ci->state.state = ci->state.editstate;
QUEUE_MSG;
break;
}
case N_MAPCRC:
{
getstring(text, p);
int crc = getint(p);
if(!ci) break;
if(strcmp(text, smapname))
{
if(ci->clientmap[0])
{
ci->clientmap[0] = '\0';
ci->mapcrc = 0;
}
else if(ci->mapcrc > 0) ci->mapcrc = 0;
break;
}
copystring(ci->clientmap, text);
ci->mapcrc = text[0] ? crc : 1;
checkmaps();
if(cq && cq != ci && cq->ownernum != ci->clientnum) cq = NULL;
break;
}
case N_CHECKMAPS:
checkmaps(sender);
break;
case N_TRYSPAWN:
if(!ci || !cq || cq->state.state!=CS_DEAD || cq->state.lastspawn>=0 || (smode && !smode->canspawn(cq))) break;
if(!ci->clientmap[0] && !ci->mapcrc)
{
ci->mapcrc = -1;
checkmaps();
if(ci == cq) { if(ci->state.state != CS_DEAD) break; }
else if(cq->ownernum != ci->clientnum) { cq = NULL; break; }
}
if(cq->state.deadflush)
{
flushevents(cq, cq->state.deadflush);
cq->state.respawn();
}
cleartimedevents(cq);
sendspawn(cq);
break;
case N_GUNSELECT:
{
int gunselect = getint(p);
if(!cq || cq->state.state!=CS_ALIVE) break;
cq->state.gunselect = gunselect >= GUN_FIST && gunselect <= GUN_PISTOL ? gunselect : GUN_FIST;
QUEUE_AI;
QUEUE_MSG;
break;
}
case N_SPAWN:
{
int ls = getint(p), gunselect = getint(p);
if(!cq || (cq->state.state!=CS_ALIVE && cq->state.state!=CS_DEAD) || ls!=cq->state.lifesequence || cq->state.lastspawn<0) break;
cq->state.lastspawn = -1;
cq->state.state = CS_ALIVE;
cq->state.gunselect = gunselect >= GUN_FIST && gunselect <= GUN_PISTOL ? gunselect : GUN_FIST;
cq->exceeded = 0;
if(smode) smode->spawned(cq);
QUEUE_AI;
QUEUE_BUF({
putint(cm->messages, N_SPAWN);
sendstate(cq->state, cm->messages);
});
break;
}
case N_SUICIDE:
{
if(cq) cq->addevent(new suicideevent);
break;
}
case N_SHOOT:
{
shotevent *shot = new shotevent;
shot->id = getint(p);
shot->millis = cq ? cq->geteventmillis(gamemillis, shot->id) : 0;
shot->gun = getint(p);
loopk(3) shot->from[k] = getint(p)/DMF;
loopk(3) shot->to[k] = getint(p)/DMF;
int hits = getint(p);
loopk(hits)
{
if(p.overread()) break;
hitinfo &hit = shot->hits.add();
hit.target = getint(p);
hit.lifesequence = getint(p);
hit.dist = getint(p)/DMF;
hit.rays = getint(p);
loopk(3) hit.dir[k] = getint(p)/DNF;
}
if(cq)
{
cq->addevent(shot);
cq->setpushed();
}
else delete shot;
break;
}
case N_EXPLODE:
{
explodeevent *exp = new explodeevent;
int cmillis = getint(p);
exp->millis = cq ? cq->geteventmillis(gamemillis, cmillis) : 0;
exp->gun = getint(p);
exp->id = getint(p);
int hits = getint(p);
loopk(hits)
{
if(p.overread()) break;
hitinfo &hit = exp->hits.add();
hit.target = getint(p);
hit.lifesequence = getint(p);
hit.dist = getint(p)/DMF;
hit.rays = getint(p);
loopk(3) hit.dir[k] = getint(p)/DNF;
}
if(cq) cq->addevent(exp);
else delete exp;
break;
}
case N_ITEMPICKUP:
{
int n = getint(p);
if(!cq) break;
pickupevent *pickup = new pickupevent;
pickup->ent = n;
cq->addevent(pickup);
break;
}
case N_TEXT:
{
QUEUE_AI;
QUEUE_MSG;
getstring(text, p);
filtertext(text, text);
QUEUE_STR(text);
if(isdedicatedserver() && cq) logoutf("%s: %s", colorname(cq), text);
break;
}
case N_SAYTEAM:
{
getstring(text, p);
if(!ci || !cq || (ci->state.state==CS_SPECTATOR && !ci->local && !ci->privilege) || !m_teammode || !cq->team[0]) break;
loopv(clients)
{
clientinfo *t = clients[i];
if(t==cq || t->state.state==CS_SPECTATOR || t->state.aitype != AI_NONE || strcmp(cq->team, t->team)) continue;
sendf(t->clientnum, 1, "riis", N_SAYTEAM, cq->clientnum, text);
}
if(isdedicatedserver() && cq) logoutf("%s <%s>: %s", colorname(cq), cq->team, text);
break;
}
case N_SWITCHNAME:
{
QUEUE_MSG;
getstring(text, p);
filtertext(ci->name, text, false, MAXNAMELEN);
if(!ci->name[0]) copystring(ci->name, "unnamed");
QUEUE_STR(ci->name);
break;
}
case N_SWITCHMODEL:
{
ci->playermodel = getint(p);
QUEUE_MSG;
break;
}
case N_SWITCHTEAM:
{
getstring(text, p);
filtertext(text, text, false, MAXTEAMLEN);
if(m_teammode && text[0] && strcmp(ci->team, text) && (!smode || smode->canchangeteam(ci, ci->team, text)) && addteaminfo(text))
{
if(ci->state.state==CS_ALIVE) suicide(ci);
copystring(ci->team, text);
aiman::changeteam(ci);
sendf(-1, 1, "riisi", N_SETTEAM, sender, ci->team, ci->state.state==CS_SPECTATOR ? -1 : 0);
}
break;
}
case N_MAPVOTE:
{
getstring(text, p);
filtertext(text, text, false);
int reqmode = getint(p);
vote(text, reqmode, sender);
break;
}
case N_ITEMLIST:
{
if((ci->state.state==CS_SPECTATOR && !ci->privilege && !ci->local) || !notgotitems || strcmp(ci->clientmap, smapname)) { while(getint(p)>=0 && !p.overread()) getint(p); break; }
int n;
while((n = getint(p))>=0 && n<MAXENTS && !p.overread())
{
server_entity se = { NOTUSED, 0, false };
while(sents.length()<=n) sents.add(se);
sents[n].type = getint(p);
if(canspawnitem(sents[n].type))
{
if(m_mp(gamemode) && delayspawn(sents[n].type)) sents[n].spawntime = spawntime(sents[n].type);
else sents[n].spawned = true;
}
}
notgotitems = false;
break;
}
case N_EDITENT:
{
int i = getint(p);
loopk(3) getint(p);
int type = getint(p);
loopk(5) getint(p);
if(!ci || ci->state.state==CS_SPECTATOR) break;
QUEUE_MSG;
bool canspawn = canspawnitem(type);
if(i<MAXENTS && (sents.inrange(i) || canspawnitem(type)))
{
server_entity se = { NOTUSED, 0, false };
while(sents.length()<=i) sents.add(se);
sents[i].type = type;
if(canspawn ? !sents[i].spawned : (sents[i].spawned || sents[i].spawntime))
{
sents[i].spawntime = canspawn ? 1 : 0;
sents[i].spawned = false;
}
}
break;
}
case N_EDITVAR:
{
int type = getint(p);
getstring(text, p);
switch(type)
{
case ID_VAR: getint(p); break;
case ID_FVAR: getfloat(p); break;
case ID_SVAR: getstring(text, p);
}
if(ci && ci->state.state!=CS_SPECTATOR) QUEUE_MSG;
break;
}
case N_PING:
sendf(sender, 1, "i2", N_PONG, getint(p));
break;
case N_CLIENTPING:
{
int ping = getint(p);
if(ci)
{
ci->ping = ping;
loopv(ci->bots) ci->bots[i]->ping = ping;
}
QUEUE_MSG;
break;
}
case N_MASTERMODE:
{
int mm = getint(p);
if((ci->privilege || ci->local) && mm>=MM_OPEN && mm<=MM_PRIVATE)
{
if((ci->privilege>=PRIV_ADMIN || ci->local) || (mastermask&(1<<mm)))
{
mastermode = mm;
allowedips.shrink(0);
if(mm>=MM_PRIVATE)
{
loopv(clients) allowedips.add(getclientip(clients[i]->clientnum));
}
sendf(-1, 1, "rii", N_MASTERMODE, mastermode);
//sendservmsgf("mastermode is now %s (%d)", mastermodename(mastermode), mastermode);
}
else
{
defformatstring(s)("mastermode %d is disabled on this server", mm);
sendf(sender, 1, "ris", N_SERVMSG, s);
}
}
break;
}
case N_CLEARBANS:
{
if(ci->privilege || ci->local)
{
bannedips.shrink(0);
sendservmsg("cleared all bans");
}
break;
}
case N_KICK:
{
int victim = getint(p);
getstring(text, p);
filtertext(text, text);
trykick(ci, victim, text);
break;
}
case N_SPECTATOR:
{
int spectator = getint(p), val = getint(p);
if(!ci->privilege && !ci->local && (spectator!=sender || (ci->state.state==CS_SPECTATOR && mastermode>=MM_LOCKED))) break;
clientinfo *spinfo = (clientinfo *)getclientinfo(spectator); // no bots
if(!spinfo || !spinfo->connected || (spinfo->state.state==CS_SPECTATOR ? val : !val)) break;
if(spinfo->state.state!=CS_SPECTATOR && val) forcespectator(spinfo);
else if(spinfo->state.state==CS_SPECTATOR && !val) unspectate(spinfo);
if(cq && cq != ci && cq->ownernum != ci->clientnum) cq = NULL;
break;
}
case N_SETTEAM:
{
int who = getint(p);
getstring(text, p);
filtertext(text, text, false, MAXTEAMLEN);
if(!ci->privilege && !ci->local) break;
clientinfo *wi = getinfo(who);
if(!m_teammode || !text[0] || !wi || !wi->connected || !strcmp(wi->team, text)) break;
if((!smode || smode->canchangeteam(wi, wi->team, text)) && addteaminfo(text))
{
if(wi->state.state==CS_ALIVE) suicide(wi);
copystring(wi->team, text, MAXTEAMLEN+1);
}
aiman::changeteam(wi);
sendf(-1, 1, "riisi", N_SETTEAM, who, wi->team, 1);
break;
}
case N_FORCEINTERMISSION:
if(ci->local && !hasnonlocalclients()) startintermission();
break;
case N_RECORDDEMO:
{
int val = getint(p);
if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break;
if(!maxdemos || !maxdemosize)
{
sendf(ci->clientnum, 1, "ris", N_SERVMSG, "the server has disabled demo recording");
break;
}
demonextmatch = val!=0;
sendservmsgf("demo recording is %s for next match", demonextmatch ? "enabled" : "disabled");
break;
}
case N_STOPDEMO:
{
if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break;
stopdemo();
break;
}
case N_CLEARDEMOS:
{
int demo = getint(p);
if(ci->privilege < (restrictdemos ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break;
cleardemos(demo);
break;
}
case N_LISTDEMOS:
if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break;
listdemos(sender);
break;
case N_GETDEMO:
{
int n = getint(p);
if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break;
senddemo(ci, n);
break;
}
case N_GETMAP:
if(!mapdata) sendf(sender, 1, "ris", N_SERVMSG, "no map to send");
else if(ci->getmap) sendf(sender, 1, "ris", N_SERVMSG, "already sending map");
else
{
sendservmsgf("[%s is getting the map]", colorname(ci));
if((ci->getmap = sendfile(sender, 2, mapdata, "ri", N_SENDMAP)))
ci->getmap->freeCallback = freegetmap;
ci->needclipboard = totalmillis ? totalmillis : 1;
}
break;
case N_NEWMAP:
{
int size = getint(p);
if(!ci->privilege && !ci->local && ci->state.state==CS_SPECTATOR) break;
if(size>=0)
{
smapname[0] = '\0';
resetitems();
notgotitems = false;
if(smode) smode->newmap();
}
QUEUE_MSG;
break;
}
case N_SETMASTER:
{
int mn = getint(p), val = getint(p);
getstring(text, p);
if(mn != ci->clientnum)
{
if(!ci->privilege && !ci->local) break;
clientinfo *minfo = (clientinfo *)getclientinfo(mn);
if(!minfo || !minfo->connected || (!ci->local && minfo->privilege >= ci->privilege) || (val && minfo->privilege)) break;
setmaster(minfo, val!=0, "", NULL, NULL, PRIV_MASTER, true);
}
else setmaster(ci, val!=0, text);
// don't broadcast the master password
break;
}
case N_ADDBOT:
{
aiman::reqadd(ci, getint(p));
break;
}
case N_DELBOT:
{
aiman::reqdel(ci);
break;
}
case N_BOTLIMIT:
{
int limit = getint(p);
if(ci) aiman::setbotlimit(ci, limit);
break;
}
case N_BOTBALANCE:
{
int balance = getint(p);
if(ci) aiman::setbotbalance(ci, balance!=0);
break;
}
case N_AUTHTRY:
{
string desc, name;
getstring(desc, p, sizeof(desc));
getstring(name, p, sizeof(name));
tryauth(ci, name, desc);
break;
}
case N_AUTHKICK:
{
string desc, name;
getstring(desc, p, sizeof(desc));
getstring(name, p, sizeof(name));
int victim = getint(p);
getstring(text, p);
filtertext(text, text);
int authpriv = PRIV_AUTH;
if(desc[0])
{
userinfo *u = users.access(userkey(name, desc));
if(u) authpriv = u->privilege; else break;
}
if(ci->local || ci->privilege >= authpriv) trykick(ci, victim, text);
else if(trykick(ci, victim, text, name, desc, authpriv, true) && tryauth(ci, name, desc))
{
ci->authkickvictim = victim;
ci->authkickreason = newstring(text);
}
break;
}
case N_AUTHANS:
{
string desc, ans;
getstring(desc, p, sizeof(desc));
uint id = (uint)getint(p);
getstring(ans, p, sizeof(ans));
answerchallenge(ci, id, ans, desc);
break;
}
case N_PAUSEGAME:
{
int val = getint(p);
if(ci->privilege < (restrictpausegame ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break;
pausegame(val > 0, ci);
break;
}
case N_GAMESPEED:
{
int val = getint(p);
if(ci->privilege < (restrictgamespeed ? PRIV_ADMIN : PRIV_MASTER) && !ci->local) break;
changegamespeed(val, ci);
break;
}
case N_COPY:
ci->cleanclipboard();
ci->lastclipboard = totalmillis ? totalmillis : 1;
goto genericmsg;
case N_PASTE:
if(ci->state.state!=CS_SPECTATOR) sendclipboard(ci);
goto genericmsg;
case N_CLIPBOARD:
{
int unpacklen = getint(p), packlen = getint(p);
ci->cleanclipboard(false);
if(ci->state.state==CS_SPECTATOR)
{
if(packlen > 0) p.subbuf(packlen);
break;
}
if(packlen <= 0 || packlen > (1<<16) || unpacklen <= 0)
{
if(packlen > 0) p.subbuf(packlen);
packlen = unpacklen = 0;
}
packetbuf q(32 + packlen, ENET_PACKET_FLAG_RELIABLE);
putint(q, N_CLIPBOARD);
putint(q, ci->clientnum);
putint(q, unpacklen);
putint(q, packlen);
if(packlen > 0) p.get(q.subbuf(packlen).buf, packlen);
ci->clipboard = q.finalize();
ci->clipboard->referenceCount++;
break;
}
case N_SERVCMD:
getstring(text, p);
break;
#define PARSEMESSAGES 1
#include "capture.h"
#include "ctf.h"
#include "collect.h"
#undef PARSEMESSAGES
case -1:
disconnect_client(sender, DISC_MSGERR);
return;
case -2:
disconnect_client(sender, DISC_OVERFLOW);
return;
default: genericmsg:
{
int size = server::msgsizelookup(type);
if(size<=0) { disconnect_client(sender, DISC_MSGERR); return; }
loopi(size-1) getint(p);
if(ci && cq && (ci != cq || ci->state.state!=CS_SPECTATOR)) { QUEUE_AI; QUEUE_MSG; }
break;
}
}
}
int laninfoport() { return SAUERBRATEN_LANINFO_PORT; }
int serverinfoport(int servport) { return servport < 0 ? SAUERBRATEN_SERVINFO_PORT : servport+1; }
int serverport(int infoport) { return infoport < 0 ? SAUERBRATEN_SERVER_PORT : infoport-1; }
const char *defaultmaster() { return "master.sauerbraten.org"; }
int masterport() { return SAUERBRATEN_MASTER_PORT; }
int numchannels() { return 3; }
#include "extinfo.h"
void serverinforeply(ucharbuf &req, ucharbuf &p)
{
if(req.remaining() && !getint(req))
{
extserverinforeply(req, p);
return;
}
putint(p, numclients(-1, false, true));
putint(p, gamepaused || gamespeed != 100 ? 7 : 5); // number of attrs following
putint(p, PROTOCOL_VERSION); // generic attributes, passed back below
putint(p, gamemode);
putint(p, m_timed ? max((gamelimit - gamemillis)/1000, 0) : 0);
putint(p, maxclients);
putint(p, serverpass[0] ? MM_PASSWORD : (!m_mp(gamemode) ? MM_PRIVATE : (mastermode || mastermask&MM_AUTOAPPROVE ? mastermode : MM_AUTH)));
if(gamepaused || gamespeed != 100)
{
putint(p, gamepaused ? 1 : 0);
putint(p, gamespeed);
}
sendstring(smapname, p);
sendstring(serverdesc, p);
sendserverinforeply(p);
}
bool servercompatible(char *name, char *sdec, char *map, int ping, const vector<int> &attr, int np)
{
return attr.length() && attr[0]==PROTOCOL_VERSION;
}
#include "aiman.h"
}
| [
"blaffablaffa@gmail.com"
] | blaffablaffa@gmail.com |
08c37d59eb1e416968e65b18f60eec1d956d5261 | 1650248808c35bd5f460f6b2af687958d9b9bcd3 | /src/sf/UintMap.h | 6c6c8030e8902f5d2d0caa3d3ed57c7ac0f9a8bc | [
"MIT",
"Zlib"
] | permissive | Sondro/spear | bf7e424c29091600e30991119e339186319daaaf | 727f41fa5197f9681337d1ff37ea63c44708f0d4 | refs/heads/master | 2023-03-25T02:30:09.418017 | 2021-01-09T16:00:12 | 2021-01-09T16:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,172 | h | #pragma once
#include "Base.h"
#include "ext/rhmap.h"
namespace sf {
struct UintKeyVal
{
uint32_t key;
uint32_t val;
};
struct UintFind
{
const rhmap *map;
uint32_t hash;
uint32_t scan;
sf_forceinline bool next(uint32_t &result) {
return rhmap_find(map, hash, &scan, &result);
}
};
struct UintMap
{
struct Iterator
{
const rhmap *map;
uint32_t hash;
uint32_t scan;
uint32_t value;
Iterator(const rhmap *beginFromMap);
Iterator() : hash(0), scan(0) { }
sf_forceinline bool operator==(const Iterator &rhs) const {
return hash + scan == rhs.hash + rhs.scan;
}
sf_forceinline bool operator!=(const Iterator &rhs) const {
return hash + scan != rhs.hash + rhs.scan;
}
Iterator &operator++();
sf_forceinline UintKeyVal operator*() {
sf_assert(scan > 0);
return { sf::hashReverse32(hash), value };
}
};
rhmap map;
UintMap();
UintMap(const UintMap &rhs);
UintMap(UintMap &&rhs);
UintMap& operator=(const UintMap &rhs);
UintMap& operator=(UintMap &&rhs);
~UintMap();
Iterator begin() const { return Iterator(&map); }
Iterator end() const { return Iterator(); }
sf_forceinline uint32_t size() const { return map.size; }
sf_forceinline uint32_t capacity() const { return map.capacity; }
void insertDuplicate(uint32_t key, uint32_t value);
bool insertPairIfNew(uint32_t key, uint32_t value);
bool insertOrUpdate(uint32_t key, uint32_t value);
uint32_t findOne(uint32_t key, uint32_t missing) const;
void updateExistingOne(uint32_t key, uint32_t prevValue, uint32_t nextValue);
uint32_t removeOne(uint32_t key, uint32_t missing);
void removeExistingPair(uint32_t key, uint32_t value);
bool removePotentialPair(uint32_t key, uint32_t value);
void removeFoundImp(uint32_t hash, uint32_t scan);
sf_forceinline void removeFound(UintFind &find) {
removeFoundImp(find.hash, find.scan);
find.scan--;
}
sf_forceinline UintFind findAll(uint32_t key) const {
UintFind find;
find.map = ↦
find.hash = sf::hash(key);
find.scan = 0;
return find;
}
void clear();
void reserve(uint32_t size)
{
if (size > map.capacity) {
growImp(size);
}
}
void growImp(uint32_t size);
};
}
| [
"samuli.1995@hotmail.com"
] | samuli.1995@hotmail.com |
fa341380bf803ae0d149c022ab014369653ec142 | 32fd4f562e5ac49b52352dc3f5b9cc00e0d7e05d | /ThirdParty/cpputest/tests/CppUTest/TestUTestMacro.cpp | b04d7d361f22b9d4147068cf87a02abc75dd2bd6 | [
"MIT",
"BSD-3-Clause"
] | permissive | JehTeh/jel | 986dd663179f00220b929e1e4d581df1abd8117a | 2c43cf23ea7b89e7ec0f7c2e9549be74ab0bbc4b | refs/heads/master | 2021-03-30T18:26:42.429234 | 2019-01-05T03:59:33 | 2019-01-05T03:59:33 | 118,649,373 | 14 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,782 | cpp | /*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__)
// Mainly this is for Visual C++, but we'll define it for any system that has the same behavior
// of a 32-bit long on a 64-bit system
#if defined(CPPUTEST_64BIT) && defined(CPPUTEST_64BIT_32BIT_LONGS)
// Forcing the value to be unsigned long long means that there's no sign-extension to perform
#define to_void_pointer(x) ((void *)x##ULL)
#define to_func_pointer(x) ((void (*)())x##ULL)
#else
// Probably not needed, but let's guarantee that the value is an unsigned long
#define to_void_pointer(x) ((void *)x##UL)
#define to_func_pointer(x) ((void (*)())x##UL)
#endif
TEST_GROUP(UnitTestMacros)
{
TestTestingFixture fixture;
};
static void _failingTestMethodWithFAIL()
{
FAIL("This test fails");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FAILMakesTheTestFailPrintsTheRightResultAndStopsExecuting)
{
fixture.runTestWithMethod(_failingTestMethodWithFAIL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("This test fails");
}
TEST(UnitTestMacros, FAILWillPrintTheFileThatItFailed)
{
fixture.runTestWithMethod(_failingTestMethodWithFAIL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT(__FILE__);
}
TEST(UnitTestMacros, FAILBehavesAsAProperMacro)
{
if (false) FAIL("")
else CHECK(true)
if (true) CHECK(true)
else FAIL("")
}
IGNORE_TEST(UnitTestMacros, FAILworksInAnIgnoredTest)
{
FAIL("die!"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _UNSIGNED_LONGS_EQUALTestMethod()
{
UNSIGNED_LONGS_EQUAL(1, 1);
UNSIGNED_LONGS_EQUAL(1, 0);
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, TestUNSIGNED_LONGS_EQUAL)
{
fixture.runTestWithMethod(_UNSIGNED_LONGS_EQUALTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>");
}
TEST(UnitTestMacros, UNSIGNED_LONGS_EQUALBehavesAsProperMacro)
{
if (false) UNSIGNED_LONGS_EQUAL(1, 0)
else UNSIGNED_LONGS_EQUAL(1, 1)
}
IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUALWorksInAnIgnoredTest)
{
UNSIGNED_LONGS_EQUAL(1, 0); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _UNSIGNED_LONGS_EQUAL_TEXTTestMethod()
{
UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed");
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, TestUNSIGNED_LONGS_EQUAL_TEXT)
{
fixture.runTestWithMethod(_UNSIGNED_LONGS_EQUAL_TEXTTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed")
else UNSIGNED_LONGS_EQUAL_TEXT(1, 1, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_TEXTWorksInAnIgnoredTest)
{
UNSIGNED_LONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
#ifdef CPPUTEST_USE_LONG_LONG
static void _LONGLONGS_EQUALTestMethod()
{
LONGLONGS_EQUAL(1, 1);
LONGLONGS_EQUAL(1, 0);
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, TestLONGLONGS_EQUAL)
{
fixture.runTestWithMethod(_LONGLONGS_EQUALTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>");
}
TEST(UnitTestMacros, LONGLONGS_EQUALBehavesAsProperMacro)
{
if (false) LONGLONGS_EQUAL(1, 0)
else LONGLONGS_EQUAL(1, 1)
}
IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUALWorksInAnIgnoredTest)
{
LONGLONGS_EQUAL(1, 0); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _LONGLONGS_EQUAL_TEXTTestMethod()
{
LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed");
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, TestLONGLONGS_EQUAL_TEXT)
{
fixture.runTestWithMethod(_LONGLONGS_EQUAL_TEXTTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, LONGLONGS_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed")
else LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest)
{
LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _UNSIGNED_LONGLONGS_EQUALTestMethod()
{
UNSIGNED_LONGLONGS_EQUAL(1, 1);
UNSIGNED_LONGLONGS_EQUAL(1, 0);
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, TestUNSIGNED_LONGLONGS_EQUAL)
{
fixture.runTestWithMethod(_UNSIGNED_LONGLONGS_EQUALTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>");
}
TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALBehavesAsProperMacro)
{
if (false) UNSIGNED_LONGLONGS_EQUAL(1, 0)
else UNSIGNED_LONGLONGS_EQUAL(1, 1)
}
IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALWorksInAnIgnoredTest)
{
UNSIGNED_LONGLONGS_EQUAL(1, 0); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod()
{
UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed");
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, TestUNSIGNED_LONGLONGS_EQUAL_TEXT)
{
fixture.runTestWithMethod(_UNSIGNED_LONGLONGS_EQUAL_TEXTTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0 (0x0)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed")
else UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 1, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUAL_TEXTWorksInAnIgnoredTest)
{
UNSIGNED_LONGLONGS_EQUAL_TEXT(1, 0, "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
#else
static void _LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod()
{
LONGLONGS_EQUAL(1, 1);
} // LCOV_EXCL_LINE
static void _UNSIGNED_LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod()
{
UNSIGNED_LONGLONGS_EQUAL(1, 1);
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, LONGLONGS_EQUALFailsWithUnsupportedFeature)
{
fixture.runTestWithMethod(_LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("\"CPPUTEST_USE_LONG_LONG\" is not supported");
}
TEST(UnitTestMacros, UNSIGNED_LONGLONGS_EQUALFailsWithUnsupportedFeature)
{
fixture.runTestWithMethod(_UNSIGNED_LONGLONGS_EQUALFailsWithUnsupportedFeatureTestMethod);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("\"CPPUTEST_USE_LONG_LONG\" is not supported");
}
#endif /* CPPUTEST_USE_LONG_LONG */
static void _failingTestMethodWithCHECK()
{
CHECK(false);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK(false) failed");
}
TEST(UnitTestMacros, CHECKBehavesAsProperMacro)
{
if (false) CHECK(false)
else CHECK(true)
}
IGNORE_TEST(UnitTestMacros, CHECKWorksInAnIgnoredTest)
{
CHECK(false); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_TEXT()
{
CHECK_TEXT(false, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK(false) failed");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, CHECK_TEXTBehavesAsProperMacro)
{
if (false) CHECK_TEXT(false, "false")
else CHECK_TEXT(true, "true")
}
IGNORE_TEST(UnitTestMacros, CHECK_TEXTWorksInAnIgnoredTest)
{
CHECK_TEXT(false, "false"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_TRUE()
{
CHECK_TRUE(false);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_TRUE)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_TRUE);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_TRUE(false) failed");
}
TEST(UnitTestMacros, CHECK_TRUEBehavesAsProperMacro)
{
if (false) CHECK_TRUE(false)
else CHECK_TRUE(true)
}
IGNORE_TEST(UnitTestMacros, CHECK_TRUEWorksInAnIgnoredTest)
{
CHECK_TRUE(false) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_TRUE_TEXT()
{
CHECK_TRUE_TEXT(false, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_TRUE_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_TRUE_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_TRUE(false) failed");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, CHECK_TRUE_TEXTBehavesAsProperMacro)
{
if (false) CHECK_TRUE_TEXT(false, "Failed because it failed")
else CHECK_TRUE_TEXT(true, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, CHECK_TRUE_TEXTWorksInAnIgnoredTest)
{
CHECK_TRUE_TEXT(false, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_FALSE()
{
CHECK_FALSE(true);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_FALSE)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_FALSE);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_FALSE(true) failed");
}
TEST(UnitTestMacros, CHECK_FALSEBehavesAsProperMacro)
{
if (false) CHECK_FALSE(true)
else CHECK_FALSE(false)
}
IGNORE_TEST(UnitTestMacros, CHECK_FALSEWorksInAnIgnoredTest)
{
CHECK_FALSE(true) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_FALSE_TEXT()
{
CHECK_FALSE_TEXT(true, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_FALSE_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_FALSE_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_FALSE(true)");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, CHECK_FALSE_TEXTBehavesAsProperMacro)
{
if (false) CHECK_FALSE_TEXT(true, "Failed because it failed")
else CHECK_FALSE_TEXT(false, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, CHECK_FALSE_TEXTWorksInAnIgnoredTest)
{
CHECK_FALSE_TEXT(true, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_EQUAL()
{
CHECK_EQUAL(1, 2);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2>");
}
static void _failingTestMethodWithCHECK_COMPARE()
{
double small = 0.5, big = 0.8;
CHECK_COMPARE(small, >=, big);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_COMPARE)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_COMPARE);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_COMPARE(0.5 >= 0.8)");
}
TEST(UnitTestMacros, CHECK_COMPAREBehavesAsProperMacro)
{
if (false) CHECK_COMPARE(1, >, 2)
else CHECK_COMPARE(1, <, 2)
}
IGNORE_TEST(UnitTestMacros, CHECK_COMPAREWorksInAnIgnoredTest)
{
CHECK_COMPARE(1, >, 2) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_COMPARE_TEXT()
{
double small = 0.5, big = 0.8;
CHECK_COMPARE_TEXT(small, >=, big, "small bigger than big");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_COMPARE_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_COMPARE_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("CHECK_COMPARE(0.5 >= 0.8)");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("small bigger than big");
}
TEST(UnitTestMacros, CHECK_COMPARE_TEXTBehavesAsProperMacro)
{
if (false) CHECK_COMPARE_TEXT(1, >, 2, "1 bigger than 2")
else CHECK_COMPARE_TEXT(1, <, 2, "1 smaller than 2")
}
IGNORE_TEST(UnitTestMacros, CHECK_COMPARE_TEXTWorksInAnIgnoredTest)
{
CHECK_COMPARE_TEXT(1, >, 2, "1 smaller than 2") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static int countInCountingMethod;
static int _countingMethod()
{
return countInCountingMethod++;
}
TEST(UnitTestMacros, LONGS_EQUAL_macroExpressionSafety)
{
LONGS_EQUAL(1, 0.4 + 0.7);
LONGS_EQUAL(0.4 + 0.7, 1);
LONGS_EQUAL_TEXT(1, 0.4 + 0.7, "-Wconversion=great");
LONGS_EQUAL_TEXT(0.4 + 0.7, 1, "-Wconversion=great");
}
TEST(UnitTestMacros, UNSIGNED_LONGS_EQUAL_macroExpressionSafety)
{
UNSIGNED_LONGS_EQUAL(1, 0.4 + 0.7);
UNSIGNED_LONGS_EQUAL(0.4 + 0.7, 1);
UNSIGNED_LONGS_EQUAL_TEXT(1, 0.4 + 0.7, "-Wconversion=great");
UNSIGNED_LONGS_EQUAL_TEXT(0.4 + 0.7, 1, "-Wconversion=great");
}
TEST(UnitTestMacros, passingCheckEqualWillNotBeEvaluatedMultipleTimesWithCHECK_EQUAL)
{
countInCountingMethod = 0;
CHECK_EQUAL(0, _countingMethod());
LONGS_EQUAL(1, countInCountingMethod);
}
static void _failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning()
{
CHECK_EQUAL(12345, _countingMethod());
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning)
{
fixture.runTestWithMethod(_failing_CHECK_EQUAL_WithActualBeingEvaluatesMultipleTimesWillGiveAWarning);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Actual Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect.");
}
static void _failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning()
{
CHECK_EQUAL(_countingMethod(), 12345);
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning)
{
fixture.runTestWithMethod(_failing_CHECK_EQUAL_WithExpectedBeingEvaluatesMultipleTimesWillGiveAWarning);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("WARNING:\n\tThe \"Expected Parameter\" parameter is evaluated multiple times resulting in different values.\n\tThus the value in the error message is probably incorrect.");
}
TEST(UnitTestMacros, failing_CHECK_EQUAL_withParamatersThatDontChangeWillNotGiveAnyWarning)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_EQUAL);
CHECK( ! fixture.output_->getOutput().contains("WARNING"));
}
TEST(UnitTestMacros, CHECK_EQUALBehavesAsProperMacro)
{
if (false) CHECK_EQUAL(1, 2)
else CHECK_EQUAL(1, 1)
}
IGNORE_TEST(UnitTestMacros, CHECK_EQUALWorksInAnIgnoredTest)
{
CHECK_EQUAL(1, 2) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithCHECK_EQUAL_TEXT()
{
CHECK_EQUAL_TEXT(1, 2, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithCHECK_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, CHECK_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) CHECK_EQUAL_TEXT(1, 2, "Failed because it failed")
else CHECK_EQUAL_TEXT(1, 1, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, CHECK_EQUAL_TEXTWorksInAnIgnoredTest)
{
CHECK_EQUAL_TEXT(1, 2, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithLONGS_EQUAL()
{
LONGS_EQUAL(1, 0xff);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithLONGS_EQUALS)
{
fixture.runTestWithMethod(_failingTestMethodWithLONGS_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 (0xff)>");
}
static void _failingTestMethodWithLONGS_EQUALWithSymbolicParameters()
{
#define _MONDAY 1
int day_of_the_week = _MONDAY+1;
LONGS_EQUAL(_MONDAY, day_of_the_week);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithLONGS_EQUALShowsSymbolicParameters)
{
fixture.runTestWithMethod(_failingTestMethodWithLONGS_EQUALWithSymbolicParameters);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("LONGS_EQUAL(_MONDAY, day_of_the_week) failed");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <2 (0x2)>");
CHECK_FALSE(fixture.getOutput().contains("Message: "));
}
TEST(UnitTestMacros, LONGS_EQUALBehavesAsProperMacro)
{
if (false) LONGS_EQUAL(1, 2)
else LONGS_EQUAL(10, 10)
}
IGNORE_TEST(UnitTestMacros, LONGS_EQUALWorksInAnIgnoredTest)
{
LONGS_EQUAL(11, 22) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithLONGS_EQUAL_TEXT()
{
LONGS_EQUAL_TEXT(1, 0xff, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithLONGS_EQUALS_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithLONGS_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected < 1 (0x1)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <255 (0xff)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, LONGS_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) LONGS_EQUAL_TEXT(1, 2, "Failed because it failed")
else LONGS_EQUAL_TEXT(10, 10, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, LONGS_EQUAL_TEXTWorksInAnIgnoredTest)
{
LONGS_EQUAL_TEXT(11, 22, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithBYTES_EQUAL()
{
BYTES_EQUAL('a', 'b');
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestMacros, FailureWithBYTES_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithBYTES_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 (0x61)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 (0x62)>");
}
TEST(UnitTestMacros, BYTES_EQUALBehavesAsProperMacro)
{
if (false) BYTES_EQUAL('a', 'b')
else BYTES_EQUAL('c', 'c')
}
IGNORE_TEST(UnitTestMacros, BYTES_EQUALWorksInAnIgnoredTest)
{
BYTES_EQUAL('q', 'w') // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithBYTES_EQUAL_TEXT()
{
BYTES_EQUAL_TEXT('a', 'b', "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestMacros, FailureWithBYTES_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithBYTES_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <97 (0x61)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <98 (0x62)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, BYTES_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) BYTES_EQUAL_TEXT('a', 'b', "Failed because it failed")
else BYTES_EQUAL_TEXT('c', 'c', "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, BYTES_EQUAL_TEXTWorksInAnIgnoredTest)
{
BYTES_EQUAL_TEXT('q', 'w', "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSIGNED_BYTES_EQUAL()
{
SIGNED_BYTES_EQUAL(-1, -2);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestMacros, FailureWithSIGNED_BYTES_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithSIGNED_BYTES_EQUAL);
#if CPPUTEST_CHAR_BIT == 16
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 (0xffff)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 (0xfffe)>");
#else
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-1 (0xff)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-2 (0xfe)>");
#endif
}
TEST(UnitTestMacros, CHARS_EQUALBehavesAsProperMacro)
{
if (false) SIGNED_BYTES_EQUAL(-1, -2)
else SIGNED_BYTES_EQUAL(-3, -3)
}
IGNORE_TEST(UnitTestMacros, CHARS_EQUALWorksInAnIgnoredTest)
{
SIGNED_BYTES_EQUAL(-7, 19) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT()
{
SIGNED_BYTES_EQUAL_TEXT(-127, -126, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestMacros, FailureWithSIGNED_BYTES_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithSIGNED_BYTES_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <-127 (0x81)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <-126 (0x82)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, CHARS_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) SIGNED_BYTES_EQUAL_TEXT(-1, -2, "Failed because it failed")
else SIGNED_BYTES_EQUAL_TEXT(-3, -3, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, SIGNED_BYTES_EQUAL_TEXTWorksInAnIgnoredTest)
{
SIGNED_BYTES_EQUAL_TEXT(-7, 19, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithPOINTERS_EQUAL()
{
POINTERS_EQUAL((void*)0xa5a5, (void*)0xf0f0);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithPOINTERS_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithPOINTERS_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>");
}
TEST(UnitTestMacros, POINTERS_EQUALBehavesAsProperMacro)
{
if (false) POINTERS_EQUAL(0, to_void_pointer(0xbeefbeef))
else POINTERS_EQUAL(to_void_pointer(0xdeadbeef), to_void_pointer(0xdeadbeef))
}
IGNORE_TEST(UnitTestMacros, POINTERS_EQUALWorksInAnIgnoredTest)
{
POINTERS_EQUAL((void*) 0xbeef, (void*) 0xdead) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithPOINTERS_EQUAL_TEXT()
{
POINTERS_EQUAL_TEXT((void*)0xa5a5, (void*)0xf0f0, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithPOINTERS_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithPOINTERS_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, POINTERS_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) POINTERS_EQUAL_TEXT(0, to_void_pointer(0xbeefbeef), "Failed because it failed")
else POINTERS_EQUAL_TEXT(to_void_pointer(0xdeadbeef), to_void_pointer(0xdeadbeef), "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, POINTERS_EQUAL_TEXTWorksInAnIgnoredTest)
{
POINTERS_EQUAL_TEXT((void*) 0xbeef, (void*) 0xdead, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithFUNCTIONPOINTERS_EQUAL()
{
FUNCTIONPOINTERS_EQUAL((void (*)())0xa5a5, (void (*)())0xf0f0);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithFUNCTIONPOINTERS_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithFUNCTIONPOINTERS_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>");
}
TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUALBehavesAsProperMacro)
{
if (false) FUNCTIONPOINTERS_EQUAL(0, to_func_pointer(0xbeefbeef))
else FUNCTIONPOINTERS_EQUAL(to_func_pointer(0xdeadbeef), to_func_pointer(0xdeadbeef))
}
IGNORE_TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUALWorksInAnIgnoredTest)
{
FUNCTIONPOINTERS_EQUAL((void (*)())0xbeef, (void (*)())0xdead) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT()
{
FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xa5a5, (void (*)())0xf0f0, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithFUNCTIONPOINTERS_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithFUNCTIONPOINTERS_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0xa5a5>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <0xf0f0>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) FUNCTIONPOINTERS_EQUAL_TEXT(0, to_func_pointer(0xbeefbeef), "Failed because it failed")
else FUNCTIONPOINTERS_EQUAL_TEXT(to_func_pointer(0xdeadbeef), to_func_pointer(0xdeadbeef), "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, FUNCTIONPOINTERS_EQUAL_TEXTWorksInAnIgnoredTest)
{
FUNCTIONPOINTERS_EQUAL_TEXT((void (*)())0xbeef, (void (*)())0xdead, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithDOUBLES_EQUAL()
{
DOUBLES_EQUAL(0.12, 44.1, 0.3);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL)
{
fixture.runTestWithMethod(_failingTestMethodWithDOUBLES_EQUAL);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0.12>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <44.1>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("threshold used was <0.3>");
}
TEST(UnitTestMacros, DOUBLES_EQUALBehavesAsProperMacro)
{
if (false) DOUBLES_EQUAL(0.0, 1.1, 0.0005)
else DOUBLES_EQUAL(0.1, 0.2, 0.2)
}
IGNORE_TEST(UnitTestMacros, DOUBLES_EQUALWorksInAnIgnoredTest)
{
DOUBLES_EQUAL(100.0, 0.0, 0.2) // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _failingTestMethodWithDOUBLES_EQUAL_TEXT()
{
DOUBLES_EQUAL_TEXT(0.12, 44.1, 0.3, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithDOUBLES_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithDOUBLES_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <0.12>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <44.1>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("threshold used was <0.3>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, DOUBLES_EQUAL_TEXTBehavesAsProperMacro)
{
if (false) DOUBLES_EQUAL_TEXT(0.0, 1.1, 0.0005, "Failed because it failed")
else DOUBLES_EQUAL_TEXT(0.1, 0.2, 0.2, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, DOUBLES_EQUAL_TEXTWorksInAnIgnoredTest)
{
DOUBLES_EQUAL_TEXT(100.0, 0.0, 0.2, "Failed because it failed") // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static bool lineOfCodeExecutedAfterCheck = false;
static void _passingTestMethod()
{
CHECK(true);
lineOfCodeExecutedAfterCheck = true;
}
TEST(UnitTestMacros, SuccessPrintsNothing)
{
fixture.runTestWithMethod(_passingTestMethod);
LONGS_EQUAL(0, fixture.getFailureCount());
fixture.assertPrintContains(".\nOK (1 tests");
CHECK(lineOfCodeExecutedAfterCheck);
}
static void _methodThatOnlyPrints()
{
UT_PRINT("Hello World!");
}
TEST(UnitTestMacros, PrintPrintsWhateverPrintPrints)
{
fixture.runTestWithMethod(_methodThatOnlyPrints);
LONGS_EQUAL(0, fixture.getFailureCount());
fixture.assertPrintContains("Hello World!");
fixture.assertPrintContains(__FILE__);
}
static void _methodThatOnlyPrintsUsingSimpleStringFromFormat()
{
UT_PRINT(StringFromFormat("Hello %s %d", "World!", 2009));
}
TEST(UnitTestMacros, PrintPrintsSimpleStringsForExampleThoseReturnedByFromString)
{
fixture.runTestWithMethod(_methodThatOnlyPrintsUsingSimpleStringFromFormat);
fixture.assertPrintContains("Hello World! 2009");
}
static int functionThatReturnsAValue()
{
CHECK(0 == 0);
CHECK_TEXT(0 == 0, "Shouldn't fail");
CHECK_TRUE(0 == 0);
CHECK_TRUE_TEXT(0 == 0, "Shouldn't fail");
CHECK_FALSE(0 != 0);
CHECK_FALSE_TEXT(0 != 0, "Shouldn't fail");
LONGS_EQUAL(1,1);
LONGS_EQUAL_TEXT(1, 1, "Shouldn't fail");
BYTES_EQUAL(0xab,0xab);
BYTES_EQUAL_TEXT(0xab, 0xab, "Shouldn't fail");
CHECK_EQUAL(100,100);
CHECK_EQUAL_TEXT(100, 100, "Shouldn't fail");
STRCMP_EQUAL("THIS", "THIS");
STRCMP_EQUAL_TEXT("THIS", "THIS", "Shouldn't fail");
DOUBLES_EQUAL(1.0, 1.0, .01);
DOUBLES_EQUAL_TEXT(1.0, 1.0, .01, "Shouldn't fail");
POINTERS_EQUAL(0, 0);
POINTERS_EQUAL_TEXT(0, 0, "Shouldn't fail");
MEMCMP_EQUAL("THIS", "THIS", 5);
MEMCMP_EQUAL_TEXT("THIS", "THIS", 5, "Shouldn't fail");
BITS_EQUAL(0x01, (unsigned char )0x01, 0xFF);
BITS_EQUAL(0x0001, (unsigned short )0x0001, 0xFFFF);
BITS_EQUAL(0x00000001, (unsigned long )0x00000001, 0xFFFFFFFF);
BITS_EQUAL_TEXT(0x01, (unsigned char )0x01, 0xFF, "Shouldn't fail");
return 0;
}
TEST(UnitTestMacros, allMacrosFromFunctionThatReturnsAValue)
{
functionThatReturnsAValue();
}
TEST(UnitTestMacros, MEMCMP_EQUALBehavesAsAProperMacro)
{
if (false) MEMCMP_EQUAL("TEST", "test", 5)
else MEMCMP_EQUAL("TEST", "TEST", 5)
}
IGNORE_TEST(UnitTestMacros, MEMCMP_EQUALWorksInAnIgnoredTest)
{
MEMCMP_EQUAL("TEST", "test", 5); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _MEMCMP_EQUALFailingTestMethodWithUnequalInput()
{
unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 };
unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 };
MEMCMP_EQUAL(expectedData, actualData, sizeof(expectedData));
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, MEMCMP_EQUALFailureWithUnequalInput)
{
fixture.runTestWithMethod(_MEMCMP_EQUALFailingTestMethodWithUnequalInput);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 03 03>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 2");
}
static void _MEMCMP_EQUALFailingTestMethodWithNullExpected()
{
unsigned char actualData[] = { 0x00, 0x01, 0x02, 0x03 };
MEMCMP_EQUAL(NULL, actualData, sizeof(actualData));
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, MEMCMP_EQUALFailureWithNullExpected)
{
fixture.runTestWithMethod(_MEMCMP_EQUALFailingTestMethodWithNullExpected);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <(null)>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 02 03>");
}
static void _MEMCMP_EQUALFailingTestMethodWithNullActual()
{
unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 };
MEMCMP_EQUAL(expectedData, NULL, sizeof(expectedData));
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, MEMCMP_EQUALFailureWithNullActual)
{
fixture.runTestWithMethod(_MEMCMP_EQUALFailingTestMethodWithNullActual);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <(null)>");
}
TEST(UnitTestMacros, MEMCMP_EQUALNullExpectedNullActual)
{
MEMCMP_EQUAL(NULL, NULL, 0);
MEMCMP_EQUAL(NULL, NULL, 1024);
}
static void _failingTestMethodWithMEMCMP_EQUAL_TEXT()
{
unsigned char expectedData[] = { 0x00, 0x01, 0x02, 0x03 };
unsigned char actualData[] = { 0x00, 0x01, 0x03, 0x03 };
MEMCMP_EQUAL_TEXT(expectedData, actualData, sizeof(expectedData), "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithMEMCMP_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithMEMCMP_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <00 01 02 03>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <00 01 03 03>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("difference starts at position 2");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, MEMCMP_EQUAL_TEXTBehavesAsAProperMacro)
{
if (false) MEMCMP_EQUAL_TEXT("TEST", "test", 5, "Failed because it failed")
else MEMCMP_EQUAL_TEXT("TEST", "TEST", 5, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, MEMCMP_EQUAL_TEXTWorksInAnIgnoredTest)
{
MEMCMP_EQUAL_TEXT("TEST", "test", 5, "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, BITS_EQUALBehavesAsAProperMacro)
{
if (false) BITS_EQUAL(0x00, 0xFF, 0xFF)
else BITS_EQUAL(0x00, 0x00, 0xFF)
}
IGNORE_TEST(UnitTestMacros, BITS_EQUALWorksInAnIgnoredTest)
{
BITS_EQUAL(0x00, 0xFF, 0xFF); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
static void _BITS_EQUALFailingTestMethodWithUnequalInput()
{
BITS_EQUAL(0x00, 0xFF, 0xFF);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, BITS_EQUALFailureWithUnequalInput)
{
fixture.runTestWithMethod(_BITS_EQUALFailingTestMethodWithUnequalInput);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("00000000>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("11111111>");
}
TEST(UnitTestMacros, BITS_EQUALZeroMaskEqual)
{
BITS_EQUAL(0x00, 0xFF, 0x00);
}
static void _failingTestMethodWithBITS_EQUAL_TEXT()
{
BITS_EQUAL_TEXT(0x00, 0xFFFFFFFF, 0xFF, "Failed because it failed");
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithBITS_EQUAL_TEXT)
{
fixture.runTestWithMethod(_failingTestMethodWithBITS_EQUAL_TEXT);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected <xxxxxxxx xxxxxxxx xxxxxxxx 00000000>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but was <xxxxxxxx xxxxxxxx xxxxxxxx 11111111>");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("Failed because it failed");
}
TEST(UnitTestMacros, BITS_EQUAL_TEXTBehavesAsAProperMacro)
{
if (false) BITS_EQUAL_TEXT(0x00, 0xFF, 0xFF, "Failed because it failed")
else BITS_EQUAL_TEXT(0x00, 0x00, 0xFF, "Failed because it failed")
}
IGNORE_TEST(UnitTestMacros, BITS_EQUAL_TEXTWorksInAnIgnoredTest)
{
BITS_EQUAL_TEXT(0x00, 0xFF, 0xFF, "Failed because it failed"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
#if CPPUTEST_USE_STD_CPP_LIB
static void _failingTestMethod_NoThrowWithCHECK_THROWS()
{
CHECK_THROWS(int, (void) (1+2));
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_THROWS_whenDoesntThrow)
{
fixture.runTestWithMethod(_failingTestMethod_NoThrowWithCHECK_THROWS);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected to throw int");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but threw nothing");
LONGS_EQUAL(1, fixture.getCheckCount());
}
static void _succeedingTestMethod_CorrectThrowWithCHECK_THROWS()
{
CHECK_THROWS(int, throw 4);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
}
TEST(UnitTestMacros, SuccessWithCHECK_THROWS)
{
fixture.runTestWithMethod(_succeedingTestMethod_CorrectThrowWithCHECK_THROWS);
LONGS_EQUAL(1, fixture.getCheckCount());
}
static void _failingTestMethod_WrongThrowWithCHECK_THROWS()
{
CHECK_THROWS(int, throw 4.3);
TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE
TEST(UnitTestMacros, FailureWithCHECK_THROWS_whenWrongThrow)
{
fixture.runTestWithMethod(_failingTestMethod_WrongThrowWithCHECK_THROWS);
CHECK_TEST_FAILS_PROPER_WITH_TEXT("expected to throw int");
CHECK_TEST_FAILS_PROPER_WITH_TEXT("but threw a different type");
LONGS_EQUAL(1, fixture.getCheckCount());
}
TEST(UnitTestMacros, MultipleCHECK_THROWS_inOneScope)
{
CHECK_THROWS(int, throw 4);
CHECK_THROWS(int, throw 4);
}
#endif
| [
"jostth7@gmail.com"
] | jostth7@gmail.com |
35e48b4a42d70bfadc17ceaf8bb267d8e49c38c8 | 755fc53a1c6d88e88cd9eb890bd077ca0738fb51 | /build/rmkdepend/mainroot.cxx | f0ff7f5fc2127c50917ac1a6cab7c3ed6762037e | [] | no_license | flueke/marabou | bf9ed463c59ad106a9d8b36c60a880a5caa79920 | 2f54e181be6f6488c019dc924fe0e40f7adc10b9 | refs/heads/master | 2023-07-06T16:15:52.030497 | 2019-01-08T09:33:00 | 2019-01-08T09:33:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,629 | cxx | // @(#)root/build:$Name: not supported by cvs2svn $:$Id: mainroot.cxx,v 1.1 2007-03-07 14:27:10 Otto.Schaile Exp $
// Author: Axel Naumann 21/03/06
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// ROOT wrapper around ROOT's mkdepend incarnation + wrapper script,
// known as depends.sh in earlier days.
// If the first(!) argument is '-R' it triggers a few special
// routines:
// * dependencies for .d files use $(wildcard ...), so gmake doesn't
// bail out if one of the dependencies doesn't exist.
// * output files starting with '/G__' and ending on ".d" are assumed to
// be dictionaries. rmkdepend generates rules for these dictionaries
// covering the .d file, and the .cxx file itself,
// so the dictionaries get re-egenerated when an included header
// file gets changed.
// * the detection / wildcarding of a dictionary file can be changed
// by specifying -R=[tag]%[ext] as parameter to -R. The default is
// "-R=/G__%.d".
// * remove output file if we encounter an error.
#include <string>
extern "C" {
#if defined(__sun) && defined(__SUNPRO_CC)
#include <signal.h>
#endif
#include "def.h"
}
#ifndef WIN32
#include <unistd.h>
#else
extern "C" int unlink(const char *FILENAME);
#endif
extern "C" int main_orig(int argc, char **argv);
int rootBuild = 0;
static int isDict = 0;
static int newFile = 0;
static int openWildcard = 0;
static std::string currentDependencies;
static std::string currentFileBase;
extern "C"
void ROOT_newFile()
{
newFile = 1;
}
void ROOT_flush()
{
if (openWildcard) {
fwrite(")\n", 2, 1, stdout); // closing "$(wildcard"
openWildcard = 0;
}
if (!currentFileBase.empty()) {
currentFileBase += "o";
fwrite(currentFileBase.c_str(), currentFileBase.length(), 1, stdout);
currentDependencies += '\n';
fwrite(currentDependencies.c_str(), currentDependencies.length(), 1, stdout);
}
currentFileBase.clear();
currentDependencies.clear();
}
extern "C"
void ROOT_adddep(char* buf, size_t len)
{
char* posColon = 0;
if (newFile)
posColon = strstr(buf, ".o: ");
if (!posColon) {
fwrite(buf, len, 1, stdout);
currentDependencies += buf;
return;
}
/* isDict:
sed -e 's@^\(.*\)\.o[ :]*\(.*\)\@
\1.d: $\(wildcard \2\)\@\1.cxx: $\(wildcard \2\)@'
-e 's@^#.*$@@'
-e '/^$/d'
| tr '@' '\n'
else
sed -e 's@^\(.*\)\.o[ :]*\(.*\)@
\1.d: $\(wildcard \2\)\@\1.o: \2@'
-e 's@^#.*$@@'
-e '/^$/d' $1.tmp
| tr '@' '\n'
*/
// flush out the old dependencies
ROOT_flush();
newFile = 0;
buf[0] = ' ';
if (isDict) {
posColon[1]=0;
char s = posColon[4]; // sove char that will be overwritten by \0 of "cxx"
strcat(posColon, "cxx");
fwrite(buf, (posColon - buf)+4, 1, stdout); // .cxx
posColon[4] = s;
}
posColon[1]='d';
fwrite(buf, (posColon - buf)+2, 1, stdout); // .d
if (!isDict) {
posColon[1] = 0;
currentFileBase = buf + 1;
currentDependencies = posColon + 2;
}
fwrite(": $(wildcard ", 13, 1, stdout);
fwrite(posColon + 4, len - (posColon + 4 - buf), 1, stdout);
openWildcard = 1;
}
int main(int argc, char **argv)
{
if (argc<3 || (strcmp(argv[1], "-R") && strncmp(argv[1], "-R=", 3)))
return main_orig(argc, argv);
rootBuild = 1;
int skip = 2;
const char* outname = argv[2]+skip;
while (outname[0] == ' ') outname = argv[2] + (++skip);
if (outname) {
const char* dicttag = "/G__%.d";
if (argv[1][2] == '=')
dicttag = argv[1] + 3;
std::string sDictTag(dicttag);
std::string sDictExt;
size_t posExt = sDictTag.find('%');
if (posExt != std::string::npos) {
sDictExt = sDictTag.substr(posExt + 1);
sDictTag.erase(posExt);
}
isDict = (strstr(outname, sDictTag.c_str()) != 0
&& (!sDictExt.length() || strstr(outname, sDictExt.c_str())));
}
argv[1] = argv[0]; // keep program name
int ret = main_orig(argc-1, &argv[1]);
if (ret) {
// delete output file
unlink(outname);
} else
ROOT_flush();
return ret;
}
| [
"Otto.Schaile@514c3d59-69d9-4452-b10b-b80f2e82d9e4"
] | Otto.Schaile@514c3d59-69d9-4452-b10b-b80f2e82d9e4 |
a2e535c8565b9926a127150cb3cfbf75416ae1e2 | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/bigneuron_AmosSironi_PrzemyslawGlowacki_SQBTree_plugin/libs/boost_1_58_0/boost/thread/executors/generic_executor_ref.hpp | 57609c91f0553d0728bf04967a92db10b017aa28 | [
"MIT"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 5,563 | hpp | // Copyright (C) 2014 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_THREAD_EXECUTORS_GENERIC_EXECUTOR_REF_HPP
#define BOOST_THREAD_EXECUTORS_GENERIC_EXECUTOR_REF_HPP
#include <boost/thread/detail/config.hpp>
#include <boost/thread/detail/delete.hpp>
#include <boost/thread/detail/move.hpp>
#include <boost/thread/executors/executor.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace executors
{
template <class Executor>
class executor_ref : public executor
{
Executor& ex;
public:
/// type-erasure to store the works to do
typedef executors::work work;
/// executor is not copyable.
BOOST_THREAD_NO_COPYABLE(executor_ref)
executor_ref(Executor& ex) : ex(ex) {}
/**
* \par Effects
* Destroys the executor.
*
* \par Synchronization
* The completion of all the closures happen before the completion of the executor destructor.
*/
~executor_ref() {};
/**
* \par Effects
* Close the \c executor for submissions.
* The worker threads will work until there is no more closures to run.
*/
void close() { ex.close(); }
/**
* \par Returns
* Whether the pool is closed for submissions.
*/
bool closed() { return ex.closed(); }
/**
* \par Effects
* The specified closure will be scheduled for execution at some point in the future.
* If invoked closure throws an exception the executor will call std::terminate, as is the case with threads.
*
* \par Synchronization
* Ccompletion of closure on a particular thread happens before destruction of thread's thread local variables.
*
* \par Throws
* \c sync_queue_is_closed if the thread pool is closed.
* Whatever exception that can be throw while storing the closure.
*/
void submit(BOOST_THREAD_RV_REF(work) closure) {
ex.submit(boost::move(closure));
}
// void submit(work& closure) {
// ex.submit(closure);
// }
/**
* \par Effects
* Try to execute one task.
*
* \par Returns
* Whether a task has been executed.
*
* \par Throws
* Whatever the current task constructor throws or the task() throws.
*/
bool try_executing_one() { return ex.try_executing_one(); }
};
class generic_executor_ref
{
shared_ptr<executor> ex;
public:
/// type-erasure to store the works to do
typedef executors::work work;
template<typename Executor>
generic_executor_ref(Executor& ex)
//: ex(make_shared<executor_ref<Executor> >(ex)) // todo check why this doesn't works with C++03
: ex( new executor_ref<Executor>(ex) )
{
}
//generic_executor_ref(generic_executor_ref const& other) noexcept {}
//generic_executor_ref& operator=(generic_executor_ref const& other) noexcept {}
/**
* \par Effects
* Close the \c executor for submissions.
* The worker threads will work until there is no more closures to run.
*/
void close() { ex->close(); }
/**
* \par Returns
* Whether the pool is closed for submissions.
*/
bool closed() { return ex->closed(); }
void submit(BOOST_THREAD_RV_REF(work) closure)
{
ex->submit(boost::forward<work>(closure));
}
/**
* \par Requires
* \c Closure is a model of Callable(void()) and a model of CopyConstructible/MoveConstructible.
*
* \par Effects
* The specified closure will be scheduled for execution at some point in the future.
* If invoked closure throws an exception the thread pool will call std::terminate, as is the case with threads.
*
* \par Synchronization
* Completion of closure on a particular thread happens before destruction of thread's thread local variables.
*
* \par Throws
* \c sync_queue_is_closed if the thread pool is closed.
* Whatever exception that can be throw while storing the closure.
*/
#if defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
template <typename Closure>
void submit(Closure & closure)
{
work w ((closure));
submit(boost::move(w));
}
#endif
void submit(void (*closure)())
{
work w ((closure));
submit(boost::move(w));
}
template <typename Closure>
void submit(BOOST_THREAD_RV_REF(Closure) closure)
{
work w = boost::move(closure);
submit(boost::move(w));
}
// size_t num_pending_closures() const
// {
// return ex->num_pending_closures();
// }
/**
* \par Effects
* Try to execute one task.
*
* \par Returns
* Whether a task has been executed.
*
* \par Throws
* Whatever the current task constructor throws or the task() throws.
*/
bool try_executing_one() { return ex->try_executing_one(); }
/**
* \par Requires
* This must be called from an scheduled task.
*
* \par Effects
* reschedule functions until pred()
*/
template <typename Pred>
bool reschedule_until(Pred const& pred)
{
do {
//schedule_one_or_yield();
if ( ! try_executing_one())
{
return false;
}
} while (! pred());
return true;
}
};
}
using executors::executor_ref;
using executors::generic_executor_ref;
}
#include <boost/config/abi_suffix.hpp>
#endif
| [
"amos.sironi@gmail.com"
] | amos.sironi@gmail.com |
4f1292ae84dbe9f11c4f861050fa99fc4765b4cf | f00687b9f8671496f417672aaf8ddffc2fa8060a | /csacademy/round-54/pair-swap.cpp | 42d0063e94d45e513accc6b8b0be7f16a4423f09 | [] | no_license | kazi-nayeem/Programming-Problems-Solutions | 29c338085f1025b2545ff66bdb0476ec4d7773c2 | 7ee29a4e06e9841388389be5566db34fbdda8f7c | refs/heads/master | 2023-02-05T15:06:50.355903 | 2020-12-30T10:19:54 | 2020-12-30T10:19:54 | 279,388,214 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,921 | cpp | #include <cstdio>
#include <sstream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <list>
#include <iostream>
#include <fstream>
#include <numeric>
#include <string>
#include <vector>
#include <cstring>
#include <map>
#include <iterator>
#include<complex>
//#include <bits/stdc++.h>
using namespace std;
#define HI printf("HI\n")
#define sf scanf
#define pf printf
#define sf1(a) scanf("%d",&a)
#define sf2(a,b) scanf("%d %d",&a,&b)
#define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c)
#define sf4(a,b,c,d) scanf("%d %d %d %d",&a,&b,&c,&d)
#define sf1ll(a) scanf("%lld",&a)
#define sf2ll(a,b) scanf("%lld %lld",&a,&b)
#define sf3ll(a,b,c) scanf("%lld %lld %lld",&a,&b,&c)
#define sf4ll(a,b,c,d) scanf("%lld %lld %lld %lld",&a,&b,&c,&d)
#define forln(i,a,n) for(int i=a ; i<n ; i++)
#define foren(i,a,n) for(int i=a ; i<=n ; i++)
#define forg0(i,a,n) for(int i=a ; i>n ; i--)
#define fore0(i,a,n) for(int i=a ; i>=n ; i--)
#define pb push_back
#define ppb pop_back
#define ppf push_front
#define popf pop_front
#define ll long long int
#define ui unsigned int
#define ull unsigned long long
#define fs first
#define sc second
#define clr( a, b ) memset((a),b,sizeof(a))
#define jora pair<int, int>
#define jora_d pair<double, double>
#define jora_ll pair<long long int, long long int>
#define mp make_pair
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define PI acos(0.0)
#define ps pf("PASS\n")
#define popc(a) (__builtin_popcount(a))
template<class T1> void deb(T1 e1) {
cout<<e1<<endl;
}
template<class T1,class T2> void deb(T1 e1,T2 e2) {
cout<<e1<<" "<<e2<<endl;
}
template<class T1,class T2,class T3> void deb(T1 e1,T2 e2,T3 e3) {
cout<<e1<<" "<<e2<<" "<<e3<<endl;
}
template<class T1,class T2,class T3,class T4> void deb(T1 e1,T2 e2,T3 e3,T4 e4) {
cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<endl;
}
template<class T1,class T2,class T3,class T4,class T5> void deb(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5) {
cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<endl;
}
template<class T1,class T2,class T3,class T4,class T5,class T6> void deb(T1 e1,T2 e2,T3 e3,T4 e4,T5 e5,T6 e6) {
cout<<e1<<" "<<e2<<" "<<e3<<" "<<e4<<" "<<e5<<" "<<e6<<endl;
}
/// <--------------------------- For Bitmasking -------------------------------->
//int on( int n, int pos ){
// return n = n|( 1<<pos );
//}
//bool check( int n, int pos ){
// return (bool)( n&( 1<<pos ) );
//}
//int off( int n, int pos ){
// return n = n&~( 1<<pos );
//}
//int toggle( int n, int pos ){
// return n = n^(1<<pos);
//}
//int count_bit( int n ){
// return __builtin_popcount( n );
//}
/// <--------------------------- End of Bitmasking -------------------------------->
/// <--------------------------- For B - Base Number System ----------------------------------->
//int base;
//int pw[10];
//void calPow(int b){
// base = b;
// pw[0] = 1;
// for( int i = 1; i<10; i++ ){
// pw[i] = pw[i-1]*base;
// }
//}
//int getV(int mask, int pos){
// mask /= pw[pos];
// return ( mask%base );
//}
//int setV(int mask, int v, int pos){
// int rem = mask%pw[pos];
// mask /= pw[pos+1];
// mask = ( mask*base ) + v;
// mask = ( mask*pw[pos] ) + rem;
// return mask;
//}
/// <--------------------------- End B - Base Number System ----------------------------------->
// moves
//int dx[]= {0,0,1,-1};/*4 side move*/
//int dy[]= {-1,1,0,0};/*4 side move*/
//int dx[]= {1,1,0,-1,-1,-1,0,1};/*8 side move*/
//int dy[]= {0,1,1,1,0,-1,-1,-1};/*8 side move*/
//int dx[]={1,1,2,2,-1,-1,-2,-2};/*night move*/
//int dy[]={2,-2,1,-1,2,-2,1,-1};/*night move*/
//double Expo(double n, int p) {
// if (p == 0)return 1;
// double x = Expo(n, p >> 1);
// x = (x * x);
// return ((p & 1) ? (x * n) : x);
//}
//ll bigmod(ll a,ll b,ll m){if(b == 0) return 1%m;ll x = bigmod(a,b/2,m);x = (x * x) % m;if(b % 2 == 1) x = (x * a) % m;return x;}
//ll BigMod(ll B,ll P,ll M){ ll R=1%M; while(P>0) {if(P%2==1){R=(R*B)%M;}P/=2;B=(B*B)%M;} return R;} /// (B^P)%M
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
#define MXN 50
#define MXE
#define MXQ
#define SZE
#define MOD
#define EPS
#define INF 100000000
#define MX 100005
#define inf 100000000
const ll mod = 1000000007ll;
//struct data{
// int v, p;
// data
//};
int arr[MX];
int nxt[MX];
int main() {
// ios_base::sync_with_stdio(0);
// freopen("00.txt", "r", stdin);
int n, k;
scanf("%d %d", &n, &k);
for(int i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
}
for(int i = n; i >= 1; i--) {
nxt[i] = i;
while(nxt[i]+1<=n && arr[nxt[i]+1]>=arr[i])
nxt[i] = nxt[nxt[i]+1];
}
// for(int i = 1; i <= n; i++)
// deb(i,nxt[i]);
for(int i = 1; i <= n; i++) {
//deb(i,nxt[i]);
int pos = nxt[i];
while(nxt[pos]+1<=n && nxt[pos]+1 <= i+k) {
pos = nxt[pos]+1;
}
if(pos <= n && pos<=i+k && arr[pos]<arr[i]) {
int ans = -1;
for(int f = pos; f <= i+k && f <= n; f++)
{
if(arr[f] == arr[pos]) ans = f;
}
pos = ans;
swap(arr[pos],arr[i]);
break;
}
}
printf("%d", arr[1]);
for(int i = 2; i <= n; i++)
printf(" %d", arr[i]);
puts("");
return 0;
}
| [
"masum.nayeem@gmail.com"
] | masum.nayeem@gmail.com |
b86e9dc9c27bd58329110b3bc2a7221b030e3d93 | 84d3ac466259f39cbcbb0cd65bbb8a12911c59a0 | /IllegalBalanceException.h | a2b9debc7436845d2d462c46ae88380b02903fca | [] | no_license | empty-works/bank-account-project | 8cfe52a48c3c3e6d58f933c76b714ac425efd126 | 554d0ccbdcc8933d17a79bb4993a439304387282 | refs/heads/master | 2022-05-31T08:36:48.909231 | 2020-05-02T04:39:40 | 2020-05-02T04:39:40 | 254,713,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | #ifndef ILLEGAL_BALANCE_EXCEPTION_H_
#define ILLEGAL_BALANCE_EXCEPTION_H_
class IllegalBalanceException: public std::exception {
public:
IllegalBalanceException() noexcept = default;
~IllegalBalanceException() = default;
virtual const char *what() const noexcept {
return "Illegal balance exception.";
}
};
#endif
| [
"pama.mark@gmail.com"
] | pama.mark@gmail.com |
bb225e74c4ac9f2e17f487fc4900316215b9138b | 7700d32ea12896662317da245b368cb269a7b673 | /C_Camera.h | cf106b0665427a4326331023ed180fe186511b40 | [] | no_license | TokiMaki/Neso_Run- | 7936fd37554ab0f229e42c8804dfcc8e7ab0d6fd | 0a27d75db1b5b671256ac4ce361febc83fa6a95b | refs/heads/master | 2023-08-09T08:10:46.145951 | 2023-07-25T09:53:39 | 2023-07-25T09:53:39 | 160,385,903 | 0 | 0 | null | 2019-02-04T13:52:22 | 2018-12-04T16:20:20 | C++ | UTF-8 | C++ | false | false | 1,091 | h | #pragma once
#pragma once
#include "Run_Time_Framework.h"
#define Move_Factor 0.5f
#define ROTATE_FACTOR 5.f
struct Vector3D {
float x;
float y;
float z;
Vector3D operator += (const Vector3D other) {
x += other.x;
y += other.y;
z += other.z;
}
};
struct Matrix3x3 {
Vector3D r1, r2, r3;
};
class C_Camera
{
private:
Vector3D RotateAngle;
Matrix3x3 m_mtxLocal;
public:
C_Camera();
~C_Camera();
GLvoid CameraZoom(unsigned char t);
GLvoid CameraMove(unsigned char t);
GLvoid CameraRotate(unsigned char t);
GLvoid CameraPos();
GLvoid CameraLook();
GLvoid CameraReset();
Vector3D GetCameraRotate() const { return RotateAngle; }
Vector3D GetCameraPos() const { return m_mtxLocal.r1; }
Vector3D GetCameraLook() const { return m_mtxLocal.r2; }
Vector3D GetCameraUp() const { return m_mtxLocal.r3; }
GLvoid SetCameraRotate(Vector3D other) { RotateAngle = other; };
GLvoid SetCameraPos(Vector3D other) { m_mtxLocal.r1 = other; };
GLvoid SetCameraLook(Vector3D other) { m_mtxLocal.r2 = other; };
GLvoid SetCameraUp(Vector3D other) { m_mtxLocal.r3 = other; };
};
| [
"40135375+TokiMaki@users.noreply.github.com"
] | 40135375+TokiMaki@users.noreply.github.com |
1963c57700fa285ffbe82713bc2fd8e89f275263 | ec6adaad2a2a7e279bf848933ea7aae6cd6062ce | /Source/encoderRtp.cpp | 14abd7952a4b239b16363e6a85ef79afd3735c37 | [] | no_license | nameisshenlei/1.0.0.beta2 | 78302f74152fe20cf232f2a8f491a8564150793a | 47d3ecb3b2ccd0c003612050d9caeb2375ea22f8 | refs/heads/master | 2020-06-13T03:35:56.431543 | 2016-12-03T06:32:48 | 2016-12-03T06:32:48 | 75,454,149 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,636 | cpp | #include "encoderRtp.h"
#include "helpFunctions.h"
#include "errorCode.h"
encoderRtp::encoderRtp(String encoderName, String memVideoName, String memAudioName)
: baseSilentEncoder(encoderName, memVideoName, memAudioName)
{
}
encoderRtp::~encoderRtp()
{
}
GstStateChangeReturn encoderRtp::onPlay()
{
String strURI = m_settingInfo->getValue(KEY_OUT_URI, "");
if (strURI.isEmpty())
{
return GST_STATE_CHANGE_FAILURE;
}
strURI = strURI.fromFirstOccurrenceOf("rtp://", false, true);
String strIp;
int iPort = 0;
strIp = strURI.upToFirstOccurrenceOf(":", false, true);
iPort = strURI.fromFirstOccurrenceOf(":", false, true).getIntValue();
if (strIp.isEmpty() || iPort <1024 || iPort > 65534)
{
return GST_STATE_CHANGE_FAILURE;
}
GstElement* elmtMPEGTSMux = nullptr;
GstElement* elmtRtpMP2TPay = nullptr;
GstElement* elmtUdpSink = nullptr;
// mpeg-ts muxer
elmtMPEGTSMux = gst_element_factory_make("mpegtsmux", "mpegtsMux");
// rtp mp2tpay
elmtRtpMP2TPay = gst_element_factory_make("rtpmp2tpay", "rtpMp2tPay");
// udp sink
elmtUdpSink = gst_element_factory_make("udpsink", "udpSink");
if (!m_elmtVideoAppSrc || !m_elmtAudioAppSrc || !elmtMPEGTSMux || !elmtRtpMP2TPay || !elmtUdpSink)
{
return GST_STATE_CHANGE_FAILURE;
}
gst_bin_add_many(GST_BIN(m_elmtPipeline)
, elmtMPEGTSMux
, elmtRtpMP2TPay
, elmtUdpSink
, nullptr);
//////////////////////////////////////////////////////////////////////////
{
g_object_set(elmtMPEGTSMux,
"alignment", 7,
nullptr);
}
{
// udp sink
g_object_set(elmtUdpSink, "host", strIp.toUTF8(), nullptr);
g_object_set(elmtUdpSink, "port", iPort, nullptr);
}
////////////////////////////////////////////////////////////////////////
// video process
if (video_h264_encoder(elmtMPEGTSMux) != 0)
{
return GST_STATE_CHANGE_FAILURE;
}
// audio process
if (audio_aac_encoder(elmtMPEGTSMux) != 0)
{
return GST_STATE_CHANGE_FAILURE;
}
if (!gst_element_link(elmtMPEGTSMux, elmtRtpMP2TPay))
{
goto PLAY_FAILED;
}
if (!gst_element_link(elmtRtpMP2TPay, elmtUdpSink))
{
goto PLAY_FAILED;
}
GstStateChangeReturn stateRet = gst_element_set_state(m_elmtPipeline, GST_STATE_PLAYING);
return stateRet;
PLAY_FAILED:
return GST_STATE_CHANGE_FAILURE;
}
void encoderRtp::timerCallback()
{
GstElement* elmt = gst_bin_get_by_name(GST_BIN(m_elmtPipeline), "udpSink");
if (elmt)
{
guint64 total_bytes = 0;
g_object_get(elmt, "bytes-served", &total_bytes, nullptr);
gst_object_unref(elmt);
writePropertiesInIniFile(m_iniFullPath, SE_ERROR_CODE_RUNNING_INFO,m_hGlobalEvent, String(L"ÒÑ·¢ËÍ ") + bytesToString(total_bytes));
}
} | [
"472843791@qq.com"
] | 472843791@qq.com |
c2eee056488ce5ded57469314d973ea719614afa | 91e2e25c16e35cb3945cc2f655fbe3e0ade99b2e | /tool_kits/ui_component/ui_kit/gui/team_info/team_search.cpp | b702b51b2d7f8b60d18627be7513bf1ea6a9025c | [] | no_license | staring/NIM_PC_UIKit | 055762bd2b2d7f286c09ecc137cb08454c8df18f | e7293bc3cf38a05db049b32a400688aa99c89994 | refs/heads/master | 2021-01-19T10:18:01.173059 | 2016-04-29T05:39:56 | 2016-04-29T05:39:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,030 | cpp | #include "team_search.h"
#include "module/emoji/richedit_util.h"
#include "gui/session/control/session_util.h"
#include "callback/team/team_callback.h"
using namespace ui;
namespace nim_comp
{
const LPCTSTR TeamSearchForm::kClassName = L"TeamSearchForm";
TeamSearchForm::TeamSearchForm()
{
}
TeamSearchForm::~TeamSearchForm()
{
}
std::wstring TeamSearchForm::GetSkinFolder()
{
return L"team_info";
}
std::wstring TeamSearchForm::GetSkinFile()
{
return L"team_search.xml";
}
ui::UILIB_RESOURCETYPE TeamSearchForm::GetResourceType() const
{
return ui::UILIB_FILE;
}
std::wstring TeamSearchForm::GetZIPFileName() const
{
return L"team_search.zip";
}
std::wstring TeamSearchForm::GetWindowClassName() const
{
return kClassName;
}
std::wstring TeamSearchForm::GetWindowId() const
{
return kClassName;
}
UINT TeamSearchForm::GetClassStyle() const
{
return (UI_CLASSSTYLE_FRAME | CS_DBLCLKS);
}
LRESULT TeamSearchForm::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if(uMsg == WM_KEYDOWN && wParam == 'V')
{
if(::GetKeyState(VK_CONTROL) < 0)
{
if(re_tid_->IsFocused())
{
re_tid_->PasteSpecial(CF_TEXT);
return 1;
}
}
}
else if (uMsg == WM_KEYDOWN && wParam == VK_RETURN)
{
if (tsp_[TSP_SEARCH]->IsVisible())
{
if (btn_search_->IsEnabled())
SendNotify(btn_search_, kEventClick);
else
re_tid_->SetFocus();
}
else if (tsp_[TSP_APPLY]->IsVisible())
{
if (btn_apply_->IsEnabled())
SendNotify(btn_apply_, kEventClick);
else
SendNotify(FindControl(L"btn_return_search"), kEventClick);
}
else if (tsp_[TSP_APPLY_OK]->IsVisible())
{
SendNotify(FindControl(L"btn_apply_ok"), kEventClick);
}
}
return __super::HandleMessage(uMsg, wParam, lParam);
}
void TeamSearchForm::InitWindow()
{
SetTaskbarTitle(L"搜索加入群");
m_pRoot->AttachBubbledEvent(ui::kEventAll, nbase::Bind(&TeamSearchForm::Notify, this, std::placeholders::_1));
m_pRoot->AttachBubbledEvent(ui::kEventClick, nbase::Bind(&TeamSearchForm::OnClicked, this, std::placeholders::_1));
tsp_[TSP_SEARCH] = FindControl(L"page_search");
tsp_[TSP_APPLY] = FindControl(L"page_apply");
tsp_[TSP_APPLY_OK] = FindControl(L"page_apply_ok");
re_tid_ = (RichEdit*) FindControl(L"re_tid");
re_tid_->SetLimitText(20);
error_tip_ = (Label*) FindControl(L"error_tip");
btn_search_ = (Button*) FindControl(L"btn_search");
team_icon_ = (Button*) FindControl(L"team_icon");
team_name_ = (Label*) FindControl(L"team_name");
team_id_ = (Label*) FindControl(L"team_id");
label_group_ = (Label*) FindControl(L"label_group");
btn_apply_ = (Button*) FindControl(L"btn_apply");
re_apply_ = (RichEdit*) FindControl(L"re_apply");
GotoPage(TSP_SEARCH);
}
void TeamSearchForm::GotoPage( TeamSearchPage page )
{
for(int i = 0; i < TSP_COUNT; i++)
{
tsp_[i]->SetVisible(false);
}
tsp_[page]->SetVisible(true);
if (page == TSP_SEARCH)
{
tid_.clear();
re_tid_->SetText(L"");
re_tid_->SetFocus();
btn_search_->SetEnabled(true);
}
}
void TeamSearchForm::ShowTeamInfo(const nim::TeamEvent& team_event)
{
team_icon_->SetBkImage( TeamService::GetInstance()->GetTeamPhoto(false) );
team_id_->SetUTF8Text(team_event.team_id_);
std::string name = team_event.team_info_.GetName();
if (name.empty())
{
tname_ = nbase::UTF8ToUTF16(team_event.team_id_);
}
else
{
tname_ = nbase::UTF8ToUTF16(name);
team_name_->SetText(tname_);
}
nim::NIMTeamType type = team_event.team_info_.GetType();
if (type == nim::kNIMTeamTypeNormal)
{
label_group_->SetVisible(true);
btn_apply_->SetEnabled(false);
}
else
{
label_group_->SetVisible(false);
btn_apply_->SetEnabled(true);
}
}
bool TeamSearchForm::Notify(ui::EventArgs* arg)
{
std::wstring name = arg->pSender->GetName();
if(arg->Type == kEventTextChange)
{
if(name == L"re_tid")
{
error_tip_->SetVisible(false);
btn_search_->SetEnabled(true);
}
}
return false;
}
bool TeamSearchForm::OnClicked( ui::EventArgs* arg )
{
std::wstring name = arg->pSender->GetName();
if(name == L"btn_search")
{
std::string tid;
{
std::wstring str = GetRichText(re_tid_);
StringHelper::Trim(str);
if( str.empty() )
{
error_tip_->SetText(L"群号不可为空");
error_tip_->SetVisible(true);
btn_search_->SetEnabled(false);
return false;
}
tid = nbase::UTF16ToUTF8(str);
}
tid_ = tid;
btn_search_->SetEnabled(false);
nim::Team::QueryTeamInfoOnlineAsync(tid_, nbase::Bind(&TeamSearchForm::OnGetTeamInfoCb, this, std::placeholders::_1));
}
else if(name == L"btn_return_search")
{
label_group_->SetVisible(false);
btn_apply_->SetEnabled(true);
GotoPage(TSP_SEARCH);
}
else if(name == L"btn_apply")
{
nim::Team::ApplyJoinAsync(tid_, "", nbase::Bind(&TeamSearchForm::OnApplyJoinCb, this, std::placeholders::_1));
GotoPage(TSP_APPLY_OK);
}
else if(name == L"btn_apply_ok")
{
this->Close();
}
return false;
}
void TeamSearchForm::OnGetTeamInfoCb(const nim::TeamEvent& team_event)
{
QLOG_APP(L"search team: {0}") << team_event.res_code_;
if (team_event.res_code_ == 200)
{
ShowTeamInfo(team_event);
GotoPage(TSP_APPLY);
}
else
{
error_tip_->SetText(L"群不存在");
error_tip_->SetVisible(true);
}
}
void TeamSearchForm::OnApplyJoinCb(const nim::TeamEvent& team_event)
{
QLOG_APP(L"apply join: {0}") << team_event.res_code_;
switch (team_event.res_code_)
{
case nim::kNIMResTeamAlreadyIn:
{
re_apply_->SetText(nbase::StringPrintf(L"已经在群里", tname_.c_str()));
}
break;
case nim::kNIMResSuccess:
{
nbase::ThreadManager::PostTask(kThreadUI, nbase::Bind(TeamCallback::OnTeamEventCallback, team_event));
re_apply_->SetText(nbase::StringPrintf(L"群 %s 管理员同意了你的加群请求", tname_.c_str()));
}
break;
case nim::kNIMResTeamApplySuccess:
re_apply_->SetText(L"你的加群请求已发送成功,请等候群主/管理员验证");
break;
default:
{
re_apply_->SetText(nbase::StringPrintf(L"群 %s 管理员拒绝了你的加群请求", tname_.c_str()));
}
break;
}
}
} | [
"redrains@qq.com"
] | redrains@qq.com |
cda767139920982b5539a16e304dc8b3a987cd4e | 069f2d7e7be9c8dfd2c7bed3af60ad1f19992190 | /2-1/객체지향프로그래밍/4/StudentIDList.cpp | cd57353fb1023758e5db6da2e0b81578fffa023a | [] | no_license | jyh4479/University_assignment | c30914bc78abff45fd610ac37deb5a110a07892c | bed00a6dc93e5d46ce2e775f5169167c27fef8cd | refs/heads/main | 2023-02-05T08:37:42.448194 | 2020-12-25T08:36:40 | 2020-12-25T08:36:40 | 305,389,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | #include "StudentIDList.h"
StudentIDList::StudentIDList()
{
}
StudentIDList::~StudentIDList()
{
}
void StudentIDList::link_id(DepartmentList&DepartmentList)
{ //Function to link the ID
Node* tmp = DepartmentList.mHead->getDown();
for (; tmp->getPrev(); tmp = tmp->getPrev());
Node* tmp2 = tmp->getNext();
for (; tmp2; tmp2 = tmp2->getNext(), tmp = tmp->getNext())
{//A half-wrapped sentence for repetition from beginning to end
tmp->getID()->setNext(tmp2->getID());
}
tmp->getID()->setNext(NULL);
} | [
"jyh.dev@gmail.com"
] | jyh.dev@gmail.com |
5a8f151a1237b6d815e8ecf00324b99209ec10c9 | 24e3e92e48b032f4cc057cd870a476ea35c1d799 | /.localhistory/C/Users/Minas Laptopers/source/repos/project 6/project 6/1539210383$main.cpp | 31983a5e31c80fde99ce2b8159a3455248138ed1 | [] | no_license | minavadamee20/project-6-Arrays-x86-Assembly-Language- | 63a762045508533b9a5bce4849bd94c0147be10c | f8a7da57f8ff19b3e7e4b58cd1ececf5a19319ad | refs/heads/master | 2020-03-31T19:27:06.875435 | 2018-10-17T20:16:04 | 2018-10-17T20:16:04 | 152,497,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | cpp | #include <iostream>
int main() {
int a[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 };
int total;
_asm {
mov ebx, 0;
mov i, 0;
lea esi, 0;
loop1:
cmp i, 12;
Je done;
add ebx, [esi];
add esi, 4;
inc i;
Jmp loop1;
done:
mov total, ebx;
}
std::cout << "total: [ " << total << " ]" << std::endl;
system("pause");
return 0;
} | [
"34077203+minavadamee20@users.noreply.github.com"
] | 34077203+minavadamee20@users.noreply.github.com |
03bda0db69894de581eb4086cfc0d4b91e9a6711 | 895c9e22ca063119e5ddeeb99067b3089c190d31 | /Binary_search/Square_Root_of_Integer.cpp | aa3de72ce0a8ff4936a2d18a30a6acebf95c22cc | [] | no_license | shivamgoel008/Data-Structure-and-Algorithms | 5c543877c6201d89de5a5393d748fa27025282b1 | 82b4694a92f8383ae867b98f2e0f2e6bfbe862b1 | refs/heads/main | 2023-08-22T20:06:20.270832 | 2021-10-09T06:02:04 | 2021-10-09T06:02:04 | 352,412,307 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,143 | cpp | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define ll long long
#define setbits(x) __builtin_popcountll(x)
#define zerobits(x) __builtin_ctzll(x)
#define fo(i,n) for(i=0;i<n;i++)
#define set(a) memset(a,0,sizeof(a))
#define MOD 1000000007
#define test() ll t; cin>>t; while(t--)
bool compare(ll a,ll b)
{
return a<b;
}
int _sqrt(int n) {
int first=0;
int second=1;
int ans;
while(first<=second)
{
long long int mid=(first+second)/2;
// cout<<mid<<endl;
if(mid*mid==n)
{
// cout<<"YES"<<endl;
ans=mid;
break;
}
else if(mid*mid>n)
second=mid-1;
else
{
ans=mid;
first=mid+1;
}
}
return ans;
}
int main ()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// test()
{
int n;
cin>>n;
cout<<_sqrt(n);
}
return 0;
} | [
"55030452+shivamgoel008@users.noreply.github.com"
] | 55030452+shivamgoel008@users.noreply.github.com |
16e4b4d6f9435c74861b3f3e72e257bdda09a183 | 93dbc87ac2bd41e1b5be46508ed62bfe9bab4d80 | /main.cpp | 6ea5a7d9b654f28917e7f3f1ffe90b6e6cbd6954 | [] | no_license | kevinagnes/GeneticAlgorithm_Tarsila | 7a7e463eca4875cbcb0dca3426ac8fa3c0d7b2d7 | 7feed2e7eedd2248cbd2d48f92a0f739b52de4ec | refs/heads/main | 2023-05-30T23:56:32.716511 | 2021-06-17T07:46:22 | 2021-06-17T07:46:22 | 377,744,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp | #include "ofMain.h"
#include "ofApp.h"
//========================================================================
int main( ){
ofSetupOpenGL(1000, 1000, OF_WINDOW); // <-------- setup the GL context
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp(new ofApp());
}
| [
"kevinagnes@gmail.com"
] | kevinagnes@gmail.com |
092fc7987ee5d479393e8461b77386bc789684a8 | f81b774e5306ac01d2c6c1289d9e01b5264aae70 | /chrome/browser/hid/hid_chooser_context.h | 73af4cbf6db18982d0486b3dbc7d7fe34a22d688 | [
"BSD-3-Clause"
] | permissive | waaberi/chromium | a4015160d8460233b33fe1304e8fd9960a3650a9 | 6549065bd785179608f7b8828da403f3ca5f7aab | refs/heads/master | 2022-12-13T03:09:16.887475 | 2020-09-05T20:29:36 | 2020-09-05T20:29:36 | 293,153,821 | 1 | 1 | BSD-3-Clause | 2020-09-05T21:02:50 | 2020-09-05T21:02:49 | null | UTF-8 | C++ | false | false | 5,084 | h | // Copyright 2019 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.
#ifndef CHROME_BROWSER_HID_HID_CHOOSER_CONTEXT_H_
#define CHROME_BROWSER_HID_HID_CHOOSER_CONTEXT_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/unguessable_token.h"
#include "components/permissions/chooser_context_base.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/device/public/mojom/hid.mojom.h"
#include "url/origin.h"
class Profile;
namespace base {
class Value;
}
// Manages the internal state and connection to the device service for the
// Human Interface Device (HID) chooser UI.
class HidChooserContext : public permissions::ChooserContextBase,
public device::mojom::HidManagerClient {
public:
explicit HidChooserContext(Profile* profile);
HidChooserContext(const HidChooserContext&) = delete;
HidChooserContext& operator=(const HidChooserContext&) = delete;
~HidChooserContext() override;
// This observer can be used to be notified when HID devices are connected or
// disconnected.
class DeviceObserver : public base::CheckedObserver {
public:
virtual void OnDeviceAdded(const device::mojom::HidDeviceInfo&);
virtual void OnDeviceRemoved(const device::mojom::HidDeviceInfo&);
virtual void OnHidManagerConnectionError();
// Called when the HidChooserContext is shutting down. Observers must remove
// themselves before returning.
virtual void OnHidChooserContextShutdown() = 0;
};
// permissions::ChooserContextBase implementation:
bool IsValidObject(const base::Value& object) override;
// In addition these methods from ChooserContextBase are overridden in order
// to expose ephemeral devices through the public interface.
std::vector<std::unique_ptr<Object>> GetGrantedObjects(
const url::Origin& requesting_origin,
const url::Origin& embedding_origin) override;
std::vector<std::unique_ptr<Object>> GetAllGrantedObjects() override;
void RevokeObjectPermission(const url::Origin& requesting_origin,
const url::Origin& embedding_origin,
const base::Value& object) override;
base::string16 GetObjectDisplayName(const base::Value& object) override;
// HID-specific interface for granting and checking permissions.
void GrantDevicePermission(const url::Origin& requesting_origin,
const url::Origin& embedding_origin,
const device::mojom::HidDeviceInfo& device);
bool HasDevicePermission(const url::Origin& requesting_origin,
const url::Origin& embedding_origin,
const device::mojom::HidDeviceInfo& device);
// For ScopedObserver.
void AddDeviceObserver(DeviceObserver* observer);
void RemoveDeviceObserver(DeviceObserver* observer);
// Forward HidManager::GetDevices.
void GetDevices(device::mojom::HidManager::GetDevicesCallback callback);
device::mojom::HidManager* GetHidManager();
// Sets |manager| as the HidManager and registers this context as a
// HidManagerClient. Calls |callback| with the set of enumerated devices once
// the client is registered and the initial enumeration is complete.
void SetHidManagerForTesting(
mojo::PendingRemote<device::mojom::HidManager> manager,
device::mojom::HidManager::GetDevicesCallback callback);
base::WeakPtr<HidChooserContext> AsWeakPtr();
private:
// device::mojom::HidManagerClient implementation:
void DeviceAdded(device::mojom::HidDeviceInfoPtr device_info) override;
void DeviceRemoved(device::mojom::HidDeviceInfoPtr device_info) override;
void EnsureHidManagerConnection();
void SetUpHidManagerConnection(
mojo::PendingRemote<device::mojom::HidManager> manager);
void InitDeviceList(std::vector<device::mojom::HidDeviceInfoPtr> devices);
void OnHidManagerConnectionError();
const bool is_incognito_;
bool is_initialized_ = false;
base::queue<device::mojom::HidManager::GetDevicesCallback>
pending_get_devices_requests_;
// Tracks the set of devices to which an origin (potentially embedded in
// another origin) has access to. Key is (requesting_origin,
// embedding_origin).
std::map<std::pair<url::Origin, url::Origin>, std::set<std::string>>
ephemeral_devices_;
// Map from device GUID to device info.
std::map<std::string, device::mojom::HidDeviceInfoPtr> devices_;
mojo::Remote<device::mojom::HidManager> hid_manager_;
mojo::AssociatedReceiver<device::mojom::HidManagerClient> client_receiver_{
this};
base::ObserverList<DeviceObserver> device_observer_list_;
base::WeakPtrFactory<HidChooserContext> weak_factory_{this};
};
#endif // CHROME_BROWSER_HID_HID_CHOOSER_CONTEXT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
94d72cfffd3e118d6e1e2973963bacb27268dc57 | 8803ba409e2b9195d86d33530837b9b15bf33209 | /ofxTetris.h | 2e6f6c44ef7a302a58e3b025880c309b8821c373 | [
"MIT"
] | permissive | ayafujiaya/ofxTetris | fb5b6fc53696196c5aacddb7b0c22e7b0e51658f | 1d8e36d8872e59f3137342a9cbe6d6c737683493 | refs/heads/master | 2021-01-10T19:11:53.813338 | 2014-07-08T14:00:25 | 2014-07-08T14:00:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,047 | h | #include "ofMain.h"
#define FIELD_WIDTH 12
#define FIELD_HEIGHT 25
/*
* テトリスの実装をクラス化して、縦横自在のテトリスを作る。
* solved 二列同士に消そうとすると一列しか消えないバグ。
* 次のテトリスを前の現在のテトリス作成時に決める
* game over 画面を実装する
* game start 画面を実装する
*/
struct POSITION {
int x;
int y;
};
struct PIECE {
int rotate;
POSITION p[4];
};
struct STATUS {
int x;
int y;
int type;
int rotate;
};
class ofxTetris {
public:
/********** basic function *******/
virtual void setup(float x, float y, int _grid = 10, int _state = 0);
virtual void update();
virtual void draw();
virtual void keyInput(int key);
/********** Tetris Logic *********/
virtual void setField();
virtual void basicProc();
virtual bool putPiece(STATUS s, bool action = false);
virtual void deleteLine();
virtual void inputProc();
virtual void deletePiece(STATUS s);
virtual void newPiece();
/************ Each block draw functions ************/
virtual void drawBlockNum(int x, int y) = 0;
virtual void drawPiece(int x, int y) = 0;
virtual void emptyBlock(int x, int y) = 0;
virtual void wallBlock(int x, int y) = 0;
virtual void setColor();
/************ Scene Select *************/
virtual void gameOver();
int field[12][25];
int grid;
float tetrisX, tetrisY;
STATUS current;
bool inputLeft, inputRight, inputUp, inputDown, inputRotate, isContinue, isSet;
ofTrueTypeFont font;
int state;
PIECE piece[8] = {
{1, {{0, 0},{0, 0}, {0 ,0}}},
{2, {{0, -1},{0, 1}, {0 ,2}}},
{4, {{0, -1},{0, 1}, {1 ,1}}},
{4, {{0, -1},{0, 1}, {-1,1}}},
{2, {{0, -1},{1, 0}, {1 ,1}}},
{2, {{0, -1},{-1,0}, {-1,1}}},
{1, {{0, 1},{1, 0}, {1 ,1}}},
{4, {{0, -1},{1, 0}, {-1 ,0}}},
};
vector<ofColor> colors;
};
| [
"takada@1-10.com"
] | takada@1-10.com |
4a9cf11ff6ef9b70df77ef553d2d3e0af8d6e54f | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /content/common/inter_process_time_ticks_converter_unittest.cc | 8b8d72157b60b1d349d70886b9f10a3572575603 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 11,827 | cc | // 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 "content/common/inter_process_time_ticks_converter.h"
#include <stdint.h>
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::TimeTicks;
namespace content {
namespace {
struct TestParams {
LocalTimeTicks local_lower_bound;
RemoteTimeTicks remote_lower_bound;
RemoteTimeTicks remote_upper_bound;
LocalTimeTicks local_upper_bound;
RemoteTimeTicks test_time;
RemoteTimeDelta test_delta;
};
struct TestResults {
LocalTimeTicks result_time;
LocalTimeDelta result_delta;
int64_t skew;
};
LocalTimeTicks GetLocalTimeTicks(int64_t value) {
return LocalTimeTicks::FromTimeTicks(
base::TimeTicks() + base::TimeDelta::FromMicroseconds(value));
}
RemoteTimeTicks GetRemoteTimeTicks(int64_t value) {
return RemoteTimeTicks::FromTimeTicks(
base::TimeTicks() + base::TimeDelta::FromMicroseconds(value));
}
TestResults RunTest(const TestParams& params) {
InterProcessTimeTicksConverter converter(
params.local_lower_bound, params.local_upper_bound,
params.remote_lower_bound, params.remote_upper_bound);
TestResults results;
results.result_time = converter.ToLocalTimeTicks(params.test_time);
results.result_delta = converter.ToLocalTimeDelta(params.test_delta);
results.skew = converter.GetSkewForMetrics().ToInternalValue();
return results;
}
TEST(InterProcessTimeTicksConverterTest, NullTime) {
// Null / zero times should remain null.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(2);
p.remote_upper_bound = GetRemoteTimeTicks(5);
p.local_upper_bound = GetLocalTimeTicks(6);
p.test_time = GetRemoteTimeTicks(0);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(0), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, NoSkew) {
// All times are monotonic and centered, so no adjustment should occur.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(2);
p.remote_upper_bound = GetRemoteTimeTicks(5);
p.local_upper_bound = GetLocalTimeTicks(6);
p.test_time = GetRemoteTimeTicks(3);
p.test_delta = RemoteTimeDelta::FromMicroseconds(1);
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(3), results.result_time);
EXPECT_EQ(LocalTimeDelta::FromMicroseconds(1), results.result_delta);
EXPECT_EQ(0, results.skew);
}
TEST(InterProcessTimeTicksConverterTest, OffsetMidpoints) {
// All times are monotonic, but not centered. Adjust the |remote_*| times so
// they are centered within the |local_*| times.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(3);
p.remote_upper_bound = GetRemoteTimeTicks(6);
p.local_upper_bound = GetLocalTimeTicks(6);
p.test_time = GetRemoteTimeTicks(4);
p.test_delta = RemoteTimeDelta::FromMicroseconds(1);
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(3), results.result_time);
EXPECT_EQ(LocalTimeDelta::FromMicroseconds(1), results.result_delta);
EXPECT_EQ(1, results.skew);
}
TEST(InterProcessTimeTicksConverterTest, DoubleEndedSkew) {
// |remote_lower_bound| occurs before |local_lower_bound| and
// |remote_upper_bound| occurs after |local_upper_bound|. We must adjust both
// bounds and scale down the delta. |test_time| is on the midpoint, so it
// doesn't change. The ratio of local time to network time is 1:2, so we scale
// |test_delta| to half.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(3);
p.remote_lower_bound = GetRemoteTimeTicks(1);
p.remote_upper_bound = GetRemoteTimeTicks(9);
p.local_upper_bound = GetLocalTimeTicks(7);
p.test_time = GetRemoteTimeTicks(5);
p.test_delta = RemoteTimeDelta::FromMicroseconds(2);
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(5), results.result_time);
EXPECT_EQ(LocalTimeDelta::FromMicroseconds(1), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, FrontEndSkew) {
// |remote_upper_bound| is coherent, but |remote_lower_bound| is not. So we
// adjust the lower bound and move |test_time| out. The scale factor is 2:3,
// but since we use integers, the numbers truncate from 3.33 to 3 and 1.33
// to 1.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(3);
p.remote_lower_bound = GetRemoteTimeTicks(1);
p.remote_upper_bound = GetRemoteTimeTicks(7);
p.local_upper_bound = GetLocalTimeTicks(7);
p.test_time = GetRemoteTimeTicks(3);
p.test_delta = RemoteTimeDelta::FromMicroseconds(2);
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(4), results.result_time);
EXPECT_EQ(LocalTimeDelta::FromMicroseconds(1), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, BackEndSkew) {
// Like the previous test, but |remote_lower_bound| is coherent and
// |remote_upper_bound| is skewed.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(1);
p.remote_upper_bound = GetRemoteTimeTicks(7);
p.local_upper_bound = GetLocalTimeTicks(5);
p.test_time = GetRemoteTimeTicks(3);
p.test_delta = RemoteTimeDelta::FromMicroseconds(2);
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(2), results.result_time);
EXPECT_EQ(LocalTimeDelta::FromMicroseconds(1), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, Instantaneous) {
// The bounds are all okay, but the |remote_lower_bound| and
// |remote_upper_bound| have the same value. No adjustments should be made and
// no divide-by-zero errors should occur.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(2);
p.remote_upper_bound = GetRemoteTimeTicks(2);
p.local_upper_bound = GetLocalTimeTicks(3);
p.test_time = GetRemoteTimeTicks(2);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(2), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, OffsetInstantaneous) {
// The bounds are all okay, but the |remote_lower_bound| and
// |remote_upper_bound| have the same value and are offset from the midpoint
// of |local_lower_bound| and |local_upper_bound|. An offset should be applied
// to make the midpoints line up.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(3);
p.remote_upper_bound = GetRemoteTimeTicks(3);
p.local_upper_bound = GetLocalTimeTicks(3);
p.test_time = GetRemoteTimeTicks(3);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(2), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, DisjointInstantaneous) {
// |local_lower_bound| and |local_upper_bound| are the same. No matter what
// the other values are, they must fit within [local_lower_bound,
// local_upper_bound]. So, all of the values should be adjusted so they are
// exactly that value.
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(2);
p.remote_upper_bound = GetRemoteTimeTicks(2);
p.local_upper_bound = GetLocalTimeTicks(1);
p.test_time = GetRemoteTimeTicks(2);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(1), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, RoundingNearEdges) {
// Verify that rounding never causes a value to appear outside the given
// |local_*| range.
const int kMaxRange = 101;
for (int i = 1; i < kMaxRange; ++i) {
for (int j = 1; j < kMaxRange; ++j) {
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(1);
p.remote_lower_bound = GetRemoteTimeTicks(1);
p.remote_upper_bound = GetRemoteTimeTicks(j);
p.local_upper_bound = GetLocalTimeTicks(i);
p.test_time = GetRemoteTimeTicks(1);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_LE(GetLocalTimeTicks(1), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
p.test_time = GetRemoteTimeTicks(j);
p.test_delta = RemoteTimeDelta::FromMicroseconds(j - 1);
results = RunTest(p);
EXPECT_LE(results.result_time, GetLocalTimeTicks(i));
EXPECT_LE(results.result_delta, LocalTimeDelta::FromMicroseconds(i - 1));
}
}
}
TEST(InterProcessTimeTicksConverterTest, DisjointRanges) {
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(10);
p.remote_lower_bound = GetRemoteTimeTicks(30);
p.remote_upper_bound = GetRemoteTimeTicks(41);
p.local_upper_bound = GetLocalTimeTicks(20);
p.test_time = GetRemoteTimeTicks(41);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(20), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, LargeValue_LocalIsLargetThanRemote) {
constexpr auto kWeek = base::TimeTicks::kMicrosecondsPerWeek;
constexpr auto kHour = base::TimeTicks::kMicrosecondsPerHour;
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(4 * kWeek);
p.remote_lower_bound = GetRemoteTimeTicks(4 * kWeek + 2 * kHour);
p.remote_upper_bound = GetRemoteTimeTicks(4 * kWeek + 4 * kHour);
p.local_upper_bound = GetLocalTimeTicks(4 * kWeek + 8 * kHour);
p.test_time = GetRemoteTimeTicks(4 * kWeek + 3 * kHour);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(4 * kWeek + 4 * kHour), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, LargeValue_RemoteIsLargetThanLocal) {
constexpr auto kWeek = base::TimeTicks::kMicrosecondsPerWeek;
constexpr auto kHour = base::TimeTicks::kMicrosecondsPerHour;
TestParams p;
p.local_lower_bound = GetLocalTimeTicks(4 * kWeek);
p.remote_lower_bound = GetRemoteTimeTicks(5 * kWeek);
p.remote_upper_bound = GetRemoteTimeTicks(5 * kWeek + 2 * kHour);
p.local_upper_bound = GetLocalTimeTicks(4 * kWeek + kHour);
p.test_time = GetRemoteTimeTicks(5 * kWeek + kHour);
p.test_delta = RemoteTimeDelta();
TestResults results = RunTest(p);
EXPECT_EQ(GetLocalTimeTicks(4 * kWeek + kHour / 2), results.result_time);
EXPECT_EQ(LocalTimeDelta(), results.result_delta);
}
TEST(InterProcessTimeTicksConverterTest, ValuesOutsideOfRange) {
InterProcessTimeTicksConverter converter(
LocalTimeTicks::FromTimeTicks(TimeTicks::FromInternalValue(15)),
LocalTimeTicks::FromTimeTicks(TimeTicks::FromInternalValue(20)),
RemoteTimeTicks::FromTimeTicks(TimeTicks::FromInternalValue(10)),
RemoteTimeTicks::FromTimeTicks(TimeTicks::FromInternalValue(25)));
RemoteTimeTicks remote_ticks =
RemoteTimeTicks::FromTimeTicks(TimeTicks::FromInternalValue(10));
int64_t result =
converter.ToLocalTimeTicks(remote_ticks).ToTimeTicks().ToInternalValue();
EXPECT_EQ(15, result);
remote_ticks =
RemoteTimeTicks::FromTimeTicks(TimeTicks::FromInternalValue(25));
result =
converter.ToLocalTimeTicks(remote_ticks).ToTimeTicks().ToInternalValue();
EXPECT_EQ(20, result);
remote_ticks =
RemoteTimeTicks::FromTimeTicks(TimeTicks::FromInternalValue(9));
result =
converter.ToLocalTimeTicks(remote_ticks).ToTimeTicks().ToInternalValue();
EXPECT_EQ(14, result);
}
} // anonymous namespace
} // namespace content
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
bb20be31a17f74db99f325c4e6ab85720e79297d | d569bdf7fdb41a1fd0920e12cadcae3c352aa16e | /Sheep.hpp | 25559e1e092b54c0a68e9f12450ce9dd0cfa7741 | [] | no_license | romankarski/PhotoEditor_C | ed61f8688b4052220d4890b41ebf8f10f84c1f31 | 5a974c523911a7b956be27c45a4dbaead4e9e1e1 | refs/heads/master | 2020-05-24T04:27:13.156457 | 2019-06-14T11:00:18 | 2019-06-14T11:00:18 | 187,092,736 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | hpp | #ifndef __Sheep__
#define __Sheep__
#include "Animal.hpp"
class Sheep : public Animal
{
public:
Sheep(int x, int y);
void collision(World& world, Organism* other_organism, const bool reproduction_possible) override;
Sheep * createChild(const Point& position) const override;
};
#endif // define __Sheep__ | [
"noreply@github.com"
] | noreply@github.com |
142d84396725a163b2a2d44c80b54585ba6f818a | 4be854bd5d2fd95149fa667da03c48d3d4036198 | /Math/tricks.cpp | a2d67cf5feae5831d2e24964b2b49cef606a6eac | [] | no_license | teochaban/royalblue | facc82638bfbc3cb0e454bf997fe0188a5268491 | ccb11d589115970024a8ddf80bb9398792741265 | refs/heads/master | 2020-08-05T16:59:42.649759 | 2020-04-18T16:04:32 | 2020-04-18T16:04:32 | 212,624,868 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cpp | ll fexp(ll a, int x, ll mod){ // Fast exponenciation returns a^x % mod
if(x==0)return 1ll;
if(x%2==0){
ll y=fexp(a, x/2, mod);
return (y*y)%mod;
}
return (a*fexp(a, x-1, mod))%mod;
}
ll divv(ll a, ll b, ll mod){ // Division with mod returns a/b % mod
return (a*fexp(b, mod-2, mod))%mod;
}
ll f[N];
ll fat(ll a, ll mod){ // Calculates factorial and stores in f % mod
if(a<=1)return 1;
return f[a]?f[a]:(f[a]=(a*fat(a-1, mod))%mod);
}
ll choose(ll n, ll k, ll mod){ // Returns n choose k % mod
return divv(fat(n, mod), (fat(k, mod)*fat(n-k, mod))%mod, mod)%mod;
}
ll gcd(ll a, ll b){ // Greatest common divisor
return b?gcd(b, a%b):a;
}
ll lcm(ll a, ll b){ // Least common multiple
return (a*b)/gcd(a, b);
}
/* Fast factorization */
int p[N];
void start_fast(int MAX){ // Runs O(nlog(n)) Needs to be called to use fast_fact or ammount_of_divisors.
for(int i=2; i<=MAX; i++){
if(p[i]==0){
for(int j=i; j<=MAX; j+=i){
p[j]=i;
}
}
}
}
vector<int>fast_fact(int x){ // Fast factorization in O(log2(x))
vector<int>ret;
while(x>1){
ret.pb(p[x]);
x/=p[x];
}
return ret;
}
int amount_of_divisors(int x){ // Calculate the ammount of divisors of a number in O(log2(x)) assume already ran start_fast.
if(x==1)return 1;
vector<int>v=fast_fact(x);
int ret=1, curr=2;
for(int i=1; i<v.size(); i++){
if(v[i]==v[i-1])curr++;
else{
ret*=curr;
curr=2;
}
}
return ret*curr;
}
| [
"teo.chaban@mail.utoronto.ca"
] | teo.chaban@mail.utoronto.ca |
0b2c3fdeda0af2bae266bbe009de83704f6b9577 | 66d59c42fc88270bed4ce6ab18e7b6b573b4cf1a | /Mark Allen - Vector header/main.cpp | e12b9ab12f3bae0f7857210bb0dddb68910e37bc | [] | no_license | bluebambu/Leetcode_cpp | 0e749322c5081ee6b61191931c853ab0ce9094f9 | 7a21e391d7a6bde4c202e46047880c30195bb023 | refs/heads/master | 2022-05-28T13:11:06.991523 | 2020-05-03T00:36:13 | 2020-05-03T00:36:13 | 260,799,312 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,216 | cpp | #ifndef VECTOR_H
#define VECTOR_H
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include "dsexceptions.h"
template <typename Object>
class Vector{
private:
int theSize;
int theCapacity;
Object * objects;
public:
explicit Vector( int initSize = 0 )
: theSize{ initSize }, theCapacity{ initSize + SPARE_CAPACITY }
{ objects = new Object[ theCapacity ]; }
Vector( const Vector & rhs )
: theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ nullptr }
{
objects = new Object[ theCapacity ];
for( int k = 0; k < theSize; ++k )
objects[ k ] = rhs.objects[ k ];
}
Vector & operator= ( const Vector & rhs ){ /// 将rhs先复制一份, 为了防止对源数据的改动?
/**
it works by using the copy-constructor's functionality to create a local copy of the data,
then takes the copied data with a swap function, swapping the old data with the new data. The
temporary copy then destructs, taking the old data with it. We are left with a copy of the new data.
*/
Vector copy = rhs;
std::swap( *this, copy );
return *this;
}
~Vector( )
{ delete [ ] objects; }
Vector( Vector && rhs ) /// move-ctor
: theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ rhs.objects }
{
rhs.objects = nullptr;
rhs.theSize = 0;
rhs.theCapacity = 0;
}
Vector & operator= ( Vector && rhs ) /// move-ctor
{
std::swap( theSize, rhs.theSize );
std::swap( theCapacity, rhs.theCapacity );
std::swap( objects, rhs.objects );
return *this;
}
bool empty( ) const
{ return size( ) == 0; }
int size( ) const
{ return theSize; }
int capacity( ) const
{ return theCapacity; }
Object & operator[]( int index )
{
#ifndef NO_CHECK
if( index < 0 || index >= size( ) )
throw ArrayIndexOutOfBoundsException{ };
#endif
return objects[ index ];
}
const Object & operator[]( int index ) const
{
#ifndef NO_CHECK
if( index < 0 || index >= size( ) )
throw ArrayIndexOutOfBoundsException{ };
#endif
return objects[ index ];
}
void resize( int newSize )
{
if( newSize > theCapacity )
reserve( newSize * 2 );
theSize = newSize;
}
void reserve( int newCapacity )
{
if( newCapacity < theSize )
return;
Object *newArray = new Object[ newCapacity ];
for( int k = 0; k < theSize; ++k )
newArray[ k ] = std::move( objects[ k ] ); /// move!!
theCapacity = newCapacity;
std::swap( objects, newArray );
delete [ ] newArray; /// old data were destructed with the newArray
}
// Stacky stuff
void push_back( const Object & x )
{
if( theSize == theCapacity )
reserve( 2 * theCapacity + 1 ); /// if size exceeds the capacity, call reserve() and expand the size doublely.
objects[ theSize++ ] = x;
}
// Stacky stuff
void push_back( Object && x )
{
if( theSize == theCapacity )
reserve( 2 * theCapacity + 1 );
objects[ theSize++ ] = std::move( x );
}
void pop_back( )
{
if( empty( ) )
throw UnderflowException{ };
--theSize;
}
const Object & back ( ) const
{
if( empty( ) )
throw UnderflowException{ };
return objects[ theSize - 1 ];
}
// Iterator stuff: not bounds checked
typedef Object * iterator;
typedef const Object * const_iterator;
iterator begin( )
{ return &objects[ 0 ]; }
const_iterator begin( ) const
{ return &objects[ 0 ]; }
iterator end( )
{ return &objects[ size( ) ]; }
const_iterator end( ) const
{ return &objects[ size( ) ]; }
static const int SPARE_CAPACITY = 2;
};
#endif
| [
"electricitymouse@gmail.com"
] | electricitymouse@gmail.com |
b73b4b153768c747a7ce125155b6eeeef3046cbd | 1b885ed0789cd6ceb4d90b20fcb093883a79eb81 | /include/CALayer.h | c471908d79e423001ddfb2be34421acaba7f914f | [] | no_license | bbqz007/xw | c6b9ba5c87a52adc0823e5332384f24d8bad6533 | fcd05bd44a605b93ba0a482600a1152dd70f116e | refs/heads/master | 2021-10-17T00:27:44.895794 | 2021-10-08T12:17:52 | 2021-10-08T12:17:52 | 60,725,788 | 8 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 4,569 | h | /**
MIT License
Copyright (c) 2015 bbqz007 <https://github.com/bbqz007, http://www.cnblogs.com/bbqzsl>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef _Z_CALayer_H_
#define _Z_CALayer_H_
#include "NSObject.h"
#include "NSArray.h"
#include "CoreGraphics.h"
# pragma warning(push)
# pragma warning(disable:4227)
class CALayer : public NSObject
{
public:
CA_EXTERN virtual ~CALayer();
CA_EXTERN CALayer();
CA_EXTERN void setNeedslayout();
CA_EXTERN BOOL needsLayout();
CA_EXTERN void layoutIfNeeded();
CA_EXTERN virtual void layoutSublayers();
CA_EXTERN void display(CGContext* ctx);
CA_EXTERN virtual void drawInContext(CGContext* ctx);
CA_EXTERN void renderInContext(CGContext* ctx);
CA_EXTERN void addSublayer(CALayer* layer);
protected:
CA_EXTERN CGPathRef makeCornerRadiusPath();
private:
CA_EXTERN virtual void applyAnimating();
#ifdef TEST_WIN32OC2
_0_property(int, i)
_0_property(int*, j)
_0_property_pri_pwi_pti(PUB, k, { return _k; }, PUB, k, { _k = t1; }, PCT, CGRect, k)
_0_property_retain(NSObject*, o)
#endif
protected:
_0_property_setter01(setFrame, CGRect, frame);
_0_property_setter01(setBounds, CGRect, bounds);
_0_property_setter(setAnchorPoint, CGPoint, anchorPoint);
_0_property_setter(setZPosition, CGFloat, zPosition);
//_0_property_pri_pwi_pti(public:, transform, ;, public:, setTransform, ;, protected:, CGAffineTransform, transform);
_0_property_setter(setTransform, CGAffineTransform, transform);
_0_property_BOOL(isHidden,setHidden, /*BOOL,*/ hidden);
_0_property_assign2(setSuperLayer, CALayer*, superLayer);
_0_property_retain2(setSublayers, NSArray*, sublayers);
_0_property_retain2(setMask, CALayer*, mask); // no impl
_0_property_BOOL(isMaskToBounds, setMaskToBounds,/*BOOL,*/ maskToBounds); // no impl
#ifdef CALAYER_IMPL_CONTENTS
NSObject* _contents; // no impl
CGRect _contentRect;
NSString* _contentsGravity;
CGFloat _contentScale;
CGFloat _contentConter;
#endif
_0_property_getset(isOpaque, setOpaque, BOOL, opaque);
_0_property_getter(isNeedsDisplayOnBoundsChange, BOOL, needsDisplayOnBoundsChange);
#if 0 /// compatible
_0_property_getter(isDrawsAsynchronously, BOOL, drawsAsynchronously); // no impl
#else
struct {
BOOL _drawsAsynchronously : 1;
BOOL _needsLayout : 1;
BOOL _needsAnimate : 1;
BOOL _needsAnimateRoot : 1;
} _layerFlags;
_0_flag_getter(isDrawsAsynchronously, _layerFlags, drawsAsynchronously);
_0_flag_getter(isNeedsAnimate, _layerFlags, needsAnimate);
_0_flag_getter(isNeedsAnimateRoot, _layerFlags, needsAnimateRoot);
#endif
_0_property(CGColor, backgroundColor);
_0_property_CGFloat(, cornerRadius);
_0_property_CGFloat(, borderWidth);
_0_property(CGColor, borderColor);
_0_property_CGFloat(, opacity);
_0_property_setter(isAllowsGroupOpacity, BOOL, allowsGroupOpacity);
_0_property_retain2(setFilters, NSArray*, filters);
_0_property_retain2(setBackgroundFilters, NSArray*, backgroundFilters);
_0_property_setter(isShouldRasterize, BOOL, shouldRasterize);
_0_property_CGFloat(, rasterizationScale);
_0_property(CGColor, shadowColor);
_0_property_CGFloat(, shadowOpacity);
_0_property_CGFloat(, shadowRadius);
_0_property_pri_pwi_pti(public:, shadowPath, ;, public:, setShadowPath, ;, protected:, CGPath, shadowPath);
_0_property_BOOL(isSmoothBorder,setSmoothBorder, /*BOOL,*/ smoothBorder);
_0_property_CGFloat(, smoothBorderWidth);
};
NS_EXPORT_CLASS_ID(CALayer)
# pragma warning(pop)
#endif
| [
"noreply@github.com"
] | noreply@github.com |
739649731b2d7b2d90704a5dc4171ce285c276b7 | a1a405631075614ba1123f5dbf7ec579a88bdf0a | /D3D_Framework/D3D_Framework/D3D_Framework/cAseLoadManager.h | c0a1df47118b625c8b972821e1bc1ab7d33db58f | [] | no_license | srhcv1004/GG | a51ff0705cfcd3670523361944d51e51ef4f7e78 | cf6ce84badba3dd7660eecac47a49e45427d3f3e | refs/heads/master | 2021-05-15T05:28:05.586814 | 2018-01-23T10:30:29 | 2018-01-23T10:30:29 | 117,953,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,624 | h | #pragma once
#include "cSingletonBase.h"
struct ST_PNT_VERTEX;
class cAseNode;
class cTexMtl;
class cAnimation;
class cAseLoadManager : public cSingletonBase<cAseLoadManager>
{
private:
FILE* m_pFile;
private:
char m_szToken[1024];
const CHAR* m_pAseFolderName;
private:
cAseNode* m_pAseRoot;
private:
CHAR* GetToken();
int GetInt();
float GetFloat();
bool IsWhite(char ch);
bool IsEqual(const CHAR* pDst, const CHAR* pSrc);
private:
void ProcessID_MATERIAL_LIST();
void ProcessID_MATERIAL(cTexMtl* pTexMtl);
void ProcessID_MAP_DIFFUSE(cTexMtl* pTexMtl);
void ProcessID_SCENE();
cAseNode* ProcessID_GEOMETRY(std::map<std::string, cAseNode*>& mapAseCharacter);
void ProcessID_NODE_TM(cAseNode* pAseNode);
void ProcessID_MESH(cAseNode* pAseNode);
void ProcessID_TM_ANIMATION(cAseNode* pAseNode, cAnimation* pAnimation);
void ProcessID_POS_TRACK(cAnimation* pAnimation);
void ProcessID_ROT_TRACK(cAnimation* pAnimation);
void ProcessID_MESH_VERTEX_LIST(std::vector<D3DXVECTOR3>& vecV);
void ProcessID_MESH_FACE_LIST(std::vector<ST_PNT_VERTEX>& vecVertex, std::vector<D3DXVECTOR3>& vecV);
void ProcessID_MESH_TVERTLIST(std::vector<D3DXVECTOR2>& vecVT);
void ProcessID_MESH_TFACELIST(std::vector<ST_PNT_VERTEX>& vecVertex, std::vector<D3DXVECTOR2>& vecVT);
void ProcessID_MESH_NORMALS(std::vector<ST_PNT_VERTEX>& vecVertex);
public:
cAseLoadManager();
virtual ~cAseLoadManager();
void Setup();
void Release();
cAseNode* LoadAse(std::map<std::string, cAseNode*>& mapAseCharacter,
const CHAR* pAseFolderName, const CHAR* pAseFileName);
};
| [
"leeyj3794@gmail.com"
] | leeyj3794@gmail.com |
aa985dc519105b2768311e9b1e0240d84f7631e9 | a21de044e9c5b4ed3777817cabb728c62f7315fc | /ocean_domination/Ship.cpp | c2e683b156bd75cf2e2859c20be6ea2d8012eb39 | [] | no_license | alyshamsy/oceandomination | 9470889b9f051086b047f7dbc7e6de4f289d2da9 | 3580c399537045c8ad0817bc7a9d81d24c85a925 | refs/heads/master | 2020-03-30T05:30:08.981859 | 2011-05-12T15:47:06 | 2011-05-12T15:47:06 | 32,115,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 760 | cpp | #include "Ship.h"
Ship::Ship() {
}
Ship::~Ship() {
}
int Ship::InitializeShip(Vector& location) {
this->health = 100;
this->location.x = location.x;
this->location.y = location.y;
this->location.z = location.z;
this->player_ammo.missiles = 50;
this->player_ammo.super_missiles = 5;
this->player_ammo.sniper_bullets = 20;
return 0;
}
int Ship::UpdateShipLocation(Vector& current_location) {
this->location.x = current_location.x;
this->location.y = current_location.y;
this->location.z = current_location.z;
return 0;
}
int Ship::UpdateHealth(int& current_health) {
this->health = current_health;
return 0;
}
int Ship::UpdateScore(int& current_score) {
this->score = current_score;
return 0;
} | [
"aly.shamsy@b23e3eda-3cbb-b783-0003-8fc1c118d970"
] | aly.shamsy@b23e3eda-3cbb-b783-0003-8fc1c118d970 |
0a3a4ce39b3936086c2d2303264811c8adfd2f6e | bcfcbef43ccfc3d76b2d0915215c1679b6eb72e3 | /include/rule_expression.h | 72e4c1fd4c61797a7dbcc18bf676a9f5812ce726 | [] | no_license | reflector0x00/C-parser | 60f3d71eeb369d018f50b7a6df806388167983b3 | a1a119be9eb136fd9659d7bf4229565288e30061 | refs/heads/master | 2022-09-16T08:23:13.241345 | 2017-12-25T12:51:06 | 2017-12-25T12:51:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,087 | h | #pragma once
#include <vector>
#include <string>
#include <functional>
#include "parse_rule.h"
#include "expression_chain.h"
template <typename T>
class expression_chain;
template <typename T>
class parse_rule;
template <typename T>
class parse_tree;
template <typename T>
using function_t = std::function<bool(parse_tree<T>&, T&, std::string&)>;
template <typename T>
class rule_expression {
std::vector<expression_chain<T>*> _expressions;
function_t<T> _function;
public:
rule_expression(rule_expression&& o) {
std::swap(_expressions, o._expressions);
_function = o._function;
}
rule_expression(parse_rule<T>& rule, bool always = true) {
_expressions.push_back(new expression_chain<T>(&rule, T(), always));
}
rule_expression(std::string id) {
_expressions.push_back(new expression_chain<T>(nullptr, id[0]));
for (size_t i = 1; i < id.length(); ++i)
_expressions[_expressions.size() - 1]->push_back(new expression_chain<T>(nullptr, id[i]));
}
rule_expression(T symbol) {
_expressions.push_back(new expression_chain<T>(nullptr, symbol));
}
rule_expression(parse_rule<T>& first, parse_rule<T>& second) {
expression_chain<T>* last = new expression_chain<T>(&second);
_expressions.push_back(new expression_chain<T>(&first, T(), true, last));
}
void put_ahead(parse_rule<T>& rule) {
expression_chain<T>* first = new expression_chain<T>(&rule, T(), true, _expressions[_expressions.size() - 1]);
_expressions[_expressions.size() - 1] = first;
}
void put_or_ahead(parse_rule<T>& rule) {
expression_chain<T>* last = new expression_chain<T>(&rule);
for (size_t i = 0; i < _expressions.size(); ++i)
std::swap(last, _expressions[i]);
_expressions.push_back(last);
}
void put_or(T symbol) {
_expressions.push_back(new expression_chain<T>(nullptr, symbol));
}
std::vector<expression_chain<T>*>&& move_expressions() {
return std::move(_expressions);
}
function_t<T> function() {
return _function;
}
void clear() {
_expressions.clear();
}
rule_expression&& operator [](function_t<T> function) {
_expressions[_expressions.size() - 1]->set_function(function);
return std::move(*this);
}
rule_expression&& operator +(rule_expression&& exp) {
_expressions[_expressions.size() - 1]->push_back(exp._expressions[0]);
for (size_t i = 1; i < exp._expressions.size(); ++i)
_expressions.push_back(exp._expressions[i]);
exp.clear();
return std::move(*this);
}
rule_expression&& operator +(parse_rule<T>& rule) {
_expressions[_expressions.size() - 1]->push_back(new expression_chain<T>(&rule));
return std::move(*this);
}
rule_expression&& operator |(rule_expression&& exp) {
for (auto x : exp._expressions)
_expressions.push_back(x);
exp._expressions.clear();
return std::move(*this);
}
rule_expression&& operator |(parse_rule<T>& rule) {
_expressions.push_back(new expression_chain<T>(&rule));
return std::move(*this);
}
~rule_expression() {
for (auto x : _expressions)
delete x;
}
};
template <typename T>
rule_expression<T> rule_terminal(T symbol) {
return rule_expression<T>(symbol);
} | [
"shiftdj.suburb@yahoo.com"
] | shiftdj.suburb@yahoo.com |
7c4bf88e05f14f9cb64818942eada7a826141585 | 3c3050f1a66acdd56bc04601c523730225940b8f | /space/space.cpp | eb7d8b0348a27c2f3f791e5b5465c38b93643c0d | [
"MIT"
] | permissive | chenhongqiao/USACO | f8e54a99598b59d461532b5a6a63a36ba124eedc | 186d9d5fffe2663effbbdb9df2c7726eeb651098 | refs/heads/master | 2023-06-25T05:10:56.754702 | 2023-06-07T19:47:42 | 2023-06-07T19:47:42 | 233,294,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | #include <iostream>
using namespace std;
int n;
char p[1005][1005];
bool u[1005][1005];
int dirx[4] = {1, -1, 0, 0};
int diry[4] = {0, 0, 1, -1};
void func(int x, int y)
{
for (int i = 0; i < 4; i++)
{
if (!(x + dirx[i] < 0 || y + diry[i] < 0 || x + dirx[i] >= n || y + diry[i] >= n || p[x + dirx[i]][y + diry[i]] == '.') && !u[x + dirx[i]][y + diry[i]])
{
u[x + dirx[i]][y + diry[i]] = true;
func(x + dirx[i], y + diry[i]);
}
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> p[i][j];
}
}
int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (p[i][j] == '*' && !u[i][j])
{
u[i][j] = true;
ans++;
func(i, j);
}
}
}
cout << ans << endl;
return 0;
} | [
"harrychen0314@gmail.com"
] | harrychen0314@gmail.com |
9e5b1809291fd834e168b50f0618be376378a80a | 96c275ff2c1e05e7c4de4d2b9077c1f5ed410319 | /Milestones/CXX_Template/BackgroundCosmology.h | 4e9d028ad9efb2d63ebae1b5372501518cc562f7 | [] | no_license | Juliethi/Cosmology2 | bd67f8fa24f8c442f0fc112de491e97256c57498 | 5f4569b6e1706588e1d37b7b88b1845164e81df8 | refs/heads/master | 2022-10-15T00:17:57.697842 | 2020-06-09T16:39:33 | 2020-06-09T16:39:33 | 240,936,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,496 | h | #ifndef _BACKGROUNDCOSMOLOGY_HEADER
#define _BACKGROUNDCOSMOLOGY_HEADER
#include <iostream>
#include <fstream>
#include "Utils.h"
using Vector = std::vector<double>;
class BackgroundCosmology{
private:
// Cosmological parameters
double h; // Little h = H0/(100km/s/Mpc)
double OmegaB; // Baryon density today
double OmegaCDM; // CDM density today
double OmegaLambda; // Dark energy density today
double Neff; // Effective number of relativistic species (3.046 or 0 if ignoring neutrinos)
double TCMB; // Temperature of the CMB today in Kelvin
// Derived parameters
double OmegaR; // Photon density today (follows from TCMB)
double OmegaNu; // Neutrino density today (follows from TCMB and Neff)
double OmegaK; // Curvature density = 1 - OmegaM - OmegaR - OmegaNu - OmegaLambda
double H0; // The Hubble parameter today H0 = 100h km/s/Mpc
// Start and end of x-integration (can be changed)
double x_start = Constants.x_start;
double x_end = Constants.x_end;
// Splines to be made
Spline eta_of_x_spline{"eta"};
public:
// Constructors
//BackgroundCosmology() = delete
BackgroundCosmology(
double h,
double OmegaB,
double OmegaCDM,
double OmegaLambda,
double Neff,
double TCMB
);
// Print some useful info about the class
void info() const;
// Do all the solving
void solve();
// Output some results to file
void output(const std::string filename) const;
// Get functions that we must implement
double eta_of_x(double x) const;
double H_of_x(double x) const;
double Hp_of_x(double x) const;
double dHpdx_of_x(double x) const;
double ddHpddx_of_x(double x) const;
double get_OmegaB(double x = 0.0) const;
double get_OmegaM(double x = 0.0) const;
double get_OmegaR(double x = 0.0) const;
double get_OmegaRtot(double x = 0.0) const;
double get_OmegaNu(double x = 0.0) const;
double get_OmegaCDM(double x = 0.0) const;
double get_OmegaLambda(double x = 0.0) const;
double get_OmegaK(double x = 0.0) const;
double get_OmegaMnu(double x = 0.0) const;
double get_H0() const;
double get_h() const;
double get_Neff() const;
double get_TCMB() const;
};
#endif
| [
"skjeggwow@gmail.com"
] | skjeggwow@gmail.com |
e2aa20793aeb271cc80dbe94fcd083597d6e774b | a5f3b0001cdb692aeffc444a16f79a0c4422b9d0 | /main/svx/source/gallery2/GallerySplitter.cxx | 813108d44587d5c6fb2f6f118867ac7d05f1b9ab | [
"Apache-2.0",
"CPL-1.0",
"bzip2-1.0.6",
"LicenseRef-scancode-other-permissive",
"Zlib",
"LZMA-exception",
"LGPL-2.0-or-later",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-philippe-de-muyter",
"OFL-1.1",
"LGPL-2.1-only",
"MPL-1.1",
"X11",
"LGPL-2.1-or-later",
"GPL-2.0-only",
... | permissive | apache/openoffice | b9518e36d784898c6c2ea3ebd44458a5e47825bb | 681286523c50f34f13f05f7b87ce0c70e28295de | refs/heads/trunk | 2023-08-30T15:25:48.357535 | 2023-08-28T19:50:26 | 2023-08-28T19:50:26 | 14,357,669 | 907 | 379 | Apache-2.0 | 2023-08-16T20:49:37 | 2013-11-13T08:00:13 | C++ | UTF-8 | C++ | false | false | 1,547 | cxx | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "precompiled_svx.hxx"
#include "GallerySplitter.hxx"
DBG_NAME(GallerySplitter)
GallerySplitter::GallerySplitter(
Window* pParent,
const ResId& rResId,
const ::boost::function<void(void)>& rDataChangeFunctor)
: Splitter( pParent, rResId ),
maDataChangeFunctor(rDataChangeFunctor)
{
DBG_CTOR(GallerySplitter,NULL);
}
GallerySplitter::~GallerySplitter()
{
DBG_DTOR(GallerySplitter,NULL);
}
void GallerySplitter::DataChanged( const DataChangedEvent& rDCEvt )
{
Splitter::DataChanged( rDCEvt );
if (maDataChangeFunctor)
maDataChangeFunctor();
}
| [
"af@apache.org"
] | af@apache.org |
779166e7db09fdda9331f3f5f13b6091a31c6353 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-firehose/include/aws/firehose/model/AmazonOpenSearchServerlessS3BackupMode.h | 39938553b44af129a1958a0324b1be779f40127f | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 838 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/firehose/Firehose_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Firehose
{
namespace Model
{
enum class AmazonOpenSearchServerlessS3BackupMode
{
NOT_SET,
FailedDocumentsOnly,
AllDocuments
};
namespace AmazonOpenSearchServerlessS3BackupModeMapper
{
AWS_FIREHOSE_API AmazonOpenSearchServerlessS3BackupMode GetAmazonOpenSearchServerlessS3BackupModeForName(const Aws::String& name);
AWS_FIREHOSE_API Aws::String GetNameForAmazonOpenSearchServerlessS3BackupMode(AmazonOpenSearchServerlessS3BackupMode value);
} // namespace AmazonOpenSearchServerlessS3BackupModeMapper
} // namespace Model
} // namespace Firehose
} // namespace Aws
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
cf356184ec3530ca195017587362eabcc160f887 | 7a327527ddce7e351956daa16cf19aa61c162f78 | /flagdoc.h | e474dfbde31c00d64a7b9fa6de25115b6210aeb0 | [] | no_license | fedorg/uflagdoc | 312ab753049ecd82226c165b4a2a55be6391dd16 | 9357294478352ad475741a519a5468b07bd43df0 | refs/heads/master | 2021-01-13T01:29:59.707534 | 2015-04-05T07:17:26 | 2015-04-05T07:17:26 | 33,433,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,262 | h | #include <vector>
#include <map>
#include <string> //std::string::operator<<
struct FFlagDoc
{
static const std::map<size_t, std::vector<std::string>> ObjectFlags;
static const size_t DescWidth;
static const size_t IndentLength;
static const size_t GetMaxLength();
static inline const std::string Indent(std::string& Name, std::string& Desc);
void FFlagDoc::operator()(size_t Flag) const;
};
const std::map<size_t, std::vector<std::string>> FFlagDoc::ObjectFlags =
{
{ 0x00000001, { "Public", "Object is visible outside its package." } },
{ 0x00000002, { "Standalone", "Keep object around for editing even if unreferenced." } },
{ 0x00000004, { "Native", "Native (UClass only)." } },
{ 0x00000008, { "Transactional", "Object is transactional." } },
{ 0x00000010, { "ClassDefaultObject", "This object is its class's default object" } },
{ 0x00000020, { "ArchetypeObject", "This object is a template for another object - treat like a class default object" } },
{ 0x00000040, { "Transient", "Don't save object." } },
// This group of flags is primarily concerned with garbage collection.
{ 0x00000080, { "RootSet", "Object will not be garbage collected, even if unreferenced." } },
{ 0x00000100, { "Unreachable", "Object is not reachable on the object graph." } },
{ 0x00000200, { "TagGarbageTemp", "This is a temp user flag for various utilities that need to use the garbage collector. The garbage collector itself does not interpret it." } },
// The group of flags tracks the stages of the lifetime of a uobject
{ 0x00000400, { "NeedLoad", "During load, indicates object needs loading." } },
{ 0x00000800, { "AsyncLoading", "Object is being asynchronously loaded." } },
{ 0x00001000, { "NeedPostLoad", "Object needs to be postloaded." } },
{ 0x00002000, { "NeedPostLoadSubobjects", "During load, indicates that the object still needs to instance subobjects and fixup serialized component references" } },
{ 0x00004000, { "PendingKill", "Objects that are pending destruction (invalid for gameplay but valid objects)" } },
{ 0x00008000, { "BeginDestroyed", "BeginDestroy has been called on the object." } },
{ 0x00010000, { "FinishDestroyed", "FinishDestroy has been called on the object." } },
// Misc. Flags
{ 0x00020000, { "BeingRegenerated", "Flagged on UObjects that are used to create UClasses (e.g. Blueprints) while they are regenerating their UClass on load (See FLinkerLoad::CreateExport())" } },
{ 0x00040000, { "DefaultSubObject", "Flagged on subobjects that are defaults" } },
{ 0x00080000, { "WasLoaded", "Flagged on UObjects that were loaded" } },
{ 0x00100000, { "TextExportTransient", "Do not export object to text form (e.g. copy/paste). Generally used for sub-objects that can be regenerated from data in their parent object." } },
{ 0x00200000, { "LoadCompleted", "Object has been completely serialized by linkerload at least once. DO NOT USE THIS FLAG, It should be replaced with RF_WasLoaded." } },
{ 0x00400000, { "InheritableComponentTemplate", "Archetype of the object can be in its super class" } },
{ 0x00800000, { "Async", "Object exists only on a different thread than the game thread." } }
};
const size_t FFlagDoc::IndentLength = FFlagDoc::GetMaxLength();
const size_t FFlagDoc::DescWidth = 50; | [
"fed0000r@gmail.com"
] | fed0000r@gmail.com |
26fa1e2a037f8c6ca4351d6811abb4646cebd5ec | 8a2294f61781b158990697a0fcca010ecdf9f684 | /src/nes/mapper/mapper233.cpp | 85f1a16ae813ccf972d844380c1371396a9b495c | [] | no_license | ruedigergad/emumaster | dce5bbfc096da9ad2d4d1127c3db41fa4ef92bae | 9ab6e8d2bc3966fcb80f6a085346fb0e509bd9e0 | refs/heads/master | 2021-01-10T20:44:34.525335 | 2017-12-29T20:04:13 | 2017-12-29T20:04:13 | 15,937,202 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | cpp | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mapper233.h"
static void writeHigh(u16 addr, u8 data)
{
Q_UNUSED(addr)
if (data & 0x20) {
nesSetRom8KBank(4, (data&0x1F)*2+0);
nesSetRom8KBank(5, (data&0x1F)*2+1);
nesSetRom8KBank(6, (data&0x1F)*2+0);
nesSetRom8KBank(7, (data&0x1F)*2+1);
} else {
u8 bank = (data&0x1E)>>1;
nesSetRom8KBank(4, bank*4+0);
nesSetRom8KBank(5, bank*4+1);
nesSetRom8KBank(6, bank*4+2);
nesSetRom8KBank(7, bank*4+3);
}
if ((data&0xC0) == 0x00)
nesSetMirroring(0, 0, 0, 1);
else if ((data&0xC0) == 0x40)
nesSetMirroring(VerticalMirroring);
else if ((data&0xC0) == 0x80)
nesSetMirroring(HorizontalMirroring);
else
nesSetMirroring(SingleHigh);
}
void Mapper233::reset()
{
NesMapper::reset();
writeHigh = ::writeHigh;
nesSetRom32KBank(0);
}
| [
"r.c.g@gmx.de"
] | r.c.g@gmx.de |
da639bee021454f0426973ea01ba0567f02c5ea8 | 293a26e691533905cdef9d40bbc43fafa473e267 | /app/src/main/jni/webrtc/modules/audio_processing/echo_cancellation_impl.cc | 3c3a2f17bf4e16369e33a50b686d8bf7dd276360 | [] | no_license | mail2chromium/Android-Audio-Processing-Using-WebRTC | 177f5d9331a2e6803047e26ff0d48134e07fcc9d | a9b08732f6eb182acff830a759ed6e21b33d1c2c | refs/heads/master | 2022-07-17T04:23:35.007417 | 2022-06-28T06:56:22 | 2022-06-28T06:56:22 | 224,626,417 | 127 | 35 | null | null | null | null | UTF-8 | C++ | false | false | 16,781 | cc | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_processing/echo_cancellation_impl.h"
#include <assert.h>
#include <string.h>
extern "C" {
#include "webrtc/modules/audio_processing/aec/aec_core.h"
}
#include "webrtc/modules/audio_processing/aec/echo_cancellation.h"
#include "webrtc/modules/audio_processing/audio_buffer.h"
namespace webrtc {
typedef void Handle;
namespace {
int16_t MapSetting(EchoCancellation::SuppressionLevel level) {
switch (level) {
case EchoCancellation::kLowSuppression:
return kAecNlpConservative;
case EchoCancellation::kModerateSuppression:
return kAecNlpModerate;
case EchoCancellation::kHighSuppression:
return kAecNlpAggressive;
}
assert(false);
return -1;
}
AudioProcessing::Error MapError(int err) {
switch (err) {
case AEC_UNSUPPORTED_FUNCTION_ERROR:
return AudioProcessing::kUnsupportedFunctionError;
case AEC_BAD_PARAMETER_ERROR:
return AudioProcessing::kBadParameterError;
case AEC_BAD_PARAMETER_WARNING:
return AudioProcessing::kBadStreamParameterWarning;
default:
// AEC_UNSPECIFIED_ERROR
// AEC_UNINITIALIZED_ERROR
// AEC_NULL_POINTER_ERROR
return AudioProcessing::kUnspecifiedError;
}
}
// Maximum length that a frame of samples can have.
static const size_t kMaxAllowedValuesOfSamplesPerFrame = 160;
// Maximum number of frames to buffer in the render queue.
// TODO(peah): Decrease this once we properly handle hugely unbalanced
// reverse and forward call numbers.
static const size_t kMaxNumFramesToBuffer = 100;
} // namespace
EchoCancellationImpl::EchoCancellationImpl(const AudioProcessing* apm,
rtc::CriticalSection* crit_render,
rtc::CriticalSection* crit_capture)
: ProcessingComponent(),
apm_(apm),
crit_render_(crit_render),
crit_capture_(crit_capture),
drift_compensation_enabled_(false),
metrics_enabled_(false),
suppression_level_(kModerateSuppression),
stream_drift_samples_(0),
was_stream_drift_set_(false),
stream_has_echo_(false),
delay_logging_enabled_(false),
extended_filter_enabled_(false),
delay_agnostic_enabled_(false),
next_generation_aec_enabled_(false),
render_queue_element_max_size_(0) {
RTC_DCHECK(apm);
RTC_DCHECK(crit_render);
RTC_DCHECK(crit_capture);
}
EchoCancellationImpl::~EchoCancellationImpl() {}
int EchoCancellationImpl::ProcessRenderAudio(const AudioBuffer* audio) {
rtc::CritScope cs_render(crit_render_);
if (!is_component_enabled()) {
return AudioProcessing::kNoError;
}
assert(audio->num_frames_per_band() <= 160);
assert(audio->num_channels() == apm_->num_reverse_channels());
int err = AudioProcessing::kNoError;
// The ordering convention must be followed to pass to the correct AEC.
size_t handle_index = 0;
render_queue_buffer_.clear();
for (size_t i = 0; i < apm_->num_output_channels(); i++) {
for (size_t j = 0; j < audio->num_channels(); j++) {
Handle* my_handle = static_cast<Handle*>(handle(handle_index));
// Retrieve any error code produced by the buffering of the farend
// signal
err = WebRtcAec_GetBufferFarendError(
my_handle, audio->split_bands_const_f(j)[kBand0To8kHz],
audio->num_frames_per_band());
if (err != AudioProcessing::kNoError) {
return MapError(err); // TODO(ajm): warning possible?
}
// Buffer the samples in the render queue.
render_queue_buffer_.insert(render_queue_buffer_.end(),
audio->split_bands_const_f(j)[kBand0To8kHz],
(audio->split_bands_const_f(j)[kBand0To8kHz] +
audio->num_frames_per_band()));
}
}
// Insert the samples into the queue.
if (!render_signal_queue_->Insert(&render_queue_buffer_)) {
// The data queue is full and needs to be emptied.
ReadQueuedRenderData();
// Retry the insert (should always work).
RTC_DCHECK_EQ(render_signal_queue_->Insert(&render_queue_buffer_), true);
}
return AudioProcessing::kNoError;
}
// Read chunks of data that were received and queued on the render side from
// a queue. All the data chunks are buffered into the farend signal of the AEC.
void EchoCancellationImpl::ReadQueuedRenderData() {
rtc::CritScope cs_capture(crit_capture_);
if (!is_component_enabled()) {
return;
}
while (render_signal_queue_->Remove(&capture_queue_buffer_)) {
size_t handle_index = 0;
size_t buffer_index = 0;
const size_t num_frames_per_band =
capture_queue_buffer_.size() /
(apm_->num_output_channels() * apm_->num_reverse_channels());
for (size_t i = 0; i < apm_->num_output_channels(); i++) {
for (size_t j = 0; j < apm_->num_reverse_channels(); j++) {
Handle* my_handle = static_cast<Handle*>(handle(handle_index));
WebRtcAec_BufferFarend(my_handle, &capture_queue_buffer_[buffer_index],
num_frames_per_band);
buffer_index += num_frames_per_band;
handle_index++;
}
}
}
}
int EchoCancellationImpl::ProcessCaptureAudio(AudioBuffer* audio) {
rtc::CritScope cs_capture(crit_capture_);
if (!is_component_enabled()) {
return AudioProcessing::kNoError;
}
if (!apm_->was_stream_delay_set()) {
return AudioProcessing::kStreamParameterNotSetError;
}
if (drift_compensation_enabled_ && !was_stream_drift_set_) {
return AudioProcessing::kStreamParameterNotSetError;
}
assert(audio->num_frames_per_band() <= 160);
assert(audio->num_channels() == apm_->num_proc_channels());
int err = AudioProcessing::kNoError;
// The ordering convention must be followed to pass to the correct AEC.
size_t handle_index = 0;
stream_has_echo_ = false;
for (size_t i = 0; i < audio->num_channels(); i++) {
for (size_t j = 0; j < apm_->num_reverse_channels(); j++) {
Handle* my_handle = handle(handle_index);
err = WebRtcAec_Process(my_handle, audio->split_bands_const_f(i),
audio->num_bands(), audio->split_bands_f(i),
audio->num_frames_per_band(),
apm_->stream_delay_ms(), stream_drift_samples_);
if (err != AudioProcessing::kNoError) {
err = MapError(err);
// TODO(ajm): Figure out how to return warnings properly.
if (err != AudioProcessing::kBadStreamParameterWarning) {
return err;
}
}
int status = 0;
err = WebRtcAec_get_echo_status(my_handle, &status);
if (err != AudioProcessing::kNoError) {
return MapError(err);
}
if (status == 1) {
stream_has_echo_ = true;
}
handle_index++;
}
}
was_stream_drift_set_ = false;
return AudioProcessing::kNoError;
}
int EchoCancellationImpl::Enable(bool enable) {
// Run in a single-threaded manner.
rtc::CritScope cs_render(crit_render_);
rtc::CritScope cs_capture(crit_capture_);
// Ensure AEC and AECM are not both enabled.
// The is_enabled call is safe from a deadlock perspective
// as both locks are already held in the correct order.
if (enable && apm_->echo_control_mobile()->is_enabled()) {
return AudioProcessing::kBadParameterError;
}
return EnableComponent(enable);
}
bool EchoCancellationImpl::is_enabled() const {
rtc::CritScope cs(crit_capture_);
return is_component_enabled();
}
int EchoCancellationImpl::set_suppression_level(SuppressionLevel level) {
{
if (MapSetting(level) == -1) {
return AudioProcessing::kBadParameterError;
}
rtc::CritScope cs(crit_capture_);
suppression_level_ = level;
}
return Configure();
}
EchoCancellation::SuppressionLevel EchoCancellationImpl::suppression_level()
const {
rtc::CritScope cs(crit_capture_);
return suppression_level_;
}
int EchoCancellationImpl::enable_drift_compensation(bool enable) {
{
rtc::CritScope cs(crit_capture_);
drift_compensation_enabled_ = enable;
}
return Configure();
}
bool EchoCancellationImpl::is_drift_compensation_enabled() const {
rtc::CritScope cs(crit_capture_);
return drift_compensation_enabled_;
}
void EchoCancellationImpl::set_stream_drift_samples(int drift) {
rtc::CritScope cs(crit_capture_);
was_stream_drift_set_ = true;
stream_drift_samples_ = drift;
}
int EchoCancellationImpl::stream_drift_samples() const {
rtc::CritScope cs(crit_capture_);
return stream_drift_samples_;
}
int EchoCancellationImpl::enable_metrics(bool enable) {
{
rtc::CritScope cs(crit_capture_);
metrics_enabled_ = enable;
}
return Configure();
}
bool EchoCancellationImpl::are_metrics_enabled() const {
rtc::CritScope cs(crit_capture_);
return metrics_enabled_;
}
// TODO(ajm): we currently just use the metrics from the first AEC. Think more
// aboue the best way to extend this to multi-channel.
int EchoCancellationImpl::GetMetrics(Metrics* metrics) {
rtc::CritScope cs(crit_capture_);
if (metrics == NULL) {
return AudioProcessing::kNullPointerError;
}
if (!is_component_enabled() || !metrics_enabled_) {
return AudioProcessing::kNotEnabledError;
}
AecMetrics my_metrics;
memset(&my_metrics, 0, sizeof(my_metrics));
memset(metrics, 0, sizeof(Metrics));
Handle* my_handle = static_cast<Handle*>(handle(0));
int err = WebRtcAec_GetMetrics(my_handle, &my_metrics);
if (err != AudioProcessing::kNoError) {
return MapError(err);
}
metrics->residual_echo_return_loss.instant = my_metrics.rerl.instant;
metrics->residual_echo_return_loss.average = my_metrics.rerl.average;
metrics->residual_echo_return_loss.maximum = my_metrics.rerl.max;
metrics->residual_echo_return_loss.minimum = my_metrics.rerl.min;
metrics->echo_return_loss.instant = my_metrics.erl.instant;
metrics->echo_return_loss.average = my_metrics.erl.average;
metrics->echo_return_loss.maximum = my_metrics.erl.max;
metrics->echo_return_loss.minimum = my_metrics.erl.min;
metrics->echo_return_loss_enhancement.instant = my_metrics.erle.instant;
metrics->echo_return_loss_enhancement.average = my_metrics.erle.average;
metrics->echo_return_loss_enhancement.maximum = my_metrics.erle.max;
metrics->echo_return_loss_enhancement.minimum = my_metrics.erle.min;
metrics->a_nlp.instant = my_metrics.aNlp.instant;
metrics->a_nlp.average = my_metrics.aNlp.average;
metrics->a_nlp.maximum = my_metrics.aNlp.max;
metrics->a_nlp.minimum = my_metrics.aNlp.min;
return AudioProcessing::kNoError;
}
bool EchoCancellationImpl::stream_has_echo() const {
rtc::CritScope cs(crit_capture_);
return stream_has_echo_;
}
int EchoCancellationImpl::enable_delay_logging(bool enable) {
{
rtc::CritScope cs(crit_capture_);
delay_logging_enabled_ = enable;
}
return Configure();
}
bool EchoCancellationImpl::is_delay_logging_enabled() const {
rtc::CritScope cs(crit_capture_);
return delay_logging_enabled_;
}
bool EchoCancellationImpl::is_delay_agnostic_enabled() const {
rtc::CritScope cs(crit_capture_);
return delay_agnostic_enabled_;
}
bool EchoCancellationImpl::is_next_generation_aec_enabled() const {
rtc::CritScope cs(crit_capture_);
return next_generation_aec_enabled_;
}
bool EchoCancellationImpl::is_extended_filter_enabled() const {
rtc::CritScope cs(crit_capture_);
return extended_filter_enabled_;
}
// TODO(bjornv): How should we handle the multi-channel case?
int EchoCancellationImpl::GetDelayMetrics(int* median, int* std) {
rtc::CritScope cs(crit_capture_);
float fraction_poor_delays = 0;
return GetDelayMetrics(median, std, &fraction_poor_delays);
}
int EchoCancellationImpl::GetDelayMetrics(int* median, int* std,
float* fraction_poor_delays) {
rtc::CritScope cs(crit_capture_);
if (median == NULL) {
return AudioProcessing::kNullPointerError;
}
if (std == NULL) {
return AudioProcessing::kNullPointerError;
}
if (!is_component_enabled() || !delay_logging_enabled_) {
return AudioProcessing::kNotEnabledError;
}
Handle* my_handle = static_cast<Handle*>(handle(0));
const int err =
WebRtcAec_GetDelayMetrics(my_handle, median, std, fraction_poor_delays);
if (err != AudioProcessing::kNoError) {
return MapError(err);
}
return AudioProcessing::kNoError;
}
struct AecCore* EchoCancellationImpl::aec_core() const {
rtc::CritScope cs(crit_capture_);
if (!is_component_enabled()) {
return NULL;
}
Handle* my_handle = static_cast<Handle*>(handle(0));
return WebRtcAec_aec_core(my_handle);
}
int EchoCancellationImpl::Initialize() {
int err = ProcessingComponent::Initialize();
{
rtc::CritScope cs(crit_capture_);
if (err != AudioProcessing::kNoError || !is_component_enabled()) {
return err;
}
}
AllocateRenderQueue();
return AudioProcessing::kNoError;
}
void EchoCancellationImpl::AllocateRenderQueue() {
const size_t new_render_queue_element_max_size = std::max<size_t>(
static_cast<size_t>(1),
kMaxAllowedValuesOfSamplesPerFrame * num_handles_required());
rtc::CritScope cs_render(crit_render_);
rtc::CritScope cs_capture(crit_capture_);
// Reallocate the queue if the queue item size is too small to fit the
// data to put in the queue.
if (render_queue_element_max_size_ < new_render_queue_element_max_size) {
render_queue_element_max_size_ = new_render_queue_element_max_size;
std::vector<float> template_queue_element(render_queue_element_max_size_);
render_signal_queue_.reset(
new SwapQueue<std::vector<float>, RenderQueueItemVerifier<float>>(
kMaxNumFramesToBuffer, template_queue_element,
RenderQueueItemVerifier<float>(render_queue_element_max_size_)));
render_queue_buffer_.resize(render_queue_element_max_size_);
capture_queue_buffer_.resize(render_queue_element_max_size_);
} else {
render_signal_queue_->Clear();
}
}
void EchoCancellationImpl::SetExtraOptions(const Config& config) {
{
rtc::CritScope cs(crit_capture_);
extended_filter_enabled_ = config.Get<ExtendedFilter>().enabled;
delay_agnostic_enabled_ = config.Get<DelayAgnostic>().enabled;
next_generation_aec_enabled_ = config.Get<NextGenerationAec>().enabled;
}
Configure();
}
void* EchoCancellationImpl::CreateHandle() const {
return WebRtcAec_Create();
}
void EchoCancellationImpl::DestroyHandle(void* handle) const {
assert(handle != NULL);
WebRtcAec_Free(static_cast<Handle*>(handle));
}
int EchoCancellationImpl::InitializeHandle(void* handle) const {
// Not locked as it only relies on APM public API which is threadsafe.
assert(handle != NULL);
// TODO(ajm): Drift compensation is disabled in practice. If restored, it
// should be managed internally and not depend on the hardware sample rate.
// For now, just hardcode a 48 kHz value.
return WebRtcAec_Init(static_cast<Handle*>(handle),
apm_->proc_sample_rate_hz(), 48000);
}
int EchoCancellationImpl::ConfigureHandle(void* handle) const {
rtc::CritScope cs_render(crit_render_);
rtc::CritScope cs_capture(crit_capture_);
assert(handle != NULL);
AecConfig config;
config.metricsMode = metrics_enabled_;
config.nlpMode = MapSetting(suppression_level_);
config.skewMode = drift_compensation_enabled_;
config.delay_logging = delay_logging_enabled_;
WebRtcAec_enable_extended_filter(
WebRtcAec_aec_core(static_cast<Handle*>(handle)),
extended_filter_enabled_ ? 1 : 0);
WebRtcAec_enable_delay_agnostic(
WebRtcAec_aec_core(static_cast<Handle*>(handle)),
delay_agnostic_enabled_ ? 1 : 0);
WebRtcAec_enable_next_generation_aec(
WebRtcAec_aec_core(static_cast<Handle*>(handle)),
next_generation_aec_enabled_ ? 1 : 0);
return WebRtcAec_set_config(static_cast<Handle*>(handle), config);
}
size_t EchoCancellationImpl::num_handles_required() const {
// Not locked as it only relies on APM public API which is threadsafe.
return apm_->num_output_channels() * apm_->num_reverse_channels();
}
int EchoCancellationImpl::GetHandleError(void* handle) const {
// Not locked as it does not rely on anything in the state.
assert(handle != NULL);
return AudioProcessing::kUnspecifiedError;
}
} // namespace webrtc
| [
"mail2ch.usman@gmail.com"
] | mail2ch.usman@gmail.com |
e16e6194d036bb2780ec7b1aa8fa7deee2f8465e | 4216559b06f85b1ca408e4be706b0cc311b7c465 | /source/src/tile.cpp | fd9522315d51988fe8db03d13b1e5d3b95a05a8b | [] | no_license | Chidoge/CaveStory | ba281fe808539b54202dbc24ff5f5b24a9187701 | 8e3d0e3648fc9ff0fbb8ac0e8e4852f785db4e25 | refs/heads/master | 2022-10-26T09:19:19.186299 | 2020-06-11T04:59:52 | 2020-06-11T04:59:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | cpp | #include "../headers/tile.h"
#include "../headers/graphics.h"
#include <SDL2/SDL.h>
Tile::Tile() {}
Tile::Tile(SDL_Texture* tileset, Vector2 size, Vector2 tilesetPosition, Vector2 position) :
_tileset(tileset),
_size(size),
_tilesetPosition(tilesetPosition),
_position(Vector2(position.x * globals::SPRITE_SCALE, position.y * globals::SPRITE_SCALE))
{}
void Tile::update(int elapsedTime) {}
void Tile::draw(Graphics &graphics) {
SDL_Rect destRect = { this->_position.x, this->_position.y, (int)(this->_size.x * globals::SPRITE_SCALE), (int)(this->_size.y * globals::SPRITE_SCALE) };
SDL_Rect sourceRect = { this->_tilesetPosition.x, this->_tilesetPosition.y, this->_size.x, this->_size.y };
graphics.blitSurface(this->_tileset, &sourceRect, &destRect);
} | [
"lincoln.choy1997@gmail.com"
] | lincoln.choy1997@gmail.com |
58d00dba55f10a9a8d0e8abb2a3ae601b7ea88a6 | 9a488a219a4f73086dc704c163d0c4b23aabfc1f | /tags/Release-0_9_0/src/Tab.cc | 986bbd88f91a3954a38c9600f7a82e24577dd618 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | BackupTheBerlios/fluxbox-svn | 47b8844b562f56d02b211fd4323c2a761b473d5b | 3ac62418ccf8ffaddbf3c181f28d2f652543f83f | refs/heads/master | 2016-09-05T14:55:27.249504 | 2007-12-14T23:27:57 | 2007-12-14T23:27:57 | 40,667,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,205 | cc | // Tab.cc for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen (fluxgen at linuxmail.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: Tab.cc,v 1.55 2003/02/18 15:11:09 rathnor Exp $
#include "Tab.hh"
#include "i18n.hh"
#include "DrawUtil.hh"
#include "Screen.hh"
#include "fluxbox.hh"
#include "ImageControl.hh"
#include <iostream>
using namespace std;
bool Tab::m_stoptabs = false;
Tab::t_tabplacementlist Tab::m_tabplacementlist[] = {
{PTOP, "Top"},
{PBOTTOM, "Bottom"},
{PLEFT, "Left"},
{PRIGHT, "Right"},
{PNONE, "none"}
};
Tab::t_tabplacementlist Tab::m_tabalignmentlist[] = {
{ALEFT, "Left"},
{ACENTER, "Center"},
{ARIGHT, "Right"},
{ARELATIVE, "Relative"},
{ANONE, "none"}
};
Tab::Tab(FluxboxWindow *win, Tab *prev, Tab *next) {
//set default values
m_focus = m_moving = false;
m_configured = true; // only set to false before Fluxbox::reconfigure
m_move_x = m_move_y = 0;
m_prev = prev; m_next = next;
m_win = win;
m_display = BaseDisplay::getXDisplay();
if ((m_win->getScreen()->getTabPlacement() == PLEFT ||
m_win->getScreen()->getTabPlacement() == PRIGHT) &&
m_win->getScreen()->isTabRotateVertical() &&
!m_win->isShaded()) {
m_size_w = m_win->getScreen()->getTabHeight();
m_size_h = m_win->getScreen()->getTabWidth();
} else {
m_size_w = m_win->getScreen()->getTabWidth();
m_size_h = m_win->getScreen()->getTabHeight();
}
createTabWindow();
calcIncrease();
}
Tab::~Tab() {
disconnect();
Fluxbox::instance()->removeTabSearch(m_tabwin);
XDestroyWindow(m_display, m_tabwin);
}
//---------------- createTabWindow ---------------
// (private)
// Creates the Window for tab to be above the title window.
// This should only be called by the constructor.
//-------------------------------------------------
void Tab::createTabWindow() {
unsigned long attrib_mask = CWBackPixmap | CWBackPixel | CWBorderPixel |
CWColormap | CWOverrideRedirect | CWEventMask;
XSetWindowAttributes attrib;
attrib.background_pixmap = None;
attrib.background_pixel = attrib.border_pixel =
m_win->getScreen()->getWindowStyle()->tab.border_color.pixel();
attrib.colormap = m_win->getScreen()->colormap();
attrib.override_redirect = True;
attrib.event_mask = ButtonPressMask | ButtonReleaseMask |
ButtonMotionMask | ExposureMask | EnterWindowMask;
//Notice that m_size_w gets the TOTAL width of tabs INCLUDING borders
m_tabwin = XCreateWindow(m_display, m_win->getScreen()->getRootWindow(),
-30000, -30000, //TODO: So that it wont flicker or
// appear before the window do
m_size_w - m_win->getScreen()->getWindowStyle()->tab.border_width_2x,
m_size_h - m_win->getScreen()->getWindowStyle()->tab.border_width_2x,
m_win->getScreen()->getWindowStyle()->tab.border_width,
m_win->getScreen()->getDepth(), InputOutput,
m_win->getScreen()->getVisual(), attrib_mask, &attrib);
//set grab
XGrabButton(m_display, Button1, Mod1Mask, m_tabwin, True,
ButtonReleaseMask | ButtonMotionMask, GrabModeAsync,
GrabModeAsync, None, Fluxbox::instance()->getMoveCursor());
//save to tabsearch
Fluxbox::instance()->saveTabSearch(m_tabwin, this);
XMapSubwindows(m_display, m_tabwin);
// don't show if the window is iconified
if (!m_win->isIconic())
XMapWindow(m_display, m_tabwin);
decorate();
}
//-------------- focus --------------------
// Called when the focus changes in m_win
// updates pixmap or color and draws the tab
//-----------------------------------------
void Tab::focus() {
if (m_win->isFocused()) {
if (m_focus_pm)
XSetWindowBackgroundPixmap(m_display, m_tabwin, m_focus_pm);
else
XSetWindowBackground(m_display, m_tabwin, m_focus_pixel);
} else {
if (m_unfocus_pm)
XSetWindowBackgroundPixmap(m_display, m_tabwin, m_unfocus_pm);
else
XSetWindowBackground(m_display, m_tabwin, m_unfocus_pixel);
}
XClearWindow(m_display, m_tabwin);
draw(false);
}
//-------------- raise --------------------
// Raises the tabs in the tablist
//-----------------------------------------
void Tab::raise() {
//get first tab
/*
Tab *tab = 0;
//raise tabs
Workspace::Stack st;
for (tab = getFirst(this); tab!=0; tab = tab->m_next) {
st.push_back(tab->m_tabwin);
}
m_win->getScreen()->raiseWindows(st);
*/
}
//-------------- lower --------------------
// Lowers the tabs in the tablist AND
// the windows the tabs relate to
//-----------------------------------------
void Tab::lower() {
Tab *current = this;
FluxboxWindow *win = 0; //convenience
//this have to be done in the correct order, otherwise we'll switch the window
//being ontop in the group
do {
XLowerWindow(m_display, current->m_tabwin); //lower tabwin and tabs window
win = current->getWindow();
win->lower();
current = current->next(); //get next
if (current == 0)
current = getFirst(this); //there weren't any after, get the first
} while (current != this);
}
//-------------- loadTheme -----------------
// loads the texture with the correct
// width and height, this is necessary in
// vertical and relative tab modes
// TODO optimize this
//------------------------------------------
void Tab::loadTheme() {
FbTk::ImageControl *image_ctrl = m_win->getScreen()->getImageControl();
Pixmap tmp = m_focus_pm;
const FbTk::Texture *texture = &(m_win->getScreen()->getWindowStyle()->tab.l_focus);
if (texture->type() & FbTk::Texture::PARENTRELATIVE ) {
const FbTk::Texture &pt = m_win->getScreen()->getWindowStyle()->tab.t_focus;
if (pt.type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
m_focus_pm = None;
m_focus_pixel = pt.color().pixel();
} else
m_focus_pm =
image_ctrl->renderImage(m_size_w, m_size_h, pt);
if (tmp) image_ctrl->removeImage(tmp);
} else {
if (texture->type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
m_focus_pm = None;
m_focus_pixel = texture->color().pixel();
} else
m_focus_pm =
image_ctrl->renderImage(m_size_w, m_size_h, *texture);
if (tmp) image_ctrl->removeImage(tmp);
}
tmp = m_unfocus_pm;
texture = &(m_win->getScreen()->getWindowStyle()->tab.l_unfocus);
if (texture->type() & FbTk::Texture::PARENTRELATIVE ) {
const FbTk::Texture &pt = m_win->getScreen()->getWindowStyle()->tab.t_unfocus;
if (pt.type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
m_unfocus_pm = None;
m_unfocus_pixel = pt.color().pixel();
} else
m_unfocus_pm =
image_ctrl->renderImage(m_size_w, m_size_h, pt);
} else {
if (texture->type() == (FbTk::Texture::FLAT | FbTk::Texture::SOLID)) {
m_unfocus_pm = None;
m_unfocus_pixel = texture->color().pixel();
} else
m_unfocus_pm =
image_ctrl->renderImage(m_size_w, m_size_h, *texture);
}
if (tmp) image_ctrl->removeImage(tmp);
}
/**
decorates the tab with current theme
*/
void Tab::decorate() {
loadTheme();
XSetWindowBorderWidth(m_display, m_tabwin,
m_win->getScreen()->getWindowStyle()->tab.border_width);
XSetWindowBorder(m_display, m_tabwin,
m_win->getScreen()->getWindowStyle()->tab.border_color.pixel());
}
/**
Deiconifies the tab
Used from FluxboxWindow to deiconify the tab when the window is deiconfied
*/
void Tab::deiconify() {
XMapWindow(m_display, m_tabwin);
}
/**
Iconifies the tab.
Used from FluxboxWindow to hide tab win when window is iconified
disconnects itself from the list
*/
void Tab::iconify() {
disconnect();
withdraw();
if(!Fluxbox::instance()->useTabs() && !m_next && !m_prev)//if we don't want to use tabs that much
m_win->setTab(false);//let's get rid of this loner tab
}
/**
Unmaps the tab from display
*/
void Tab::withdraw() {
XUnmapWindow(m_display, m_tabwin);
}
/**
Set/reset the the sticky on all windows in the list
*/
void Tab::stick() {
Tab *tab;
bool wasstuck = m_win->isStuck();
//now do stick for all windows in the list
for (tab = getFirst(this); tab != 0; tab = tab->m_next) {
FluxboxWindow *win = tab->m_win; //just for convenience
if (wasstuck) {
win->blackbox_attrib.flags ^= BaseDisplay::ATTRIB_OMNIPRESENT;
win->blackbox_attrib.attrib ^= BaseDisplay::ATTRIB_OMNIPRESENT;
win->stuck = false;
} else {
win->stuck = true;
BScreen *screen = win->getScreen();
if (!win->isIconic() && !(win->getWorkspaceNumber() !=
screen->getCurrentWorkspaceID())) {
screen->reassociateWindow(win, screen->getCurrentWorkspaceID(), true);
}
win->blackbox_attrib.flags |= BaseDisplay::ATTRIB_OMNIPRESENT;
win->blackbox_attrib.attrib |= BaseDisplay::ATTRIB_OMNIPRESENT;
}
win->setState(win->current_state);
}
}
/**
Resize the window's in the tablist
*/
void Tab::resize() {
Tab *tab;
//now move and resize the windows in the list
for (tab = getFirst(this); tab != 0; tab = tab->m_next) {
if (tab!=this) {
tab->m_win->moveResize(m_win->getXFrame(), m_win->getYFrame(),
m_win->getWidth(), m_win->getHeight());
}
}
// need to resize tabs if in relative mode
if (m_win->getScreen()->getTabAlignment() == ARELATIVE) {
calcIncrease();
setPosition();
}
}
/**
Shades the windows in the tablist
*/
void Tab::shade() {
Tab *tab;
for(tab = getFirst(this); tab != 0; tab = tab->m_next) {
if (tab==this)
continue;
tab->m_win->shade();
}
if (m_win->getScreen()->getTabPlacement() == PLEFT ||
m_win->getScreen()->getTabPlacement() == PRIGHT) {
resizeGroup();
calcIncrease();
}
if (!(m_win->getScreen()->getTabPlacement() == PTOP))
setPosition();
}
/**
Draws the tab
if pressed = true then it draws the tab in pressed
mode else it draws it in normal mode
TODO: the "draw in pressed mode"
*/
void Tab::draw(bool pressed) const {
XClearWindow(m_display, m_tabwin);
if (m_win->getTitle().size() == 0) // we don't have anything to draw
return;
GC gc = ((m_win->isFocused()) ? m_win->getScreen()->getWindowStyle()->tab.l_text_focus_gc :
m_win->getScreen()->getWindowStyle()->tab.l_text_unfocus_gc);
Theme::WindowStyle *winstyle = m_win->getScreen()->getWindowStyle();
size_t dlen = m_win->getTitle().size();
size_t max_width = m_size_w; // special cases in rotated mode
if (winstyle->tab.font.isRotated() && !m_win->isShaded())
max_width = m_size_h;
int dx = DrawUtil::doAlignment(max_width, 1, //m_win->frame.bevel_w,
winstyle->tab.justify,
winstyle->tab.font,
m_win->getTitle().c_str(), m_win->getTitle().size(), dlen);
int dy = winstyle->tab.font.ascent() + 1; //m_win->frame.bevel_w;
bool rotate = false;
// swap dx and dy if we're rotated
if (winstyle->tab.font.isRotated() && !m_win->isShaded()) {
int tmp = dy;
dy = m_size_h - dx; // upside down (reverse direction)
dx = tmp;
rotate = true;
}
// draw normal without rotation
winstyle->tab.font.drawText(
m_tabwin,
m_win->getScreen()->getScreenNumber(),
gc,
m_win->getTitle().c_str(), dlen,
dx, dy,
rotate);
}
/**
Helper for the Tab::setPosition() call
returns the y position component correctly
according to shading in cases PBOTTOM and
isShaded()
*/
int Tab::setPositionShadingHelper(bool shaded) {
if (shaded) {
return m_win->getYFrame() + m_win->getTitleHeight() +
m_win->getScreen()->getBorderWidth2x();
} else {
return m_win->getYFrame() + m_win->getHeight() +
m_win->getScreen()->getBorderWidth2x();
}
}
/**
Helpers for correct alignment of tabs used
by the setPosition() call
return x/y positions correctly according to
alignment, the 1st for cases PTOP and PBOTTOM
the 2nd for cases PLEFT and PRIGHT
*/
int Tab::setPositionTBAlignHelper(Alignment align) {
switch(align) {
case ARELATIVE:
case ALEFT:
return m_win->getXFrame();
break;
case ACENTER:
return calcCenterXPos();
break;
case ARIGHT:
return m_win->getXFrame() + m_win->getWidth() +
m_win->getScreen()->getBorderWidth2x() - m_size_w;
default:
#ifdef DEBUG
cerr << __FILE__ << ":" <<__LINE__ << ": " <<
"Unsupported Alignment" << endl;
#endif //DEBUG
return 0;
break;
}
}
int Tab::setPositionLRAlignHelper(Alignment align) {
switch(align) {
case ALEFT:
return m_win->getYFrame() - m_size_h + m_win->getHeight() +
m_win->getScreen()->getBorderWidth2x();
break;
case ACENTER:
return calcCenterYPos();
break;
case ARELATIVE:
case ARIGHT:
return m_win->getYFrame();
break;
default:
#ifdef DEBUG
cerr << __FILE__ << ":"<< __LINE__ << ": " <<
"Unsupported Alignment" << endl;
#endif //DEBUG
return 0;
break;
}
}
/**
Position tab ( follow the m_win pos ).
(and resize)
Set new position of the other tabs in the chain
*/
void Tab::setPosition() {
//don't do anything if the tablist is freezed
if (m_stoptabs)
return;
Tab *tab;
int pos_x = 0, pos_y = 0;
m_stoptabs = true; //freeze tablist
//and check for max tabs
//Tab placement + alignment
switch (m_win->getScreen()->getTabPlacement()) {
case PTOP:
pos_y = m_win->getYFrame() - m_size_h;
pos_x = setPositionTBAlignHelper(
m_win->getScreen()->getTabAlignment());
break;
case PBOTTOM:
pos_y = setPositionShadingHelper(m_win->isShaded());
pos_x = setPositionTBAlignHelper(
m_win->getScreen()->getTabAlignment());
break;
case PLEFT:
pos_x = m_win->isShaded() ?
setPositionTBAlignHelper(m_win->getScreen()->getTabAlignment()) :
m_win->getXFrame() - m_size_w;
pos_y = m_win->isShaded() ?
setPositionShadingHelper(true) :
setPositionLRAlignHelper(m_win->getScreen()->getTabAlignment());
break;
case PRIGHT:
pos_x = m_win->isShaded() ?
setPositionTBAlignHelper(m_win->getScreen()->getTabAlignment()) :
m_win->getXFrame() + m_win->getWidth() +
m_win->getScreen()->getBorderWidth2x();
pos_y = m_win->isShaded() ?
setPositionShadingHelper(true) :
setPositionLRAlignHelper(m_win->getScreen()->getTabAlignment());
break;
default:
if(m_win->isShaded()) {
pos_y = setPositionShadingHelper(true);
pos_x = setPositionTBAlignHelper(
m_win->getScreen()->getTabAlignment());
} else {
setPositionShadingHelper(false);
}
break;
}
for (tab = getFirst(this);
tab!=0;
pos_x += tab->m_inc_x, pos_y += tab->m_inc_y,
tab = tab->m_next){
XMoveWindow(m_display, tab->m_tabwin, pos_x, pos_y);
//dont move FluxboxWindow if the iterator = this
if (tab != this) {
tab->m_win->moveResize(m_win->getXFrame(), m_win->getYFrame(),
m_win->getWidth(), m_win->getHeight());
}
}
m_stoptabs = false;//thaw tablist
}
//Moves the tab to the left
void Tab::movePrev() {
insert(m_prev);
}
//Moves the tab to the next tab if m_next != 0
void Tab::moveNext() {
if(m_next == 0)
return;
Tab *tmp = m_next;
disconnect();
tmp->insert(this);
}
/**
calculates m_inc_x and m_inc_y for tabs
used for positioning the tabs.
*/
void Tab::calcIncrease() {
Tab *tab;
int inc_x = 0, inc_y = 0;
unsigned int i = 0, tabs = numObjects();
if (m_win->getScreen()->getTabPlacement() == PTOP ||
m_win->getScreen()->getTabPlacement() == PBOTTOM ||
m_win->isShaded()) {
inc_y = 0;
switch(m_win->getScreen()->getTabAlignment()) {
case ALEFT:
inc_x = m_size_w;
break;
case ACENTER:
inc_x = m_size_w;
break;
case ARIGHT:
inc_x = -m_size_w;
break;
case ARELATIVE:
inc_x = calcRelativeWidth();
break;
default:
break;
}
} else if (m_win->getScreen()->getTabPlacement() == PLEFT ||
m_win->getScreen()->getTabPlacement() == PRIGHT) {
inc_x = 0;
switch(m_win->getScreen()->getTabAlignment()) {
case ALEFT:
inc_y = -m_size_h;
break;
case ACENTER:
inc_y = m_size_h;
break;
case ARIGHT:
inc_y = m_size_h;
break;
case ARELATIVE:
inc_y = calcRelativeHeight();
break;
default:
break;
}
}
for (tab = getFirst(this); tab!=0; tab = tab->m_next, i++) {
//TODO: move this out from here?
if ((m_win->getScreen()->getTabPlacement() == PTOP ||
m_win->getScreen()->getTabPlacement() == PBOTTOM ||
m_win->isShaded()) &&
m_win->getScreen()->getTabAlignment() == ARELATIVE) {
if (!((m_win->getWidth() +
m_win->getScreen()->getBorderWidth2x()) % tabs) ||
i >= ((m_win->getWidth() +
m_win->getScreen()->getBorderWidth2x()) % tabs)) {
tab->setTabWidth(inc_x);
tab->m_inc_x = inc_x;
} else { // adding 1 extra pixel to get tabs like win width
tab->setTabWidth(inc_x + 1);
tab->m_inc_x = inc_x + 1;
}
tab->m_inc_y = inc_y;
} else if (m_win->getScreen()->getTabAlignment() == ARELATIVE) {
if (!((m_win->getHeight() +
m_win->getScreen()->getBorderWidth2x()) % tabs) ||
i >= ((m_win->getHeight() +
m_win->getScreen()->getBorderWidth2x()) % tabs)) {
tab->setTabHeight(inc_y);
tab->m_inc_y = inc_y;
} else {
// adding 1 extra pixel to get tabs match window width
tab->setTabHeight(inc_y + 1);
tab->m_inc_y = inc_y + 1;
}
tab->m_inc_x = inc_x;
} else { // non relative modes
tab->m_inc_x = inc_x;
tab->m_inc_y = inc_y;
}
}
}
/**
Handle button press event here.
*/
void Tab::buttonPressEvent(XButtonEvent *be) {
//draw in pressed mode
draw(true);
//invoke root menu with auto-tab?
/* if (be->button == 3) {
BScreen *screen = m_win->getScreen();
Rootmenu *rootmenu = screen->getRootmenu();
if (! rootmenu->isVisible()) {
Fluxbox::instance()->checkMenu();
screen->getRootmenu()->move(be->x_root, be->y_root-rootmenu->titleHeight());
rootmenu->setAutoGroupWindow(m_win->getClientWindow());
rootmenu->show();
}
}
//otherwise let the window handle the event
else {
//set window to titlewindow so we can take advantage of drag function
be->window = m_win->frame().titlebar().window();
//call windows buttonpress eventhandler
m_win->buttonPressEvent(*be);
}
*/
}
/**
Handle button release event here.
If tab is dropped then it should try to find
the window where the tab where dropped.
*/
void Tab::buttonReleaseEvent(XButtonEvent *be) {
if (m_moving) {
m_moving = false;
//erase tabmoving rectangle
XDrawRectangle(m_display, m_win->getScreen()->getRootWindow(),
m_win->getScreen()->getOpGC(),
m_move_x, m_move_y,
m_size_w, m_size_h);
Fluxbox::instance()->ungrab();
XUngrabPointer(m_display, CurrentTime);
//storage of window and pos of window where we dropped the tab
Window child;
int dest_x = 0, dest_y = 0;
//find window on coordinates of buttonReleaseEvent
if (XTranslateCoordinates(m_display, m_win->getScreen()->getRootWindow(),
m_win->getScreen()->getRootWindow(),
be->x_root, be->y_root, &dest_x, &dest_y, &child)) {
Tab *tab = Fluxbox::instance()->searchTab(child);
FluxboxWindow *win = Fluxbox::instance()->searchWindow(child);
if(win!=0 && m_win->getScreen()->isSloppyWindowGrouping())
win->setTab(true);
//search tablist for a tabwindow
if ( (tab!=0) || (m_win->getScreen()->isSloppyWindowGrouping() &&
(win!=0) && (tab = win->getTab())!=0)) {
if (tab == this) // inserting ourself to ourself causes a disconnect
return;
// do only attach a hole chain if we dropped the
// first tab in the dropped chain...
if (m_prev)
disconnect();
// attach this tabwindow chain to the tabwindow chain we found.
tab->insert(this);
} else { //Dropped nowhere
disconnect();
// convenience
unsigned int placement = m_win->getScreen()->getTabPlacement();
// (ab)using dest_x and dest_y
dest_x = be->x_root;
dest_y = be->y_root;
if (placement == PTOP || placement == PBOTTOM || m_win->isShaded()) {
if (placement == PBOTTOM && !m_win->isShaded())
dest_y -= m_win->getHeight();
else if (placement != PTOP && m_win->isShaded())
dest_y -= m_win->getTitleHeight();
else // PTOP
dest_y += m_win->getTitleHeight();
switch(m_win->getScreen()->getTabAlignment()) {
case ACENTER:
dest_x -= (m_win->getWidth() / 2) - (m_size_w / 2);
break;
case ARIGHT:
dest_x -= m_win->getWidth() - m_size_w;
break;
default:
break;
}
} else { // PLEFT & PRIGHT
if (placement == PRIGHT)
dest_x = be->x_root - m_win->getWidth();
switch(m_win->getScreen()->getTabAlignment()) {
case ACENTER:
dest_y -= (m_win->getHeight() / 2) - (m_size_h / 2);
break;
case ALEFT:
dest_y -= m_win->getHeight() - m_size_h;
break;
default:
break;
}
}
//TODO: this causes an calculate increase event, even if we
// only are moving a window
m_win->moveResize(dest_x, dest_y, m_win->getWidth(), m_win->getHeight());
if(!Fluxbox::instance()->useTabs())
m_win->setTab(false);//Remove tab from window, as it is now alone...
}
}
} else {
//raise this tabwindow
raise();
//set window to title window soo we can use m_win handler for menu
be->window = m_win->frame().titlebar().window();
//call windows buttonrelease event handler so it can popup a menu if needed
m_win->buttonReleaseEvent(*be);
}
}
//------------- exposeEvent ------------
// Handle expose event here.
// Draws the tab unpressed
//--------------------------------------
void Tab::exposeEvent(XExposeEvent *ee) {
draw(false);
}
//----------- motionNotifyEvent --------
// Handles motion event here
// Draws the rectangle of moving tab
//--------------------------------------
void Tab::motionNotifyEvent(XMotionEvent *me) {
Fluxbox *fluxbox = Fluxbox::instance();
//if mousebutton 2 is pressed
if (me->state & Button2Mask) {
if (!m_moving) {
m_moving = true;
XGrabPointer(m_display, me->window, False, Button2MotionMask |
ButtonReleaseMask, GrabModeAsync, GrabModeAsync,
None, fluxbox->getMoveCursor(), CurrentTime);
fluxbox->grab();
m_move_x = me->x_root - 1;
m_move_y = me->y_root - 1;
XDrawRectangle(m_display, m_win->getScreen()->getRootWindow(),
m_win->getScreen()->getOpGC(),
m_move_x, m_move_y,
m_size_w, m_size_h);
} else {
int dx = me->x_root - 1, dy = me->y_root - 1;
dx -= m_win->getScreen()->getBorderWidth();
dy -= m_win->getScreen()->getBorderWidth();
if (m_win->getScreen()->getEdgeSnapThreshold()) {
int drx = m_win->getScreen()->getWidth() - (dx + 1);
if (dx > 0 && dx < drx && dx < m_win->getScreen()->getEdgeSnapThreshold())
dx = 0;
else if (drx > 0 && drx < m_win->getScreen()->getEdgeSnapThreshold())
dx = m_win->getScreen()->getWidth() - 1;
int dtty, dbby, dty, dby;
dty = dy - dtty;
dby = dbby - (dy + 1);
if (dy > 0 && dty < m_win->getScreen()->getEdgeSnapThreshold())
dy = dtty;
else if (dby > 0 && dby < m_win->getScreen()->getEdgeSnapThreshold())
dy = dbby - 1;
}
//erase rectangle
XDrawRectangle(m_display, m_win->getScreen()->getRootWindow(),
m_win->getScreen()->getOpGC(),
m_move_x, m_move_y,
m_size_w, m_size_h);
//redraw rectangle at new pos
m_move_x = dx;
m_move_y = dy;
XDrawRectangle(m_display, m_win->getScreen()->getRootWindow(),
m_win->getScreen()->getOpGC(),
m_move_x, m_move_y,
m_size_w, m_size_h);
}
}
}
//-------------- getFirst() ---------
// Returns the first Tab in the chain
// of currentchain.
//-----------------------------------
Tab *Tab::getFirst(Tab *current) {
if (!current)
return 0;
Tab *i=current;
for (; i->m_prev != 0; i = i->m_prev);
return i;
}
//-------------- getLast() ---------
// Returns the last Tab in the chain
// of currentchain.
//-----------------------------------
Tab *Tab::getLast(Tab *current) {
if (!current)
return 0;
Tab *i=current;
for (; i->m_next != 0; i = i->m_next);
return i;
}
//-------------- insert ------------
// (private)
// Inserts a tab in the chain
//----------------------------------
void Tab::insert(Tab *tab) {
if (!tab || tab == this) //dont insert if the tab = 0 or the tab = this
return;
Tab *first = getFirst(this);
//if the tab already in chain then disconnect it
for (; first!=0; first = first->m_next) {
if (first==tab) {
#ifdef DEBUG
cerr<<"Tab already in chain. Disconnecting!"<<endl;
#endif // DEBUG
tab->disconnect();
break;
}
}
//get last tab in the chain to be inserted
Tab *last = tab;
for (; last->m_next!=0; last=last->m_next);
//do sticky before we connect it to the chain
//sticky bit on window
if (m_win->isStuck() != tab->m_win->isStuck()) {
tab->m_win->stuck = !m_win->stuck; // it will toggle
tab->stick(); //this will set all the m_wins in the list
}
//connect the tab to this chain
if (m_next)
m_next->m_prev = last;
tab->m_prev = this;
last->m_next = m_next;
m_next = tab;
bool resize_tabs = false;
//TODO: cleanup and optimize
//move and resize all windows in the tablist we inserted
//only from first tab of the inserted chain to the last
for (; tab!=last->m_next; tab=tab->m_next) {
if (m_win->isShaded() != tab->m_win->isShaded()) {
tab->m_stoptabs = true; // we don't want any actions performed on the
// tabs, just the tab windows!
if (m_win->getScreen()->getTabPlacement() == PLEFT ||
m_win->getScreen()->getTabPlacement() == PRIGHT)
resize_tabs = true;
// if the window we are grouping to, we need to shade the tab window
// _after_ reconfigure
if(m_win->isShaded()) {
tab->m_win->moveResize(m_win->getXFrame(), m_win->getYFrame(),
m_win->getWidth(), m_win->getHeight());
tab->m_win->shade();
} else {
tab->m_win->shade(); // switch to correct shade state
tab->m_win->moveResize(m_win->getXFrame(), m_win->getYFrame(),
m_win->getWidth(), m_win->getHeight());
}
tab->m_stoptabs = false;
// both window have the same shaded state and have different sizes,
// checking this so that I'll only do shade on windows if configure did
// anything.
} else if ((m_win->getWidth() != tab->m_win->getWidth()) ||
(m_win->getHeight() != tab->m_win->getHeight())) {
tab->m_win->moveResize(m_win->getXFrame(), m_win->getYFrame(),
m_win->getWidth(), m_win->getHeight());
// need to shade the tab window as configure will mess it up
if (m_win->isShaded())
tab->m_win->shade();
}
}
// resize if in relative mode or resize_tabs is true
if(m_win->getScreen()->getTabAlignment() == ARELATIVE ||
resize_tabs) {
resizeGroup();
calcIncrease();
}
// reposition tabs
setPosition();
}
//---------- disconnect() --------------
// Disconnects the tab from any chain
//--------------------------------------
void Tab::disconnect() {
Tab *tmp = 0;
Fluxbox *fluxbox = Fluxbox::instance();
if (m_prev) { //if this have a chain to "the left" (previous tab) then set it's next to this next
m_prev->m_next = m_next;
if(!m_next && !fluxbox->useTabs())//Only two tabs in list, remove tab from remaining window
m_prev->m_win->setTab(false);
else
tmp = m_prev;
}
if (m_next) { //if this have a chain to "the right" (next tab) then set it's prev to this prev
m_next->m_prev = m_prev;
if(!m_prev && !fluxbox->useTabs())//Only two tabs in list, remove tab from remaining window
m_next->m_win->setTab(false);
else
tmp = m_next;
}
//mark as no chain, previous and next.
m_prev = 0;
m_next = 0;
//reposition the tabs
if (tmp) {
if (m_win->getScreen()->getTabAlignment() == ARELATIVE)
tmp->calcIncrease();
tmp->setPosition();
}
if (m_win->getScreen()->getTabAlignment() == ARELATIVE)
calcIncrease();
setPosition();
}
// ------------ setTabWidth --------------
// Sets Tab width _including_ borders
// ---------------------------------------
void Tab::setTabWidth(unsigned int w) {
if (w > m_win->getScreen()->getWindowStyle()->tab.border_width_2x &&
w != m_size_w) {
m_size_w = w;
XResizeWindow(m_display, m_tabwin,
m_size_w - m_win->getScreen()->getWindowStyle()->tab.border_width_2x,
m_size_h - m_win->getScreen()->getWindowStyle()->tab.border_width_2x);
loadTheme(); // rerender themes to right size
focus(); // redraw the window
}
}
// ------------ setTabHeight ---------
// Sets Tab height _including_ borders
// ---------------------------------------
void Tab::setTabHeight(unsigned int h) {
if (h > m_win->getScreen()->getWindowStyle()->tab.border_width_2x &&
h != m_size_h) {
m_size_h = h;
XResizeWindow(m_display, m_tabwin,
m_size_w - m_win->getScreen()->getWindowStyle()->tab.border_width_2x,
m_size_h - m_win->getScreen()->getWindowStyle()->tab.border_width_2x);
loadTheme(); // rerender themes to right size
focus(); // redraw the window
}
}
// ------------ resizeGroup --------------
// This function is used when (un)shading
// to get right size/width of tabs when
// PLeft || PRight && isTabRotateVertical
// ---------------------------------------
void Tab::resizeGroup() {
Tab *first;
for (first = getFirst(this); first != 0; first = first->m_next) {
if ((m_win->getScreen()->getTabPlacement() == PLEFT ||
m_win->getScreen()->getTabPlacement() == PRIGHT) &&
m_win->getScreen()->isTabRotateVertical() &&
!m_win->isShaded()) {
first->setTabWidth(m_win->getScreen()->getTabHeight());
first->setTabHeight(m_win->getScreen()->getTabWidth());
} else {
first->setTabWidth(m_win->getScreen()->getTabWidth());
first->setTabHeight(m_win->getScreen()->getTabHeight());
}
//TODO: do I have to set this all the time?
first->m_configured = true; //used in Fluxbox::reconfigure()
}
}
//------------- calcRelativeWidth --------
// Returns: Calculated width for relative
// alignment
//----------------------------------------
unsigned int Tab::calcRelativeWidth() {
unsigned int num=0;
//calculate num objs in list (extract this to a function?)
for (Tab *first=getFirst(this); first!=0; first=first->m_next, num++);
return ((m_win->getWidth() + m_win->getScreen()->getBorderWidth2x())/num);
}
/**
Returns the number of objects in
the TabGroup.
*/
unsigned int Tab::numObjects() {
unsigned int num = 0;
for (Tab *tab = getFirst(this); tab != 0; tab = tab->m_next, num++);
return num;
}
/**
Returns: Calculated height for relative
alignment
*/
unsigned int Tab::calcRelativeHeight() {
return ((m_win->getHeight() +
m_win->getScreen()->getBorderWidth2x())/numObjects());
}
//------------- calcCenterXPos -----------
// Returns: Calculated x position for
// centered alignment
//----------------------------------------
unsigned int Tab::calcCenterXPos() {
return (m_win->getXFrame() + ((m_win->getWidth() -
(m_size_w * numObjects())) / 2));
}
//------------- calcCenterYPos -----------
// Returns: Calculated y position for
// centered alignment
//----------------------------------------
unsigned int Tab::calcCenterYPos() {
return (m_win->getYFrame() + ((m_win->getHeight() -
(m_size_h * numObjects())) / 2));
}
//------- getTabPlacementString ----------
// Returns the tabplacement string of the
// tabplacement number on success else 0.
//----------------------------------------
const char *Tab::getTabPlacementString(Tab::Placement placement) {
for (int i=0; i<(PNONE / 5); i++) {
if (m_tabplacementlist[i] == placement)
return m_tabplacementlist[i].string;
}
return 0;
}
//------- getTabPlacementNum -------------
// Returns the tabplacement number of the
// tabplacement string on success else
// the type none on failure.
//----------------------------------------
Tab::Placement Tab::getTabPlacementNum(const char *string) {
for (int i=0; i<(PNONE / 5); i ++) {
if (m_tabplacementlist[i] == string) {
return static_cast<Tab::Placement>(m_tabplacementlist[i].tp);
}
}
return PNONE;
}
//------- getTabAlignmentString ----------
// Returns the tabplacement string of the
// tabplacement number on success else 0.
//----------------------------------------
const char *Tab::getTabAlignmentString(Tab::Alignment alignment) {
for (int i=0; i<ANONE; i++) {
if (m_tabalignmentlist[i] == alignment)
return m_tabalignmentlist[i].string;
}
return 0;
}
//------- getTabAlignmentNum -------------
// Returns the tabplacement number of the
// tabplacement string on success else
// the type none on failure.
//----------------------------------------
Tab::Alignment Tab::getTabAlignmentNum(const char *string) {
for (int i=0; i<ANONE; i++) {
if (m_tabalignmentlist[i] == string) {
return static_cast<Tab::Alignment>(m_tabalignmentlist[i].tp);
}
}
return ANONE;
}
//---------- addWindowToGroup ------------
// Add a window the the tabbed group
//----------------------------------------
bool Tab::addWindowToGroup(FluxboxWindow *otherWindow)
{
if (!otherWindow || otherWindow == m_win)
return false;
Tab *otherTab = otherWindow->getTab();
if (!otherTab)
return false;
insert(otherTab);
return true;
}
| [
"(no author)@54ec5f11-9ae8-0310-9a2b-99d706b22625"
] | (no author)@54ec5f11-9ae8-0310-9a2b-99d706b22625 |
92a25ee556c15f8a1e52420129669d637695c126 | 0f44a7db952534d7ffaa58a178fd1a6e68546ded | /test-c/wrapperCaller.cpp | 22d34efc7c233c2015fd73f17635cf49b8c6f29e | [] | no_license | ayushchatur/cuda-sandbox | c59a1c0adfd823650d434b1adfc853b96d94cdec | b23ff870053877b87dcf8d9c004caa0b099b1eee | refs/heads/master | 2023-08-20T04:12:13.431320 | 2021-10-09T18:45:56 | 2021-10-09T18:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 119 | cpp | #include "open_acc_map_header.cuh"
#include <stdio.h>
#include <stdlib.h>
void wrapperCaller(int b)
{
wrapper(b);
}
| [
"talgat.manglayev@gmail.com"
] | talgat.manglayev@gmail.com |
cf052f5f1d59d2e4cf146f2c98d473c18fc81274 | b6d2cb74a76194fd25fdc3607ef828e94d98039e | /Codeforces/550C.cpp | 1277a2dfb7e2f45289f7eabbd44b514e08e3a516 | [] | no_license | giovaneaf/CompetitiveProgramming | 22d63481015ab45a03d527c866cae339cffeb5fb | 863f6bc61497591cb98e50973aa23bfcb9879ab8 | refs/heads/master | 2021-06-07T20:28:45.116299 | 2021-05-25T00:38:16 | 2021-05-25T00:38:16 | 131,643,425 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,770 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef pair<int, bool> ib;
#define FOR(a, b, c) for(int a = b; a < c; ++a)
#define RFOR(a, b, c) for(int a = b; a >= c; --a)
#define mp(a, b) make_pair(a, b)
#define all(v) v.begin(), v.end()
#define ii pair<int, int>
#define vi vector<int>
#define vii vector<ii>
#define vvi vector<vi>
#define vb vector<bool>
#define fst first
#define snd second
#define MAXN 5010
#define LOGMAXN 20
#define MAXM 1000010
#define INF 1000000007
#define INFLL 1000000000000000000LL
#define EPS 1e-9
#define MOD 1000000007LL
#define ITER 10000000
#define DEBUG 0
int memo[101][2][2][9];
int n;
string s;
int solve(int pos, bool used, bool valid, int rem)
{
if(pos == n) return valid && (rem == 0);
if(memo[pos][used][valid][rem] == -1)
{
int nrem = (used ? ((rem*10 + s[pos]-'0')%8) : rem);
int ans = max(solve(pos+1, false, valid || used, nrem), solve(pos+1, true, true, nrem));
memo[pos][used][valid][rem] = ans;
}
//printf("%d %d %d %d = %d\n", pos, used, valid, rem, memo[pos][used][valid][rem]);
return memo[pos][used][valid][rem];
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(0);
while(cin >> s)
{
memset(memo, -1, sizeof(memo));
n = (int) s.size();
FOR(i, 0, 2)
{
solve(0, i == 1, i == 1, 0);
}
if(memo[0][false][false][0] == 1 || memo[0][true][true][0] == 1)
{
string ans;
bool valid = false;
int rem = 0;
FOR(i, 0, (int) s.size())
{
if(memo[i][true][true][rem] == 1)
{
ans += s[i];
rem = (rem*10 + s[i]-'0')%8;
}
}
if((int) ans.size() > 0)
{
printf("YES\n");
printf("%s\n", ans.c_str());
}
else
printf("NO\n");
}
else
{
printf("NO\n");
}
}
return 0;
}
| [
"giovaneaf1995@gmail.com"
] | giovaneaf1995@gmail.com |
71e2d13a3c95f5d9169c10764bba5c6c1d9f18e3 | e366027ffef496d43350b044d0574127c512d690 | /src/xpcc/math/geometry/vector4_impl.hpp | c253ed23460704f104fe2705bea929d5fd29d840 | [] | no_license | roboterclubaachen/xpcc | aa504f3d0a8246861dd00ea437cc7b938a869669 | 010924901947381d20e83b838502880eb2ffea72 | refs/heads/develop | 2021-01-24T11:18:27.233788 | 2019-01-03T18:55:35 | 2019-01-03T18:55:35 | 3,626,127 | 163 | 51 | null | 2018-06-30T19:15:55 | 2012-03-05T10:49:18 | C | UTF-8 | C++ | false | false | 19,844 | hpp | // coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2011, Roboterclub Aachen e.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Roboterclub Aachen e.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__VECTOR4_HPP
#error "Don't include this file directly, use 'vector4.hpp' instead!"
#endif
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector()
:
x(),
y(),
z(),
w()
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(T inX, T inY, T inZ, T inW)
:
x(inX),
y(inY),
z(inZ),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 1> &inY, const xpcc::Vector<T, 1> &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX.x),
y(inY.x),
z(inZ.x),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 1> &inY, const xpcc::Vector<T, 1> &inZ, const T &inW)
:
x(inX.x),
y(inY.x),
z(inZ.x),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 1> &inY, const T &inZ, const T &inW)
:
x(inX.x),
y(inY.x),
z(inZ),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const T &inY, const xpcc::Vector<T, 1> &inZ, const T &inW)
:
x(inX.x),
y(inY),
z(inZ.x),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 1> &inY, const xpcc::Vector<T, 1> &inZ, const T &inW)
:
x(inX),
y(inY.x),
z(inZ.x),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const T &inY, const T &inZ, const T &inW)
:
x(inX.x),
y(inY),
z(inZ),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 1> &inY, const T &inZ, const T &inW)
:
x(inX),
y(inY.x),
z(inZ),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 1> &inY, const T &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX.x),
y(inY.x),
z(inZ),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const T &inY, const T &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX.x),
y(inY),
z(inZ),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 1> &inY, const T &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX),
y(inY.x),
z(inZ),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const T &inY, const T &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX),
y(inY),
z(inZ),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const T &inY, const xpcc::Vector<T, 1> &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX.x),
y(inY),
z(inZ.x),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const T &inY, const xpcc::Vector<T, 1> &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX),
y(inY),
z(inZ.x),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 1> &inY, const xpcc::Vector<T, 1> &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inX),
y(inY.x),
z(inZ.x),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 2> &inXY, const xpcc::Vector<T, 1> &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inXY.x),
y(inXY.y),
z(inZ.x),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 2> &inXY, const xpcc::Vector<T, 1> &inZ, const T &inW)
:
x(inXY.x),
y(inXY.y),
z(inZ.x),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 2> &inXY, const T &inZ, const T &inW)
:
x(inXY.x),
y(inXY.y),
z(inZ),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 2> &inXY, const T &inZ, const xpcc::Vector<T, 1> &inW)
:
x(inXY.x),
y(inXY.y),
z(inZ),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 2> &inYZ, const xpcc::Vector<T, 1> &inW)
:
x(inX.x),
y(inYZ.x),
z(inYZ.y),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 2> &inYZ, const T &inW)
:
x(inX.x),
y(inYZ.x),
z(inYZ.y),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 2> &inYZ, const T &inW)
:
x(inX),
y(inYZ.x),
z(inYZ.y),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 2> &inYZ, const xpcc::Vector<T, 1> &inW)
:
x(inX),
y(inYZ.x),
z(inYZ.y),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 1> &inY, const xpcc::Vector<T, 2> &inZW)
:
x(inX.x),
y(inY.x),
z(inZW.x),
w(inZW.y)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const T &inY, const xpcc::Vector<T, 2> &inZW)
:
x(inX.x),
y(inY),
z(inZW.x),
w(inZW.y)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const T &inY, const xpcc::Vector<T, 2> &inZW)
:
x(inX),
y(inY),
z(inZW.x),
w(inZW.y)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 1> &inY, const xpcc::Vector<T, 2> &inZW)
:
x(inX),
y(inY.x),
z(inZW.x),
w(inZW.y)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 2> &inXY, const xpcc::Vector<T, 2> &inZW)
:
x(inXY.x),
y(inXY.y),
z(inZW.x),
w(inZW.y)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 3> &inXYZ, const xpcc::Vector<T, 1> &inW)
:
x(inXYZ.x),
y(inXYZ.y),
z(inXYZ.z),
w(inW.x)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 3> &inXYZ, const T &inW)
:
x(inXYZ.x),
y(inXYZ.y),
z(inXYZ.z),
w(inW)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 1> &inX, const xpcc::Vector<T, 3> &inYZW)
:
x(inX.x),
y(inYZW.x),
z(inYZW.y),
w(inYZW.z)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const T &inX, const xpcc::Vector<T, 3> &inYZW)
:
x(inX),
y(inYZW.x),
z(inYZW.y),
w(inYZW.z)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Matrix<T, 4, 1> &rhs)
:
x(reinterpret_cast<const T*>(&rhs)[0]),
y(reinterpret_cast<const T*>(&rhs)[1]),
z(reinterpret_cast<const T*>(&rhs)[2]),
w(reinterpret_cast<const T*>(&rhs)[3])
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(const xpcc::Vector<T, 4> &rhs)
:
x(rhs.x),
y(rhs.y),
z(rhs.z),
w(rhs.w)
{
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>::Vector(T inVal)
:
x(inVal),
y(inVal),
z(inVal),
w(inVal)
{
}
// ----------------------------------------------------------------------------
template<typename T>
void
xpcc::Vector<T, 4>::set(const T& x_, const T& y_, const T& z_, const T& w_)
{
this->x = x_;
this->y = y_;
this->z = z_;
this->w = w_;
}
// ----------------------------------------------------------------------------
template<typename T>
void
xpcc::Vector<T, 4>::setX(const T& value)
{
this->x = value;
}
template<typename T>
void
xpcc::Vector<T, 4>::setY(const T& value)
{
this->y = value;
}
template<typename T>
void
xpcc::Vector<T, 4>::setZ(const T& value)
{
this->z = value;
}
template<typename T>
void
xpcc::Vector<T, 4>::setW(const T& value)
{
this->w = value;
}
// ----------------------------------------------------------------------------
template<typename T>
const T&
xpcc::Vector<T, 4>::getX() const
{
return this->x;
}
template<typename T>
const T&
xpcc::Vector<T, 4>::getY() const
{
return this->y;
}
template<typename T>
const T&
xpcc::Vector<T, 4>::getZ() const
{
return this->z;
}
template<typename T>
const T&
xpcc::Vector<T, 4>::getW() const
{
return this->w;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>&
xpcc::Vector<T, 4>::operator = (const xpcc::Matrix<T, 4, 1> &rhs)
{
x = reinterpret_cast<const T*>(&rhs)[0];
y = reinterpret_cast<const T*>(&rhs)[1];
z = reinterpret_cast<const T*>(&rhs)[2];
w = reinterpret_cast<const T*>(&rhs)[3];
return *this;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>&
xpcc::Vector<T, 4>::operator = (const xpcc::Vector<T, 4> &rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
w = rhs.w;
return *this;
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::Vector<T, 4>::operator == (const xpcc::Vector<T, 4> &rhs) const
{
return (rhs.x == x) && (rhs.y == y) && (rhs.z == z) && (rhs.w == w);
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::Vector<T, 4>::operator != (const xpcc::Vector<T, 4> &rhs) const
{
return (rhs.x != x) || (rhs.y != y) || (rhs.z != z) || (rhs.w != w);
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::Vector<T, 4>::operator < (const xpcc::Vector<T, 4> &rhs) const
{
return (x < rhs.x) || ((x == rhs.x) && ((y < rhs.y) || ((y == rhs.y) && ((z < rhs.z) || ((z == rhs.z) && (w < rhs.w))))));
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::Vector<T, 4>::operator <= (const xpcc::Vector<T, 4> &rhs) const
{
return (x < rhs.x) || ((x == rhs.x) && ((y < rhs.y) || ((y == rhs.y) && ((z < rhs.z) || ((z == rhs.z) && (w <= rhs.w))))));
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::Vector<T, 4>::operator > (const xpcc::Vector<T, 4> &rhs) const
{
return (x > rhs.x) || ((x == rhs.x) && ((y > rhs.y) || ((y == rhs.y) && ((z > rhs.z) || ((z == rhs.z) && (w > rhs.w))))));
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::Vector<T, 4>::operator >= (const xpcc::Vector<T, 4> &rhs) const
{
return (x > rhs.x) || ((x == rhs.x) && ((y > rhs.y) || ((y == rhs.y) && ((z > rhs.z) || ((z == rhs.z) && (w >= rhs.w))))));
}
// ----------------------------------------------------------------------------
template<typename T>
const T&
xpcc::Vector<T, 4>::operator [] (uint8_t index) const
{
return reinterpret_cast<const T*>(this)[index];
}
// ----------------------------------------------------------------------------
template<typename T>
T&
xpcc::Vector<T, 4>::operator [] (uint8_t index)
{
return reinterpret_cast<T*>(this)[index];
}
// ----------------------------------------------------------------------------
template<typename T>
T*
xpcc::Vector<T, 4>::ptr()
{
return reinterpret_cast<T*>(this);
}
// ----------------------------------------------------------------------------
template<typename T>
const T*
xpcc::Vector<T, 4>::ptr() const
{
return reinterpret_cast<const T*>(this);
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>
xpcc::Vector<T, 4>::operator + (const xpcc::Vector<T, 4> &rhs) const
{
return xpcc::Vector<T, 4>(x+rhs.x, y+rhs.y, z+rhs.z, w+rhs.w);
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>
xpcc::Vector<T, 4>::operator - (const xpcc::Vector<T, 4> &rhs) const
{
return xpcc::Vector<T, 4>(x-rhs.x, y-rhs.y, z-rhs.z, w-rhs.w);
}
// ----------------------------------------------------------------------------
template<typename T>
T
xpcc::Vector<T, 4>::operator * (const xpcc::Vector<T, 4> &rhs) const
{
return x*rhs.x + y*rhs.y + z*rhs.z + w*rhs.w;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>
xpcc::Vector<T, 4>::operator * (const T &rhs) const
{
return xpcc::Vector<T, 4>(x*rhs, y*rhs, z*rhs, w*rhs);
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>
xpcc::Vector<T, 4>::operator / (const T &rhs) const
{
return xpcc::Vector<T, 4>(x/rhs, y/rhs, z/rhs, w/rhs);
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>&
xpcc::Vector<T, 4>::operator += (const xpcc::Vector<T, 4> &rhs)
{
x += rhs.x;
y += rhs.y;
z += rhs.z;
w += rhs.w;
return *this;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>&
xpcc::Vector<T, 4>::operator -= (const xpcc::Vector<T, 4> &rhs)
{
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
w -= rhs.w;
return *this;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>&
xpcc::Vector<T, 4>::operator *= (const T &rhs)
{
x *= rhs;
y *= rhs;
z *= rhs;
w *= rhs;
return *this;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>&
xpcc::Vector<T, 4>::operator /= (const T &rhs)
{
x /= rhs;
y /= rhs;
z /= rhs;
w /= rhs;
return *this;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>
xpcc::Vector<T, 4>::operator - () const
{
return xpcc::Vector<T, 4>(-x, -y, -z, -w);
}
// ----------------------------------------------------------------------------
template<typename T>
float
xpcc::Vector<T, 4>::getLength() const
{
return std::sqrt(getLengthSquared());
}
// ----------------------------------------------------------------------------
template<typename T>
float
xpcc::Vector<T, 4>::getLengthSquared() const
{
return x*x + y*y + z*z + w*w;
}
// ----------------------------------------------------------------------------
template<typename T>
void
xpcc::Vector<T, 4>::scale(float newLength)
{
*this = scaled(newLength);
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>
xpcc::Vector<T, 4>::scaled(float newLength) const
{
float scale = newLength / getLength();
return *this * scale;
}
// ----------------------------------------------------------------------------
template<typename T>
void
xpcc::Vector<T, 4>::normalize()
{
scale(1.0f);
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 4>
xpcc::Vector<T, 4>::normalized() const
{
return scaled(1.0);
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Matrix<T, 4, 1>&
xpcc::Vector<T, 4>::asMatrix()
{
return *(xpcc::Matrix<T, 4, 1>*)this;
}
template<typename T>
const xpcc::Matrix<T, 4, 1>&
xpcc::Vector<T, 4>::asMatrix() const
{
return *(xpcc::Matrix<T, 4, 1>*)this;
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Matrix<T, 1, 4>&
xpcc::Vector<T, 4>::asTransposedMatrix()
{
return *(xpcc::Matrix<T, 1, 4>*)this;
}
template<typename T>
const xpcc::Matrix<T, 1, 4>&
xpcc::Vector<T, 4>::asTransposedMatrix() const
{
return *(xpcc::Matrix<T, 1, 4>*)this;
}
// ----------------------------------------------------------------------------
template<typename T>
static inline xpcc::Vector<T,4>
operator * (const T &lhs, const xpcc::Vector<T,4> &rhs)
{
return rhs * lhs;
}
template<class T, class U>
static inline xpcc::Vector<U,4>
operator * (const xpcc::Matrix<T, 4, 4> &lhs, const xpcc::Vector<U,4> &rhs)
{
return lhs * rhs.asTMatrix();
}
| [
"fabian.greif@rwth-aachen.de"
] | fabian.greif@rwth-aachen.de |
fd46198019ac284edef1bcf09db311b839117df3 | 571110a073ac9e632018aef09443e4a291f5b82f | /src/neut_dice/src/gamalib/mutex/atomics.h | 7268195f832ac3ff9864aaffa7eac49a8a72f122 | [] | no_license | ampereira/ttH_dilep | 2fa06be80d532ccc8f441d66c6f94f5f1e9e1c66 | d92567fdc8ad01b0880b29ab05a80bde8280cda6 | refs/heads/master | 2021-01-25T10:16:26.759329 | 2014-05-20T14:03:02 | 2014-05-20T14:03:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,945 | h | /*
* atomics.h
*
* Created on: Dec 6, 2012
* Author: jbarbosa
*/
#ifndef ATOMICS_T_H_
#define ATOMICS_T_H_
template<DEVICE_TYPE, typename T>
class atomic {
public:
volatile T _value;
atomic() {
}
atomic(T value) : _value(value) {
}
T valCAS(T prev, T next);
T boolCAS(T prev, T next) ;
T exchange(T value);
template<typename T2> inline T2 cast(void);
T add(T value);
T sub(T value);
T operator+(const T value);
T operator-(const T value);
T operator+=(const T value);
T operator-=(const T value);
T operator=(const T value);
T& operator=(const T& value);
T operator++(int);
T operator--(int);
};
#ifndef __CUDACC__
template<typename T>
class atomic<CPU_X86,T> {
public:
volatile T _value;
atomic() {
}
atomic(T value) : _value(value) {
}
inline T valCAS(T prev, T next) __attribute__((always_inline)) {
return __sync_val_compare_and_swap(&_value,prev,next);
}
inline bool boolCAS(T prev, T next) __attribute__((always_inline)) {
return (prev==__sync_val_compare_and_swap(&_value,prev,next));
}
inline T exchange(T value) __attribute__((always_inline)) {
return (T)__sync_lock_test_and_set(&_value,value);
}
template<typename T2> inline T2 cast(void) {
return static_cast<T2>(_value);
}
inline T add(T value) __attribute__((always_inline)) {
return __sync_fetch_and_add(&_value,value);
}
inline T sub(T value) __attribute__((always_inline)) {
return __sync_fetch_and_sub(&_value,value);
}
inline T operator+(const T value) __attribute__((always_inline)) {
add(value);
}
inline T operator-(const T value) __attribute__((always_inline)) {
sub(value);
}
inline T operator+=(const T value) __attribute__((always_inline)) {
add(value);
}
inline T operator-=(const T value) __attribute__((always_inline)) {
sub(value);
}
inline T operator=(const T value) __attribute__((always_inline)) {
exchange(value);
}
inline T& operator=(const T& value) __attribute__((always_inline)) {
return exchange(value);
}
inline T operator++(int) __attribute__((always_inline)) {
return add(1);
}
inline T operator--(int) __attribute__((always_inline)) {
return sub(1);
}
};
template<>
class atomic<CPU_X86,double> {
public:
volatile unsigned long long _value;
atomic() {
}
atomic(double value) : _value(value) {
}
inline double valCAS(double prev, double next) __attribute__((always_inline)) {
unsigned long long* p = reinterpret_cast<unsigned long long*>(&prev);
unsigned long long* n = reinterpret_cast<unsigned long long*>(&next);
unsigned long long a = __sync_val_compare_and_swap(&_value,*p,*n);
return *reinterpret_cast<volatile double*>(&_value);
}
inline bool boolCAS(double prev, double next) __attribute__((always_inline)) {
unsigned long long* p = reinterpret_cast<unsigned long long*>(&prev);
unsigned long long* n = reinterpret_cast<unsigned long long*>(&next);
return __sync_bool_compare_and_swap(&_value,*p,*n);
}
inline double exchange(double value) __attribute__((always_inline)) {
double prev = _value;
_value=value;
asm volatile("sfence" ::: "memory");
return prev;
}
template<typename T2> inline T2 cast(void) {
return static_cast<T2>(*reinterpret_cast<volatile double*>(&_value));
}
inline double add(double value) __attribute__((always_inline)) {
double v = *reinterpret_cast<volatile double*>(&_value);
double n = v + value;
while(!boolCAS(v,n)) {
asm volatile("sfence" ::: "memory");
v = *reinterpret_cast<volatile double*>(&_value);
n = v + value;
}
return v;
}
inline double sub(double value) __attribute__((always_inline)) {
double v = *reinterpret_cast<volatile double*>(&_value);
double n = v - value;
while(!boolCAS(v,n)) {
v = *reinterpret_cast<volatile double*>(&_value);
n = v - value;
}
return v;
}
inline double operator+(const double value) __attribute__((always_inline)) {
add(value);
}
inline double operator-(const double value) __attribute__((always_inline)) {
sub(value);
}
inline double operator+=(const double value) __attribute__((always_inline)) {
add(value);
}
inline double operator-=(const double value) __attribute__((always_inline)) {
sub(value);
}
inline double operator=(const double value) __attribute__((always_inline)) {
exchange(value);
}
// inline double& operator=(const double& value) __attribute__((always_inline)) {
// return exchange(value);
// }
inline double operator++(int) __attribute__((always_inline)) {
return add(1.f);
}
inline double operator--(int) __attribute__((always_inline)) {
return sub(1.f);
}
};
#else
template<typename T>
class atomic<GPU_CUDA,T> {
public:
T _value;
atomic() {
}
atomic(T value) : _value(value) {
}
__device__ __inline__ T valCAS(T prev, T next) {
return atomicCAS(&_value,prev,next);
}
__device__ __inline__ T boolCAS(T prev, T next) {
return __any(prev==atomicCAS(&_value,prev,next));
}
__device__ __inline__ T exchange(T value) {
T prev = _value;
_value=value;
__threadfence_system();
return prev;
}
template<typename T2> __device__ __inline__ T2 cast(void) {
return (T2)(_value);
}
__device__ __inline__ T add(T value) {
return atomicAdd(&_value,value);
}
__device__ __inline__ T sub(T value) {
return atomicSub(&_value,value);
}
__device__ __inline__ T operator+(const T value) {
add(value);
}
__device__ __inline__ T operator-(const T value) {
sub(value);
}
__device__ __inline__ T operator+=(const T value) {
add(value);
}
__device__ __inline__ T operator-=(const T value) {
sub(value);
}
__device__ __inline__ T operator=(const T value) {
exchange(value);
}
__device__ __inline__ T& operator=(const T& value) {
return exchange(value);
}
__device__ __inline__ T operator++(int) {
add(1);
}
__device__ __inline__ T operator--(int) {
sub(1);
}
};
#endif
#endif /* ATOMICS_T_H_ */
| [
"lazeroth89@gmail.com"
] | lazeroth89@gmail.com |
dfb424ee7dff9e4ae025108b296b542c2289e668 | d7fb85e2ea96f563da58108972892909580b6f2c | /Livro.cpp | a341c5b116dd8edd67acb837c649744561d6e0a3 | [
"MIT"
] | permissive | felipeavs/Sistema-Biblioteca | ab718c8aae7c96b0c8f0055a622fb6ac345e1a47 | 6f99a569ff6c176a6329611f7ac4731619cd5628 | refs/heads/main | 2023-01-05T00:19:16.627534 | 2020-11-06T22:28:43 | 2020-11-06T22:28:43 | 310,718,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,283 | cpp | //
// Created by felip on 14/10/2018.
//
#include "Livro.h"
#include "iomanip"
#include <ios>
#include <iostream>
Livro::Livro(vector <string> Escritor, string Titulo, vector <string> Capitulos, int Ano, string Idioma, vector <string> Keywords){
setEscritores(Escritor);
setTitulo(Titulo);
setCapitulos(Capitulos);
setAno(Ano);
setIdioma(Idioma);
setKeywords(Keywords);
}
Livro::Livro(){
setTitulo("");
setAno(0);
setIdioma("");
}
Livro::~Livro(){}
//Escritor----------------------------------------------------
void Livro::setEscritores(vector <string> Escritor){
this -> Escritores = Escritor;
}
vector <string> Livro::getEscritores()const{
return Escritores;
}
//Titulo------------------------------------------------------
void Livro::setTitulo(string Titulo) {
this -> Titulo = Titulo;
}
string Livro::getTitulo()const{
return Titulo;
}
//Capitulo----------------------------------------------------
void Livro::setCapitulos(vector <string> Capitulos){
this -> Capitulos = Capitulos;
}
vector <string> Livro::getCapitulos() const{
return Capitulos;
}
//Ano de publicação-------------------------------------------
void Livro::setAno(int Ano){
this -> Ano = Ano;
}
int Livro::getAno() const{
return Ano;
}
//Idioma------------------------------------------------------
void Livro::setIdioma(string Idioma){
this -> Idioma = Idioma;
}
string Livro::getIdioma() const{
return Idioma;
}
//Keywords----------------------------------------------------
void Livro::setKeywords(vector <string> keywords){
this -> Keywords = keywords;
}
vector <string> Livro::getKeywords() const {
return Keywords;
}
//----------------------------------------------------------------------------------------------------------------------
ostream&operator<<(ostream& out, const Livro& book){
int aux = 0;
for(auto v: book.getTitulo()){
if(aux == 30)
break;
out << v;
aux ++;
}
out << setw(31 - book.getTitulo().length()) << "|";
string nome = book.getEscritores()[0];
out << setw(31 - book.getEscritores()[0].length());
aux = 0;
for(auto u: nome){
if(aux == 30)
break;
out << u;
aux ++;
}
out << "|";
aux = 0;
for(auto v: book.getIdioma()){
if(aux == 10)
break;
out << v;
aux ++;
}
out << setw(11 - book.getIdioma().length()) << "|";
if(book.getCapitulos().size() > 10) {
out << setfill(' ') << setw(12) << "0" << book.getCapitulos().size() << "|";
}
else{
out << setfill(' ') << setw(13);
out << "00" << book.getCapitulos().size() << "|";
}
out << setw(13) << "0" << book.getKeywords().size() << "|" << setfill(' ');
return out;
}
//----------------------------------------------------------------------------------------------------------------------
list <Livro*> Livro::retornaColecaoIdioma(list <Livro*> Livros, string idioma){
list <Livro*> ColecaoPorIdioma;
for(auto elem: Livros){
if(elem->getIdioma() == idioma){
ColecaoPorIdioma.push_back(elem);
}
}
return ColecaoPorIdioma;
}
//----------------------------------------------------------------------------------------------------------------------
list <Livro*> Livro::retornaColecaoLivrosMesmoNome(list<Livro*> Livros, string Titulo){
list<Livro*> ColecaoMesmoTitulo;
for(auto elem: Livros){
if(elem->getTitulo() == Titulo){
ColecaoMesmoTitulo.push_back(elem);
}
}
return ColecaoMesmoTitulo;
}
//----------------------------------------------------------------------------------------------------------------------
set <string> Livro::retornaColecaoKeyWords(list<Livro*> Livro){
set <string> colecao;
for(auto elem: Livro){
for(auto k: elem->getKeywords()){
colecao.insert(k);
}
}
return colecao;
}
//----------------------------------------------------------------------------------------------------------------------
int Livro::retornaQuantidadeDeLivrosKeywords(list<Livro*> Livro,string key){
int i = 0;
for(auto elem: Livro){
for(auto elem2: elem->getKeywords()){
if(elem2 == key){
i++;
}
}
}
return i;
}
//----------------------------------------------------------------------------------------------------------------------
bool menorString(Livro* e1, Livro* e2){
unsigned int i = 0;
while((i < e1->getEscritores()[i].length()) && (i < e2->getEscritores()[0].length())){
if(tolower(e1->getEscritores()[0][i]) < tolower(e2->getEscritores()[0][i]))
return true;
else if(tolower(e1->getEscritores()[0][i]) > tolower(e2->getEscritores()[0][i]))
return false;
i++;
}
return (e1->getEscritores()[i].length() < e2->getEscritores()[i].length());
}
list<Livro*> Livro::retornaPesquisaPorCapitulo(list<Livro*> Livros, int nCapitulo){
list <Livro*> aux;
for(auto *elem: Livros){
if(elem->getCapitulos().size() <= nCapitulo){
aux.push_back(elem);
}
}
aux.sort(menorString);
return aux;
}
| [
"felipeavs95@gmail.com"
] | felipeavs95@gmail.com |
3bcff10de84ab6a006670dc01e0041447859d0c9 | c62f59b2317c60f19944090e0b9b3283b6637a21 | /BattleTankLowPoly/Source/BattleTankLowPoly/BattleTankLowPolyGameModeBase.cpp | 0cc764200f3934fc8ac034a75f7c2485ae1ee3e9 | [] | no_license | rwreynolds/04_BattleTankLowPoly | 6ec20d87b7db1bc33e446065b190eb3f094628f5 | d60a87a85345ff7993dc3a1a95ae186b92c46f9e | refs/heads/master | 2021-04-12T08:44:45.396239 | 2018-05-01T19:36:57 | 2018-05-01T19:36:57 | 126,172,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "BattleTankLowPolyGameModeBase.h"
| [
"rwrmail1@gmail.com"
] | rwrmail1@gmail.com |
e576ffb869870d5275613f62586feb221f9627da | 304a7e9de80635c751bcdc4932ac7107dfe6f7ac | /adaptiveFreqOsc2/adaptiveFreqOsc2.ino | 72c717a9607d2dcc1c7ecd82947b73d68e6c105c | [
"MIT"
] | permissive | MartinStokroos/adaptiveFreqOsc | 01c0a19023df259fde9df2f87a0040d2070a9741 | 39d43956ddc885c66b1367148fc658fdfd676019 | refs/heads/master | 2020-04-12T10:55:04.229422 | 2020-01-10T20:07:27 | 2020-01-10T20:07:27 | 162,444,499 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,266 | ino | /*
* File: adaptiveFreqOsc2.ino
* Purpose: Adaptive Frequency Oscillator Demo
* Version: 1.0.0
* Date: 07-01-2020
* Created by: Martin Stokroos
* URL: https://github.com/MartinStokroos/adaptiveFreqOsc
*
* License: MIT License
*
* This adaptive Hopf frequency oscillator synchronizes to the periodic input signal applied to the
* analog input pin A0. The periodic (AC) drive signal should be biased on 2.5V DC.
* The amplitude of the drive signal should be limited to 2.5V. Without drive signal (but with DC-bias), the
* oscillator starts outputting the intrinsic frequency, defined by the constant 'F_INIT'.
*
* This is a fast implementation on interrupt basis. Timer1 generates the loop frequency and triggers the ADC.
* 3kHz is almost the maximum loop rate to perform all calculations.
*
* The oscillator output pin, defined by PWM_OUT, has a PWM frequency of about 31kHz. Use a low-pass filter
* to observe the oscillator output wave in the frequency range of a few Hz to a few tens of Hz.
*
* - use the 'q' and 'a' keys to modify and set the value for Epsilon
* - use the 'w' and 's' keys to modify and set the value for gamma
* - use the 'e' and 'd' keys to modify and set the value for mu
* - press 'f' to print the current frequency.
*
*/
// Library to be included for fast digital I/O when observing the timing with an oscilloscope.
//#include <digitalWriteFast.h> // library for high performance digital reads and writes by jrraines
// see http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1267553811/0
// and http://code.google.com/p/digitalwritefast/
#define LPERIOD 500000 // the main loop period time in us. In this case 500ms.
#define PIN_LED 13 // PLL locking status indicator LED
#define PIN_PWMA 9 // Timer1 OCR1A 10-bit PWM
#define PIN_PWMB 10 // Timer1 OCR1B 10-bit PWM
#define PIN_PWMC 3 // Timer 2 8-bit PWM
#define PIN_PWMD 11 // Timer 8-bit PWM
#define PIN_DEBUG 4 // test output pin
#define F_INIT 10.0
// global vars
volatile int adcVal;
int dcBias = 512; //dc-bias byte value
unsigned long nextLoop;
char c; // incoming character from console
// adaptive Hopf oscillator parameters
#define T 1/3000.0 // loop frequency = 3kHz.
float Eps = 20.0; // coupling strength (K>0).
// Oscillator locks faster at higher values, but the ripple of the frequency is larger.
float gamma = 10.0; // the oscillator follows the amplitude of the stimulus better for larger values for g.
// May causes instability at large values for gamma.
float mu = 5.0; // Seems to scale the output amplitude. May Cause instability at large values for mu.
float x = 1.0; // starting point of the oscillator. x=1, y=0 starts as a cosine.
float x_new = 0.0;
float xdot = 0.0;
float y = 0.0;
float y_new = 0.0;
float ydot = 0.0;
float ohm = 2*PI*F_INIT;
float ohm_new = 0.0;
float ohmdot = 0.0;
float F = 0.0;
// ******************************************************************
// Setup
// ******************************************************************
void setup(){
cli(); // disable interrupts
pinMode(PIN_LED, OUTPUT);
pinMode(PIN_PWMA, OUTPUT);
pinMode(PIN_PWMB, OUTPUT);
pinMode(PIN_PWMC, OUTPUT);
pinMode(PIN_PWMD, OUTPUT);
pinMode(PIN_DEBUG, OUTPUT);
Serial.begin(115200);
// initialize ADC for continuous sampling mode
DIDR0 = 0x3F; // digital inputs disabled for ADC0D to ADC5D
bitSet(ADMUX, REFS0); // Select Vcc=5V as the ADC reference voltage
bitClear(ADMUX, REFS1);
bitClear(ADMUX, MUX0); // select ADC CH# 0
bitClear(ADMUX, MUX1);
bitClear(ADMUX, MUX2);
bitClear(ADMUX, MUX3);
bitSet(ADCSRA, ADEN); // AD-converter enabled
bitSet(ADCSRA, ADATE); // auto-trigger enabled
bitSet(ADCSRA, ADIE); // ADC interrupt enabled
bitSet(ADCSRA, ADPS0); // ADC clock prescaler set to 128
bitSet(ADCSRA, ADPS1);
bitSet(ADCSRA, ADPS2);
bitClear(ADCSRB, ACME); // Analog Comparator (ADC)Multiplexer enable OFF
bitClear(ADCSRB, ADTS0); // triggered by Timer/Counter1 Overflow
bitSet(ADCSRB, ADTS1);
bitSet(ADCSRB, ADTS2);
bitSet(ADCSRA, ADSC); // start conversion
/* TIMER1 configured for phase and frequency correct PWM-mode 8, top=ICR1 */
// prescaler = 1:
bitSet(TCCR1B, CS10);
bitClear(TCCR1B, CS11);
bitClear(TCCR1B, CS12);
// mode 8:
bitClear(TCCR1A, WGM10);
bitClear(TCCR1A, WGM11);
bitClear(TCCR1B, WGM12);
bitSet(TCCR1B, WGM13);
// top value. f_TIM1 = fclk/(2*N*TOP)
ICR1 = 2667; // f=3kHz.
// set output compare for pin 9 and 10 (for now we don't use PWM from Tim1 on pin 9 and 10)
//bitClear(TCCR1A, COM1A0); // Compare Match PWM 9
//bitSet(TCCR1A, COM1A1);
//bitSet(TCCR1A, COM1B0); // Compare Match PWM 10 - inverted channel
//bitSet(TCCR1A, COM1B1);
// PWM output on pin 3&11 (8-bit Tim2 OCR)
TCCR2B = (TCCR2B & 0xF8)|0x01; // set Pin3 + Pin11 PWM frequency to 31250Hz
// enable TIMER1 compare interrupt
bitSet(TIMSK1, TOIE1); // enable Timer1 Interrupt
sei(); // global enable interrupts
// start PWM out on pin 3&11
analogWrite(PIN_PWMC, 127);
analogWrite(PIN_PWMD, 127);
nextLoop = micros() + LPERIOD; // Set the loop timer variable for the next loop interval.
}
// ******************************************************************
// Main loop
// ******************************************************************
void loop(){
digitalWrite(PIN_LED, !digitalRead(PIN_LED)); // toggle the LED
if(Serial.available()){
c = Serial.read();
if(c == 'q') { // use the 'q' and 'a' keys to set Eps
Eps += 1;
Eps = constrain(Eps, 0, 100);
Serial.print("Epsilon: ");
Serial.println(Eps,1);
}
if(c == 'a') {
Eps -= 1;
Eps = constrain(Eps, 0, 100);
Serial.print("Epsilon: ");
Serial.println(Eps,1);
}
if(c == 'w') { // use the 'w' and 's' keys to set gamma.
gamma += 1.0;
gamma = constrain(gamma, 0, 500);
Serial.print("gamma: ");
Serial.println(gamma,1);
}
if(c == 's') {
gamma -= 1.0;
gamma = constrain(gamma, 0, 500);
Serial.print("gamma: ");
Serial.println(gamma,1);
}
if(c == 'e') { // use the 'e' and 'd' keys to set mu
mu += 0.1;
mu = constrain(mu, -10, 10);
Serial.print("mu: ");
Serial.println(mu,1);
}
if(c == 'd') {
mu -= 0.1;
mu = constrain(mu, -10, 10);
Serial.print("mu: ");
Serial.println(mu,1);
}
if(c == 'f') { // print frequency
Serial.print("freq: ");
Serial.println(ohm/(2*PI),2);
}
}
while(nextLoop > micros()); // wait until the end of the time interval
nextLoop += LPERIOD; // set next loop time at current time + LOOP_PERIOD
}
/* ******************************************************************
* ADC ISR. The ADC is triggered by Timer1.
* Here we do the fast things at a constant rate. f=3kHz (=60 sampl./grid-period @50Hz)
* *******************************************************************/
ISR(ADC_vect){
//digitalWriteFast(PIN_DEBUG, HIGH); //for checking the interrupt frequency
// read the current ADC input channel
adcVal=ADCL; // store low byte
adcVal+=ADCH<<8; // store high byte
// write out PWM pin 11, direct through
//OCR2A = adcVal>>2;
F = (float)(adcVal-dcBias)/512.0; // make input sample float and normalize.
xdot = gamma*( mu-(sq(x) + sq(y)) )*x - ohm*y + Eps*F;
ydot = gamma*( mu-(sq(x) + sq(y)) )*y + ohm*x;
ohmdot = -Eps*F*y/( sqrt(sq(x) + sq(y)) );
x_new = x + T*xdot;
y_new = y + T*ydot;
ohm_new = ohm + T*ohmdot;
x = x_new;
y = y_new;
ohm = ohm_new;
// write out 8-bit PWM pin 3&11, Hopf-outputs
OCR2B = round(40*x) + 127; // in-phase output. 40 is a rough scaling.
OCR2A = round(40*y) + 127; // quadrature output
// write out 10bit PWM output registers A&B (pin9 and pin10).
//OCR1AH = adcVal>>8; //MSB
//OCR1AL = adcVal; //LSB
//(inverted phase) output:
//OCR1BH = OCR1AH; //MSB
//OCR1BL = OCR1AL; //LSB
//digitalWriteFast(PIN_DEBUG, LOW);
}
/* ******************************************************************
* Timer1 ISR
*********************************************************************/
ISR(TIMER1_OVF_vect) {
//empty ISR. Only used for triggering the ADC.
}
| [
"p229763@fwn-nb4-25-129.chem.rug.nl"
] | p229763@fwn-nb4-25-129.chem.rug.nl |
2f143cce90f1148ff40ed72d1e7cb11b599f10f6 | d8446827771cd79eb13242d21b0ca103035c467d | /day02/ex00/main.cpp | 283eb13c137a8bdf09b955f868058f77ff88a1e5 | [] | no_license | vuslysty/piscineCPP | e3ef3aabbef053eca29e1fad0695eeda85bc00c2 | 91a583ed4a0352c904fa485202752f8105230520 | refs/heads/master | 2020-06-20T19:16:15.561261 | 2019-07-16T15:51:59 | 2019-07-16T15:51:59 | 197,219,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | cpp | //
// Created by Vladyslav USLYSTYI on 2019-06-26.
//
#include <iostream>
#include "Fixed.hpp"
int main()
{
Fixed a;
Fixed b(a);
Fixed c;
c = b;
std::cout << a.getRawBits() << std::endl;
std::cout << b.getRawBits() << std::endl;
std::cout << c.getRawBits() << std::endl;
return (0);
} | [
"vuslysty@e2r11p11.unit.ua"
] | vuslysty@e2r11p11.unit.ua |
6d91516403fd13c2f674a65c1d6d87a4c42e03e7 | 5af2c24622fb7bb355066a2f4690fe8fe7d9348b | /src/examples/11_module/09_rule_of_5/rule_of_five.cpp | c4bdfa6994760af00ca78bc38c6808becc207a59 | [
"MIT"
] | permissive | acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-artgonzalezacc | 90f9f798fbfe91bbe242e64a2f7dd4df3c30ab92 | d36da91eaafb6afb3b7e711917ffe1601d0b2119 | refs/heads/master | 2020-07-13T07:52:07.065836 | 2019-12-05T01:07:17 | 2019-12-05T01:07:17 | 205,037,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30 | cpp | #include "rule_of_five.h"
//
| [
"arturo.gonzalez@austincc.edu"
] | arturo.gonzalez@austincc.edu |
2ab6c0501a4babba5443b42e7db08eff57711743 | 620aa93afee144803783a7a03a1a8f978efdf18e | /Course-3/Week-1/W1-B.cpp | b5eb1f14cb850c852c648478660c18bcf99f8a9f | [] | no_license | Mohiiit/DSA-Coursera-Specialization | 80a902eedaeb3055a6b9a43dbc8458593d11b9de | bfd29e0e44d835def06ea2f96f652639df264f98 | refs/heads/master | 2022-07-22T17:00:56.510773 | 2020-05-16T17:04:50 | 2020-05-16T17:04:50 | 260,699,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,106 | cpp | /*
Mohit Dhattarwal
*/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define foreach(it, v) for(auto it=(v).begin(); it != (v).end(); ++it)
#define gcd(a,b) __gcd(a,b)
#define fastio() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define filewr() freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define tr(...) cout<<__FUNCTION__<<' '<<__LINE__<<" = ";trace(#__VA_ARGS__, __VA_ARGS__)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<string,ll> psl;
typedef pair<ll,string> pls;
template<typename S, typename T>
ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;}
template<typename T>
ostream& operator<<(ostream& out,vector<T> const& v){
int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;}
template<typename T>
void trace(const char* name, T&& arg1){cout<<name<<" : "<<arg1<<endl;}
template<typename T, typename... Args>
void trace(const char* names, T&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma-names)<<" : "<<arg1<<" | ";trace(comma+1,args...);}
const ld PI = 3.1415926535897932384626433832795;
typedef tree<int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> indexed_set;
void explore(vector<ll> a[], vector<bool> &visit, ll u)
{
visit[u] = true;
for(ll i =0; i<a[u].size(); i++)
{
if(visit[a[u][i]]==false)
{
explore(a,visit, a[u][i]);
}
}
}
void dfs(vector<ll> a[], ll n)
{
vector<bool> visit(n+1,false);
ll count = 0;
for(ll i =1; i<=n; i++)
{
if(visit[i]==false)
{
count++;
explore(a,visit,i);
}
}
cout<<count<<endl;
}
void solve()
{
ll n, m, u, v;
cin>>n>>m;
vector<ll> a[n+1];
for(ll i =0; i<m; i++)
{
cin>>u>>v;
a[u].pb(v);
a[v].pb(u);
}
dfs(a,n);
}
int main(){
fastio();
ll t;
t = 1;
while(t--)
{
solve();
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
5c46ce75e30bb3dbf390f18f7bbe1ccf0422505d | c601f5af43f387818c88c62df80e334e177ac6f6 | /windows/runner/main.cpp | 0a3cb736ccb01406d3663cfef3b60a339789c817 | [
"MIT"
] | permissive | msilvamolina/flutter_wavi_cuentas_claras | 3bda3095bcaef6978f06d15513e98949fb148a18 | c578c06072f4512689aa315a09039d28bfcb1e87 | refs/heads/main | 2023-06-08T14:28:23.935046 | 2021-06-27T08:12:57 | 2021-06-27T08:12:57 | 380,685,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | cpp | #include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "run_loop.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
RunLoop run_loop;
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(&run_loop, project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"flutter_wavi_claras", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
run_loop.Run();
::CoUninitialize();
return EXIT_SUCCESS;
}
| [
"msilvamolina@gmail.com"
] | msilvamolina@gmail.com |
ba0c7bd51048db3ac184f8c749543e5d1ee031bd | 80d97bc5ff8a43da99893a57f03002e68081d780 | /scintilla/lexers/LexHaskell.cxx | 8e007fac8f1421f9ae7b266485a3f385263d9009 | [
"LicenseRef-scancode-scintilla",
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ProgerXP/Notepad2e | 38798db10e0fe0a5602a463a5681bd653afe3bb6 | c703f11bc278457286b3ca1565047a3b09ccdf8d | refs/heads/master | 2023-09-05T23:32:07.576076 | 2023-07-27T11:03:30 | 2023-07-27T11:03:49 | 10,840,481 | 376 | 50 | NOASSERTION | 2022-08-22T14:06:36 | 2013-06-21T10:28:18 | C++ | UTF-8 | C++ | false | false | 37,475 | cxx | /******************************************************************
* LexHaskell.cxx
*
* A haskell lexer for the scintilla code control.
* Some stuff "lended" from LexPython.cxx and LexCPP.cxx.
* External lexer stuff inspired from the caml external lexer.
* Folder copied from Python's.
*
* Written by Tobias Engvall - tumm at dtek dot chalmers dot se
*
* Several bug fixes by Krasimir Angelov - kr.angelov at gmail.com
*
* Improved by kudah <kudahkukarek@gmail.com>
*
* TODO:
* * A proper lexical folder to fold group declarations, comments, pragmas,
* #ifdefs, explicit layout, lists, tuples, quasi-quotes, splces, etc, etc,
* etc.
*
*****************************************************************/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <string>
#include <vector>
#include <map>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "PropSetSimple.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "CharacterCategory.h"
#include "LexerModule.h"
#include "OptionSet.h"
#include "DefaultLexer.h"
using namespace Scintilla;
// See https://github.com/ghc/ghc/blob/master/compiler/parser/Lexer.x#L1682
// Note, letter modifiers are prohibited.
static int u_iswupper (int ch) {
CharacterCategory c = CategoriseCharacter(ch);
return c == ccLu || c == ccLt;
}
static int u_iswalpha (int ch) {
CharacterCategory c = CategoriseCharacter(ch);
return c == ccLl || c == ccLu || c == ccLt || c == ccLo;
}
static int u_iswalnum (int ch) {
CharacterCategory c = CategoriseCharacter(ch);
return c == ccLl || c == ccLu || c == ccLt || c == ccLo
|| c == ccNd || c == ccNo;
}
static int u_IsHaskellSymbol(int ch) {
CharacterCategory c = CategoriseCharacter(ch);
return c == ccPc || c == ccPd || c == ccPo
|| c == ccSm || c == ccSc || c == ccSk || c == ccSo;
}
static inline bool IsHaskellLetter(const int ch) {
if (IsASCII(ch)) {
return (ch >= 'a' && ch <= 'z')
|| (ch >= 'A' && ch <= 'Z');
} else {
return u_iswalpha(ch) != 0;
}
}
static inline bool IsHaskellAlphaNumeric(const int ch) {
if (IsASCII(ch)) {
return IsAlphaNumeric(ch);
} else {
return u_iswalnum(ch) != 0;
}
}
static inline bool IsHaskellUpperCase(const int ch) {
if (IsASCII(ch)) {
return ch >= 'A' && ch <= 'Z';
} else {
return u_iswupper(ch) != 0;
}
}
static inline bool IsAnHaskellOperatorChar(const int ch) {
if (IsASCII(ch)) {
return
( ch == '!' || ch == '#' || ch == '$' || ch == '%'
|| ch == '&' || ch == '*' || ch == '+' || ch == '-'
|| ch == '.' || ch == '/' || ch == ':' || ch == '<'
|| ch == '=' || ch == '>' || ch == '?' || ch == '@'
|| ch == '^' || ch == '|' || ch == '~' || ch == '\\');
} else {
return u_IsHaskellSymbol(ch) != 0;
}
}
static inline bool IsAHaskellWordStart(const int ch) {
return IsHaskellLetter(ch) || ch == '_';
}
static inline bool IsAHaskellWordChar(const int ch) {
return ( IsHaskellAlphaNumeric(ch)
|| ch == '_'
|| ch == '\'');
}
static inline bool IsCommentBlockStyle(int style) {
return (style >= SCE_HA_COMMENTBLOCK && style <= SCE_HA_COMMENTBLOCK3);
}
static inline bool IsCommentStyle(int style) {
return (style >= SCE_HA_COMMENTLINE && style <= SCE_HA_COMMENTBLOCK3)
|| ( style == SCE_HA_LITERATE_COMMENT
|| style == SCE_HA_LITERATE_CODEDELIM);
}
// styles which do not belong to Haskell, but to external tools
static inline bool IsExternalStyle(int style) {
return ( style == SCE_HA_PREPROCESSOR
|| style == SCE_HA_LITERATE_COMMENT
|| style == SCE_HA_LITERATE_CODEDELIM);
}
static inline int CommentBlockStyleFromNestLevel(const unsigned int nestLevel) {
return SCE_HA_COMMENTBLOCK + (nestLevel % 3);
}
// Mangled version of lexlib/Accessor.cxx IndentAmount.
// Modified to treat comment blocks as whitespace
// plus special case for commentline/preprocessor.
static int HaskellIndentAmount(Accessor &styler, const Sci_Position line) {
// Determines the indentation level of the current line
// Comment blocks are treated as whitespace
Sci_Position pos = styler.LineStart(line);
Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
char ch = styler[pos];
int style = styler.StyleAt(pos);
int indent = 0;
bool inPrevPrefix = line > 0;
Sci_Position posPrev = inPrevPrefix ? styler.LineStart(line-1) : 0;
while (( ch == ' ' || ch == '\t'
|| IsCommentBlockStyle(style)
|| style == SCE_HA_LITERATE_CODEDELIM)
&& (pos < eol_pos)) {
if (inPrevPrefix) {
char chPrev = styler[posPrev++];
if (chPrev != ' ' && chPrev != '\t') {
inPrevPrefix = false;
}
}
if (ch == '\t') {
indent = (indent / 8 + 1) * 8;
} else { // Space or comment block
indent++;
}
pos++;
ch = styler[pos];
style = styler.StyleAt(pos);
}
indent += SC_FOLDLEVELBASE;
// if completely empty line or the start of a comment or preprocessor...
if ( styler.LineStart(line) == styler.Length()
|| ch == ' '
|| ch == '\t'
|| ch == '\n'
|| ch == '\r'
|| IsCommentStyle(style)
|| style == SCE_HA_PREPROCESSOR)
return indent | SC_FOLDLEVELWHITEFLAG;
else
return indent;
}
struct OptionsHaskell {
bool magicHash;
bool allowQuotes;
bool implicitParams;
bool highlightSafe;
bool cpp;
bool stylingWithinPreprocessor;
bool fold;
bool foldComment;
bool foldCompact;
bool foldImports;
OptionsHaskell() {
magicHash = true; // Widespread use, enabled by default.
allowQuotes = true; // Widespread use, enabled by default.
implicitParams = false; // Fell out of favor, seldom used, disabled.
highlightSafe = true; // Moderately used, doesn't hurt to enable.
cpp = true; // Widespread use, enabled by default;
stylingWithinPreprocessor = false;
fold = false;
foldComment = false;
foldCompact = false;
foldImports = false;
}
};
static const char * const haskellWordListDesc[] = {
"Keywords",
"FFI",
"Reserved operators",
0
};
struct OptionSetHaskell : public OptionSet<OptionsHaskell> {
OptionSetHaskell() {
DefineProperty("lexer.haskell.allow.hash", &OptionsHaskell::magicHash,
"Set to 0 to disallow the '#' character at the end of identifiers and "
"literals with the haskell lexer "
"(GHC -XMagicHash extension)");
DefineProperty("lexer.haskell.allow.quotes", &OptionsHaskell::allowQuotes,
"Set to 0 to disable highlighting of Template Haskell name quotations "
"and promoted constructors "
"(GHC -XTemplateHaskell and -XDataKinds extensions)");
DefineProperty("lexer.haskell.allow.questionmark", &OptionsHaskell::implicitParams,
"Set to 1 to allow the '?' character at the start of identifiers "
"with the haskell lexer "
"(GHC & Hugs -XImplicitParams extension)");
DefineProperty("lexer.haskell.import.safe", &OptionsHaskell::highlightSafe,
"Set to 0 to disallow \"safe\" keyword in imports "
"(GHC -XSafe, -XTrustworthy, -XUnsafe extensions)");
DefineProperty("lexer.haskell.cpp", &OptionsHaskell::cpp,
"Set to 0 to disable C-preprocessor highlighting "
"(-XCPP extension)");
DefineProperty("styling.within.preprocessor", &OptionsHaskell::stylingWithinPreprocessor,
"For Haskell code, determines whether all preprocessor code is styled in the "
"preprocessor style (0, the default) or only from the initial # to the end "
"of the command word(1)."
);
DefineProperty("fold", &OptionsHaskell::fold);
DefineProperty("fold.comment", &OptionsHaskell::foldComment);
DefineProperty("fold.compact", &OptionsHaskell::foldCompact);
DefineProperty("fold.haskell.imports", &OptionsHaskell::foldImports,
"Set to 1 to enable folding of import declarations");
DefineWordListSets(haskellWordListDesc);
}
};
class LexerHaskell : public DefaultLexer {
bool literate;
Sci_Position firstImportLine;
int firstImportIndent;
WordList keywords;
WordList ffi;
WordList reserved_operators;
OptionsHaskell options;
OptionSetHaskell osHaskell;
enum HashCount {
oneHash
,twoHashes
,unlimitedHashes
};
enum KeywordMode {
HA_MODE_DEFAULT = 0
,HA_MODE_IMPORT1 = 1 // after "import", before "qualified" or "safe" or package name or module name.
,HA_MODE_IMPORT2 = 2 // after module name, before "as" or "hiding".
,HA_MODE_IMPORT3 = 3 // after "as", before "hiding"
,HA_MODE_MODULE = 4 // after "module", before module name.
,HA_MODE_FFI = 5 // after "foreign", before FFI keywords
,HA_MODE_TYPE = 6 // after "type" or "data", before "family"
};
enum LiterateMode {
LITERATE_BIRD = 0 // if '>' is the first character on the line,
// color '>' as a codedelim and the rest of
// the line as code.
// else if "\begin{code}" is the only word on the
// line except whitespace, switch to LITERATE_BLOCK
// otherwise color the line as a literate comment.
,LITERATE_BLOCK = 1 // if the string "\end{code}" is encountered at column
// 0 ignoring all later characters, color the line
// as a codedelim and switch to LITERATE_BIRD
// otherwise color the line as code.
};
struct HaskellLineInfo {
unsigned int nestLevel; // 22 bits ought to be enough for anybody
unsigned int nonexternalStyle; // 5 bits, widen if number of styles goes
// beyond 31.
bool pragma;
LiterateMode lmode;
KeywordMode mode;
HaskellLineInfo(int state) :
nestLevel (state >> 10)
, nonexternalStyle ((state >> 5) & 0x1F)
, pragma ((state >> 4) & 0x1)
, lmode (static_cast<LiterateMode>((state >> 3) & 0x1))
, mode (static_cast<KeywordMode>(state & 0x7))
{}
int ToLineState() {
return
(nestLevel << 10)
| (nonexternalStyle << 5)
| (pragma << 4)
| (lmode << 3)
| mode;
}
};
inline void skipMagicHash(StyleContext &sc, const HashCount hashes) const {
if (options.magicHash && sc.ch == '#') {
sc.Forward();
if (hashes == twoHashes && sc.ch == '#') {
sc.Forward();
} else if (hashes == unlimitedHashes) {
while (sc.ch == '#') {
sc.Forward();
}
}
}
}
bool LineContainsImport(const Sci_Position line, Accessor &styler) const {
if (options.foldImports) {
Sci_Position currentPos = styler.LineStart(line);
int style = styler.StyleAt(currentPos);
Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
while (currentPos < eol_pos) {
int ch = styler[currentPos];
style = styler.StyleAt(currentPos);
if (ch == ' ' || ch == '\t'
|| IsCommentBlockStyle(style)
|| style == SCE_HA_LITERATE_CODEDELIM) {
currentPos++;
} else {
break;
}
}
return (style == SCE_HA_KEYWORD
&& styler.Match(currentPos, "import"));
} else {
return false;
}
}
inline int IndentAmountWithOffset(Accessor &styler, const Sci_Position line) const {
const int indent = HaskellIndentAmount(styler, line);
const int indentLevel = indent & SC_FOLDLEVELNUMBERMASK;
return indentLevel <= ((firstImportIndent - 1) + SC_FOLDLEVELBASE)
? indent
: (indentLevel + firstImportIndent) | (indent & ~SC_FOLDLEVELNUMBERMASK);
}
inline int IndentLevelRemoveIndentOffset(const int indentLevel) const {
return indentLevel <= ((firstImportIndent - 1) + SC_FOLDLEVELBASE)
? indentLevel
: indentLevel - firstImportIndent;
}
public:
LexerHaskell(bool literate_)
: literate(literate_)
, firstImportLine(-1)
, firstImportIndent(0)
{}
virtual ~LexerHaskell() {}
void SCI_METHOD Release() override {
delete this;
}
int SCI_METHOD Version() const override {
return lvOriginal;
}
const char * SCI_METHOD PropertyNames() override {
return osHaskell.PropertyNames();
}
int SCI_METHOD PropertyType(const char *name) override {
return osHaskell.PropertyType(name);
}
const char * SCI_METHOD DescribeProperty(const char *name) override {
return osHaskell.DescribeProperty(name);
}
Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
const char * SCI_METHOD DescribeWordListSets() override {
return osHaskell.DescribeWordListSets();
}
Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;
void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;
void * SCI_METHOD PrivateCall(int, void *) override {
return 0;
}
static ILexer *LexerFactoryHaskell() {
return new LexerHaskell(false);
}
static ILexer *LexerFactoryLiterateHaskell() {
return new LexerHaskell(true);
}
};
Sci_Position SCI_METHOD LexerHaskell::PropertySet(const char *key, const char *val) {
if (osHaskell.PropertySet(&options, key, val)) {
return 0;
}
return -1;
}
Sci_Position SCI_METHOD LexerHaskell::WordListSet(int n, const char *wl) {
WordList *wordListN = 0;
switch (n) {
case 0:
wordListN = &keywords;
break;
case 1:
wordListN = &ffi;
break;
case 2:
wordListN = &reserved_operators;
break;
}
Sci_Position firstModification = -1;
if (wordListN) {
WordList wlNew;
wlNew.Set(wl);
if (*wordListN != wlNew) {
wordListN->Set(wl);
firstModification = 0;
}
}
return firstModification;
}
void SCI_METHOD LexerHaskell::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle
,IDocument *pAccess) {
LexAccessor styler(pAccess);
Sci_Position lineCurrent = styler.GetLine(startPos);
HaskellLineInfo hs = HaskellLineInfo(lineCurrent ? styler.GetLineState(lineCurrent-1) : 0);
// Do not leak onto next line
if (initStyle == SCE_HA_STRINGEOL)
initStyle = SCE_HA_DEFAULT;
else if (initStyle == SCE_HA_LITERATE_CODEDELIM)
initStyle = hs.nonexternalStyle;
StyleContext sc(startPos, length, initStyle, styler);
int base = 10;
bool dot = false;
bool inDashes = false;
bool alreadyInTheMiddleOfOperator = false;
assert(!(IsCommentBlockStyle(initStyle) && hs.nestLevel == 0));
while (sc.More()) {
// Check for state end
if (!IsExternalStyle(sc.state)) {
hs.nonexternalStyle = sc.state;
}
// For lexer to work, states should unconditionally forward at least one
// character.
// If they don't, they should still check if they are at line end and
// forward if so.
// If a state forwards more than one character, it should check every time
// that it is not a line end and cease forwarding otherwise.
if (sc.atLineEnd) {
// Remember the line state for future incremental lexing
styler.SetLineState(lineCurrent, hs.ToLineState());
lineCurrent++;
}
// Handle line continuation generically.
if (sc.ch == '\\' && (sc.chNext == '\n' || sc.chNext == '\r')
&& ( sc.state == SCE_HA_STRING
|| sc.state == SCE_HA_PREPROCESSOR)) {
// Remember the line state for future incremental lexing
styler.SetLineState(lineCurrent, hs.ToLineState());
lineCurrent++;
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
sc.Forward();
continue;
}
if (sc.atLineStart) {
if (sc.state == SCE_HA_STRING || sc.state == SCE_HA_CHARACTER) {
// Prevent SCE_HA_STRINGEOL from leaking back to previous line
sc.SetState(sc.state);
}
if (literate && hs.lmode == LITERATE_BIRD) {
if (!IsExternalStyle(sc.state)) {
sc.SetState(SCE_HA_LITERATE_COMMENT);
}
}
}
// External
// Literate
if ( literate && hs.lmode == LITERATE_BIRD && sc.atLineStart
&& sc.ch == '>') {
sc.SetState(SCE_HA_LITERATE_CODEDELIM);
sc.ForwardSetState(hs.nonexternalStyle);
}
else if (literate && hs.lmode == LITERATE_BIRD && sc.atLineStart
&& ( sc.ch == ' ' || sc.ch == '\t'
|| sc.Match("\\begin{code}"))) {
sc.SetState(sc.state);
while ((sc.ch == ' ' || sc.ch == '\t') && sc.More())
sc.Forward();
if (sc.Match("\\begin{code}")) {
sc.Forward(static_cast<int>(strlen("\\begin{code}")));
bool correct = true;
while (!sc.atLineEnd && sc.More()) {
if (sc.ch != ' ' && sc.ch != '\t') {
correct = false;
}
sc.Forward();
}
if (correct) {
sc.ChangeState(SCE_HA_LITERATE_CODEDELIM); // color the line end
hs.lmode = LITERATE_BLOCK;
}
}
}
else if (literate && hs.lmode == LITERATE_BLOCK && sc.atLineStart
&& sc.Match("\\end{code}")) {
sc.SetState(SCE_HA_LITERATE_CODEDELIM);
sc.Forward(static_cast<int>(strlen("\\end{code}")));
while (!sc.atLineEnd && sc.More()) {
sc.Forward();
}
sc.SetState(SCE_HA_LITERATE_COMMENT);
hs.lmode = LITERATE_BIRD;
}
// Preprocessor
else if (sc.atLineStart && sc.ch == '#' && options.cpp
&& (!options.stylingWithinPreprocessor || sc.state == SCE_HA_DEFAULT)) {
sc.SetState(SCE_HA_PREPROCESSOR);
sc.Forward();
}
// Literate
else if (sc.state == SCE_HA_LITERATE_COMMENT) {
sc.Forward();
}
else if (sc.state == SCE_HA_LITERATE_CODEDELIM) {
sc.ForwardSetState(hs.nonexternalStyle);
}
// Preprocessor
else if (sc.state == SCE_HA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.SetState(options.stylingWithinPreprocessor
? SCE_HA_DEFAULT
: hs.nonexternalStyle);
sc.Forward(); // prevent double counting a line
} else if (options.stylingWithinPreprocessor && !IsHaskellLetter(sc.ch)) {
sc.SetState(SCE_HA_DEFAULT);
} else {
sc.Forward();
}
}
// Haskell
// Operator
else if (sc.state == SCE_HA_OPERATOR) {
int style = SCE_HA_OPERATOR;
if ( sc.ch == ':'
&& !alreadyInTheMiddleOfOperator
// except "::"
&& !( sc.chNext == ':'
&& !IsAnHaskellOperatorChar(sc.GetRelative(2)))) {
style = SCE_HA_CAPITAL;
}
alreadyInTheMiddleOfOperator = false;
while (IsAnHaskellOperatorChar(sc.ch))
sc.Forward();
char s[100];
sc.GetCurrent(s, sizeof(s));
if (reserved_operators.InList(s))
style = SCE_HA_RESERVED_OPERATOR;
sc.ChangeState(style);
sc.SetState(SCE_HA_DEFAULT);
}
// String
else if (sc.state == SCE_HA_STRING) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_HA_STRINGEOL);
sc.ForwardSetState(SCE_HA_DEFAULT);
} else if (sc.ch == '\"') {
sc.Forward();
skipMagicHash(sc, oneHash);
sc.SetState(SCE_HA_DEFAULT);
} else if (sc.ch == '\\') {
sc.Forward(2);
} else {
sc.Forward();
}
}
// Char
else if (sc.state == SCE_HA_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_HA_STRINGEOL);
sc.ForwardSetState(SCE_HA_DEFAULT);
} else if (sc.ch == '\'') {
sc.Forward();
skipMagicHash(sc, oneHash);
sc.SetState(SCE_HA_DEFAULT);
} else if (sc.ch == '\\') {
sc.Forward(2);
} else {
sc.Forward();
}
}
// Number
else if (sc.state == SCE_HA_NUMBER) {
if (sc.atLineEnd) {
sc.SetState(SCE_HA_DEFAULT);
sc.Forward(); // prevent double counting a line
} else if (IsADigit(sc.ch, base)) {
sc.Forward();
} else if (sc.ch=='.' && dot && IsADigit(sc.chNext, base)) {
sc.Forward(2);
dot = false;
} else if ((base == 10) &&
(sc.ch == 'e' || sc.ch == 'E') &&
(IsADigit(sc.chNext) || sc.chNext == '+' || sc.chNext == '-')) {
sc.Forward();
if (sc.ch == '+' || sc.ch == '-')
sc.Forward();
} else {
skipMagicHash(sc, twoHashes);
sc.SetState(SCE_HA_DEFAULT);
}
}
// Keyword or Identifier
else if (sc.state == SCE_HA_IDENTIFIER) {
int style = IsHaskellUpperCase(sc.ch) ? SCE_HA_CAPITAL : SCE_HA_IDENTIFIER;
assert(IsAHaskellWordStart(sc.ch));
sc.Forward();
while (sc.More()) {
if (IsAHaskellWordChar(sc.ch)) {
sc.Forward();
} else if (sc.ch == '.' && style == SCE_HA_CAPITAL) {
if (IsHaskellUpperCase(sc.chNext)) {
sc.Forward();
style = SCE_HA_CAPITAL;
} else if (IsAHaskellWordStart(sc.chNext)) {
sc.Forward();
style = SCE_HA_IDENTIFIER;
} else if (IsAnHaskellOperatorChar(sc.chNext)) {
sc.Forward();
style = sc.ch == ':' ? SCE_HA_CAPITAL : SCE_HA_OPERATOR;
while (IsAnHaskellOperatorChar(sc.ch))
sc.Forward();
break;
} else {
break;
}
} else {
break;
}
}
skipMagicHash(sc, unlimitedHashes);
char s[100];
sc.GetCurrent(s, sizeof(s));
KeywordMode new_mode = HA_MODE_DEFAULT;
if (keywords.InList(s)) {
style = SCE_HA_KEYWORD;
} else if (style == SCE_HA_CAPITAL) {
if (hs.mode == HA_MODE_IMPORT1 || hs.mode == HA_MODE_IMPORT3) {
style = SCE_HA_MODULE;
new_mode = HA_MODE_IMPORT2;
} else if (hs.mode == HA_MODE_MODULE) {
style = SCE_HA_MODULE;
}
} else if (hs.mode == HA_MODE_IMPORT1 &&
strcmp(s,"qualified") == 0) {
style = SCE_HA_KEYWORD;
new_mode = HA_MODE_IMPORT1;
} else if (options.highlightSafe &&
hs.mode == HA_MODE_IMPORT1 &&
strcmp(s,"safe") == 0) {
style = SCE_HA_KEYWORD;
new_mode = HA_MODE_IMPORT1;
} else if (hs.mode == HA_MODE_IMPORT2) {
if (strcmp(s,"as") == 0) {
style = SCE_HA_KEYWORD;
new_mode = HA_MODE_IMPORT3;
} else if (strcmp(s,"hiding") == 0) {
style = SCE_HA_KEYWORD;
}
} else if (hs.mode == HA_MODE_TYPE) {
if (strcmp(s,"family") == 0)
style = SCE_HA_KEYWORD;
}
if (hs.mode == HA_MODE_FFI) {
if (ffi.InList(s)) {
style = SCE_HA_KEYWORD;
new_mode = HA_MODE_FFI;
}
}
sc.ChangeState(style);
sc.SetState(SCE_HA_DEFAULT);
if (strcmp(s,"import") == 0 && hs.mode != HA_MODE_FFI)
new_mode = HA_MODE_IMPORT1;
else if (strcmp(s,"module") == 0)
new_mode = HA_MODE_MODULE;
else if (strcmp(s,"foreign") == 0)
new_mode = HA_MODE_FFI;
else if (strcmp(s,"type") == 0
|| strcmp(s,"data") == 0)
new_mode = HA_MODE_TYPE;
hs.mode = new_mode;
}
// Comments
// Oneliner
else if (sc.state == SCE_HA_COMMENTLINE) {
if (sc.atLineEnd) {
sc.SetState(hs.pragma ? SCE_HA_PRAGMA : SCE_HA_DEFAULT);
sc.Forward(); // prevent double counting a line
} else if (inDashes && sc.ch != '-' && !hs.pragma) {
inDashes = false;
if (IsAnHaskellOperatorChar(sc.ch)) {
alreadyInTheMiddleOfOperator = true;
sc.ChangeState(SCE_HA_OPERATOR);
}
} else {
sc.Forward();
}
}
// Nested
else if (IsCommentBlockStyle(sc.state)) {
if (sc.Match('{','-')) {
sc.SetState(CommentBlockStyleFromNestLevel(hs.nestLevel));
sc.Forward(2);
hs.nestLevel++;
} else if (sc.Match('-','}')) {
sc.Forward(2);
assert(hs.nestLevel > 0);
if (hs.nestLevel > 0)
hs.nestLevel--;
sc.SetState(
hs.nestLevel == 0
? (hs.pragma ? SCE_HA_PRAGMA : SCE_HA_DEFAULT)
: CommentBlockStyleFromNestLevel(hs.nestLevel - 1));
} else {
sc.Forward();
}
}
// Pragma
else if (sc.state == SCE_HA_PRAGMA) {
if (sc.Match("#-}")) {
hs.pragma = false;
sc.Forward(3);
sc.SetState(SCE_HA_DEFAULT);
} else if (sc.Match('-','-')) {
sc.SetState(SCE_HA_COMMENTLINE);
sc.Forward(2);
inDashes = false;
} else if (sc.Match('{','-')) {
sc.SetState(CommentBlockStyleFromNestLevel(hs.nestLevel));
sc.Forward(2);
hs.nestLevel = 1;
} else {
sc.Forward();
}
}
// New state?
else if (sc.state == SCE_HA_DEFAULT) {
// Digit
if (IsADigit(sc.ch)) {
hs.mode = HA_MODE_DEFAULT;
sc.SetState(SCE_HA_NUMBER);
if (sc.ch == '0' && (sc.chNext == 'X' || sc.chNext == 'x')) {
// Match anything starting with "0x" or "0X", too
sc.Forward(2);
base = 16;
dot = false;
} else if (sc.ch == '0' && (sc.chNext == 'O' || sc.chNext == 'o')) {
// Match anything starting with "0o" or "0O", too
sc.Forward(2);
base = 8;
dot = false;
} else {
sc.Forward();
base = 10;
dot = true;
}
}
// Pragma
else if (sc.Match("{-#")) {
hs.pragma = true;
sc.SetState(SCE_HA_PRAGMA);
sc.Forward(3);
}
// Comment line
else if (sc.Match('-','-')) {
sc.SetState(SCE_HA_COMMENTLINE);
sc.Forward(2);
inDashes = true;
}
// Comment block
else if (sc.Match('{','-')) {
sc.SetState(CommentBlockStyleFromNestLevel(hs.nestLevel));
sc.Forward(2);
hs.nestLevel = 1;
}
// String
else if (sc.ch == '\"') {
sc.SetState(SCE_HA_STRING);
sc.Forward();
}
// Character or quoted name or promoted term
else if (sc.ch == '\'') {
hs.mode = HA_MODE_DEFAULT;
sc.SetState(SCE_HA_CHARACTER);
sc.Forward();
if (options.allowQuotes) {
// Quoted type ''T
if (sc.ch=='\'' && IsAHaskellWordStart(sc.chNext)) {
sc.Forward();
sc.ChangeState(SCE_HA_IDENTIFIER);
} else if (sc.chNext != '\'') {
// Quoted name 'n or promoted constructor 'N
if (IsAHaskellWordStart(sc.ch)) {
sc.ChangeState(SCE_HA_IDENTIFIER);
// Promoted constructor operator ':~>
} else if (sc.ch == ':') {
alreadyInTheMiddleOfOperator = false;
sc.ChangeState(SCE_HA_OPERATOR);
// Promoted list or tuple '[T]
} else if (sc.ch == '[' || sc.ch== '(') {
sc.ChangeState(SCE_HA_OPERATOR);
sc.ForwardSetState(SCE_HA_DEFAULT);
}
}
}
}
// Operator starting with '?' or an implicit parameter
else if (sc.ch == '?') {
hs.mode = HA_MODE_DEFAULT;
alreadyInTheMiddleOfOperator = false;
sc.SetState(SCE_HA_OPERATOR);
if ( options.implicitParams
&& IsAHaskellWordStart(sc.chNext)
&& !IsHaskellUpperCase(sc.chNext)) {
sc.Forward();
sc.ChangeState(SCE_HA_IDENTIFIER);
}
}
// Operator
else if (IsAnHaskellOperatorChar(sc.ch)) {
hs.mode = HA_MODE_DEFAULT;
sc.SetState(SCE_HA_OPERATOR);
}
// Braces and punctuation
else if (sc.ch == ',' || sc.ch == ';'
|| sc.ch == '(' || sc.ch == ')'
|| sc.ch == '[' || sc.ch == ']'
|| sc.ch == '{' || sc.ch == '}') {
sc.SetState(SCE_HA_OPERATOR);
sc.ForwardSetState(SCE_HA_DEFAULT);
}
// Keyword or Identifier
else if (IsAHaskellWordStart(sc.ch)) {
sc.SetState(SCE_HA_IDENTIFIER);
// Something we don't care about
} else {
sc.Forward();
}
}
// This branch should never be reached.
else {
assert(false);
sc.Forward();
}
}
sc.Complete();
}
void SCI_METHOD LexerHaskell::Fold(Sci_PositionU startPos, Sci_Position length, int // initStyle
,IDocument *pAccess) {
if (!options.fold)
return;
Accessor styler(pAccess, NULL);
Sci_Position lineCurrent = styler.GetLine(startPos);
if (lineCurrent <= firstImportLine) {
firstImportLine = -1; // readjust first import position
firstImportIndent = 0;
}
const Sci_Position maxPos = startPos + length;
const Sci_Position maxLines =
maxPos == styler.Length()
? styler.GetLine(maxPos)
: styler.GetLine(maxPos - 1); // Requested last line
const Sci_Position docLines = styler.GetLine(styler.Length()); // Available last line
// Backtrack to previous non-blank line so we can determine indent level
// for any white space lines
// and so we can fix any preceding fold level (which is why we go back
// at least one line in all cases)
bool importHere = LineContainsImport(lineCurrent, styler);
int indentCurrent = IndentAmountWithOffset(styler, lineCurrent);
while (lineCurrent > 0) {
lineCurrent--;
importHere = LineContainsImport(lineCurrent, styler);
indentCurrent = IndentAmountWithOffset(styler, lineCurrent);
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG))
break;
}
int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
if (importHere) {
indentCurrentLevel = IndentLevelRemoveIndentOffset(indentCurrentLevel);
if (firstImportLine == -1) {
firstImportLine = lineCurrent;
firstImportIndent = (1 + indentCurrentLevel) - SC_FOLDLEVELBASE;
}
if (firstImportLine != lineCurrent) {
indentCurrentLevel++;
}
}
indentCurrent = indentCurrentLevel | (indentCurrent & ~SC_FOLDLEVELNUMBERMASK);
// Process all characters to end of requested range
//that hangs over the end of the range. Cap processing in all cases
// to end of document.
while (lineCurrent <= docLines && lineCurrent <= maxLines) {
// Gather info
Sci_Position lineNext = lineCurrent + 1;
importHere = false;
int indentNext = indentCurrent;
if (lineNext <= docLines) {
// Information about next line is only available if not at end of document
importHere = LineContainsImport(lineNext, styler);
indentNext = IndentAmountWithOffset(styler, lineNext);
}
if (indentNext & SC_FOLDLEVELWHITEFLAG)
indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel;
// Skip past any blank lines for next indent level info; we skip also
// comments (all comments, not just those starting in column 0)
// which effectively folds them into surrounding code rather
// than screwing up folding.
while (lineNext < docLines && (indentNext & SC_FOLDLEVELWHITEFLAG)) {
lineNext++;
importHere = LineContainsImport(lineNext, styler);
indentNext = IndentAmountWithOffset(styler, lineNext);
}
int indentNextLevel = indentNext & SC_FOLDLEVELNUMBERMASK;
if (importHere) {
indentNextLevel = IndentLevelRemoveIndentOffset(indentNextLevel);
if (firstImportLine == -1) {
firstImportLine = lineNext;
firstImportIndent = (1 + indentNextLevel) - SC_FOLDLEVELBASE;
}
if (firstImportLine != lineNext) {
indentNextLevel++;
}
}
indentNext = indentNextLevel | (indentNext & ~SC_FOLDLEVELNUMBERMASK);
const int levelBeforeComments = Maximum(indentCurrentLevel,indentNextLevel);
// Now set all the indent levels on the lines we skipped
// Do this from end to start. Once we encounter one line
// which is indented more than the line after the end of
// the comment-block, use the level of the block before
Sci_Position skipLine = lineNext;
int skipLevel = indentNextLevel;
while (--skipLine > lineCurrent) {
int skipLineIndent = IndentAmountWithOffset(styler, skipLine);
if (options.foldCompact) {
if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > indentNextLevel) {
skipLevel = levelBeforeComments;
}
int whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG;
styler.SetLevel(skipLine, skipLevel | whiteFlag);
} else {
if ( (skipLineIndent & SC_FOLDLEVELNUMBERMASK) > indentNextLevel
&& !(skipLineIndent & SC_FOLDLEVELWHITEFLAG)) {
skipLevel = levelBeforeComments;
}
styler.SetLevel(skipLine, skipLevel);
}
}
int lev = indentCurrent;
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))
lev |= SC_FOLDLEVELHEADERFLAG;
}
// Set fold level for this line and move to next line
styler.SetLevel(lineCurrent, options.foldCompact ? lev : lev & ~SC_FOLDLEVELWHITEFLAG);
indentCurrent = indentNext;
indentCurrentLevel = indentNextLevel;
lineCurrent = lineNext;
}
// NOTE: Cannot set level of last line here because indentCurrent doesn't have
// header flag set; the loop above is crafted to take care of this case!
//styler.SetLevel(lineCurrent, indentCurrent);
}
LexerModule lmHaskell(SCLEX_HASKELL, LexerHaskell::LexerFactoryHaskell, "haskell", haskellWordListDesc);
LexerModule lmLiterateHaskell(SCLEX_LITERATEHASKELL, LexerHaskell::LexerFactoryLiterateHaskell, "literatehaskell", haskellWordListDesc);
| [
"cshnik@users.noreply.github.com"
] | cshnik@users.noreply.github.com |
34bf2aee627903f2d4ddea6021ba5dc6c0891109 | 6fe521009f63b13daa8126ccc970dfcb58b3e2d1 | /MatrixGraph.cpp | 8b1e725caafe5ef60ea0a5d1d421cb702f9f4a67 | [] | no_license | yaskev/travellingsalesman | 7a63478769554b10318c3dffc86a684f66fa3bdf | 400c9485fb9c6013d5a68d39df026777672ba6cf | refs/heads/master | 2020-05-17T20:29:28.127566 | 2019-05-23T18:44:48 | 2019-05-23T18:44:48 | 183,946,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | cpp | #include "MatrixGraph.h"
#include <vector>
using namespace std;
MatrixGraph::MatrixGraph(int vertNumber) {
adjTable.reserve(vertNumber);
for (int i = 0; i < vertNumber; ++i)
adjTable.emplace_back(vertNumber);
}
void MatrixGraph::AddEdge(int from, int to, double weight) {
adjTable[from][to] = weight;
}
vector<double> MatrixGraph::GetNextVertices(int vertex) const {
return adjTable[vertex];
}
vector<double> MatrixGraph::GetPrevVertices(int vertex) const {
return adjTable[vertex];
}
| [
"yaskevich.san@mail.ru"
] | yaskevich.san@mail.ru |
8e5d6f839e3c92229d522404471d8359143cf08f | 092e8797ce9a28a5ae4ad9f473dd6612aa80d210 | /compiler/Engines/template-engine/specific/include/ConnectorExportPort.hpp | 83b5ae72eea928abd557a732f368229215c9bb57 | [
"LicenseRef-scancode-cecill-b-en"
] | permissive | toandv/IFinder | faf4730e5065ff6bc2c457b432b9bb100b027bba | 7d7c48c87034fb1f66ceb5473f516dd833f49450 | refs/heads/master | 2021-04-19T23:44:27.674959 | 2020-03-24T07:36:33 | 2020-03-24T07:36:33 | 249,641,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,451 | hpp | /**
* Copyright Verimag laboratory.
*
* contributors:
* Jacques Combaz (jacques.combaz@univ-grenoble-alpes.fr)
*
* This software is a computer program whose purpose is to generate
* executable code from BIP models.
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*/
#ifndef _BIP_Engine_ConnectorExportPort_HPP_
#define _BIP_Engine_ConnectorExportPort_HPP_
// inherited classes
#include <ConnectorExportPortItf.hpp>
#include "Port.hpp"
class ConnectorExportPort : public virtual PortItf, public virtual Port, public ConnectorExportPortItf {
public:
// constructors
ConnectorExportPort(const string &name);
// destructor
virtual ~ConnectorExportPort();
// getters for references
virtual vector<PortValue *> &portValues();
virtual const vector<PortValue *> &portValues() const;
virtual bool hasPortValues() const;
// setters for references
virtual void addPortValue(PortValue &portValue);
virtual void clearPortValues();
};
#endif // _BIP_Engine_ConnectorExportPort_HPP_
| [
"you@example.com"
] | you@example.com |
550ae1a675af3a7d6292791ba0cb5fea5523f997 | 993723aa8e927fff777c1b4114b4ede09556a199 | /Classes/utility/StackLayerMgr.h | 6f44f73d23420e0777a96e060af54d7a742eec07 | [] | no_license | joyate/taoist | 6803a868126ba0df7ea85eaba939ce76c19ff7b2 | 15a6127e43f2cc82f5b8b274968dd99027de50bc | refs/heads/master | 2021-01-21T10:30:07.048778 | 2017-03-01T08:29:48 | 2017-03-01T08:29:48 | 83,441,921 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 417 | h | #pragma once
#include "cocos2d.h"
USING_NS_CC;
class StackLayer;
class StackLayerMgr
{
public:
StackLayerMgr(void);
~StackLayerMgr(void);
static StackLayerMgr* getInstance();
// 开启一个层叠级
void beginStackLayer();
// 压入节点
void pushLayer(Node* _node);
void popLayer();
protected:
// 这个有系统自动调用
void endStackLayer();
private:
Vector<StackLayer*> m_vec_sl;
};
| [
"fengzhiyun21@163.com"
] | fengzhiyun21@163.com |
26a5a8820fca03bf45fa820649f9443c1dd6bd87 | 81e58fd239797acf0450358a3971e6bfaaa01de3 | /Includes/Assertion.h | bd0dbaf19bc770157e89062ac8c54c957edf011a | [] | no_license | abanza/LocalTestHarness | 6e2aeb065282e08f3e522f267f57f113ba7af065 | e2a942ec19e46b74098e7c0881ce7f026ae78446 | refs/heads/master | 2022-11-23T17:57:27.181411 | 2022-11-07T18:00:21 | 2022-11-07T18:00:21 | 200,908,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,631 | h | ///////////////////////////////////////////////////////////////////////////////
// Assertion.h - Assertion class definition //
// Author: Adelard Banza, //
///////////////////////////////////////////////////////////////////////////////
#ifndef ASSERTION_H
#define ASSERTION_H
#include <memory>
#include <sstream>
#include <stack>
#include <string>
#include "TestLogger.h"
#ifdef TESTINGHARNESS_EXPORTS // inside the dll
#define TESTING_HARNESS_API __declspec(dllexport)
#else // outside dll
#define TESTING_HARNESS_API __declspec(dllimport)
#endif
/*
* Definition of Assertion methods, to be used inside of test cases for detailed logging of expected tesing conditions
*/
/*
* Assert equals asserts that the expected value is equal to the observed value, for the codition being tested. If both values are equal
* the assertion will log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertEquals(const std::string& condition, const T1 expectedValue, const T2 actualValue)
* condition - a string representing the condition being tested
* expectedValue - the value that is expected for this test
* actualValue - the value that was observed while running this test
*/
template<typename T1, typename T2> void TESTING_HARNESS_API assertEquals(const std::string&, const T1&, const T2&);
/*
* Assert not equals asserts that the expected value is different to the observed value, for the codition being tested.
* If the values are not equal the assertion will succeed and log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertNotEquals(const std::string& condition, const T1 expectedValue, const T2 actualValue)
* condition - a string representing the condition being tested
* expectedValue - the value that is expected for this test
* actualValue - the value that was observed while running this test
*/
template<typename T1, typename T2> void TESTING_HARNESS_API assertNotEquals(const std::string&, const T1&, const T2&);
/*
* Assert less than asserts that the testValue value is less than to the comparison value, for the codition being tested.
* If the inequality holds then the assertion will pass and log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertLessThan(const std::string& condition, const T1 testValue, const T2 comparisonValue)
* condition - a string representing the condition being tested
* testValue - the value that is expected for this test
* comparisonValue - the value that was observed while running this test
*/
template<typename T1, typename T2> void TESTING_HARNESS_API assertLessThan(const std::string&, const T1&, const T2&);
/*
* Assert less than asserts that the testValue value is grater than than to the comparison value, for the codition being tested.
* If the inequality holds then the assertion will pass and log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertLessThan(const std::string& condition, const T1 testValue, const T2 comparisonValue)
* condition - a string representing the condition being tested
* testValue - the value that is expected for this test
* comparisonValue - the value that was observed while running this test
*/
template<typename T1, typename T2> void TESTING_HARNESS_API assertLessThan(const std::string&, const T1&, const T2&);
/*
* Assert not Null asserts that the expected pointer value is not null, for the condition being tested.
* If this assertion is true it will log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertNotNull(const std::string& condition, const T* const testPointer)
* condition - a string representing the condition being tested
* testPointer - the pointer value being tested
*/
template<typename T> void TESTING_HARNESS_API assertNotNull(const std::string&, const T* const);
/*
* Assert Null asserts that the expected pointer value is null, for the condition being tested.
* If this assertion is true it will log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertNull(const std::string& condition, const T* const testPointer)
* condition - a string representing the condition being tested
* testPointer - the pointer value being tested
*/
template<typename T> void TESTING_HARNESS_API assertNull(const std::string&, const T* const);
/*
* Assert false asserts that the expected boolean value is false, for the condition being tested.
* If this assertion is true it will log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertFalse(const std::string& condition, bool value)
* condition - a string representing the condition being tested
* value - the boolean value being tested
*/
void TESTING_HARNESS_API assertFalse(const std::string&, bool);
/*
* Assert true asserts that the expected boolean value is true, for the condition being tested.
* If this assertion is true it will log an info message based on the condition,
* if not equal an error message will be logged, and the test case will be reported as failed.
*
* Usage: assertTrue(const std::string& condition, bool value)
* condition - a string representing the condition being tested
* value - the boolean value being tested
*/
void TESTING_HARNESS_API assertTrue(const std::string& s, bool val);
/*
* Assert fail asserts condition being tested has failed.
* Will always log an error message based on the condition,
* and the test case will in all cases be reported as failed.
*
* Usage: assertFail(const std::string& condition)
* condition - a string representing the condition being tested
*/
void TESTING_HARNESS_API assertFail(const std::string&);
/*
* Assert success asserts condition being tested has succeeded.
* Will always log an info message based on the condition.
*
* Usage: assertSuccess(const std::string& condition)
* condition - a string representing the condition being tested
*/
void TESTING_HARNESS_API assertSuccess(const std::string&);
/*
* The AssertionManager is a Singleton class that provided the functionality required for the assertion methods.
* This is a internal utility class that is not meant to be publicly accessed or modified.
*/
class TESTING_HARNESS_API AssertionManager
{
public:
static AssertionManager& getInstance();
~AssertionManager();
template<typename T1, typename T2> friend void assertEquals(const std::string& msg, const T1& t1, const T2& t2);
template<typename T> friend void assertNotNull(const std::string& s, const T* const tPtr);
friend void assertTrue(const std::string&, bool);
friend void assertFalse(const std::string&, bool);
friend void assertFail(const std::string&);
friend void assertSuccess(const std::string&);
void pushCntx(const std::string&, TestLogger*);
bool popCntx();
private:
AssertionManager();
bool assertCntx(const std::string& msg, TestLogger* logger);
void logSuccess(const std::string&);
void logFail(const std::string&);
static AssertionManager* instance;
std::stack<std::pair<std::pair<std::string, bool>, TestLogger*>> ctxStack;
};
// see declarations above
template<typename T1, typename T2>
void assertEquals(const std::string& msg, const T1& t1, const T2& t2)
{
AssertionManager& assertM = AssertionManager::getInstance();
if (t2 == t1)
{
std::stringstream s;
s << "assertEquals passed: " << msg << " received " << t1 << " while expecting " << t2;
assertM.logSuccess(s.str());
}
else
{
std::stringstream s;
s << "assertEquals failed: " << msg << " received " << t1 << " while expecting " << t2;
assertM.logFail(s.str());
}
}
// see declarations above
template<typename T>
void assertNotNull(const std::string& s, const T* const tPtr)
{
AssertionManager& assertM = AssertionManager::getInstance();
if (tPtr != nullptr_t)
{
std::stringstream s;
s << "assertNotNull passed for " << msg;
assertM.logSuccess(s.str());
}
else
{
std::stringstream s;
s << "assertNotNull failed " << msg;
assertM.logFail(s.str());
}
}
#endif // ASSERTION_H
| [
"adelardb@gmail.com"
] | adelardb@gmail.com |
6382bf26f814579a4b247c91865165087057ebca | 48e576904e046700cd06199394c7d75efd912363 | /pose2command/src/pose2command_last7.cpp | 81d2eb919e80f3389df5e91e01ca1143d5482810 | [] | no_license | Juna2/Autolift | cd5053c2cf004ca0f28fd881729929980f073a43 | bb3d81206b7599b3a73d68a2b42ab5654fd0ce07 | refs/heads/master | 2020-03-22T16:22:30.675783 | 2018-07-10T13:54:53 | 2018-07-10T13:54:53 | 140,322,510 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,240 | cpp | #include "ros/ros.h"
#include <iostream>
#include "geometry_msgs/PoseStamped.h"
#include "std_msgs/Float64.h"
#include "dynamixel_msgs/JointState.h"
#define OFFSET -0.052333
std_msgs::Float64 *degree = new std_msgs::Float64;
std_msgs::Float64 *degree2 = new std_msgs::Float64;
std_msgs::Float64 *vel = new std_msgs::Float64;
std_msgs::Float64 *vel2 = new std_msgs::Float64;
std_msgs::Float64 *vel3 = new std_msgs::Float64;
double orientation_x = 1;
double orientation_y = 1;
double orientation_z = 1;
double current_pos = 1;
double current_pos2 = 1;
void PoseCallback(const geometry_msgs::PoseStamped::ConstPtr& PoseStamped);
void PositionCallback_1(const dynamixel_msgs::JointState::ConstPtr& Joint);
void PositionCallback_2(const dynamixel_msgs::JointState::ConstPtr& Joint);
int main(int argc, char **argv)
{
ros::init(argc, argv, "pose2command");
ros::NodeHandle nh;
ros::Subscriber get_pose = nh.subscribe("/aruco_single/pose", 100, PoseCallback);
ros::Subscriber get_position = nh.subscribe("/tilt_controller/state", 100, PositionCallback_1);
ros::Subscriber get_position2 = nh.subscribe("/tilt_controller2/state", 100, PositionCallback_2);
ros::Publisher give_degree = nh.advertise<std_msgs::Float64>("/tilt_controller/command", 50);
ros::Publisher give_degree2 = nh.advertise<std_msgs::Float64>("/tilt_controller2/command", 50);
ros::Publisher give_vel = nh.advertise<std_msgs::Float64>("/pan_controller3/command", 50);
ros::Publisher give_vel2 = nh.advertise<std_msgs::Float64>("/pan_controller4/command", 50);
ros::Publisher give_vel3 = nh.advertise<std_msgs::Float64>("/pan_controller5/command", 50);
degree->data = 0.0;
degree2->data = 0.0;
vel->data = 0.0;
vel2->data = 0.0;
vel3->data = 0.0;
ros::Rate loop_rate(10);
while(ros::ok())
{
//degree->data = (degree->data) + OFFSET;
//degree2->data = (degree2->data) + OFFSET;
nh.getParam("degree", degree->data);
nh.getParam("degree2", degree2->data);
nh.getParam("vel", vel->data);
nh.getParam("vel2", vel2->data);
nh.getParam("vel3", vel3->data);
give_degree.publish(*degree);
give_degree2.publish(*degree2);
give_vel.publish(*vel);
give_vel2.publish(*vel2);
give_vel3.publish(*vel3);
nh.setParam("orientation_x", orientation_x);
nh.setParam("orientation_y", orientation_y);
nh.setParam("orientation_z", orientation_z);
nh.setParam("current_pos", current_pos);
nh.setParam("current_pos2", current_pos2);
//ROS_INFO("degree : %f", degree.data);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
void PoseCallback(const geometry_msgs::PoseStamped::ConstPtr& PoseStamped)
{
orientation_x = PoseStamped->pose.orientation.x;
orientation_y = PoseStamped->pose.orientation.y;
orientation_z = PoseStamped->pose.orientation.z;
//ROS_INFO("%f", orientation_x);
}
void PositionCallback_1(const dynamixel_msgs::JointState::ConstPtr& Joint)
{
current_pos = Joint->current_pos;
}
void PositionCallback_2(const dynamixel_msgs::JointState::ConstPtr& Joint)
{
current_pos2 = Joint->current_pos;
} | [
"boophopi@hanmail.net"
] | boophopi@hanmail.net |
7d7a5ec58473e139ae31a5227ecc431a25d0b6f6 | 3cb4a09b65598e8fe958dc79a0c189167b6f529b | /Set.h | a49c6d0d000c41eb91444dbc36f1fc69f3338c5c | [] | no_license | timconnorz/CS32-Project-2 | 7d08ac86dcade8d667b20622c11d6be1e244eab5 | 27ec015c5e650e34b64e02881420406d93c8313a | refs/heads/master | 2020-12-24T20:14:38.746108 | 2016-04-26T18:09:41 | 2016-04-26T18:09:41 | 57,150,901 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 703 | h |
#ifndef SET_H
#define SET_H
#include <string>
using namespace std;
typedef string ItemType;
class Set
{
public:
Set();
~Set();
Set(const Set& other);
Set& Set::operator=(const Set& rhs);
bool empty() const;
int size() const;
bool insert(const ItemType& value);
bool erase(const ItemType& value);
bool contains(const ItemType& value) const;
bool get(int pos, ItemType& value) const;
void swap(Set& other);
private:
struct Node
{
ItemType data;
Node* next;
Node* prev;
};
Node* head;
Node* tail;
int s_size = 0;
};
void unite(const Set& s1, const Set& s2, Set& result);
void subtract(const Set& s1, const Set& s2, Set& result);
#endif | [
"timconnors@yahoo.com"
] | timconnors@yahoo.com |
188b0ea3e0cd6cc3f34b5d54b9435401beee320b | 58e335be610148a5359a04ee006b003881b4567c | /SW Expert Academy/Learn/01/scanPasscode.cpp | 0953686259249015e4eb3e410abaf39cb156569f | [] | no_license | ssionii/Algorithm | 9997285bddc719da15d544a55d0dfe18815dcf22 | 76798b16013a0e8af0b94f050ad8d7b3391b10ed | refs/heads/master | 2021-07-05T13:16:08.190403 | 2020-09-08T13:32:47 | 2020-09-08T13:32:47 | 177,825,052 | 2 | 0 | null | null | null | null | UHC | C++ | false | false | 3,102 | cpp | #include <iostream>
#include <string>
using namespace std;
// 10진수를 2진수로
string convert(int deci) {
string result = "";
char temp[4];
for (int i = 3; i >= 0; i--) {
temp[i] = (char)(deci % 2 + 48);
deci /= 2;
}
for (int i = 0; i < 4; i++) result += temp[i];
return result;
}
// 16진수를 10진수로
string hexToBinary(string hex) {
string temp_s, result = "";
for (int i = 0; i <= 1; i++) {
int temp = (int)hex[i];
if (temp >= 65 && temp <= 70) {
temp -= 55;
temp_s = convert(temp);
}
else if (temp >= 48 && temp <= 57) {
temp -= 48;
temp_s = convert(temp);
}
result += temp_s;
}
return result;
}
int getInfo(string passcode) {
string info[] = { "3211", "2221", "2122", "1411", "1132",
"1231", "1114", "1312", "1213", "3112" };
string ratio;
char cur = passcode[0];
int count = 0;
for (int i = 0; i <= passcode.length(); i++) {
if (cur == passcode[i])
count++;
else {
ratio += (char)(count+48);
cur = passcode[i];
count = 1;
}
}
bool possible = true;
while (possible == true) {
for (int i = 0; i < 4; i++) {
if (ratio[i] % 2 != 0) {
possible = false;
break;
}
}
if (possible == true) {
for (int i = 0; i < 4; i++) {
ratio[i] = (((int)ratio[i] - 48) / 2 + 48);
}
}
}
for (int index = 0; index < 10; index++) {
if (ratio.compare(info[index]) == 0)
return index;
}
return -1;
}
int main() {
int test_case;
cin >> test_case;
for (int case_num = 0; case_num < test_case; case_num++) {
int N, M;
cin >> N >> M;
string *arr = new string[N];
bool flag = false;
int result = 0;
for (int i = 0; i < N; i++) {
cin >> arr[i];
for (int z = M - 1; z >= 0; z--) {
if (arr[i][z] != '0' && flag == false) {
// flag를 true로 바꿔서 test case 한개 당 한 줄만 받을 수 있도록
flag = true;
// 2진수 암호스트링으로 변환
string passcode;
for (int t = 0; t < M; t += 2) {
passcode += hexToBinary(arr[i].substr(t, 2));
}
// 암호스트링 뽑아내기
int start;
for (int j = passcode.length() - 1; j >= 0; j--) {
if (passcode[j] != '0') {
start = j - 55;
// vericode의 길이가 14일 때는 start를 다르게 해줘야 함,,,
// 암호코드 변환
int vericode[8];
fill_n(vericode, 8, -1);
int length = 7;
for (int l = 0; l < 8; l++) {
while (vericode[l] == -1) {
vericode[l] = getInfo(passcode.substr(start, length));
if(vericode[l] == -1)
length += 7;
}
cout << endl;
cout << l << " : " << vericode[l] << endl;
start += length;
}
int sum = 0, tresult = 0;
for (int k = 0; k < 8; k++) {
if (k % 2 == 0 && k != 7)
sum += vericode[k] * 3;
else
sum += vericode[k];
tresult += vericode[k];
}
if (sum % 10 == 0)
result = tresult;
j -= 57;
}
}
}
}
}
cout << "#" << case_num + 1 << " " << result << endl;
}
return 0;
} | [
"mn04098@naver.com"
] | mn04098@naver.com |
509455dc962cd524949d8dea8aa062671e0c0bbd | ded8ee844027437f916e11d8c0b41c7880e2d58f | /samples/server/petstore/restbed/api/UserApi.h | 4e0205f971d88bd31a65103de9c596ac763afb12 | [
"Apache-2.0"
] | permissive | rbkmoney/swagger-codegen | 7e1f6677877a30cf725768f31933528727529ede | cedfc45cc4d9d365c03f4f2fe367d8c3893ad509 | refs/heads/master | 2021-12-08T11:02:37.372013 | 2021-09-14T09:58:45 | 2021-09-14T09:58:45 | 61,725,659 | 2 | 7 | NOASSERTION | 2021-09-14T09:58:46 | 2016-06-22T14:28:28 | Mustache | UTF-8 | C++ | false | false | 3,305 | h | /**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* UserApi.h
*
*
*/
#ifndef UserApi_H_
#define UserApi_H_
#include <memory>
#include <corvusoft/restbed/session.hpp>
#include <corvusoft/restbed/resource.hpp>
#include <corvusoft/restbed/service.hpp>
#include "User.h"
#include <string>
#include <vector>
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
class UserApi: public restbed::Service
{
public:
UserApi();
~UserApi();
void startService(int const& port);
void stopService();
};
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
class UserApiUserResource: public restbed::Resource
{
public:
UserApiUserResource();
virtual ~UserApiUserResource();
void POST_method_handler(const std::shared_ptr<restbed::Session> session);
};
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <remarks>
///
/// </remarks>
class UserApiUserCreateWithArrayResource: public restbed::Resource
{
public:
UserApiUserCreateWithArrayResource();
virtual ~UserApiUserCreateWithArrayResource();
void POST_method_handler(const std::shared_ptr<restbed::Session> session);
};
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <remarks>
///
/// </remarks>
class UserApiUserCreateWithListResource: public restbed::Resource
{
public:
UserApiUserCreateWithListResource();
virtual ~UserApiUserCreateWithListResource();
void POST_method_handler(const std::shared_ptr<restbed::Session> session);
};
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
class UserApiUserUsernameResource: public restbed::Resource
{
public:
UserApiUserUsernameResource();
virtual ~UserApiUserUsernameResource();
void DELETE_method_handler(const std::shared_ptr<restbed::Session> session);
void GET_method_handler(const std::shared_ptr<restbed::Session> session);
void PUT_method_handler(const std::shared_ptr<restbed::Session> session);
};
/// <summary>
/// Logs user into the system
/// </summary>
/// <remarks>
///
/// </remarks>
class UserApiUserLoginResource: public restbed::Resource
{
public:
UserApiUserLoginResource();
virtual ~UserApiUserLoginResource();
void GET_method_handler(const std::shared_ptr<restbed::Session> session);
};
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <remarks>
///
/// </remarks>
class UserApiUserLogoutResource: public restbed::Resource
{
public:
UserApiUserLogoutResource();
virtual ~UserApiUserLogoutResource();
void GET_method_handler(const std::shared_ptr<restbed::Session> session);
};
}
}
}
}
#endif /* UserApi_H_ */
| [
"wing328hk@gmail.com"
] | wing328hk@gmail.com |
068e4fb0056bb5099da3fbe64caab7e1af8739ed | 18e9d72615eb37062a5f5dafba8b970331e606e7 | /dynamicProgramming/diceCombinations.cpp | 87d7fec8145cc56869addda1931147d8531db879 | [] | no_license | 2020201079/CSES | fc7ca9d78a6ac02f96a77936f748f89de7ce20a5 | e68fe4381130567492eb35416ce1fcefe9515a1c | refs/heads/main | 2023-07-16T03:54:11.508273 | 2021-09-05T14:02:30 | 2021-09-05T14:02:30 | 378,653,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;cin>>n;
int m = 1e9+7;
vector<int> dp(n+1);
for(int i=1;i<=n;i++){
if(i<=6){
dp[i] = 1;
}
for(int j=1;j<=6;j++){
if(i-j>=1){
dp[i] = (dp[i]+dp[i-j])%m;
}
}
}
cout<<dp[n]<<endl;
} | [
"varunnambigari.iit@gmail.com"
] | varunnambigari.iit@gmail.com |
36d4cc1336f4e3eb98aa283cbfc210d9ef01f427 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_10192.cpp | 0cc5c639b030f5eec13ea3d860edd43ebb258adb | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 124 | cpp | {
__archive_read_filter_consume(self->upstream,
state->consume_unnotified);
state->consume_unnotified = 0;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
1f4cf9256a8258c14972d468ba5e7cf7478be981 | c37e4d3f33214718cfdb9e6319bb9906f9b53bc1 | /Source/PrefabricatorEditor/Public/Asset/PrefabricatorAssetBroker.h | f63bce1666032ed9706ea46e25bf35cb618a019d | [
"MIT"
] | permissive | ProjectBorealis/prefabricator-ue4 | 29684e90ff22952fcf874dd1eed1aebfe4cddd81 | 1ce626f07c7470e6c1de12e37ef86746ae932cbf | refs/heads/master | 2023-06-24T02:29:25.320982 | 2022-12-04T13:38:26 | 2022-12-04T13:38:26 | 164,132,371 | 9 | 1 | MIT | 2023-06-19T01:18:46 | 2019-01-04T16:50:42 | C++ | UTF-8 | C++ | false | false | 1,149 | h | //$ Copyright 2015-21, Code Respawn Technologies Pvt Ltd - All Rights Reserved $//
#pragma once
#include "CoreMinimal.h"
#include "Asset/PrefabricatorAsset.h"
#include "Prefab/PrefabComponent.h"
#include "ComponentAssetBroker.h"
/** Asset broker for the prefab asset */
class PREFABRICATOREDITOR_API FPrefabricatorAssetBroker : public IComponentAssetBroker {
public:
virtual UClass* GetSupportedAssetClass() override {
return UPrefabricatorAssetInterface::StaticClass();
}
virtual bool AssignAssetToComponent(UActorComponent* InComponent, UObject* InAsset) override {
if (UPrefabComponent* PrefabComponent = Cast<UPrefabComponent>(InComponent)) {
UPrefabricatorAssetInterface* PrefabAsset = Cast<UPrefabricatorAssetInterface>(InAsset);
if (PrefabAsset && PrefabAsset) {
PrefabComponent->PrefabAssetInterface = PrefabAsset;
return true;
}
}
return false;
}
virtual UObject* GetAssetFromComponent(UActorComponent* InComponent) override {
if (UPrefabComponent* PrefabComponent = Cast<UPrefabComponent>(InComponent)) {
return PrefabComponent->PrefabAssetInterface.LoadSynchronous();
}
return nullptr;
}
};
| [
"ali.akbar@coderespawn.com"
] | ali.akbar@coderespawn.com |
f4a5201f659ad857d9aea59e5b8771e97dc093e8 | a7967f24e2e94c95d9e582dfa2d4c2a0ffe377ba | /SQL/ODBC/include/Poco/SQL/ODBC/Diagnostics.h | efe8e82b436da23a8b95efa5864ece30817d4e30 | [
"BSL-1.0"
] | permissive | Bjoe/poco | fe5ffedead31571a7d7ff784c7c91b2212f5b8a3 | 70c99c94938fd45f183f8bf965da3d0e49de36be | refs/heads/develop | 2021-05-23T03:17:53.435469 | 2018-05-20T03:47:32 | 2018-05-20T03:47:32 | 61,287,105 | 0 | 1 | NOASSERTION | 2019-01-04T12:01:08 | 2016-06-16T11:22:51 | C | UTF-8 | C++ | false | false | 5,672 | h | //
// Diagnostics.h
//
// Library: Data/ODBC
// Package: ODBC
// Module: Diagnostics
//
// Definition of Diagnostics.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef SQL_ODBC_Diagnostics_INCLUDED
#define SQL_ODBC_Diagnostics_INCLUDED
#include "Poco/SQL/ODBC/ODBC.h"
#include <vector>
#include <cstring>
#ifdef POCO_OS_FAMILY_WINDOWS
#include <windows.h>
#endif
#include <sqlext.h>
namespace Poco {
namespace SQL {
namespace ODBC {
template <typename H, SQLSMALLINT handleType>
class Diagnostics
/// Utility class providing functionality for retrieving ODBC diagnostic
/// records. Diagnostics object must be created with corresponding handle
/// as constructor argument. During construction, diagnostic records fields
/// are populated and the object is ready for querying.
{
public:
static const unsigned int SQL_STATE_SIZE = SQL_SQLSTATE_SIZE + 1;
static const unsigned int SQL_MESSAGE_LENGTH = SQL_MAX_MESSAGE_LENGTH + 1;
static const unsigned int SQL_NAME_LENGTH = 128;
static const std::string DATA_TRUNCATED;
struct DiagnosticFields
{
/// SQLGetDiagRec fields
SQLCHAR _sqlState[SQL_STATE_SIZE];
SQLCHAR _message[SQL_MESSAGE_LENGTH];
SQLINTEGER _nativeError;
};
typedef std::vector<DiagnosticFields> FieldVec;
typedef typename FieldVec::const_iterator Iterator;
explicit Diagnostics(const H& handle)
/// Creates and initializes the Diagnostics.
{
std::memset(_connectionName, 0, sizeof(_connectionName));
std::memset(_serverName, 0, sizeof(_serverName));
diagnostics(handle);
}
~Diagnostics()
/// Destroys the Diagnostics.
{
}
std::string sqlState(int index) const
/// Returns SQL state.
{
poco_assert (index < count());
return std::string((char*) _fields[index]._sqlState);
}
std::string message(int index) const
/// Returns error message.
{
poco_assert (index < count());
return std::string((char*) _fields[index]._message);
}
long nativeError(int index) const
/// Returns native error code.
{
poco_assert (index < count());
return _fields[index]._nativeError;
}
std::string connectionName() const
/// Returns the connection name.
/// If there is no active connection, connection name defaults to NONE.
/// If connection name is not applicable for query context (such as when querying environment handle),
/// connection name defaults to NOT_APPLICABLE.
{
return std::string((char*) _connectionName);
}
std::string serverName() const
/// Returns the server name.
/// If the connection has not been established, server name defaults to NONE.
/// If server name is not applicable for query context (such as when querying environment handle),
/// connection name defaults to NOT_APPLICABLE.
{
return std::string((char*) _serverName);
}
int count() const
/// Returns the number of contained diagnostic records.
{
return (int) _fields.size();
}
void reset()
/// Resets the diagnostic fields container.
{
_fields.clear();
}
const FieldVec& fields() const
{
return _fields;
}
Iterator begin() const
{
return _fields.begin();
}
Iterator end() const
{
return _fields.end();
}
const Diagnostics& diagnostics(const H& handle)
{
DiagnosticFields df;
SQLSMALLINT count = 1;
SQLSMALLINT messageLength = 0;
static const std::string none = "None";
static const std::string na = "Not applicable";
reset();
while (!Utility::isError(SQLGetDiagRec(handleType,
handle,
count,
df._sqlState,
&df._nativeError,
df._message,
SQL_MESSAGE_LENGTH,
&messageLength)))
{
if (1 == count)
{
// success of the following two calls is optional
// (they fail if connection has not been established yet
// or return empty string if not applicable for the context)
if (Utility::isError(SQLGetDiagField(handleType,
handle,
count,
SQL_DIAG_CONNECTION_NAME,
_connectionName,
sizeof(_connectionName),
&messageLength)))
{
std::size_t len = sizeof(_connectionName) > none.length() ?
none.length() : sizeof(_connectionName) - 1;
std::memcpy(_connectionName, none.c_str(), len);
}
else if (0 == _connectionName[0])
{
std::size_t len = sizeof(_connectionName) > na.length() ?
na.length() : sizeof(_connectionName) - 1;
std::memcpy(_connectionName, na.c_str(), len);
}
if (Utility::isError(SQLGetDiagField(handleType,
handle,
count,
SQL_DIAG_SERVER_NAME,
_serverName,
sizeof(_serverName),
&messageLength)))
{
std::size_t len = sizeof(_serverName) > none.length() ?
none.length() : sizeof(_serverName) - 1;
std::memcpy(_serverName, none.c_str(), len);
}
else if (0 == _serverName[0])
{
std::size_t len = sizeof(_serverName) > na.length() ?
na.length() : sizeof(_serverName) - 1;
std::memcpy(_serverName, na.c_str(), len);
}
}
_fields.push_back(df);
std::memset(df._sqlState, 0, SQL_STATE_SIZE);
std::memset(df._message, 0, SQL_MESSAGE_LENGTH);
df._nativeError = 0;
++count;
}
return *this;
}
private:
Diagnostics();
/// SQLGetDiagField fields
SQLCHAR _connectionName[SQL_NAME_LENGTH];
SQLCHAR _serverName[SQL_NAME_LENGTH];
/// Diagnostics container
FieldVec _fields;
};
typedef Diagnostics<SQLHENV, SQL_HANDLE_ENV> EnvironmentDiagnostics;
typedef Diagnostics<SQLHDBC, SQL_HANDLE_DBC> ConnectionDiagnostics;
typedef Diagnostics<SQLHSTMT, SQL_HANDLE_STMT> StatementDiagnostics;
typedef Diagnostics<SQLHDESC, SQL_HANDLE_DESC> DescriptorDiagnostics;
} } } // namespace Poco::SQL::ODBC
#endif
| [
"noreply@github.com"
] | noreply@github.com |
faf36b301dd4c3bbcf509b317128d9b805dad48d | e80e554658cbacdad8cbbcdcd40569577adea977 | /LFS_Coffee_Filler/LFS_Coffee_Filler.ino | 9c2667d8e9f7b4caf753fa6306e3b371953d6922 | [] | no_license | Anitalex/arduino | e250f8c3f4f0fc1bc162af98063ed07870dc452a | 1322ebc3d5b292a73cbc71ff9a13c32394b820b9 | refs/heads/main | 2022-12-25T11:35:01.964730 | 2020-10-06T00:51:57 | 2020-10-06T00:51:57 | 301,568,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | ino | const int valve = 13;
const int sensor = A0;
int input_val;
void setup() {
Serial.begin(9600);
pinMode(valve, OUTPUT);
pinMode(sensor, INPUT);
}
void loop() {
input_val = analogRead(sensor);
Serial.print("input sensor reads");
Serial.println(input_val);
if (input_val <= 10)
{digitalWrite(valve, HIGH);}
else
{digitalWrite(valve, LOW);}
}
| [
"carlos.mccray@live.com"
] | carlos.mccray@live.com |
8cb94126d1b83e7f28a591b44949b5902941b099 | 46f53e9a564192eed2f40dc927af6448f8608d13 | /ash/wm/panels/panel_layout_manager.h | 1a2dadbd00207cf9b27db861fee1e7943002019a | [
"BSD-3-Clause"
] | permissive | sgraham/nope | deb2d106a090d71ae882ac1e32e7c371f42eaca9 | f974e0c234388a330aab71a3e5bbf33c4dcfc33c | refs/heads/master | 2022-12-21T01:44:15.776329 | 2015-03-23T17:25:47 | 2015-03-23T17:25:47 | 32,344,868 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,928 | h | // Copyright (c) 2012 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.
#ifndef ASH_WM_PANELS_PANEL_LAYOUT_MANAGER_H_
#define ASH_WM_PANELS_PANEL_LAYOUT_MANAGER_H_
#include <list>
#include "ash/ash_export.h"
#include "ash/display/display_controller.h"
#include "ash/shelf/shelf_icon_observer.h"
#include "ash/shelf/shelf_layout_manager_observer.h"
#include "ash/shell_observer.h"
#include "ash/wm/window_state_observer.h"
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/aura/layout_manager.h"
#include "ui/aura/window_observer.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/keyboard/keyboard_controller_observer.h"
#include "ui/wm/public/activation_change_observer.h"
namespace aura {
class Window;
class WindowTracker;
}
namespace gfx {
class Rect;
}
namespace views {
class Widget;
}
namespace ash {
class PanelCalloutWidget;
class Shelf;
class ShelfLayoutManager;
// PanelLayoutManager is responsible for organizing panels within the
// workspace. It is associated with a specific container window (i.e.
// kShellWindowId_PanelContainer) and controls the layout of any windows
// added to that container.
//
// The constructor takes a |panel_container| argument which is expected to set
// its layout manager to this instance, e.g.:
// panel_container->SetLayoutManager(new PanelLayoutManager(panel_container));
class ASH_EXPORT PanelLayoutManager
: public aura::LayoutManager,
public ShelfIconObserver,
public ShellObserver,
public aura::WindowObserver,
public wm::WindowStateObserver,
public aura::client::ActivationChangeObserver,
public keyboard::KeyboardControllerObserver,
public DisplayController::Observer,
public ShelfLayoutManagerObserver {
public:
explicit PanelLayoutManager(aura::Window* panel_container);
~PanelLayoutManager() override;
// Call Shutdown() before deleting children of panel_container.
void Shutdown();
void StartDragging(aura::Window* panel);
void FinishDragging();
void ToggleMinimize(aura::Window* panel);
// Hide / Show the panel callout widgets.
void SetShowCalloutWidgets(bool show);
// Returns the callout widget (arrow) for |panel|.
views::Widget* GetCalloutWidgetForPanel(aura::Window* panel);
Shelf* shelf() { return shelf_; }
void SetShelf(Shelf* shelf);
// Overridden from aura::LayoutManager:
void OnWindowResized() override;
void OnWindowAddedToLayout(aura::Window* child) override;
void OnWillRemoveWindowFromLayout(aura::Window* child) override;
void OnWindowRemovedFromLayout(aura::Window* child) override;
void OnChildWindowVisibilityChanged(aura::Window* child,
bool visibile) override;
void SetChildBounds(aura::Window* child,
const gfx::Rect& requested_bounds) override;
// Overridden from ShelfIconObserver
void OnShelfIconPositionsChanged() override;
// Overridden from ShellObserver
void OnOverviewModeEnded() override;
void OnShelfAlignmentChanged(aura::Window* root_window) override;
// Overridden from aura::WindowObserver
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override;
// Overridden from ash::wm::WindowStateObserver
void OnPostWindowStateTypeChange(wm::WindowState* window_state,
wm::WindowStateType old_type) override;
// Overridden from aura::client::ActivationChangeObserver
void OnWindowActivated(aura::Window* gained_active,
aura::Window* lost_active) override;
// Overridden from DisplayController::Observer
void OnDisplayConfigurationChanged() override;
// Overridden from ShelfLayoutManagerObserver
void WillChangeVisibilityState(ShelfVisibilityState new_state) override;
private:
friend class PanelLayoutManagerTest;
friend class PanelWindowResizerTest;
friend class DockedWindowResizerTest;
friend class DockedWindowLayoutManagerTest;
friend class WorkspaceControllerTest;
friend class AcceleratorControllerTest;
views::Widget* CreateCalloutWidget();
struct PanelInfo{
PanelInfo() : window(NULL), callout_widget(NULL), slide_in(false) {}
bool operator==(const aura::Window* other_window) const {
return window == other_window;
}
// A weak pointer to the panel window.
aura::Window* window;
// The callout widget for this panel. This pointer must be managed
// manually as this structure is used in a std::list. See
// http://www.chromium.org/developers/smart-pointer-guidelines
PanelCalloutWidget* callout_widget;
// True on new and restored panel windows until the panel has been
// positioned. The first time Relayout is called the panel will be shown,
// and slide into position and this will be set to false.
bool slide_in;
};
typedef std::list<PanelInfo> PanelList;
void MinimizePanel(aura::Window* panel);
void RestorePanel(aura::Window* panel);
// Called whenever the panel layout might change.
void Relayout();
// Called whenever the panel stacking order needs to be updated (e.g. focus
// changes or a panel is moved).
void UpdateStacking(aura::Window* active_panel);
// Update the callout arrows for all managed panels.
void UpdateCallouts();
// Overridden from keyboard::KeyboardControllerObserver:
void OnKeyboardBoundsChanging(const gfx::Rect& keyboard_bounds) override;
// Parent window associated with this layout manager.
aura::Window* panel_container_;
// Protect against recursive calls to OnWindowAddedToLayout().
bool in_add_window_;
// Protect against recursive calls to Relayout().
bool in_layout_;
// Indicates if the panel callout widget should be created.
bool show_callout_widgets_;
// Ordered list of unowned pointers to panel windows.
PanelList panel_windows_;
// The panel being dragged.
aura::Window* dragged_panel_;
// The shelf we are observing for shelf icon changes.
Shelf* shelf_;
// The shelf layout manager being observed for visibility changes.
ShelfLayoutManager* shelf_layout_manager_;
// When not NULL, the shelf is hidden (i.e. full screen) and this tracks the
// set of panel windows which have been temporarily hidden and need to be
// restored when the shelf becomes visible again.
scoped_ptr<aura::WindowTracker> restore_windows_on_shelf_visible_;
// The last active panel. Used to maintain stacking order even if no panels
// are currently focused.
aura::Window* last_active_panel_;
base::WeakPtrFactory<PanelLayoutManager> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(PanelLayoutManager);
};
} // namespace ash
#endif // ASH_WM_PANELS_PANEL_LAYOUT_MANAGER_H_
| [
"scottmg@chromium.org"
] | scottmg@chromium.org |
5242bb7fa3f1900b5a5fd9f3f91adee738571afd | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom-shared-internal.h | f35ef298ad94a1d0935375b22177c8aaa2c8c1d5 | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,623 | h | // Copyright 2016 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.
#ifndef THIRD_PARTY_BLINK_PUBLIC_MOJOM_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_HANDLE_MOJOM_SHARED_INTERNAL_H_
#define THIRD_PARTY_BLINK_PUBLIC_MOJOM_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_HANDLE_MOJOM_SHARED_INTERNAL_H_
#include "mojo/public/cpp/bindings/lib/array_internal.h"
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
#include "mojo/public/cpp/bindings/lib/map_data_internal.h"
#include "mojo/public/cpp/bindings/lib/buffer.h"
#include "third_party/blink/public/mojom/native_file_system/native_file_system_file_handle.mojom-shared-internal.h"
#include "third_party/blink/public/mojom/native_file_system/native_file_system_error.mojom-shared-internal.h"
#include "third_party/blink/public/mojom/native_file_system/native_file_system_transfer_token.mojom-shared-internal.h"
#include "mojo/public/cpp/bindings/lib/native_enum_data.h"
#include "mojo/public/interfaces/bindings/native_struct.mojom-shared-internal.h"
#include "base/component_export.h"
namespace mojo {
namespace internal {
class ValidationContext;
}
}
namespace blink {
namespace mojom {
namespace internal {
class NativeFileSystemEntry_Data;
class NativeFileSystemHandle_Data;
#pragma pack(push, 1)
class COMPONENT_EXPORT(MOJOM_SHARED_BLINK_COMMON_EXPORT) NativeFileSystemHandle_Data {
public:
// Used to identify Mojom Union Data Classes.
typedef void MojomUnionDataType;
NativeFileSystemHandle_Data() {}
// Do nothing in the destructor since it won't be called when it is a
// non-inlined union.
~NativeFileSystemHandle_Data() {}
class BufferWriter {
public:
BufferWriter() = default;
void Allocate(mojo::internal::Buffer* serialization_buffer) {
serialization_buffer_ = serialization_buffer;
index_ = serialization_buffer_->Allocate(sizeof(NativeFileSystemHandle_Data));
new (data()) NativeFileSystemHandle_Data();
}
void AllocateInline(mojo::internal::Buffer* serialization_buffer,
void* ptr) {
const char* start = static_cast<const char*>(
serialization_buffer->data());
const char* slot = static_cast<const char*>(ptr);
DCHECK_GT(slot, start);
serialization_buffer_ = serialization_buffer;
index_ = slot - start;
new (data()) NativeFileSystemHandle_Data();
}
bool is_null() const { return !serialization_buffer_; }
NativeFileSystemHandle_Data* data() {
DCHECK(!is_null());
return serialization_buffer_->Get<NativeFileSystemHandle_Data>(index_);
}
NativeFileSystemHandle_Data* operator->() { return data(); }
private:
mojo::internal::Buffer* serialization_buffer_ = nullptr;
size_t index_ = 0;
};
static bool Validate(const void* data,
mojo::internal::ValidationContext* validation_context,
bool inlined);
bool is_null() const { return size == 0; }
void set_null() {
size = 0U;
tag = static_cast<NativeFileSystemHandle_Tag>(0);
data.unknown = 0U;
}
enum class NativeFileSystemHandle_Tag : uint32_t {
FILE,
DIRECTORY,
};
// A note on layout:
// "Each non-static data member is allocated as if it were the sole member of
// a struct." - Section 9.5.2 ISO/IEC 14882:2011 (The C++ Spec)
union MOJO_ALIGNAS(8) Union_ {
Union_() : unknown(0) {}
mojo::internal::Interface_Data f_file;
mojo::internal::Interface_Data f_directory;
uint64_t unknown;
};
uint32_t size;
NativeFileSystemHandle_Tag tag;
Union_ data;
};
static_assert(sizeof(NativeFileSystemHandle_Data) == mojo::internal::kUnionDataSize,
"Bad sizeof(NativeFileSystemHandle_Data)");
class COMPONENT_EXPORT(MOJOM_SHARED_BLINK_COMMON_EXPORT) NativeFileSystemEntry_Data {
public:
class BufferWriter {
public:
BufferWriter() = default;
void Allocate(mojo::internal::Buffer* serialization_buffer) {
serialization_buffer_ = serialization_buffer;
index_ = serialization_buffer_->Allocate(sizeof(NativeFileSystemEntry_Data));
new (data()) NativeFileSystemEntry_Data();
}
bool is_null() const { return !serialization_buffer_; }
NativeFileSystemEntry_Data* data() {
DCHECK(!is_null());
return serialization_buffer_->Get<NativeFileSystemEntry_Data>(index_);
}
NativeFileSystemEntry_Data* operator->() { return data(); }
private:
mojo::internal::Buffer* serialization_buffer_ = nullptr;
size_t index_ = 0;
DISALLOW_COPY_AND_ASSIGN(BufferWriter);
};
static bool Validate(const void* data,
mojo::internal::ValidationContext* validation_context);
mojo::internal::StructHeader header_;
internal::NativeFileSystemHandle_Data entry_handle;
mojo::internal::Pointer<mojo::internal::String_Data> name;
private:
NativeFileSystemEntry_Data();
~NativeFileSystemEntry_Data() = delete;
};
static_assert(sizeof(NativeFileSystemEntry_Data) == 32,
"Bad sizeof(NativeFileSystemEntry_Data)");
// Used by NativeFileSystemEntry::WrapAsMessage to lazily serialize the struct.
template <typename UserType, typename DataView>
struct NativeFileSystemEntry_UnserializedMessageContext
: public mojo::internal::UnserializedMessageContext {
public:
static const mojo::internal::UnserializedMessageContext::Tag kMessageTag;
NativeFileSystemEntry_UnserializedMessageContext(
uint32_t message_name,
uint32_t message_flags,
UserType input)
: mojo::internal::UnserializedMessageContext(&kMessageTag, message_name, message_flags)
, user_data_(std::move(input)) {}
~NativeFileSystemEntry_UnserializedMessageContext() override = default;
UserType TakeData() {
return std::move(user_data_);
}
private:
// mojo::internal::UnserializedMessageContext:
void Serialize(mojo::internal::SerializationContext* context,
mojo::internal::Buffer* buffer) override {
NativeFileSystemEntry_Data::BufferWriter writer;
mojo::internal::Serialize<DataView>(user_data_, buffer, &writer, context);
}
UserType user_data_;
};
template <typename UserType, typename DataView>
const mojo::internal::UnserializedMessageContext::Tag
NativeFileSystemEntry_UnserializedMessageContext<UserType, DataView>::kMessageTag = {};
#pragma pack(pop)
} // namespace internal
} // namespace mojom
} // namespace blink
#endif // THIRD_PARTY_BLINK_PUBLIC_MOJOM_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_HANDLE_MOJOM_SHARED_INTERNAL_H_ | [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
d454bcf171603307daea8bd52c5c3837a7701432 | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /gpu/config/gpu_control_list.h | 64ac36f2ea5401bd0e06a435cd95e08381a6ee55 | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 10,466 | h | // Copyright (c) 2013 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.
#ifndef GPU_CONFIG_GPU_CONTROL_LIST_H_
#define GPU_CONFIG_GPU_CONTROL_LIST_H_
#include <stddef.h>
#include <set>
#include <string>
#include <vector>
#include "base/containers/hash_tables.h"
#include "base/values.h"
#include "gpu/config/gpu_info.h"
#include "gpu/gpu_export.h"
namespace gpu {
struct GpuControlListData;
struct GPUInfo;
class GPU_EXPORT GpuControlList {
public:
typedef base::hash_map<int, std::string> FeatureMap;
enum OsType {
kOsLinux,
kOsMacosx,
kOsWin,
kOsChromeOS,
kOsAndroid,
kOsFuchsia,
kOsAny
};
enum OsFilter {
// In loading, ignore all entries that belong to other OS.
kCurrentOsOnly,
// In loading, keep all entries. This is for testing only.
kAllOs
};
enum NumericOp {
kBetween, // <= * <=
kEQ, // =
kLT, // <
kLE, // <=
kGT, // >
kGE, // >=
kAny,
kUnknown // Indicates the data is invalid.
};
enum MultiGpuStyle {
kMultiGpuStyleOptimus,
kMultiGpuStyleAMDSwitchable,
kMultiGpuStyleAMDSwitchableIntegrated,
kMultiGpuStyleAMDSwitchableDiscrete,
kMultiGpuStyleNone
};
enum MultiGpuCategory {
// This entry applies if this is the primary GPU on the system.
kMultiGpuCategoryPrimary,
// This entry applies if this is a secondary GPU on the system.
kMultiGpuCategorySecondary,
// This entry applies if this is the active GPU on the system.
kMultiGpuCategoryActive,
// This entry applies if this is any of the GPUs on the system.
kMultiGpuCategoryAny,
kMultiGpuCategoryNone
};
enum GLType {
kGLTypeGL, // This is default on MacOSX, Linux, ChromeOS
kGLTypeGLES, // This is default on Android
kGLTypeANGLE, // This is default on Windows
kGLTypeNone
};
enum VersionStyle {
kVersionStyleNumerical,
kVersionStyleLexical,
kVersionStyleUnknown
};
struct GPU_EXPORT Version {
NumericOp op;
VersionStyle style;
const char* value1;
const char* value2;
bool IsSpecified() const { return op != kUnknown; }
bool Contains(const std::string& version_string, char splitter) const;
bool Contains(const std::string& version_string) const {
return Contains(version_string, '.');
}
// Compare two version strings.
// Return 1 if version > version_ref,
// 0 if version = version_ref,
// -1 if version < version_ref.
// Note that we only compare as many segments as both versions contain.
// For example: Compare("10.3.1", "10.3") returns 0,
// Compare("10.3", "10.3.1") returns 0.
// If "version_style" is Lexical, the first segment is compared
// numerically, all other segments are compared lexically.
// Lexical is used for AMD Linux driver versions only.
static int Compare(const std::vector<std::string>& version,
const std::vector<std::string>& version_ref,
VersionStyle version_style);
};
struct GPU_EXPORT DriverInfo {
const char* driver_vendor;
Version driver_version;
Version driver_date;
bool Contains(const GPUInfo& gpu_info) const;
};
struct GPU_EXPORT GLStrings {
const char* gl_vendor;
const char* gl_renderer;
const char* gl_extensions;
const char* gl_version;
bool Contains(const GPUInfo& gpu_info) const;
};
struct GPU_EXPORT MachineModelInfo {
size_t machine_model_name_size;
const char* const* machine_model_names;
Version machine_model_version;
bool Contains(const GPUInfo& gpu_info) const;
};
struct GPU_EXPORT More {
// These are just part of Entry fields that are less common.
// Putting them to a separate struct to save Entry data size.
GLType gl_type;
Version gl_version;
Version pixel_shader_version;
bool in_process_gpu;
uint32_t gl_reset_notification_strategy;
bool direct_rendering;
Version gpu_count;
uint32_t test_group;
// Return true if GL_VERSION string does not fit the entry info
// on GL type and GL version.
bool GLVersionInfoMismatch(const std::string& gl_version_string) const;
bool Contains(const GPUInfo& gpu_info) const;
// Return the default GL type, depending on the OS.
// See GLType declaration.
static GLType GetDefaultGLType();
};
struct GPU_EXPORT Conditions {
OsType os_type;
Version os_version;
uint32_t vendor_id;
size_t device_id_size;
const uint32_t* device_ids;
MultiGpuCategory multi_gpu_category;
MultiGpuStyle multi_gpu_style;
const DriverInfo* driver_info;
const GLStrings* gl_strings;
const MachineModelInfo* machine_model_info;
size_t gpu_series_list_size;
const GpuSeriesType* gpu_series_list;
const More* more;
bool Contains(OsType os_type,
const std::string& os_version,
const GPUInfo& gpu_info) const;
// Determines whether we needs more gpu info to make the blacklisting
// decision. It should only be checked if Contains() returns true.
bool NeedsMoreInfo(const GPUInfo& gpu_info) const;
};
struct GPU_EXPORT Entry {
uint32_t id;
const char* description;
size_t feature_size;
const int* features;
size_t disabled_extension_size;
const char* const* disabled_extensions;
size_t disabled_webgl_extension_size;
const char* const* disabled_webgl_extensions;
size_t cr_bug_size;
const uint32_t* cr_bugs;
Conditions conditions;
size_t exception_size;
const Conditions* exceptions;
bool Contains(OsType os_type,
const std::string& os_version,
const GPUInfo& gpu_info) const;
bool AppliesToTestGroup(uint32_t target_test_group) const;
// Determines whether we needs more gpu info to make the blacklisting
// decision. It should only be checked if Contains() returns true.
bool NeedsMoreInfo(const GPUInfo& gpu_info, bool consider_exceptions) const;
void GetFeatureNames(base::ListValue* feature_names,
const FeatureMap& feature_map) const;
// Logs a control list match for this rule in the list identified by
// |control_list_logging_name|.
void LogControlListMatch(
const std::string& control_list_logging_name) const;
};
explicit GpuControlList(const GpuControlListData& data);
virtual ~GpuControlList();
// Collects system information and combines them with gpu_info and control
// list information to decide which entries are applied to the current
// system and returns the union of features specified in each entry.
// If os is kOsAny, use the current OS; if os_version is empty, use the
// current OS version.
std::set<int32_t> MakeDecision(OsType os,
const std::string& os_version,
const GPUInfo& gpu_info);
// Same as the above function, but instead of using the entries with no
// "test_group" specified or "test_group" = 0, using the entries with
// "test_group" = |target_test_group|.
std::set<int32_t> MakeDecision(OsType os,
const std::string& os_version,
const GPUInfo& gpu_info,
uint32_t target_test_group);
// Return the active entry indices from the last MakeDecision() call.
const std::vector<uint32_t>& GetActiveEntries() const;
// Return corresponding entry IDs from entry indices.
std::vector<uint32_t> GetEntryIDsFromIndices(
const std::vector<uint32_t>& entry_indices) const;
// Collects all disabled extensions.
std::vector<std::string> GetDisabledExtensions();
// Collects all disabled WebGL extensions.
std::vector<std::string> GetDisabledWebGLExtensions();
// Returns the description and bugs from active entries provided.
// Each problems has:
// {
// "description": "Your GPU is too old",
// "crBugs": [1234],
// }
// The use case is we compute the entries from GPU process and send them to
// browser process, and call GetReasons() in browser process.
void GetReasons(base::ListValue* problem_list,
const std::string& tag,
const std::vector<uint32_t>& entries) const;
// Return the largest entry id. This is used for histogramming.
uint32_t max_entry_id() const;
// Check if we need more gpu info to make the decisions.
// This is computed from the last MakeDecision() call.
// If yes, we should create a gl context and do a full gpu info collection.
bool needs_more_info() const { return needs_more_info_; }
// Returns the number of entries. This is only for tests.
size_t num_entries() const;
// Register a feature to FeatureMap.
void AddSupportedFeature(const std::string& feature_name, int feature_id);
// Enables logging of control list decisions.
void EnableControlListLogging(const std::string& control_list_logging_name) {
control_list_logging_enabled_ = true;
control_list_logging_name_ = control_list_logging_name;
}
protected:
// Return false if an entry index goes beyond |total_entries|.
static bool AreEntryIndicesValid(const std::vector<uint32_t>& entry_indices,
size_t total_entries);
private:
friend class GpuControlListEntryTest;
friend class VersionInfoTest;
// Gets the current OS type.
static OsType GetOsType();
size_t entry_count_;
const Entry* entries_;
// This records all the entries that are appliable to the current user
// machine. It is updated everytime MakeDecision() is called and is used
// later by GetDecisionEntries().
std::vector<uint32_t> active_entries_;
uint32_t max_entry_id_;
bool needs_more_info_;
// The features a GpuControlList recognizes and handles.
FeatureMap feature_map_;
bool control_list_logging_enabled_;
std::string control_list_logging_name_;
};
struct GPU_EXPORT GpuControlListData {
size_t entry_count;
const GpuControlList::Entry* entries;
GpuControlListData() : entry_count(0u), entries(nullptr) {}
GpuControlListData(size_t a_entry_count,
const GpuControlList::Entry* a_entries)
: entry_count(a_entry_count), entries(a_entries) {}
};
} // namespace gpu
#endif // GPU_CONFIG_GPU_CONTROL_LIST_H_
| [
"artem@brave.com"
] | artem@brave.com |
ae279ccb271f83c131b3048b7104d4dd00825934 | 8d0a8be1992e6c3faf67f6da2f10e4d4918be210 | /src/core/javascript_dialog_controller_p.h | 0d7552ce21ff75eaa95ea111acd211a19c5d61c2 | [] | no_license | Metrological/qtwebengine | e31f7798585188580601ce35882ffe9046f19bb4 | 7bb72a0b500f9ea7d8b3b37adc24a2700a309d2d | refs/heads/master | 2021-01-24T22:26:39.095136 | 2014-04-28T23:16:21 | 2014-04-28T23:16:21 | 18,896,266 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,982 | h | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebEngine module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef JAVASCRIPT_DIALOG_CONTROLLER_P_H
#define JAVASCRIPT_DIALOG_CONTROLLER_P_H
#include "content/public/browser/javascript_dialog_manager.h"
#include "web_contents_adapter_client.h"
#include <QString>
namespace content {
class WebContents;
}
class JavaScriptDialogControllerPrivate {
public:
void dialogFinished(bool accepted, const base::string16 &promptValue);
JavaScriptDialogControllerPrivate(WebContentsAdapterClient::JavascriptDialogType, const QString &message, const QString &prompt
, const QUrl &securityOrigin, const content::JavaScriptDialogManager::DialogClosedCallback &
, content::WebContents *);
WebContentsAdapterClient::JavascriptDialogType type;
QString message;
QString defaultPrompt;
QUrl securityOrigin;
QString userInput;
content::JavaScriptDialogManager::DialogClosedCallback callback;
content::WebContents *contents;
};
#endif // JAVASCRIPT_DIALOG_CONTROLLER_P_H
| [
"gerrit-noreply@qt-project.org"
] | gerrit-noreply@qt-project.org |
2adaed3b618b8112a8aaa553c48779297a73c2f0 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/asio/detail/resolver_service.hpp | f1cdca66915880ae5503231c99310f520268d37a | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,739 | hpp | //
// detail/resolver_service.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_RESOLVER_SERVICE_HPP
#define BOOST_ASIO_DETAIL_RESOLVER_SERVICE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <sstd/boost/asio/detail/config.hpp>
#if !defined(BOOST_ASIO_WINDOWS_RUNTIME)
#include <sstd/boost/asio/ip/basic_resolver_query.hpp>
#include <sstd/boost/asio/ip/basic_resolver_results.hpp>
#include <sstd/boost/asio/detail/concurrency_hint.hpp>
#include <sstd/boost/asio/detail/memory.hpp>
#include <sstd/boost/asio/detail/resolve_endpoint_op.hpp>
#include <sstd/boost/asio/detail/resolve_query_op.hpp>
#include <sstd/boost/asio/detail/resolver_service_base.hpp>
#include <sstd/boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace detail {
template <typename Protocol>
class resolver_service :
public service_base<resolver_service<Protocol> >,
public resolver_service_base
{
public:
// The implementation type of the resolver. A cancellation token is used to
// indicate to the background thread that the operation has been cancelled.
typedef socket_ops::shared_cancel_token_type implementation_type;
// The endpoint type.
typedef typename Protocol::endpoint endpoint_type;
// The query type.
typedef boost::asio::ip::basic_resolver_query<Protocol> query_type;
// The results type.
typedef boost::asio::ip::basic_resolver_results<Protocol> results_type;
// Constructor.
resolver_service(boost::asio::io_context& io_context)
: service_base<resolver_service<Protocol> >(io_context),
resolver_service_base(io_context)
{
}
// Destroy all user-defined handler objects owned by the service.
void shutdown()
{
this->base_shutdown();
}
// Perform any fork-related housekeeping.
void notify_fork(boost::asio::io_context::fork_event fork_ev)
{
this->base_notify_fork(fork_ev);
}
// Resolve a query to a list of entries.
results_type resolve(implementation_type&, const query_type& query,
boost::system::error_code& ec)
{
boost::asio::detail::addrinfo_type* address_info = 0;
socket_ops::getaddrinfo(query.host_name().c_str(),
query.service_name().c_str(), query.hints(), &address_info, ec);
auto_addrinfo auto_address_info(address_info);
return ec ? results_type() : results_type::create(
address_info, query.host_name(), query.service_name());
}
// Asynchronously resolve a query to a list of entries.
template <typename Handler>
void async_resolve(implementation_type& impl,
const query_type& query, Handler& handler)
{
// Allocate and construct an operation to wrap the handler.
typedef resolve_query_op<Protocol, Handler> op;
typename op::ptr p = { boost::asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(impl, query, io_context_impl_, handler);
BOOST_ASIO_HANDLER_CREATION((io_context_impl_.context(),
*p.p, "resolver", &impl, 0, "async_resolve"));
start_resolve_op(p.p);
p.v = p.p = 0;
}
// Resolve an endpoint to a list of entries.
results_type resolve(implementation_type&,
const endpoint_type& endpoint, boost::system::error_code& ec)
{
char host_name[NI_MAXHOST];
char service_name[NI_MAXSERV];
socket_ops::sync_getnameinfo(endpoint.data(), endpoint.size(),
host_name, NI_MAXHOST, service_name, NI_MAXSERV,
endpoint.protocol().type(), ec);
return ec ? results_type() : results_type::create(
endpoint, host_name, service_name);
}
// Asynchronously resolve an endpoint to a list of entries.
template <typename Handler>
void async_resolve(implementation_type& impl,
const endpoint_type& endpoint, Handler& handler)
{
// Allocate and construct an operation to wrap the handler.
typedef resolve_endpoint_op<Protocol, Handler> op;
typename op::ptr p = { boost::asio::detail::addressof(handler),
op::ptr::allocate(handler), 0 };
p.p = new (p.v) op(impl, endpoint, io_context_impl_, handler);
BOOST_ASIO_HANDLER_CREATION((io_context_impl_.context(),
*p.p, "resolver", &impl, 0, "async_resolve"));
start_resolve_op(p.p);
p.v = p.p = 0;
}
};
} // namespace detail
} // namespace asio
} // namespace boost
#include <sstd/boost/asio/detail/pop_options.hpp>
#endif // !defined(BOOST_ASIO_WINDOWS_RUNTIME)
#endif // BOOST_ASIO_DETAIL_RESOLVER_SERVICE_HPP
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
bf0045ecfab2da3aef76c2ae907c7da8a34de842 | b3734617473f2446b5f6284dfaef016c857c88c6 | /src/problems/vrptw/operators/pd_shift.h | b16ff4aac9c296a9a93380da48ee6e032b8c160e | [
"BSD-2-Clause"
] | permissive | vernitgarg/vroom | 5003462ede17ffd008dc9e3a44951066b2207aeb | 9b7165ec568bd0443ca1f01ba2353a504b895157 | refs/heads/master | 2023-06-08T14:00:23.360069 | 2023-04-06T09:07:34 | 2023-04-06T09:07:34 | 250,543,310 | 0 | 0 | null | 2020-03-27T13:35:46 | 2020-03-27T13:35:45 | null | UTF-8 | C++ | false | false | 853 | h | #ifndef VRPTW_PD_SHIFT_H
#define VRPTW_PD_SHIFT_H
/*
This file is part of VROOM.
Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "problems/cvrp/operators/pd_shift.h"
namespace vroom::vrptw {
class PDShift : public cvrp::PDShift {
private:
std::vector<Index> _source_without_pd;
TWRoute& _tw_s_route;
TWRoute& _tw_t_route;
Amount _best_t_delivery;
void compute_gain() override;
public:
PDShift(const Input& input,
const utils::SolutionState& sol_state,
TWRoute& tw_s_route,
Index s_vehicle,
Index s_p_rank,
Index s_d_rank,
TWRoute& tw_t_route,
Index t_vehicle,
const Eval& gain_threshold);
void log_route(const std::vector<Index>& route) const;
void apply() override;
};
} // namespace vroom::vrptw
#endif
| [
"git@coupey.fr"
] | git@coupey.fr |
e979a731f2de2acb56801818329f5bd0a58d6f0d | 7f5390b9049e13387c3a6db7cd39d822a8357e6e | /Problem.h | 9b33da3e2583daa8f418be6637b16485e85534e8 | [] | no_license | cyoung-cs/Math_Trainer | c92cdb9fba47a11dcb81319cabe97a2f319c5023 | fe30ff9d144757d9d0687b4bf60fba9b36b8615e | refs/heads/master | 2021-01-18T16:18:35.590354 | 2016-05-02T10:52:20 | 2016-05-02T10:52:20 | 57,427,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | h | #include <string>
#ifndef __string_h__
#define __string_h__
class Problem {
private:
int id;
std::string solution;
std::string question;
std::string gen_form;
std::string subject;
public:
Problem(std::string subject, std::string question, std::string answer, std::string gen_form);
bool answer(std::string query);
bool check(std::string query);
std::string get_subject();
std::string get_gen_form();
std::string get_question();
};
#endif
| [
"youngchristopherlee@gmail.com"
] | youngchristopherlee@gmail.com |
ff670884df0a26b02413cc13f0f7bf7ed5be1f22 | 6f36ab50dc7578f5ca161c5b861c68e839535b74 | /acm/ceshi.cpp | 026a6d4c2d4178e6def387ee3ad1b3a313488503 | [] | no_license | RandyLambert/daily | 144e49eb945ce6b33a8d06c409b8db1318d01526 | be1634663d5248f7abcc92e4a42f193411ad5aca | refs/heads/master | 2021-06-24T01:45:54.574544 | 2021-04-14T16:15:35 | 2021-04-14T16:15:35 | 207,723,773 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | #include <iostream>
bool a[100];
int n;
int main(){
scanf("%d",&n);
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
if(i == j){
a[i] = a[i];
}
else{
if(a[j] == 0){
a[j] = 1;
}
else{
a[j] = 0;
}
}
}
for(int k = 0;k < n;k++){
printf("%d",a[k]);
}
putchar('\n');
}
}
| [
"1249604462@qq.com"
] | 1249604462@qq.com |
770f417e181ae209ff8deffd3619eed585ecd0cd | 32d8f212fe91d2f3bfcaa3ab582b2c51f13ecaf0 | /HW3/main.cpp | 8e7c86b9017392690aa847b771e96717b2f79bbd | [] | no_license | ivanrudn0303/ParallelProgramming | 19e44818dd5be9b73aa56cecc874e090742da3a2 | 7e01431176dfbf905193937495b5aae3fd14ff81 | refs/heads/master | 2020-07-27T12:24:26.337160 | 2019-12-23T06:07:51 | 2019-12-23T06:07:51 | 209,088,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,653 | cpp | #include "SkipList.hpp"
#include <iostream>
#include <mutex>
#include <thread>
std::mutex m;
void f(int num, int idx, SkipList<int>* skip)
{
for (int i = idx; i < num * 1000; i += num)
{
if (i == 0)
continue;
// m.lock();
skip->insert(i, i * 3);
// m.unlock();
}
}
void f2(int num, int idx, SkipList<int>* skip)
{
int sRes;
for (int i = idx; i < num * 1000; i += num)
{
if (i == 0)
continue;
skip->find(i, sRes);
if (sRes != 3 * i)
std::cout << "bad res = " << sRes << " i = " << i << std::endl;
}
}
void f3(int num, int idx, SkipList<int>* skip)
{
for (int i = idx; i < num * 1000; i += num)
{
if (i == 0)
continue;
skip->remove(i);
// std::cout << "deleted" << i << std::endl;
}
}
int main()
{
SkipList<int> sTest;
std::thread t1(f, 4, 0, &sTest);
std::thread t2(f, 4, 1, &sTest);
std::thread t3(f, 4, 2, &sTest);
std::thread t4(f, 4, 3, &sTest);
std::cout << "here1\n";
int sRes;
// for (int i = 0; i < 4 * 1000; ++i)
// {
// while (!sTest.find(i, sRes));
// if (sRes != i * 3)
// std::cout << "sRes " << sRes << std::endl;
// }
t1.join();
t2.join();
t3.join();
t4.join();
sTest.Check();
// sTest.remove(1);
std::cout << "here2\n";
std::thread t11(f2, 4, 0, &sTest);
std::thread t12(f2, 4, 1, &sTest);
std::thread t13(f2, 4, 2, &sTest);
std::thread t14(f2, 4, 3, &sTest);
t11.join();
t12.join();
t13.join();
t14.join();
sTest.Check();
return 0;
}
| [
"ivanrudn0303@gmail.com"
] | ivanrudn0303@gmail.com |
4f3bd3b7dc58f9824089f7507bd894a95124989a | 6cef71c16c6ba5b670a83c4dad7d843bfa156d03 | /MdSpi.cpp | e899c2fecb65b9efd5e822943a5c9dc415bf7145 | [] | no_license | TobeGodman/CTPDEV | 117527be6c277bf5c054839ac6dadd65f7a6c466 | 9c4f3f32a5923d1a05f75bb3bbd51f2bcfa53777 | refs/heads/master | 2021-01-17T22:47:40.363657 | 2014-05-14T14:10:16 | 2014-05-14T14:10:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,991 | cpp | #include "MdSpi.h"
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
// USER_API参数
extern CThostFtdcMdApi* pUserApi;
// 配置参数
extern char FRONT_ADDR[];
extern TThostFtdcBrokerIDType BROKER_ID;
extern TThostFtdcInvestorIDType INVESTOR_ID;
extern TThostFtdcPasswordType PASSWORD;
extern char* ppInstrumentID[];
extern int iInstrumentID;
// 请求编号
extern int iRequestID;
void CMdSpi::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID,
bool bIsLast)
{
cerr << "--->>> " << __FUNCTION__ << endl;
IsErrorRspInfo(pRspInfo);
}
void CMdSpi::OnFrontDisconnected(int nReason)
{
cerr << "--->>> " << __FUNCTION__ << endl;
cerr << "--->>> Reason = " << nReason << endl;
}
void CMdSpi::OnHeartBeatWarning(int nTimeLapse)
{
cerr << "--->>> " << __FUNCTION__ << endl;
cerr << "--->>> nTimerLapse = " << nTimeLapse << endl;
}
void CMdSpi::OnFrontConnected()
{
cerr << "--->>> " << __FUNCTION__ << endl;
///用户登录请求
ReqUserLogin();
}
void CMdSpi::ReqUserLogin()
{
CThostFtdcReqUserLoginField req;
memset(&req, 0, sizeof(req));
strcpy(req.BrokerID, BROKER_ID);
strcpy(req.UserID, INVESTOR_ID);
strcpy(req.Password, PASSWORD);
int iResult = pUserApi->ReqUserLogin(&req, ++iRequestID);
cerr << "--->>> send user login request: "
<< ((iResult == 0) ? "successed" : "failed") << endl;
}
void CMdSpi::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin,
CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << "--->>> " << __FUNCTION__ << endl;
if (bIsLast && !IsErrorRspInfo(pRspInfo))
{
///获取当前交易日
cerr << "--->>>get trading date = " << pUserApi->GetTradingDay()
<< endl;
// 请求订阅行情
SubscribeMarketData();
}
}
void CMdSpi::SubscribeMarketData()
{
int iResult = pUserApi->SubscribeMarketData(ppInstrumentID, iInstrumentID);
cerr << "--->>> send hangqing dingyue: "
<< ((iResult == 0) ? "successed" : "failed") << endl;
}
void CMdSpi::OnRspSubMarketData(
CThostFtdcSpecificInstrumentField *pSpecificInstrument,
CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << __FUNCTION__ << endl;
}
void CMdSpi::OnRspUnSubMarketData(
CThostFtdcSpecificInstrumentField *pSpecificInstrument,
CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
cerr << __FUNCTION__ << endl;
}
void CMdSpi::OnRtnDepthMarketData(
CThostFtdcDepthMarketDataField *pDepthMarketData)
{
//cerr << __FUNCTION__ << endl;
cout << pDepthMarketData->InstrumentID << " "
<< pDepthMarketData->LastPrice << endl;
}
bool CMdSpi::IsErrorRspInfo(CThostFtdcRspInfoField *pRspInfo)
{
// 如果ErrorID != 0, 说明收到了错误的响应
bool bResult = ((pRspInfo) && (pRspInfo->ErrorID != 0));
if (bResult)
cerr << "--->>> ErrorID=" << pRspInfo->ErrorID << ", ErrorMsg="
<< pRspInfo->ErrorMsg << endl;
return bResult;
}
| [
"cepinlin@gmail.com"
] | cepinlin@gmail.com |
471745eb719fa974c65bc0a11967cd26760d0bb3 | f4f63d03d16371530858fbceb7587a230cad82d2 | /Program/BaseFramework/Src/System/Shader/KdPostProcessShader/KdPostProcessShader.h | 90296165a1139b4909c63810cd67eb432ef9adc9 | [] | no_license | UmakoshiIbuki/SnowFiat- | a35da2a11fa14546c8c95c64e8c792817babd043 | 19894b0635e579b5c3864f940597c9056bc9e1f4 | refs/heads/master | 2023-05-03T09:06:16.313963 | 2021-05-19T10:28:47 | 2021-05-19T10:28:47 | 326,605,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,343 | h |
#pragma once
struct KdBlurTexture
{
void Create(int w, int h)
{
int divideValue = 2;
for (int i = 0; i < 5; i++)
{
m_rt[i][0] = std::make_shared<KdTexture>();
m_rt[i][0]->CreateRenderTarget(w / divideValue, h / divideValue,
DXGI_FORMAT_R16G16B16A16_FLOAT);
m_rt[i][1] = std::make_shared<KdTexture>();
m_rt[i][1]->CreateRenderTarget(w / divideValue, h / divideValue,
DXGI_FORMAT_R16G16B16A16_FLOAT);
divideValue *= 2;
}
}
std::shared_ptr<KdTexture> m_rt[5][2];
};
class KdPostProcessShader
{
public:
struct Vertex
{
Math::Vector3 Pos;
Math::Vector2 UV;
};
bool Init();
void Release();
~KdPostProcessShader()
{
Release();
}
void ColorDraw(const KdTexture* tex, const Math::Vector4& color = { 1,1,1,1 });
void BlurDraw(const KdTexture* tex, const Math::Vector2& dir);
void BrightFiltering(const KdTexture* destRT, const KdTexture* srcTex);
void KdPostProcessShader::GenerateBlur(KdBlurTexture& blurTex, const KdTexture* srcTex)
{
RestoreRenderTarget rrt;
D3D11_VIEWPORT saveVP;
UINT numVP = 1;
D3D.GetDevContext()->RSGetViewports(&numVP, &saveVP);
D3D11_VIEWPORT vp;
for (int i = 0; i < 5; i++)
{
D3D.GetDevContext()->OMSetRenderTargets(
1, blurTex.m_rt[i][0]->GetRTViewAddress(), nullptr);
vp = D3D11_VIEWPORT{ 0.0f, 0.0f, (float)blurTex.m_rt[i][0]->GetWidth(),
(float)blurTex.m_rt[i][0]->GetHeight(), 0.0f, 1.0f };
D3D.GetDevContext()->RSSetViewports(1, &vp);
if (i == 0)
{
ColorDraw(srcTex);
}
else
{
ColorDraw(blurTex.m_rt[i - 1][0].get());
}
D3D.GetDevContext()->OMSetRenderTargets(1,
blurTex.m_rt[i][1]->GetRTViewAddress(), nullptr);
BlurDraw(blurTex.m_rt[i][0].get(), { 1, 0 });
D3D.GetDevContext()->OMSetRenderTargets(1,
blurTex.m_rt[i][0]->GetRTViewAddress(), nullptr);
BlurDraw(blurTex.m_rt[i][1].get(), { 0, 1 });
}
D3D.GetDevContext()->RSSetViewports(1, &saveVP);
}
private:
ID3D11VertexShader* m_VS = nullptr;
ID3D11InputLayout* m_inputLayout = nullptr;
ID3D11PixelShader* m_colorPS = nullptr;
ID3D11PixelShader* m_HBrightPS = nullptr;
struct cbColor {
Math::Vector4 Color = { 1,1,1,1 };
};
ID3D11PixelShader* m_blurPS = nullptr;
struct cbBlur {
Math::Vector4 Offset[31];
};
KdConstantBuffer<cbBlur> m_cb0_Blur;
KdConstantBuffer<cbColor> m_cb0_Color;
}; | [
"kd1264639@st.kobedenshi.ac.jp"
] | kd1264639@st.kobedenshi.ac.jp |
5b13e0c742ab9c25933f7b7ca7cb6e34f439c97c | 96faf6fd7cfb327131018b0e238a819e028999aa | /mbed-os/features/lorawan/lorastack/phy/LoRaPHYAS923.h | 17f943dbce10d27059b0a7ada89efbd9d7b6b811 | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | KolonIoT/Pelion | 9b1b42375a6cd4050c6bd3787a0bdfc0d7cc566d | 156eab454e87b5f5bbe4a662d7beb1482051a855 | refs/heads/master | 2020-07-01T13:54:12.712655 | 2019-08-08T06:35:57 | 2019-08-08T06:35:57 | 201,188,751 | 1 | 2 | Apache-2.0 | 2020-03-07T20:02:25 | 2019-08-08T06:02:07 | C | UTF-8 | C++ | false | false | 2,024 | h | /**
* @file LoRaPHYAS923.h
*
* @brief Implements LoRaPHY for Asia-Pacific 923 MHz band
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013 Semtech
* ___ _____ _ ___ _ _____ ___ ___ ___ ___
* / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __|
* \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _|
* |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
* embedded.connectivity.solutions===============
*
* \endcode
*
*
* License: Revised BSD License, see LICENSE.TXT file include in the project
*
* Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jaeckle ( STACKFORCE )
*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#ifndef MBED_OS_LORAPHY_AS923_H_
#define MBED_OS_LORAPHY_AS923_H_
#include "LoRaPHY.h"
/*!
* LoRaMac maximum number of channels
*/
#define AS923_MAX_NB_CHANNELS 16
/*!
* Maximum number of bands
*/
#define AS923_MAX_NB_BANDS 1
#define AS923_CHANNEL_MASK_SIZE 1
class LoRaPHYAS923 : public LoRaPHY {
public:
LoRaPHYAS923(LoRaWANTimeHandler &lora_time);
virtual ~LoRaPHYAS923();
virtual int8_t get_alternate_DR(uint8_t nb_trials);
virtual bool set_next_channel(channel_selection_params_t* nextChanParams,
uint8_t* channel, lorawan_time_t* time,
lorawan_time_t* aggregatedTimeOff );
virtual uint8_t apply_DR_offset(int8_t dr, int8_t drOffset );
private:
channel_params_t channels[AS923_MAX_NB_CHANNELS];
band_t bands[AS923_MAX_NB_BANDS];
uint16_t channel_mask[AS923_CHANNEL_MASK_SIZE];
uint16_t default_channel_mask[AS923_CHANNEL_MASK_SIZE];
};
#endif /* MBED_OS_LORAPHY_AS923_H_ */
| [
"hyunjae_woo@kolon.com"
] | hyunjae_woo@kolon.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.