blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f07153fbbb5e07ca51da804013b6994a95034328
5bb5e7cb8a1341d2c3db744e09babb684f8f314d
/Module/Log/sql_log.h
ea8373cdffcb121d35ecf37a08d6479a93470c6c
[]
no_license
jerry-zzz/ShakerMe
a0621e2c71115a393a2511172d41ca7e225654ea
d3423cd4a8c7320103fd8efaf07d485871314268
refs/heads/master
2020-09-26T10:11:39.900567
2019-12-06T03:01:40
2019-12-06T03:01:40
226,233,746
0
0
null
null
null
null
UTF-8
C++
false
false
954
h
#ifndef SQL_LOG_H #define SQL_LOG_H #include <QObject> #include <QReadWriteLock> class Sql_Log : public QObject { Q_OBJECT public: explicit Sql_Log(QObject *parent = nullptr); // 设置log文件路径 void set_file_path(QString dir, QString file); // 返回log文件路径 QString get_dir_path(void); QString get_file_path(void); signals: // 输出log信息 void sig_bind_tablewidget(QString datetime, QString type, QString user, QString msg); public slots: // 根据时间段 显示log记录 void read_select_time(QString dbPath, QString table, QString starttime, QString endtime); // 获取所有log记录 void read_all(QString dbPath, QString table); // 记录log信息到数据库 void record(QString dbPath, QString table, QString datetime, QString userID, QString msg); private: QString dir_path; QString file_path; QReadWriteLock log_Lock; }; #endif // SQL_LOG_H
[ "13085610320@163.com" ]
13085610320@163.com
da21042d1bb57265304a96bbbd4eb9ffbf77eac9
1049415125c2c64f9ce714ecb4c15b3f3c130bee
/include/ListBox.h
970146ba03d5d46982db42f86afa2c9d41e9032f
[ "MIT" ]
permissive
gearsns/TxtMiru2
3d53588d839b4304fb822630b5d1b78b6e66d21f
f829803721354e0639e791ba63962bd702aebfd1
refs/heads/master
2022-11-01T17:33:23.977198
2019-11-30T02:35:58
2019-11-30T02:35:58
208,549,945
5
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,793
h
#ifndef __LIST_BOX_H__ #define __LIST_BOX_H__ #include "ComonCtrl.h" #include <windowsx.h> class CGrListBox : public CGrComonCtrl { public: // リストボックスを作成します。 // hWnd [in]: 親ウインドウのハンドル // 戻り値 [out]: 作成したステータスウインドウのハンドル virtual HWND Create(HINSTANCE hInst, HWND hWnd); int AddString(LPCTSTR str) { return ListBox_AddString(m_hWnd, str); } int GetCurSel() { return ListBox_GetCurSel(m_hWnd); } int GetTextLen(int idx) { return ListBox_GetTextLen(m_hWnd, idx); } int GetText(int idx, LPCTSTR lpszBuffer) { return ListBox_GetText(m_hWnd, idx, lpszBuffer); } int GetCaretIndex() { return ListBox_GetCaretIndex(m_hWnd); } int GetCount() { return ListBox_GetCount(m_hWnd); } int DeleteString(int idx) { return ListBox_DeleteString(m_hWnd, idx); } int InsertString(int idx, LPCTSTR lpszBuffer) { return ListBox_InsertString(m_hWnd, idx, lpszBuffer); } int SetCaretIndex(int idx) { return ListBox_SetCaretIndex(m_hWnd, idx); } int SetCurSel(int idx) { return ListBox_SetCurSel(m_hWnd, idx); } int SetText(int idx, LPCTSTR lpszBuffer); LRESULT GetItemData(int index) { return ListBox_GetItemData(m_hWnd, index); } int SetItemData(int index, LPARAM data) { return ListBox_SetItemData(m_hWnd, index, data); } BOOL ResetContent() { return ListBox_ResetContent(m_hWnd); } }; #endif
[ "gears.ns@gmail.com" ]
gears.ns@gmail.com
fffaeea1a4f14360e4c3398b1211c38bae6d47cd
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-restbed-server/generated/model/ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties.h
5680cb81dc7c4db86dbd08d04479a47d9b257463
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
1,952
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ /* * ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties.h * * */ #ifndef ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties_H_ #define ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties_H_ #include "ConfigNodePropertyString.h" #include <memory> namespace org { namespace openapitools { namespace server { namespace model { /// <summary> /// /// </summary> class ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties { public: ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties(); virtual ~ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties(); std::string toJsonString(); void fromJsonString(std::string const& jsonString); ///////////////////////////////////////////// /// ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties members /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyString> getEventTopics() const; void setEventTopics(std::shared_ptr<ConfigNodePropertyString> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyString> getEventFilter() const; void setEventFilter(std::shared_ptr<ConfigNodePropertyString> value); protected: std::shared_ptr<ConfigNodePropertyString> m_Event_topics; std::shared_ptr<ConfigNodePropertyString> m_Event_filter; }; } } } } #endif /* ComAdobeCqSocialActivitystreamsListenerImplEventListenerHandlerProperties_H_ */
[ "cliffano@gmail.com" ]
cliffano@gmail.com
fed2470d19eb338ab1e6279c8f493a6dd2fd3875
8029d4bab7be395f438e0f62d8920a473c9334dc
/mythread.cpp
10432fa54f8b9dfaf75ed2727312f133895e9373
[]
no_license
Liurunyuan/guiJ75
2bab2e436075129871d5c9ca1be5fe52855cee86
5a819c837f049adf049cfe104f638f6efe692204
refs/heads/master
2022-02-16T07:16:52.293974
2019-04-08T11:42:48
2019-04-08T11:42:48
182,366,109
0
0
null
null
null
null
UTF-8
C++
false
false
159
cpp
#include "mythread.h" MyThread::MyThread() { } void MyThread::run() { while(1) { qDebug() << "mThread1"; QThread::sleep(3); } }
[ "liurunyuan0802@163.com" ]
liurunyuan0802@163.com
e066d7e0d120f3007d29e908f0054af55811edf7
769e14ed0ae07950d8455b25f4c311fefd4ab5b4
/C-Plus-Plus/search/binary_search.cpp
65f552b2d6e94af3d7d2e1400b6348cc9c4b0df7
[ "MIT" ]
permissive
20-1-SKKU-OSS/2020-1-OSS-7
cf8f32412e1a50daa7bd61021b50a4d0c4aa07b6
16d29392c476cd88a7c158155fe471e5e86bdd74
refs/heads/master
2022-09-26T03:57:29.916954
2020-06-10T07:28:57
2020-06-10T07:28:57
259,804,828
0
0
null
2020-06-10T07:28:58
2020-04-29T02:31:11
Python
UTF-8
C++
false
false
939
cpp
#include <iostream> // binary_search function int binary_search(int a[], int l, int r, int key) { while (l <= r) { int m = l + (r - l) / 2; if (key == a[m]) return m; else if (key < a[m]) r = m - 1; else l = m + 1; } return -1; } int main(int argc, char const *argv[]) { int n, key; std::cout << "Enter size of array: "; std::cin >> n; std::cout << "Enter array elements: "; int *a = new int[n]; // this loop use for store value in Array for (int i = 0; i < n; i++) { std::cin >> a[i]; } std::cout << "Enter search key: "; std::cin >> key; // this is use for find value in given array int res = binary_search(a, 0, n - 1, key); if (res != -1) std::cout << key << " found at index " << res << std::endl; else std::cout << key << " not found" << std::endl; return 0; }
[ "hojoon0205@gmail.com" ]
hojoon0205@gmail.com
67b4456d8e7d1c07bb873e0995eb35bccab2ce16
30ef15f604c2fce34ddf69834e33e293361956c5
/Program Design/Arduino/sFPI_test_interface/sFPI_test_interface.ino
20309360125e660c36327323f37e5c4c37433212
[]
no_license
aviatorblue62/sFPI
1c1c4e1189791cadeea47b9777fb63a31a07712b
20faa4194643c8566c7f651499bc9f08bd302904
refs/heads/master
2016-09-14T21:15:29.652999
2016-03-18T21:44:04
2016-03-18T21:44:04
49,546,039
0
0
null
null
null
null
UTF-8
C++
false
false
2,247
ino
/* sFPI Processor version 1.0 Copyright (c) 2015 David Miles Houston This sketch uses the following assoicated pins in conjunction with the MCP4725 DAC, for use with the output manipulation of the sFPI Driver program and with data collection, storage, and processing. It uses I2C to com- muicate with the DAC and its associated libraries. This data will be sent to a computer via usb interface every cycle of the wave and processed through an interactive GUI. Pin Name Pin Location --------- -------------- SCL A4 SDA A5 Data_IN A0 Wave_IN A1 Signal_AT_1 A2 Signal_AT_2 A3 */ #define bitres 1025 int photodiode_data[bitres]; int ramp_function[bitres]; int data[2]; int max_count = 10; int counter = 0; boolean transmit; int recieved = 87456; void setup() { Serial.begin(9600); // Set A0, A1, A2 for analog inputs. // A5 and A4 have already been set in the Adafruit Header File as SCL and SDA. DDRC |= 0x01; PORTC |= 0x01; pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); analogWrite(13, 255); digitalWrite(8,HIGH); } void loop(){ Serial.print("\n\n--- Data Start ---\n\n"); for (int count = 0; count < 10; count++) { digitalWrite(8,HIGH); photodiode_data[counter] = PINC; Serial.print(PINC); DDRC = 0x02; PORTC = 0x02; delay(1); ramp_function[counter] = PINC; Serial.print(PINC); } delay(500); transmit = true; digitalWrite(9,HIGH); digitalWrite(8,LOW); delay(100); digitalWrite(9,LOW); delay(100); /* photodiode_data[max_count-1] = recieved; ramp_function[max_count-1] = recieved; data[0] = *photodiode_data; data[1] = *ramp_function; if (transmit == true){ digitalWrite(10,HIGH); digitalWrite(9,LOW); delay(100); if (Serial.available() > 0){ for (int j = 0; j < 2; j = j + 1){ for (int i = 0; i < max_count-1; i = i + 1){ int * output = &data[j]; Serial.print("Cool"); } } } }*/ }
[ "miles.dave.houston@gmail.com" ]
miles.dave.houston@gmail.com
11eedf54e6feffc3e520e5ad1bac154b6279a41c
28261dd3abc51ee4bdefc6489530c29c2185184c
/src/gtest/doxygen/build/generated_src/commentscan.cpp
d68330c3b22fea1bd66ded38fb12f23da17ccefe
[ "LicenseRef-scancode-generic-cla" ]
no_license
audreybender/cppcourse-brunel
d97d6453655eb7c154e14284a1f9fcd081ec8b33
227b9fc2ff0e27d8d26b4b039e5e6aa886d2dfa8
refs/heads/master
2021-08-09T03:00:48.045421
2017-11-12T01:47:31
2017-11-12T01:47:31
105,807,155
0
0
null
null
null
null
UTF-8
C++
false
false
321,588
cpp
#line 2 "/home/localguest/Documents/SVIII/Neurone/gtest/doxygen/build/generated_src/commentscan.cpp" #line 4 "/home/localguest/Documents/SVIII/Neurone/gtest/doxygen/build/generated_src/commentscan.cpp" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define yy_create_buffer commentscanYY_create_buffer #define yy_delete_buffer commentscanYY_delete_buffer #define yy_flex_debug commentscanYY_flex_debug #define yy_init_buffer commentscanYY_init_buffer #define yy_flush_buffer commentscanYY_flush_buffer #define yy_load_buffer_state commentscanYY_load_buffer_state #define yy_switch_to_buffer commentscanYY_switch_to_buffer #define yyin commentscanYYin #define yyleng commentscanYYleng #define yylex commentscanYYlex #define yylineno commentscanYYlineno #define yyout commentscanYYout #define yyrestart commentscanYYrestart #define yytext commentscanYYtext #define yywrap commentscanYYwrap #define yyalloc commentscanYYalloc #define yyrealloc commentscanYYrealloc #define yyfree commentscanYYfree #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE commentscanYYrestart(commentscanYYin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int commentscanYYleng; extern FILE *commentscanYYin, *commentscanYYout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up commentscanYYtext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via commentscanYYrestart()), so that the user can continue scanning by * just pointing commentscanYYin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when commentscanYYtext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int commentscanYYleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow commentscanYYwrap()'s to do buffer switches * instead of setting up a fresh commentscanYYin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void commentscanYYrestart (FILE *input_file ); void commentscanYY_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE commentscanYY_create_buffer (FILE *file,int size ); void commentscanYY_delete_buffer (YY_BUFFER_STATE b ); void commentscanYY_flush_buffer (YY_BUFFER_STATE b ); void commentscanYYpush_buffer_state (YY_BUFFER_STATE new_buffer ); void commentscanYYpop_buffer_state (void ); static void commentscanYYensure_buffer_stack (void ); static void commentscanYY_load_buffer_state (void ); static void commentscanYY_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER commentscanYY_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE commentscanYY_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE commentscanYY_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE commentscanYY_scan_bytes (yyconst char *bytes,int len ); void *commentscanYYalloc (yy_size_t ); void *commentscanYYrealloc (void *,yy_size_t ); void commentscanYYfree (void * ); #define yy_new_buffer commentscanYY_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ commentscanYYensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ commentscanYY_create_buffer(commentscanYYin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ commentscanYYensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ commentscanYY_create_buffer(commentscanYYin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define commentscanYYwrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; FILE *commentscanYYin = (FILE *) 0, *commentscanYYout = (FILE *) 0; typedef int yy_state_type; extern int commentscanYYlineno; int commentscanYYlineno = 1; extern char *commentscanYYtext; #define yytext_ptr commentscanYYtext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up commentscanYYtext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ commentscanYYleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 209 #define YY_END_OF_BUFFER 210 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_acclist[775] = { 0, 79, 79, 127, 127, 141, 141, 156, 156, 200, 200, 147, 147, 210, 209, 46, 209, 46, 209, 45, 209, 46, 209, 46, 209, 46, 209, 46, 209, 44, 46, 209, 46, 209, 46, 209, 27, 46, 209, 46, 209, 46, 209, 46, 209, 46, 209, 46, 209, 44, 46, 209, 46, 209, 46, 209, 92, 209, 91, 209, 92, 209, 89, 92, 209, 92, 209, 92, 209, 209, 93, 209, 117, 209, 116, 209, 117, 209, 114, 117, 209, 117, 209, 74, 209, 74, 209, 73, 209, 74, 209, 74, 209, 74, 209, 70, 74, 209, 74, 209, 74, 209, 78, 209, 77, 209, 78, 209, 75, 78, 209, 78, 209, 78, 209, 78, 209, 82, 209, 81, 209, 79, 82, 209, 79, 82, 209, 82, 209, 79, 82, 209, 79, 82, 209, 82, 209, 74, 209, 73, 209, 74, 209, 74, 209, 74, 209, 74, 209, 74, 209, 105, 209, 104, 209, 102, 105, 209, 105, 209, 109, 209, 108, 209, 109, 209, 109, 209, 113, 209, 112, 209, 113, 209, 113, 209, 101, 209, 98, 209, 101, 209, 99, 101, 209, 101, 209, 101, 209, 97, 209, 97, 209, 95, 97, 209, 96, 97, 209,16478, 60, 209, 59, 209, 60, 209, 57, 60, 209, 60, 209, 64, 209, 64, 209, 63, 209, 64, 209, 64, 209, 64, 209, 61, 64, 209, 64, 209, 64, 209, 68, 209, 67, 209, 68, 209, 65, 68, 209, 68, 209, 85, 209, 83, 209, 209, 87, 209, 88, 209, 209, 123, 209, 122, 209, 121, 123, 209, 123, 209, 127, 130, 209, 124, 209, 127, 130, 209, 130, 209, 130, 209, 132, 209, 131, 209, 209, 135, 209, 135, 209, 133, 209, 135, 209, 135, 209, 141, 145, 209, 142, 209, 145, 209, 145, 209, 145, 209, 145, 209, 145, 209, 120, 209, 118, 209, 120, 209, 154, 209, 154, 209, 152, 209, 146, 154, 209, 151, 154, 209, 154, 209, 157, 209, 156, 157, 209, 155, 209, 157, 209, 164, 165, 209, 163, 209, 165, 209, 165, 209, 165, 209, 175, 176, 209, 166, 209, 176, 209, 176, 209, 176, 209, 179, 209, 177, 209, 179, 209, 183, 209, 181, 209, 180, 183, 209, 183, 209, 186, 189, 209, 184, 209, 187, 189, 209, 188, 189, 209, 189, 209, 189, 209, 192, 209, 190, 209, 192, 209, 195, 209, 194, 209, 195, 209, 193, 195, 209, 195, 209, 198, 209, 197, 209, 198, 209, 196, 198, 209, 198, 209, 54, 56, 209, 55, 209, 56, 209, 56, 209, 138, 209, 137, 209, 136, 138, 209, 138, 209, 49, 50, 209, 48, 209, 50, 209, 50, 209, 200, 202, 209, 201, 209, 202, 209, 202, 209, 202, 209, 205, 209, 204, 209, 203, 205, 209, 205, 209, 207, 208, 209, 206, 209, 208, 209, 147, 209, 147, 150, 209, 148, 209, 149, 209, 43, 4, 36, 38, 40, 38, 26, 26, 18, 26, 18, 18, 24, 25, 20, 26, 27, 18, 18, 18, 18, 30, 31, 36, 28, 89, 89, 90, 89, 93, 114, 114, 115, 70, 70, 72, 70, 75, 75, 76, 75, 79, 79, 79, 79, 79, 79, 80, 79, 102, 103, 106, 107, 111, 110, 111, 99, 99, 100, 99, 96,16478, 8286, 96,16478, 57, 57, 57, 58, 61, 61, 62, 61, 65, 65, 66, 83, 84, 87, 86, 121, 127, 124, 127, 129, 129, 126, 131, 134, 141, 144, 143, 119, 146, 151, 153, 156, 155, 164, 175, 178, 180, 182, 186, 185, 191, 193, 193, 196, 196, 54, 136, 49, 200, 199, 203, 207, 147, 26, 37, 35, 42, 38, 42, 42, 42, 38, 42, 42, 39, 6, 34, 1, 1, 2, 18, 18, 22, 23, 20, 5, 18, 18, 32, 35, 29, 89, 89, 70, 75, 75, 79, 79, 79, 99, 99, 57, 57, 57, 57, 61, 65, 128, 51, 52, 53, 47, 199, 203, 42, 42, 16, 33, 1, 19, 2, 18, 18, 18, 89, 69, 75, 79, 79, 71, 99, 57, 57, 57, 65, 128, 159, 167, 47, 203, 15, 41, 6, 13, 18, 21, 18, 18, 89, 75, 79, 99, 3, 14, 7, 18, 21, 18, 18, 89, 75, 79, 99, 83, 161, 169, 18, 18, 18, 89, 75, 79, 99, 140, 160, 158, 168, 18, 18, 18, 89, 91, 116, 73, 75, 77, 79, 81, 104, 108, 112, 98, 99, 59, 63, 67, 85, 88, 122, 125, 132, 133, 139, 142, 118, 152, 162, 163, 166, 177, 181, 184, 190, 194, 197, 137, 48, 201, 204, 206, 12, 9, 8, 18, 18, 5, 18, 170, 11, 10, 18, 18, 18, 18, 173, 17, 18, 17, 18, 174, 171, 17, 18, 174, 172, 43 } ; static yyconst flex_int16_t yy_accept[1149] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 11, 11, 11, 11, 11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 27, 29, 32, 34, 36, 39, 41, 43, 45, 47, 49, 52, 54, 56, 58, 60, 62, 65, 67, 69, 70, 72, 74, 76, 78, 81, 83, 85, 87, 89, 91, 93, 95, 98, 100, 102, 104, 106, 108, 111, 113, 115, 117, 119, 121, 124, 127, 129, 132, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 185, 187, 189, 191, 193, 196, 200, 202, 204, 206, 209, 211, 213, 215, 217, 219, 221, 223, 226, 228, 230, 232, 234, 236, 239, 241, 243, 245, 246, 248, 250, 251, 253, 255, 258, 260, 263, 265, 268, 270, 272, 274, 276, 277, 279, 281, 283, 285, 287, 290, 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312, 314, 317, 320, 322, 324, 327, 329, 331, 334, 336, 338, 340, 342, 345, 347, 349, 351, 353, 355, 357, 359, 361, 363, 366, 368, 371, 373, 376, 379, 381, 383, 385, 387, 389, 391, 393, 395, 398, 400, 402, 404, 406, 409, 411, 414, 416, 418, 420, 422, 424, 427, 429, 432, 434, 436, 438, 441, 443, 445, 447, 449, 451, 453, 456, 458, 461, 463, 465, 467, 470, 472, 474, 474, 474, 474, 474, 475, 475, 475, 476, 476, 476, 476, 476, 476, 477, 478, 479, 479, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 481, 481, 482, 483, 484, 485, 486, 487, 488, 490, 491, 492, 493, 494, 495, 495, 495, 495, 495, 495, 495, 496, 497, 498, 498, 499, 499, 499, 499, 499, 499, 500, 501, 501, 501, 501, 502, 503, 503, 504, 505, 505, 506, 506, 506, 507, 507, 507, 507, 507, 507, 508, 508, 508, 509, 509, 509, 510, 510, 510, 510, 511, 511, 512, 513, 513, 513, 513, 514, 515, 515, 516, 517, 517, 518, 519, 520, 520, 520, 521, 521, 522, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 524, 524, 525, 525, 525, 526, 526, 528, 528, 528, 529, 529, 530, 530, 530, 531, 532, 532, 532, 532, 533, 534, 536, 536, 537, 539, 540, 540, 540, 541, 541, 542, 542, 543, 543, 543, 543, 543, 543, 544, 544, 544, 545, 545, 546, 546, 546, 546, 547, 548, 548, 549, 549, 550, 550, 551, 551, 551, 552, 552, 553, 553, 554, 554, 555, 555, 556, 557, 558, 558, 559, 560, 560, 561, 561, 562, 562, 562, 562, 562, 563, 563, 564, 565, 566, 566, 566, 566, 567, 567, 567, 568, 569, 569, 570, 570, 571, 572, 572, 572, 573, 573, 573, 573, 574, 574, 574, 574, 574, 574, 574, 575, 575, 576, 576, 577, 577, 578, 578, 579, 579, 579, 580, 580, 581, 581, 582, 582, 582, 583, 583, 584, 584, 584, 585, 585, 585, 586, 586, 587, 587, 587, 588, 589, 589, 590, 590, 590, 591, 591, 592, 593, 593, 593, 593, 593, 594, 595, 596, 598, 599, 600, 602, 603, 604, 604, 604, 604, 604, 604, 604, 604, 604, 604, 605, 605, 605, 605, 605, 605, 606, 607, 608, 609, 610, 611, 612, 613, 613, 614, 615, 616, 617, 617, 617, 617, 617, 618, 619, 619, 620, 621, 621, 622, 622, 622, 622, 622, 622, 623, 624, 624, 625, 626, 626, 627, 627, 628, 628, 628, 628, 628, 628, 628, 629, 629, 630, 631, 632, 633, 634, 634, 634, 635, 635, 636, 636, 636, 636, 636, 636, 636, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 637, 638, 639, 640, 640, 640, 641, 641, 642, 642, 643, 643, 643, 643, 643, 643, 643, 644, 645, 646, 646, 646, 646, 646, 646, 646, 646, 646, 646, 646, 646, 646, 647, 648, 649, 650, 651, 651, 651, 652, 653, 653, 653, 653, 654, 654, 654, 655, 655, 655, 656, 657, 657, 658, 659, 659, 659, 659, 660, 660, 661, 662, 663, 663, 663, 664, 664, 664, 664, 664, 664, 665, 665, 665, 665, 665, 665, 665, 665, 665, 665, 665, 666, 666, 666, 666, 667, 667, 667, 667, 667, 667, 667, 667, 667, 667, 667, 667, 667, 668, 668, 668, 669, 669, 669, 669, 670, 670, 670, 671, 671, 671, 671, 671, 671, 671, 673, 673, 673, 673, 674, 675, 676, 677, 677, 678, 678, 678, 679, 680, 680, 680, 680, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 681, 682, 683, 683, 683, 683, 683, 684, 684, 684, 684, 684, 685, 686, 687, 688, 689, 689, 689, 690, 691, 691, 691, 691, 692, 692, 692, 692, 692, 692, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 693, 694, 694, 694, 694, 694, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 695, 696, 697, 698, 699, 699, 699, 700, 701, 701, 701, 701, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, 703, 703, 703, 703, 703, 703, 703, 703, 703, 704, 705, 705, 705, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 707, 708, 709, 711, 712, 713, 715, 717, 718, 719, 720, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 731, 732, 732, 732, 732, 732, 732, 732, 732, 733, 734, 735, 736, 737, 737, 737, 737, 737, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 749, 749, 749, 750, 751, 752, 753, 754, 755, 756, 756, 756, 756, 756, 756, 756, 756, 756, 756, 756, 757, 757, 757, 758, 759, 759, 759, 760, 760, 761, 761, 761, 761, 761, 761, 761, 761, 761, 761, 761, 761, 761, 762, 762, 763, 763, 763, 763, 763, 763, 763, 764, 764, 764, 766, 766, 768, 768, 768, 769, 770, 770, 772, 772, 772, 773, 773, 773, 773, 773, 773, 774, 775, 775 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 6, 7, 8, 9, 10, 11, 1, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 21, 21, 21, 21, 21, 22, 22, 22, 23, 1, 24, 1, 25, 1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 32, 32, 36, 37, 38, 39, 40, 32, 41, 32, 42, 43, 32, 32, 32, 32, 32, 44, 45, 46, 1, 47, 1, 48, 49, 50, 51, 52, 53, 54, 55, 56, 32, 57, 58, 59, 60, 61, 62, 32, 63, 64, 65, 66, 67, 68, 69, 70, 32, 71, 72, 73, 74, 1, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75 } ; static yyconst flex_int32_t yy_meta[76] = { 0, 1, 2, 3, 4, 5, 1, 6, 7, 8, 9, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 18, 19, 20, 21, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 1, 24, 1, 25, 23, 23, 23, 23, 23, 23, 23, 23, 26, 23, 23, 23, 27, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 28, 29, 30, 31, 32 } ; static yyconst flex_int16_t yy_base[1384] = { 0, 0, 0, 0, 74, 146, 220, 5082, 5081, 294, 0, 369, 0, 444, 518, 592, 666, 740, 0, 815, 0, 74, 75, 77, 80, 890, 964, 1038, 0, 1113, 0, 1188, 0, 1263, 0, 1338, 0, 87, 90, 1413, 0, 91, 95, 1488, 0, 109, 121, 158, 183, 82, 96, 1563, 1638, 128, 140, 190, 205, 237, 243, 99, 112, 1713, 0, 244, 452, 131, 134, 1788, 0, 1863, 0, 234, 449, 456, 458, 1938, 0, 196, 463, 467, 469, 2013, 2087, 135, 136, 193, 246, 5082, 9743, 9743, 500, 209, 5074, 5066, 5048, 181, 531, 2156, 2215, 551, 2282, 2355, 98, 250, 616, 690, 478, 624, 9743, 9743, 5066, 468, 488, 1578, 5069, 9743, 9743, 9743, 0, 90, 553, 9743, 695, 914, 920, 937, 5041, 994, 576, 269, 9743, 9743, 5051, 542, 609, 5031, 1653, 9743, 9743, 2427, 1587, 1662, 2026, 9743, 2118, 998, 1002, 2060, 2164, 5032, 2038, 281, 9743, 9743, 0, 583, 9743, 9743, 5047, 647, 9743, 9743, 5046, 654, 9743, 9743, 5045, 908, 1572, 2211, 9743, 0, 9743, 199, 9743, 9743, 0, 2241, 945, 9743, 2050, 2112, 2174, 2278, 4997, 2124, 1613, 717, 9743, 9743, 0, 4998, 1619, 9743, 4997, 1626, 0, 9743, 2072, 9743, 9743, 0, 4967, 537, 9743, 4968, 2294, 2077, 9743, 0, 4959, 9743, 469, 9743, 4998, 4952, 0, 9743, 9743, 4978, 4982, 4943, 131, 9743, 9743, 2146, 9743, 275, 9743, 9743, 607, 2200, 9743, 641, 9743, 4947, 0, 9743, 9743, 54, 528, 0, 9743, 9743, 672, 967, 9743, 9743, 2250, 9743, 9743, 0, 2267, 0, 9743, 9743, 9743, 9743, 2274, 9743, 9743, 2307, 9743, 9743, 0, 164, 4946, 9743, 9743, 0, 244, 4915, 0, 9743, 4905, 4904, 9743, 9743, 0, 4909, 0, 9743, 4938, 4904, 0, 9743, 9743, 4875, 120, 9743, 9743, 4930, 4900, 0, 9743, 4899, 0, 0, 9743, 9743, 629, 2494, 2561, 988, 2320, 4898, 4937, 9743, 0, 4920, 4916, 0, 533, 533, 9743, 9743, 2635, 4915, 565, 4923, 669, 1565, 71, 562, 216, 516, 2339, 587, 604, 4887, 4872, 9743, 4920, 607, 2709, 4862, 4874, 901, 9743, 9743, 0, 1671, 979, 2226, 2326, 2338, 2782, 643, 2344, 712, 936, 2387, 656, 2388, 2396, 1025, 9743, 1673, 2435, 2421, 2460, 4926, 9743, 2127, 888, 2255, 1597, 9743, 2451, 4924, 9743, 707, 4917, 926, 4902, 1665, 9743, 4866, 2508, 2519, 4897, 2531, 2555, 1699, 2592, 2559, 2150, 2392, 9743, 4860, 2476, 2485, 4893, 4906, 9743, 2314, 2165, 2402, 2412, 9743, 2580, 4904, 485, 2854, 2928, 4903, 9743, 2649, 2214, 2668, 4902, 2461, 9743, 2678, 2586, 2735, 4885, 2743, 2767, 2614, 2810, 2818, 0, 2878, 2624, 2660, 2169, 0, 2512, 9743, 4849, 4899, 9743, 2548, 9743, 4847, 4897, 9743, 2619, 9743, 4845, 4895, 9743, 2557, 2339, 2659, 2668, 9743, 2706, 896, 2065, 9743, 2199, 2772, 2842, 0, 2883, 4872, 2955, 2687, 9743, 4836, 2913, 2980, 4870, 2988, 2963, 2848, 3005, 3013, 2697, 9743, 4831, 2905, 3017, 0, 4869, 4877, 4867, 2725, 9743, 4825, 4864, 4825, 2754, 9743, 4821, 0, 2760, 9743, 4820, 0, 4819, 2404, 9743, 4831, 4828, 9743, 4865, 2786, 9743, 4814, 0, 4813, 1672, 4858, 4857, 9743, 4805, 0, 9743, 9743, 4802, 4800, 2829, 9743, 4798, 2536, 9743, 2693, 2835, 9743, 4797, 2917, 9743, 4807, 4793, 0, 419, 4795, 4789, 0, 4786, 4792, 4793, 487, 4748, 2892, 9743, 4747, 0, 3022, 9743, 4746, 0, 3027, 9743, 4745, 3032, 9743, 4738, 1575, 4786, 1596, 4766, 4729, 1672, 4777, 2121, 4762, 4726, 0, 4774, 631, 0, 4694, 0, 677, 4689, 0, 0, 4679, 4718, 0, 4677, 0, 4676, 0, 4679, 4673, 4707, 0, 4711, 1625, 4702, 9743, 9743, 4695, 3079, 4692, 4699, 9743, 4699, 889, 4662, 4645, 1571, 983, 2311, 2203, 2383, 9743, 2077, 2223, 2266, 4648, 4638, 4679, 2293, 3037, 0, 2340, 2579, 9743, 9743, 0, 0, 0, 3054, 2824, 3046, 2346, 3023, 3050, 9743, 3104, 3109, 2401, 3097, 3110, 3116, 0, 4639, 3141, 3154, 4638, 4668, 3118, 3146, 3152, 1578, 3208, 3155, 3180, 3216, 4678, 2710, 2837, 4634, 4633, 4632, 3166, 3183, 3219, 3246, 3254, 3281, 3289, 4622, 4621, 0, 0, 4658, 4618, 4604, 4608, 4605, 4604, 0, 0, 4603, 4601, 4598, 4600, 4594, 4593, 4592, 4588, 4578, 4590, 4580, 4583, 4584, 2919, 4567, 4548, 3712, 3704, 3703, 3702, 3699, 3698, 0, 3697, 0, 3696, 9743, 9743, 9743, 3693, 3719, 2490, 3686, 0, 3684, 3720, 3681, 3680, 3003, 3675, 3717, 0, 3282, 2525, 9743, 2286, 3663, 3662, 863, 2344, 3694, 2606, 2364, 3059, 2191, 3670, 3657, 9743, 2550, 9743, 0, 3063, 3617, 3644, 3202, 3268, 3312, 3316, 3320, 3308, 3628, 3191, 9743, 3345, 3623, 3322, 3392, 3466, 3358, 9743, 3611, 3609, 3600, 3340, 0, 3352, 3419, 3446, 3594, 3592, 3612, 3568, 3560, 3557, 3549, 3542, 0, 3540, 3536, 3534, 3437, 3518, 3514, 3508, 3499, 3500, 3490, 9743, 3480, 3474, 3467, 9743, 3458, 3469, 3444, 3443, 3441, 3437, 3414, 3402, 3392, 3386, 3373, 3369, 2635, 3365, 3360, 3401, 3354, 3353, 3347, 9743, 3377, 3417, 9743, 3366, 3338, 3321, 2419, 3364, 3452, 9743, 2445, 3316, 3330, 3385, 3300, 2943, 3454, 3513, 3408, 3312, 3310, 3475, 3506, 3308, 3300, 3299, 3503, 3540, 3292, 3290, 3286, 3278, 3282, 3280, 3278, 3276, 3268, 3264, 3246, 3245, 3240, 3248, 911, 3223, 3228, 2746, 3219, 3224, 3213, 3208, 3193, 3184, 3183, 3165, 3177, 115, 3154, 3138, 3134, 1982, 3136, 3130, 3125, 3116, 3115, 3108, 3097, 3096, 3095, 3088, 3079, 3065, 3061, 3083, 9743, 3019, 3029, 2445, 3456, 9743, 3051, 3503, 3015, 3008, 3073, 9743, 3530, 3545, 3546, 3021, 3017, 3548, 3563, 3001, 2991, 2989, 3554, 3602, 3611, 2984, 2964, 2956, 9743, 2955, 2947, 2945, 2938, 2931, 2922, 2919, 557, 2910, 2898, 2901, 2906, 2902, 2896, 2887, 2898, 2885, 2890, 2874, 2864, 2863, 9743, 2858, 0, 0, 2853, 9743, 2828, 2805, 2828, 2828, 2826, 2813, 2799, 2794, 2786, 2776, 2775, 2769, 2767, 2762, 2757, 2753, 2737, 2729, 2724, 2711, 2704, 2448, 2735, 3551, 2691, 2680, 3481, 3582, 3596, 3617, 2686, 2680, 3619, 3632, 2679, 2678, 2669, 3640, 2668, 2663, 2658, 2653, 2625, 2621, 2620, 2613, 2594, 2603, 2571, 0, 2554, 2555, 2539, 2531, 9743, 2525, 2508, 2495, 2482, 2481, 2480, 2466, 0, 9743, 9743, 2462, 2464, 9743, 2459, 2431, 2417, 2403, 2395, 2385, 2379, 2372, 2367, 2361, 2316, 2311, 2300, 2287, 2267, 2263, 2261, 2247, 2215, 3624, 2241, 2240, 3181, 3055, 3616, 3647, 9743, 9743, 3649, 3668, 9743, 9743, 9743, 3655, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 2190, 9743, 2181, 2166, 2148, 2140, 2141, 2127, 2110, 9743, 9743, 9743, 9743, 9743, 2101, 2095, 2869, 2053, 2056, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 9743, 2082, 2051, 3651, 9743, 9743, 9743, 3442, 3694, 2025, 3696, 2005, 2000, 1986, 1988, 1977, 1641, 1647, 1638, 1634, 1610, 9743, 1598, 1570, 9743, 9743, 1559, 3679, 3241, 223, 3700, 975, 964, 935, 916, 915, 923, 890, 851, 872, 3269, 669, 622, 3704, 970, 3705, 592, 581, 496, 470, 441, 427, 9743, 3407, 417, 3552, 2149, 3706, 201, 181, 3578, 9743, 139, 3587, 568, 116, 3641, 58, 678, 16, 3642, 2093, 9743, 3712, 9743, 3763, 3795, 3827, 3859, 3891, 3923, 3955, 3987, 4019, 4051, 4083, 4115, 4147, 4179, 4211, 4243, 4275, 4307, 4339, 4371, 4403, 4435, 4467, 4499, 4531, 4563, 4595, 4620, 4640, 4657, 4678, 4697, 4718, 4749, 4775, 4807, 4817, 4834, 4865, 4896, 4927, 4959, 4985, 5017, 5044, 5075, 5106, 5137, 5155, 5187, 5219, 5251, 5277, 5287, 5318, 5328, 5359, 5390, 5421, 5452, 5462, 5479, 5497, 5529, 5547, 5579, 5611, 5642, 5659, 5691, 5723, 5754, 5781, 5813, 5831, 5863, 5873, 5890, 5900, 5917, 5949, 5967, 5999, 6031, 6051, 6083, 6115, 6141, 6172, 6182, 6197, 6217, 6230, 6257, 6267, 6284, 6299, 6325, 6352, 6378, 6404, 6436, 6453, 6478, 6509, 6540, 6571, 6603, 6618, 6650, 6676, 6702, 6734, 6766, 6793, 6819, 6850, 6881, 6912, 6944, 6975, 6993, 7025, 7057, 7089, 7115, 7141, 7172, 7203, 7213, 7244, 7275, 7306, 7337, 7352, 7369, 7394, 7412, 7444, 7462, 7494, 7526, 7551, 7569, 7601, 7633, 7664, 7691, 7723, 7741, 7773, 7790, 7815, 7832, 7857, 7889, 7907, 7939, 7971, 3697, 7991, 8006, 8038, 8070, 8085, 8117, 8135, 8150, 8177, 8209, 8240, 3702, 8266, 8293, 8311, 3707, 8337, 8358, 8384, 8394, 8426, 8441, 8467, 8493, 8525, 8552, 8579, 8611, 8642, 8668, 8694, 8725, 8756, 8787, 8802, 8812, 8829, 8839, 8854, 8886, 8896, 8906, 3720, 8926, 8958, 8976, 8993, 9020, 4606, 9051, 9078, 9088, 9114, 9140, 9163, 9195, 9221, 9253, 9280, 9306, 9316, 9347, 9378, 9395, 9410, 9428, 9455, 9486, 9518, 9550, 9582, 9614, 9646, 9678, 9710, 4611 } ; static yyconst flex_int16_t yy_def[1384] = { 0, 1148, 1148, 1147, 3, 1149, 1149, 1150, 1150, 1147, 9, 1147, 11, 1151, 1151, 1152, 1152, 1147, 17, 1147, 19, 1153, 1153, 1154, 1154, 1155, 1155, 1147, 27, 1147, 29, 1147, 31, 1147, 33, 1147, 35, 1156, 1156, 1147, 39, 1157, 1157, 1147, 43, 1158, 1158, 1159, 1159, 1160, 1160, 1161, 1161, 1162, 1162, 1163, 1163, 1164, 1164, 1165, 1165, 1147, 61, 1166, 1166, 1167, 1167, 1147, 67, 1147, 69, 1168, 1168, 1168, 1168, 1147, 75, 1169, 1169, 1170, 1170, 1171, 1171, 1172, 1172, 1173, 1173, 1147, 1147, 1147, 1147, 1147, 1174, 1175, 1176, 1176, 1177, 1147, 1178, 1179, 1180, 1147, 1147, 1176, 1176, 1177, 1176, 1147, 1147, 1147, 1181, 1182, 1182, 1182, 1183, 1147, 1147, 1147, 1184, 1185, 1147, 1147, 1147, 1147, 1186, 1186, 1147, 1187, 1147, 1188, 1147, 1147, 1189, 1190, 1190, 1147, 1190, 1147, 1147, 1191, 1192, 1192, 1192, 1147, 1192, 1147, 1147, 1193, 1193, 1147, 1194, 1195, 1147, 1147, 1196, 1147, 1147, 1147, 1197, 1147, 1147, 1147, 1198, 1147, 1147, 1147, 1199, 1200, 1200, 1200, 1147, 1201, 1147, 1202, 1147, 1147, 1203, 1204, 1147, 1147, 1147, 1147, 1205, 1205, 1147, 1206, 1147, 1207, 1147, 1147, 1208, 1209, 1147, 1147, 1210, 1147, 1211, 1147, 1147, 1147, 1147, 1212, 1147, 1213, 1147, 1214, 1147, 1215, 1147, 1216, 1147, 1147, 1147, 1147, 1217, 1147, 1218, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1219, 1147, 1147, 1219, 1147, 1147, 1147, 1147, 1147, 1220, 1147, 1147, 1147, 1147, 1221, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1222, 1147, 1223, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1224, 1225, 1147, 1147, 1147, 1226, 1227, 1147, 1228, 1147, 1147, 1147, 1147, 1147, 1229, 1147, 1230, 1147, 1147, 1147, 1231, 1147, 1147, 1147, 1147, 1147, 1147, 1232, 1147, 1233, 1147, 1147, 1234, 1234, 1147, 1147, 1147, 1235, 1235, 1147, 1147, 1147, 1236, 1147, 1237, 1238, 1239, 1240, 1147, 1239, 1147, 1147, 1241, 1239, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1242, 1235, 1242, 334, 334, 1147, 1147, 1243, 1244, 1245, 1245, 1245, 1245, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1239, 1147, 1147, 1239, 1239, 1147, 1147, 1246, 1147, 1247, 1248, 1247, 1147, 1147, 1247, 1249, 1147, 1250, 1251, 1250, 1147, 1147, 1147, 1147, 1147, 1252, 1147, 1252, 1253, 1254, 1252, 1253, 1255, 1147, 1147, 1147, 1254, 1254, 1256, 1257, 1147, 1258, 1259, 1258, 1147, 1147, 1258, 1260, 1260, 1261, 1261, 1260, 1147, 1262, 1263, 1262, 1260, 1147, 1147, 1262, 1147, 1264, 1147, 1264, 1265, 1266, 1264, 1147, 1267, 1265, 1266, 1266, 1268, 1269, 1147, 1147, 1147, 1270, 1147, 1147, 1147, 1147, 1271, 1147, 1147, 1147, 1147, 1272, 1147, 1273, 1274, 1273, 1147, 1147, 1273, 1275, 1147, 1147, 1275, 1276, 1147, 1277, 1276, 1147, 1278, 1147, 1147, 1147, 1147, 1279, 1147, 1279, 1280, 1281, 1279, 1280, 1147, 1147, 1147, 1281, 1281, 1282, 1283, 1284, 1283, 1147, 1147, 1147, 1285, 1147, 1147, 1147, 1147, 1286, 1147, 1147, 1147, 1287, 1147, 1288, 1147, 1289, 1147, 1147, 1290, 1147, 1147, 1147, 1291, 1147, 1147, 1292, 1292, 1147, 1147, 1293, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1294, 1147, 1294, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1295, 1147, 1147, 1147, 1296, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1297, 1147, 1147, 1147, 1298, 1147, 1147, 1147, 1147, 1147, 1147, 1299, 1300, 1299, 1147, 1147, 1301, 1302, 1301, 1147, 1147, 1303, 1147, 1147, 1304, 1147, 1305, 1147, 1147, 1306, 1307, 1147, 1308, 1309, 1147, 1310, 1147, 1311, 1147, 1147, 1312, 1313, 1314, 1147, 1315, 1147, 1147, 1315, 1316, 1315, 1314, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1317, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1318, 1318, 1319, 1147, 1320, 1147, 1147, 1321, 1322, 1323, 1324, 1324, 1147, 1147, 1147, 1147, 1147, 1315, 1147, 1147, 1325, 1325, 1326, 1327, 1147, 1328, 1328, 1147, 1329, 1330, 1330, 1331, 1147, 1332, 1333, 1333, 1334, 1335, 1147, 1336, 1147, 1147, 1147, 1337, 1337, 1338, 1339, 1340, 1341, 1341, 1147, 1147, 1342, 1343, 1344, 1147, 1147, 1147, 1147, 1147, 1345, 1346, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1347, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1348, 1147, 1349, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1350, 1147, 1351, 1147, 1147, 1147, 1147, 1352, 1353, 1354, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1355, 1355, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1356, 1357, 1358, 1359, 1360, 1360, 1147, 1147, 1361, 1362, 1147, 1363, 1147, 1363, 1147, 1364, 1365, 1365, 1366, 1147, 1147, 1147, 1147, 1367, 1368, 1369, 1369, 1370, 1147, 1147, 1371, 1147, 1147, 1147, 1147, 1147, 1372, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1351, 1147, 1147, 1147, 1147, 1373, 1354, 1147, 1147, 1147, 1147, 1147, 1147, 1374, 1147, 1147, 1147, 1147, 1357, 1147, 1360, 1360, 1147, 1362, 1147, 1147, 1364, 1366, 1147, 1147, 1147, 1367, 1375, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1376, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1373, 1147, 1147, 1147, 1147, 1377, 1147, 1374, 1374, 1147, 1147, 1357, 1147, 1360, 1360, 1362, 1147, 1147, 1364, 1366, 1147, 1147, 1147, 1367, 1375, 1375, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1378, 1379, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1377, 1377, 1147, 1147, 1357, 1360, 1360, 1362, 1147, 1147, 1364, 1366, 1147, 1147, 1147, 1367, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1380, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1381, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1357, 1360, 1360, 1362, 1147, 1147, 1364, 1366, 1147, 1147, 1147, 1367, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1382, 1147, 1147, 1147, 1357, 1147, 1383, 1360, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1382, 1382, 1357, 1383, 1360, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1357, 1383, 1360, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1357, 1383, 1360, 1147, 1147, 1147, 1147, 1147, 1147, 1383, 1147, 1147, 1147, 1383, 1147, 1147, 1383, 1147, 1383, 0, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147 } ; static yyconst flex_int16_t yy_nxt[9819] = { 0, 89, 90, 91, 89, 90, 89, 92, 89, 93, 89, 89, 89, 89, 89, 94, 89, 95, 96, 89, 94, 94, 94, 89, 97, 89, 98, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 89, 100, 89, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 89, 89, 89, 89, 89, 101, 157, 157, 101, 161, 158, 158, 161, 162, 224, 981, 162, 102, 103, 197, 104, 105, 197, 204, 106, 106, 107, 204, 224, 352, 88, 247, 352, 88, 205, 528, 598, 372, 205, 529, 212, 213, 374, 212, 247, 214, 206, 1143, 159, 159, 206, 163, 212, 213, 163, 212, 225, 214, 598, 233, 234, 198, 233, 260, 198, 207, 260, 294, 294, 207, 225, 233, 234, 248, 233, 107, 108, 108, 109, 108, 108, 108, 110, 215, 108, 108, 248, 108, 108, 108, 217, 108, 218, 108, 112, 215, 571, 931, 112, 108, 108, 219, 235, 1142, 932, 261, 220, 513, 261, 295, 295, 552, 512, 221, 235, 217, 554, 218, 312, 108, 113, 108, 237, 570, 238, 297, 219, 313, 281, 1140, 450, 220, 222, 450, 298, 299, 311, 237, 221, 238, 303, 304, 282, 303, 451, 239, 108, 108, 108, 108, 108, 108, 109, 108, 108, 108, 110, 222, 108, 108, 239, 108, 108, 108, 240, 108, 273, 108, 112, 242, 283, 243, 112, 108, 108, 242, 254, 243, 297, 240, 981, 352, 599, 305, 352, 255, 256, 298, 299, 274, 1138, 557, 244, 108, 113, 108, 559, 617, 244, 257, 390, 390, 390, 390, 599, 311, 517, 391, 274, 517, 1117, 245, 424, 424, 424, 424, 518, 245, 258, 425, 108, 108, 108, 108, 116, 116, 117, 116, 116, 116, 116, 116, 118, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 116, 120, 116, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 116, 116, 116, 116, 119, 121, 122, 123, 122, 122, 121, 121, 121, 124, 121, 121, 121, 121, 121, 121, 121, 121, 125, 121, 121, 121, 121, 126, 121, 121, 121, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 121, 128, 121, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 121, 121, 121, 129, 127, 130, 130, 131, 130, 130, 130, 132, 273, 130, 130, 254, 130, 130, 130, 273, 130, 273, 130, 134, 255, 256, 281, 134, 135, 130, 285, 504, 285, 1135, 504, 274, 505, 678, 257, 679, 282, 286, 275, 286, 275, 1133, 364, 365, 130, 136, 130, 365, 640, 287, 274, 287, 357, 258, 358, 358, 358, 275, 300, 275, 311, 300, 1147, 365, 283, 981, 405, 365, 288, 365, 288, 130, 130, 130, 130, 130, 130, 131, 130, 130, 130, 132, 301, 130, 130, 981, 130, 130, 130, 365, 130, 583, 130, 134, 583, 685, 494, 134, 135, 130, 314, 302, 310, 315, 310, 316, 584, 495, 598, 686, 1132, 375, 376, 311, 375, 311, 396, 397, 130, 136, 130, 397, 310, 591, 310, 310, 591, 310, 310, 310, 598, 530, 318, 311, 387, 388, 528, 387, 496, 598, 529, 428, 429, 397, 428, 130, 130, 130, 130, 137, 137, 138, 137, 137, 137, 139, 377, 137, 137, 598, 137, 137, 137, 980, 137, 1147, 137, 141, 1147, 617, 604, 141, 142, 143, 353, 1147, 1141, 353, 981, 389, 312, 598, 359, 1147, 397, 359, 430, 300, 397, 354, 300, 604, 137, 144, 137, 351, 598, 360, 311, 523, 524, 352, 523, 351, 352, 433, 434, 981, 433, 1131, 397, 301, 438, 439, 352, 438, 609, 352, 598, 137, 137, 137, 137, 137, 137, 138, 137, 137, 137, 139, 302, 137, 137, 697, 137, 137, 137, 610, 137, 700, 137, 141, 525, 1127, 351, 141, 142, 143, 355, 356, 435, 355, 351, 378, 378, 378, 378, 440, 701, 314, 698, 310, 315, 310, 316, 593, 137, 144, 137, 379, 355, 356, 311, 355, 380, 473, 473, 473, 473, 617, 532, 372, 474, 1144, 533, 1126, 374, 593, 594, 595, 534, 318, 535, 137, 137, 137, 137, 121, 145, 146, 145, 145, 121, 121, 121, 147, 121, 121, 121, 121, 121, 121, 121, 121, 148, 121, 121, 121, 121, 149, 121, 121, 121, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 121, 128, 121, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 121, 121, 121, 151, 150, 152, 152, 153, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 152, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 152, 155, 152, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 152, 152, 152, 152, 154, 164, 164, 165, 164, 164, 164, 166, 450, 164, 164, 450, 164, 164, 164, 808, 164, 629, 164, 168, 613, 629, 451, 168, 164, 164, 378, 378, 378, 378, 1124, 981, 378, 378, 378, 378, 444, 445, 808, 381, 715, 445, 379, 629, 164, 169, 164, 380, 379, 384, 384, 384, 384, 380, 372, 614, 381, 459, 460, 374, 459, 1123, 715, 445, 621, 379, 622, 622, 622, 915, 380, 164, 164, 164, 164, 164, 164, 165, 164, 164, 164, 166, 615, 164, 164, 916, 164, 164, 164, 1122, 164, 611, 164, 168, 611, 981, 981, 168, 164, 164, 303, 304, 461, 303, 383, 1121, 378, 378, 378, 378, 414, 414, 414, 414, 414, 414, 414, 414, 164, 169, 164, 383, 379, 719, 536, 617, 415, 380, 386, 532, 415, 416, 1120, 533, 617, 416, 1129, 355, 356, 534, 355, 535, 1119, 305, 719, 164, 164, 164, 164, 170, 170, 88, 170, 170, 170, 170, 170, 171, 170, 170, 170, 170, 170, 170, 172, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 170, 170, 170, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 173, 170, 170, 170, 170, 173, 174, 174, 175, 174, 174, 174, 174, 174, 176, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 174, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 174, 178, 174, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 177, 174, 174, 174, 174, 177, 179, 180, 181, 180, 180, 179, 179, 179, 182, 179, 179, 179, 179, 179, 179, 179, 179, 183, 179, 179, 179, 179, 184, 179, 179, 179, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 179, 186, 179, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 179, 179, 179, 187, 185, 188, 188, 189, 188, 188, 188, 188, 188, 190, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 188, 192, 188, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 188, 188, 188, 188, 191, 88, 88, 193, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 88, 195, 88, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 194, 88, 88, 88, 88, 194, 199, 199, 200, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 199, 202, 199, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 199, 199, 199, 199, 201, 88, 88, 208, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 88, 210, 88, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 209, 88, 88, 88, 88, 209, 226, 227, 228, 226, 227, 226, 226, 226, 226, 226, 226, 229, 226, 226, 226, 226, 366, 367, 226, 366, 1077, 406, 226, 226, 226, 226, 1147, 445, 596, 552, 406, 445, 1147, 365, 554, 366, 367, 365, 366, 406, 597, 408, 409, 226, 231, 226, 409, 718, 406, 596, 552, 470, 471, 445, 470, 554, 1115, 479, 480, 365, 479, 368, 597, 583, 484, 485, 583, 484, 409, 718, 226, 226, 226, 226, 226, 226, 227, 228, 226, 227, 226, 226, 226, 226, 226, 226, 229, 226, 226, 226, 226, 398, 399, 226, 398, 1114, 472, 226, 226, 226, 226, 1113, 481, 375, 376, 1147, 375, 1147, 397, 486, 504, 627, 397, 504, 627, 505, 1147, 409, 226, 231, 226, 409, 310, 1147, 310, 310, 557, 310, 310, 310, 1112, 559, 1111, 311, 397, 311, 400, 390, 390, 390, 390, 1110, 1109, 409, 391, 226, 226, 226, 226, 226, 249, 249, 250, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 249, 252, 249, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 249, 249, 249, 249, 251, 262, 262, 263, 262, 262, 262, 262, 262, 264, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 262, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 262, 266, 262, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 265, 262, 262, 262, 262, 265, 267, 267, 268, 267, 267, 267, 267, 267, 269, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 267, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 267, 271, 267, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 270, 267, 267, 267, 267, 270, 276, 276, 277, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 276, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 276, 279, 276, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 276, 276, 276, 276, 278, 289, 289, 290, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 410, 936, 1108, 289, 289, 289, 289, 421, 414, 414, 421, 1147, 409, 1107, 1106, 937, 409, 422, 406, 462, 462, 462, 462, 415, 289, 292, 289, 1105, 416, 414, 414, 414, 414, 1104, 450, 463, 417, 450, 409, 1102, 464, 488, 489, 1098, 488, 415, 499, 500, 451, 499, 416, 289, 289, 289, 289, 289, 289, 290, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 289, 1097, 1096, 1095, 289, 289, 289, 289, 462, 462, 462, 462, 722, 490, 411, 412, 498, 411, 501, 1147, 462, 462, 462, 462, 463, 289, 292, 289, 419, 464, 1147, 409, 617, 557, 722, 409, 463, 1147, 559, 364, 365, 464, 514, 515, 365, 514, 634, 634, 634, 634, 1146, 1093, 289, 289, 289, 289, 319, 409, 1092, 413, 420, 420, 420, 420, 1091, 646, 365, 417, 646, 320, 462, 462, 462, 462, 1090, 422, 415, 465, 638, 321, 322, 416, 638, 1089, 323, 324, 463, 516, 617, 325, 326, 464, 327, 328, 1088, 450, 520, 521, 450, 520, 321, 322, 1087, 1137, 638, 323, 324, 446, 447, 451, 446, 325, 326, 329, 330, 327, 328, 331, 331, 331, 331, 812, 611, 1147, 445, 611, 332, 643, 445, 1086, 598, 643, 419, 331, 331, 333, 1085, 454, 454, 454, 454, 522, 467, 812, 455, 1084, 537, 538, 723, 537, 445, 598, 448, 643, 335, 456, 456, 456, 457, 1079, 1078, 336, 337, 541, 542, 617, 541, 1147, 365, 723, 545, 546, 365, 545, 468, 468, 468, 468, 618, 1075, 338, 465, 339, 340, 331, 331, 331, 331, 724, 728, 463, 539, 728, 332, 365, 464, 497, 497, 497, 497, 331, 331, 335, 548, 549, 1074, 548, 600, 543, 724, 600, 805, 497, 497, 498, 547, 303, 304, 304, 303, 1073, 333, 611, 343, 1072, 611, 396, 397, 344, 345, 601, 397, 805, 497, 611, 600, 611, 611, 600, 611, 353, 613, 627, 353, 1071, 627, 467, 338, 550, 339, 340, 346, 652, 397, 346, 620, 652, 1070, 601, 305, 602, 351, 497, 347, 347, 617, 348, 349, 1069, 809, 350, 350, 351, 1068, 603, 301, 614, 617, 652, 721, 619, 602, 721, 359, 353, 598, 359, 353, 387, 388, 809, 387, 623, 624, 302, 623, 603, 627, 360, 360, 627, 494, 601, 615, 351, 351, 598, 625, 398, 399, 351, 398, 495, 626, 1147, 397, 311, 359, 1067, 397, 359, 351, 401, 401, 1066, 401, 401, 401, 402, 1065, 401, 401, 360, 401, 401, 401, 1064, 401, 351, 401, 404, 397, 1063, 496, 404, 401, 405, 357, 879, 358, 358, 358, 1062, 351, 351, 311, 359, 411, 412, 359, 411, 1061, 626, 364, 365, 401, 404, 401, 365, 879, 598, 620, 390, 390, 390, 390, 1060, 351, 953, 391, 1019, 1147, 1147, 1147, 1147, 1059, 794, 351, 1147, 794, 365, 598, 401, 401, 401, 401, 331, 331, 331, 331, 953, 1058, 1019, 630, 378, 378, 378, 378, 428, 429, 1057, 428, 331, 331, 578, 384, 384, 384, 384, 1056, 379, 804, 381, 524, 804, 380, 351, 1147, 1147, 1147, 1147, 379, 517, 331, 1147, 517, 380, 1054, 1053, 1052, 336, 337, 518, 1147, 433, 434, 728, 433, 1147, 728, 1051, 378, 378, 378, 378, 378, 378, 378, 378, 338, 1050, 339, 340, 331, 331, 331, 331, 379, 1049, 444, 445, 379, 380, 386, 445, 611, 380, 386, 611, 331, 331, 331, 414, 414, 414, 414, 1048, 383, 384, 384, 384, 384, 396, 397, 1047, 381, 445, 397, 415, 1147, 578, 1046, 721, 416, 379, 721, 1045, 336, 337, 380, 424, 424, 424, 424, 1043, 438, 439, 425, 438, 397, 424, 424, 424, 424, 731, 601, 338, 425, 339, 340, 585, 794, 639, 585, 794, 585, 585, 585, 585, 585, 585, 585, 586, 585, 587, 585, 587, 588, 585, 981, 406, 1042, 585, 585, 585, 590, 1147, 1147, 1147, 1147, 383, 408, 409, 1147, 446, 447, 409, 446, 406, 1147, 1041, 1147, 445, 585, 585, 585, 445, 1040, 1039, 406, 1147, 409, 1038, 459, 460, 409, 459, 1147, 409, 1147, 408, 409, 1147, 470, 471, 409, 470, 406, 445, 1147, 585, 585, 585, 585, 585, 611, 646, 409, 611, 646, 1037, 1147, 1147, 1147, 1147, 1036, 422, 409, 444, 445, 1035, 479, 480, 445, 479, 1034, 1032, 1147, 1147, 1147, 644, 420, 420, 420, 420, 1031, 1030, 1027, 417, 1147, 1147, 1147, 1147, 1026, 1021, 445, 1147, 415, 1147, 1020, 484, 485, 416, 484, 881, 1147, 488, 489, 653, 488, 1147, 1018, 1017, 421, 414, 414, 421, 1016, 454, 454, 454, 454, 1015, 422, 1147, 455, 1147, 1147, 346, 415, 1014, 346, 499, 500, 416, 499, 456, 456, 456, 457, 347, 347, 919, 348, 349, 920, 1013, 350, 350, 351, 1012, 999, 301, 419, 999, 1011, 420, 420, 420, 420, 1010, 1147, 1009, 417, 421, 414, 414, 421, 1008, 1007, 611, 302, 415, 611, 422, 514, 515, 416, 514, 1006, 415, 520, 521, 646, 520, 416, 646, 1005, 454, 454, 454, 454, 1004, 422, 473, 473, 473, 473, 351, 401, 401, 474, 401, 401, 401, 640, 1003, 401, 401, 457, 401, 401, 401, 617, 401, 1094, 641, 404, 1094, 735, 1002, 404, 401, 405, 421, 414, 414, 421, 419, 454, 454, 454, 454, 1001, 422, 1000, 455, 998, 537, 538, 415, 537, 401, 404, 401, 416, 997, 456, 456, 456, 457, 473, 473, 473, 473, 994, 993, 992, 474, 462, 462, 462, 462, 523, 524, 781, 523, 991, 781, 401, 401, 401, 401, 401, 401, 463, 401, 401, 401, 640, 464, 401, 401, 990, 401, 401, 401, 989, 401, 611, 401, 404, 611, 988, 987, 404, 401, 401, 986, 985, 981, 454, 454, 454, 454, 984, 525, 983, 455, 462, 462, 462, 462, 982, 979, 978, 401, 404, 401, 656, 656, 656, 457, 782, 977, 463, 468, 468, 468, 468, 464, 976, 617, 465, 1147, 1147, 1147, 1147, 975, 888, 974, 1147, 463, 401, 401, 401, 401, 464, 973, 972, 1147, 468, 468, 468, 468, 1147, 729, 971, 465, 462, 462, 462, 462, 1147, 1147, 1147, 1147, 463, 541, 542, 1147, 541, 464, 545, 546, 463, 545, 970, 548, 549, 464, 548, 968, 728, 967, 621, 728, 622, 622, 622, 729, 729, 623, 624, 966, 623, 623, 624, 467, 623, 611, 1081, 304, 611, 1081, 810, 1147, 736, 810, 611, 963, 737, 611, 626, 962, 957, 956, 626, 729, 611, 811, 952, 611, 467, 585, 729, 951, 585, 811, 585, 585, 585, 585, 585, 585, 585, 586, 585, 587, 585, 587, 712, 585, 617, 1082, 711, 585, 585, 585, 590, 623, 624, 729, 623, 734, 623, 624, 950, 623, 364, 629, 949, 626, 815, 629, 738, 626, 585, 713, 585, 737, 626, 1147, 629, 311, 948, 626, 629, 364, 365, 396, 638, 958, 365, 947, 638, 629, 741, 741, 741, 741, 946, 945, 944, 585, 585, 585, 585, 585, 629, 743, 743, 743, 743, 943, 365, 406, 638, 1147, 638, 742, 942, 941, 638, 396, 397, 739, 408, 643, 397, 626, 940, 643, 742, 406, 626, 939, 611, 444, 652, 611, 1147, 938, 652, 935, 638, 934, 741, 741, 741, 741, 397, 1147, 643, 643, 1147, 652, 643, 611, 1147, 652, 611, 745, 401, 401, 652, 401, 401, 401, 640, 742, 401, 401, 933, 401, 401, 401, 406, 401, 643, 401, 747, 652, 930, 929, 747, 401, 401, 408, 409, 928, 444, 445, 409, 927, 406, 445, 611, 1080, 925, 611, 617, 454, 454, 454, 454, 401, 747, 401, 754, 757, 757, 757, 757, 924, 409, 817, 455, 445, 923, 755, 755, 755, 457, 611, 1125, 748, 611, 1125, 753, 922, 457, 921, 401, 401, 401, 401, 454, 454, 454, 454, 918, 917, 1116, 455, 454, 454, 454, 454, 314, 914, 310, 455, 310, 803, 656, 656, 656, 457, 913, 912, 911, 311, 656, 656, 656, 457, 617, 623, 624, 910, 623, 623, 624, 909, 623, 623, 624, 818, 623, 364, 365, 908, 736, 907, 365, 906, 819, 905, 626, 904, 738, 903, 626, 396, 397, 902, 626, 901, 397, 311, 743, 743, 743, 743, 897, 896, 365, 454, 454, 454, 454, 444, 445, 895, 754, 892, 445, 891, 406, 880, 397, 820, 880, 742, 887, 755, 755, 755, 457, 408, 409, 885, 884, 878, 409, 823, 406, 626, 445, 877, 611, 626, 881, 611, 876, 626, 401, 401, 711, 401, 401, 401, 640, 828, 401, 401, 409, 401, 401, 401, 874, 401, 1134, 641, 747, 1134, 873, 872, 747, 401, 405, 824, 573, 871, 454, 454, 454, 454, 870, 364, 365, 754, 869, 314, 365, 310, 868, 310, 803, 401, 747, 401, 755, 755, 755, 457, 311, 611, 886, 867, 611, 757, 757, 757, 757, 866, 365, 883, 455, 611, 883, 955, 611, 890, 955, 865, 401, 401, 401, 401, 401, 401, 457, 401, 401, 401, 640, 864, 401, 401, 811, 401, 401, 401, 881, 401, 611, 401, 747, 611, 840, 841, 747, 401, 401, 842, 396, 397, 843, 844, 863, 397, 617, 845, 862, 1101, 846, 847, 883, 848, 861, 883, 860, 401, 747, 401, 406, 889, 623, 624, 859, 623, 858, 397, 444, 445, 857, 408, 409, 445, 893, 811, 409, 736, 406, 611, 1022, 856, 611, 626, 401, 401, 401, 401, 855, 454, 454, 454, 454, 854, 611, 445, 754, 611, 409, 853, 955, 1136, 898, 955, 1136, 894, 852, 899, 899, 899, 457, 364, 365, 396, 397, 851, 365, 406, 397, 444, 445, 850, 617, 881, 445, 849, 959, 1139, 408, 409, 1139, 611, 626, 409, 611, 406, 1136, 617, 365, 1136, 397, 839, 961, 838, 964, 611, 445, 837, 611, 836, 969, 454, 454, 454, 454, 409, 835, 960, 754, 965, 454, 454, 454, 454, 834, 611, 833, 754, 611, 899, 899, 899, 457, 1076, 617, 832, 1076, 477, 899, 899, 899, 457, 364, 365, 396, 397, 406, 365, 617, 397, 1139, 1145, 1023, 1139, 1145, 1024, 1077, 408, 409, 831, 1100, 830, 409, 1100, 406, 444, 445, 827, 617, 365, 445, 397, 364, 365, 396, 397, 826, 365, 825, 397, 444, 445, 406, 1077, 409, 445, 1083, 1025, 1100, 1028, 822, 1100, 445, 408, 409, 821, 617, 816, 409, 365, 406, 397, 1029, 1081, 304, 611, 1081, 445, 611, 611, 1033, 1077, 611, 611, 611, 1136, 611, 611, 1136, 703, 409, 303, 304, 814, 303, 813, 601, 703, 807, 806, 703, 703, 730, 801, 730, 730, 730, 733, 800, 733, 733, 733, 703, 799, 798, 573, 305, 796, 617, 795, 703, 701, 617, 703, 703, 1118, 793, 617, 617, 792, 791, 790, 789, 1103, 1082, 788, 787, 786, 785, 1128, 1130, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 156, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 167, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 211, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 241, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 259, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 272, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 291, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 293, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 306, 306, 784, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 309, 730, 783, 730, 730, 730, 733, 780, 733, 733, 733, 779, 778, 776, 775, 309, 774, 309, 309, 309, 773, 772, 771, 770, 309, 310, 769, 310, 310, 768, 310, 767, 765, 764, 310, 310, 763, 310, 310, 310, 317, 762, 317, 317, 317, 317, 761, 317, 477, 759, 758, 317, 317, 317, 317, 317, 317, 334, 334, 334, 752, 751, 750, 749, 386, 334, 744, 740, 727, 726, 334, 334, 334, 334, 334, 334, 334, 334, 334, 725, 334, 334, 341, 717, 341, 341, 716, 341, 714, 1147, 311, 341, 341, 311, 341, 341, 341, 342, 342, 342, 311, 711, 581, 709, 708, 342, 707, 706, 573, 704, 342, 342, 342, 342, 342, 342, 342, 342, 342, 702, 342, 342, 361, 361, 699, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 363, 696, 695, 557, 694, 693, 363, 552, 363, 363, 363, 363, 363, 692, 691, 363, 363, 363, 363, 363, 363, 690, 689, 688, 687, 363, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 371, 684, 371, 371, 371, 683, 682, 681, 680, 371, 373, 677, 373, 373, 526, 676, 675, 373, 674, 373, 373, 373, 673, 672, 507, 507, 373, 382, 382, 382, 382, 671, 670, 382, 668, 501, 496, 667, 666, 665, 664, 382, 483, 663, 382, 477, 661, 477, 382, 659, 382, 382, 382, 463, 658, 655, 382, 382, 385, 385, 385, 385, 442, 650, 437, 649, 432, 648, 415, 640, 640, 640, 385, 394, 385, 385, 385, 386, 635, 385, 379, 385, 385, 385, 632, 372, 631, 370, 385, 392, 392, 392, 392, 362, 612, 392, 610, 607, 606, 605, 592, 311, 311, 581, 307, 579, 576, 574, 573, 570, 392, 568, 392, 392, 392, 567, 565, 563, 562, 392, 393, 393, 560, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 395, 555, 526, 512, 511, 510, 395, 508, 395, 395, 395, 395, 395, 507, 503, 395, 395, 395, 395, 395, 395, 496, 492, 483, 477, 395, 403, 403, 463, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 407, 407, 442, 437, 432, 415, 394, 407, 394, 407, 407, 407, 407, 407, 379, 407, 407, 407, 407, 407, 407, 407, 370, 362, 311, 308, 407, 418, 418, 418, 418, 307, 1147, 418, 115, 115, 1147, 1147, 1147, 1147, 1147, 418, 1147, 1147, 418, 1147, 1147, 1147, 418, 1147, 418, 418, 418, 1147, 1147, 1147, 418, 418, 423, 423, 423, 423, 1147, 1147, 1147, 1147, 423, 1147, 1147, 1147, 1147, 1147, 423, 1147, 423, 423, 1147, 1147, 1147, 423, 1147, 423, 423, 423, 1147, 1147, 1147, 1147, 423, 426, 426, 426, 426, 1147, 1147, 426, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 426, 1147, 426, 426, 426, 1147, 1147, 1147, 1147, 426, 427, 1147, 1147, 427, 1147, 1147, 1147, 1147, 427, 1147, 427, 427, 427, 1147, 1147, 1147, 1147, 427, 431, 431, 1147, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 436, 436, 1147, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 441, 441, 1147, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 443, 1147, 1147, 1147, 1147, 1147, 443, 1147, 443, 443, 443, 443, 443, 1147, 1147, 443, 443, 443, 443, 443, 443, 1147, 1147, 1147, 1147, 443, 449, 1147, 449, 449, 449, 1147, 1147, 1147, 1147, 449, 452, 1147, 1147, 452, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 452, 1147, 1147, 1147, 452, 1147, 1147, 1147, 1147, 452, 1147, 452, 452, 452, 1147, 1147, 1147, 1147, 452, 453, 1147, 453, 453, 453, 1147, 1147, 1147, 1147, 453, 458, 458, 458, 458, 1147, 1147, 458, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 458, 458, 1147, 1147, 1147, 458, 1147, 458, 458, 458, 1147, 1147, 1147, 1147, 458, 466, 466, 466, 466, 1147, 1147, 466, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 466, 1147, 1147, 466, 1147, 1147, 1147, 466, 1147, 466, 466, 466, 1147, 1147, 1147, 466, 466, 469, 469, 469, 469, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 469, 1147, 469, 469, 1147, 1147, 1147, 469, 1147, 469, 469, 469, 1147, 1147, 1147, 1147, 469, 475, 475, 475, 475, 1147, 1147, 475, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 475, 1147, 475, 475, 475, 1147, 1147, 1147, 1147, 475, 476, 1147, 476, 476, 476, 1147, 1147, 1147, 1147, 476, 478, 1147, 478, 1147, 1147, 1147, 1147, 478, 1147, 478, 478, 478, 1147, 1147, 1147, 1147, 478, 482, 482, 1147, 482, 1147, 1147, 1147, 1147, 482, 1147, 482, 482, 482, 1147, 1147, 1147, 1147, 482, 487, 487, 1147, 487, 487, 487, 487, 487, 487, 487, 487, 1147, 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 1147, 487, 487, 487, 487, 487, 487, 487, 487, 491, 1147, 1147, 491, 1147, 1147, 1147, 1147, 491, 1147, 491, 491, 491, 1147, 1147, 1147, 1147, 491, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 1147, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 495, 495, 1147, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 1147, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 497, 497, 1147, 497, 1147, 497, 497, 497, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 497, 497, 497, 1147, 497, 497, 1147, 1147, 1147, 1147, 1147, 497, 502, 1147, 1147, 502, 1147, 1147, 1147, 1147, 502, 1147, 502, 502, 502, 1147, 1147, 1147, 1147, 502, 506, 506, 1147, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 509, 509, 1147, 509, 1147, 509, 509, 509, 509, 509, 509, 1147, 509, 509, 509, 509, 1147, 509, 509, 509, 509, 1147, 509, 1147, 509, 509, 509, 509, 509, 509, 509, 509, 519, 1147, 1147, 519, 1147, 1147, 1147, 1147, 519, 1147, 1147, 1147, 1147, 519, 519, 1147, 519, 1147, 1147, 1147, 1147, 519, 1147, 519, 519, 519, 527, 527, 1147, 527, 1147, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 1147, 527, 1147, 527, 527, 527, 527, 527, 527, 527, 527, 531, 531, 1147, 531, 1147, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 1147, 531, 1147, 531, 531, 531, 531, 531, 531, 531, 531, 540, 1147, 1147, 540, 1147, 1147, 1147, 1147, 540, 1147, 540, 540, 540, 1147, 1147, 1147, 1147, 540, 544, 544, 1147, 544, 544, 544, 544, 544, 544, 1147, 1147, 544, 544, 544, 544, 544, 544, 544, 544, 544, 544, 1147, 544, 1147, 544, 544, 544, 544, 544, 544, 544, 544, 551, 1147, 551, 551, 551, 1147, 1147, 1147, 1147, 551, 553, 1147, 553, 553, 1147, 1147, 1147, 553, 1147, 553, 553, 553, 1147, 1147, 1147, 1147, 553, 556, 1147, 556, 556, 556, 1147, 1147, 1147, 1147, 556, 558, 1147, 558, 558, 1147, 1147, 1147, 558, 1147, 558, 558, 558, 1147, 1147, 1147, 1147, 558, 561, 561, 1147, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 1147, 561, 1147, 561, 561, 561, 561, 561, 561, 561, 561, 564, 1147, 1147, 564, 1147, 1147, 1147, 1147, 564, 1147, 564, 564, 564, 1147, 1147, 1147, 1147, 564, 566, 566, 1147, 566, 566, 566, 566, 566, 566, 566, 566, 566, 566, 566, 1147, 566, 566, 566, 566, 566, 566, 566, 566, 1147, 566, 566, 566, 566, 566, 566, 566, 566, 569, 569, 1147, 569, 569, 569, 569, 569, 569, 569, 569, 1147, 569, 569, 569, 569, 569, 569, 569, 569, 569, 1147, 569, 1147, 569, 569, 569, 569, 569, 569, 569, 569, 572, 1147, 572, 572, 572, 572, 572, 1147, 1147, 1147, 572, 1147, 572, 572, 572, 1147, 1147, 1147, 1147, 572, 575, 575, 1147, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 1147, 575, 575, 575, 575, 575, 575, 575, 575, 577, 577, 577, 577, 577, 577, 577, 577, 577, 1147, 1147, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 334, 334, 334, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 334, 334, 334, 334, 334, 334, 334, 334, 334, 1147, 334, 334, 306, 306, 1147, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 306, 309, 1147, 309, 309, 309, 1147, 1147, 1147, 1147, 309, 580, 580, 1147, 1147, 1147, 580, 1147, 580, 580, 580, 1147, 1147, 1147, 1147, 580, 310, 1147, 310, 310, 1147, 310, 1147, 1147, 1147, 310, 310, 1147, 310, 310, 310, 582, 1147, 1147, 582, 1147, 1147, 1147, 1147, 582, 1147, 582, 582, 582, 589, 1147, 1147, 589, 1147, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 608, 1147, 608, 608, 608, 1147, 1147, 1147, 608, 616, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 616, 1147, 616, 616, 616, 341, 1147, 341, 341, 1147, 341, 1147, 1147, 1147, 341, 341, 1147, 341, 341, 341, 342, 1147, 1147, 342, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 342, 342, 342, 342, 342, 361, 361, 1147, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, 363, 1147, 1147, 1147, 1147, 1147, 363, 1147, 363, 363, 363, 363, 363, 1147, 1147, 363, 363, 363, 363, 363, 363, 1147, 1147, 1147, 1147, 363, 628, 1147, 1147, 1147, 1147, 1147, 628, 1147, 628, 1147, 628, 628, 628, 1147, 1147, 628, 628, 628, 628, 628, 628, 1147, 1147, 1147, 1147, 628, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 369, 373, 1147, 373, 373, 1147, 1147, 1147, 373, 1147, 373, 373, 373, 1147, 1147, 1147, 1147, 373, 371, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 371, 1147, 371, 371, 371, 1147, 1147, 1147, 1147, 371, 382, 382, 382, 382, 1147, 1147, 382, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 382, 1147, 1147, 382, 1147, 1147, 1147, 382, 1147, 382, 382, 382, 1147, 1147, 1147, 382, 382, 385, 385, 385, 385, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 385, 1147, 385, 385, 385, 1147, 1147, 385, 1147, 385, 385, 385, 1147, 1147, 1147, 1147, 385, 392, 392, 392, 392, 1147, 1147, 392, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 392, 1147, 392, 392, 392, 1147, 1147, 1147, 1147, 392, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 1147, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 636, 1147, 636, 1147, 1147, 636, 1147, 636, 636, 636, 1147, 1147, 1147, 1147, 636, 393, 393, 1147, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 393, 395, 1147, 1147, 1147, 1147, 1147, 395, 1147, 395, 395, 395, 395, 395, 1147, 1147, 395, 395, 395, 395, 395, 395, 1147, 1147, 1147, 1147, 395, 637, 1147, 1147, 1147, 1147, 1147, 637, 1147, 637, 1147, 637, 637, 637, 1147, 1147, 637, 637, 637, 637, 637, 637, 1147, 1147, 1147, 1147, 637, 401, 401, 1147, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 403, 403, 1147, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, 407, 407, 1147, 1147, 1147, 1147, 1147, 407, 1147, 407, 407, 407, 407, 407, 1147, 407, 407, 407, 407, 407, 407, 407, 1147, 1147, 1147, 1147, 407, 642, 1147, 1147, 1147, 1147, 1147, 642, 1147, 642, 1147, 642, 642, 642, 1147, 1147, 642, 642, 642, 642, 642, 642, 1147, 1147, 1147, 1147, 642, 418, 418, 418, 418, 1147, 1147, 418, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 418, 1147, 1147, 418, 1147, 1147, 1147, 418, 1147, 418, 418, 418, 1147, 1147, 1147, 418, 418, 423, 423, 423, 423, 1147, 1147, 1147, 1147, 423, 1147, 1147, 1147, 1147, 1147, 423, 1147, 423, 423, 1147, 1147, 1147, 423, 1147, 423, 423, 423, 1147, 1147, 1147, 1147, 423, 426, 426, 426, 426, 1147, 1147, 426, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 426, 1147, 426, 426, 426, 1147, 1147, 1147, 1147, 426, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 1147, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 647, 1147, 1147, 647, 1147, 1147, 1147, 1147, 647, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 647, 1147, 1147, 1147, 1147, 647, 1147, 647, 647, 647, 1147, 1147, 1147, 1147, 647, 427, 1147, 1147, 427, 1147, 1147, 1147, 1147, 427, 1147, 427, 427, 427, 1147, 1147, 1147, 1147, 427, 431, 431, 1147, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 431, 436, 436, 1147, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 436, 441, 441, 1147, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 441, 443, 1147, 1147, 1147, 1147, 1147, 443, 1147, 443, 443, 443, 443, 443, 1147, 1147, 443, 443, 443, 443, 443, 443, 1147, 1147, 1147, 1147, 443, 651, 1147, 1147, 1147, 1147, 1147, 651, 1147, 651, 1147, 651, 651, 651, 1147, 1147, 651, 651, 651, 651, 651, 651, 1147, 1147, 1147, 1147, 651, 452, 1147, 1147, 452, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 452, 1147, 1147, 1147, 452, 1147, 1147, 1147, 1147, 452, 1147, 452, 452, 452, 1147, 1147, 1147, 1147, 452, 458, 458, 458, 458, 1147, 1147, 458, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 458, 458, 1147, 1147, 1147, 458, 1147, 458, 458, 458, 1147, 1147, 1147, 1147, 458, 654, 1147, 654, 654, 654, 1147, 1147, 1147, 1147, 654, 657, 657, 657, 657, 1147, 1147, 657, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 657, 657, 1147, 1147, 1147, 657, 1147, 657, 657, 657, 1147, 1147, 1147, 1147, 657, 466, 466, 466, 466, 1147, 1147, 466, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 466, 1147, 1147, 466, 1147, 1147, 1147, 466, 1147, 466, 466, 466, 1147, 1147, 1147, 466, 466, 469, 469, 469, 469, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 469, 1147, 469, 469, 1147, 1147, 1147, 469, 1147, 469, 469, 469, 1147, 1147, 1147, 1147, 469, 475, 475, 475, 475, 1147, 1147, 475, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 475, 1147, 475, 475, 475, 1147, 1147, 1147, 1147, 475, 660, 1147, 1147, 1147, 1147, 660, 1147, 660, 660, 660, 1147, 1147, 1147, 1147, 660, 478, 1147, 478, 1147, 1147, 1147, 1147, 478, 1147, 478, 478, 478, 1147, 1147, 1147, 1147, 478, 662, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 662, 1147, 662, 662, 662, 1147, 1147, 1147, 1147, 662, 482, 482, 1147, 482, 1147, 1147, 1147, 1147, 482, 1147, 482, 482, 482, 1147, 1147, 1147, 1147, 482, 487, 487, 1147, 487, 487, 487, 487, 487, 487, 487, 487, 1147, 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 1147, 487, 487, 487, 487, 487, 487, 487, 487, 491, 1147, 1147, 491, 1147, 1147, 1147, 1147, 491, 1147, 491, 491, 491, 1147, 1147, 1147, 1147, 491, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 1147, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 495, 495, 1147, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 1147, 495, 495, 495, 495, 495, 495, 495, 495, 495, 495, 669, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 669, 1147, 669, 669, 669, 1147, 1147, 1147, 1147, 669, 502, 1147, 1147, 502, 1147, 1147, 1147, 1147, 502, 1147, 502, 502, 502, 1147, 1147, 1147, 1147, 502, 506, 506, 1147, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 506, 509, 509, 1147, 509, 1147, 509, 509, 509, 509, 509, 509, 1147, 509, 509, 509, 509, 1147, 509, 509, 509, 509, 1147, 509, 1147, 509, 509, 509, 509, 509, 509, 509, 509, 519, 1147, 1147, 519, 1147, 1147, 1147, 1147, 519, 1147, 1147, 1147, 1147, 519, 519, 1147, 519, 1147, 1147, 1147, 1147, 519, 1147, 519, 519, 519, 527, 527, 1147, 527, 1147, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 1147, 527, 1147, 527, 527, 527, 527, 527, 527, 527, 527, 531, 531, 1147, 531, 1147, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 531, 1147, 531, 1147, 531, 531, 531, 531, 531, 531, 531, 531, 540, 1147, 1147, 540, 1147, 1147, 1147, 1147, 540, 1147, 540, 540, 540, 1147, 1147, 1147, 1147, 540, 544, 544, 1147, 544, 544, 544, 544, 544, 544, 1147, 1147, 544, 544, 544, 544, 544, 544, 544, 544, 544, 544, 1147, 544, 1147, 544, 544, 544, 544, 544, 544, 544, 544, 553, 1147, 553, 553, 1147, 1147, 1147, 553, 1147, 553, 553, 553, 1147, 1147, 1147, 1147, 553, 551, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 551, 1147, 551, 551, 551, 1147, 1147, 1147, 1147, 551, 558, 1147, 558, 558, 1147, 1147, 1147, 558, 1147, 558, 558, 558, 1147, 1147, 1147, 1147, 558, 556, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 556, 1147, 556, 556, 556, 1147, 1147, 1147, 1147, 556, 561, 561, 1147, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 1147, 561, 1147, 561, 561, 561, 561, 561, 561, 561, 561, 564, 1147, 1147, 564, 1147, 1147, 1147, 1147, 564, 1147, 564, 564, 564, 1147, 1147, 1147, 1147, 564, 566, 566, 1147, 566, 566, 566, 566, 566, 566, 566, 566, 566, 566, 566, 1147, 566, 566, 566, 566, 566, 566, 566, 566, 1147, 566, 566, 566, 566, 566, 566, 566, 566, 569, 569, 1147, 569, 569, 569, 569, 569, 569, 569, 569, 1147, 569, 569, 569, 569, 569, 569, 569, 569, 569, 1147, 569, 1147, 569, 569, 569, 569, 569, 569, 569, 569, 572, 1147, 572, 572, 572, 572, 572, 1147, 1147, 1147, 572, 1147, 572, 572, 572, 1147, 1147, 1147, 1147, 572, 705, 1147, 1147, 1147, 1147, 705, 1147, 705, 705, 705, 1147, 1147, 1147, 1147, 705, 575, 575, 1147, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 575, 1147, 575, 575, 575, 575, 575, 575, 575, 575, 577, 577, 577, 577, 577, 577, 577, 577, 577, 1147, 1147, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 580, 580, 1147, 1147, 1147, 580, 1147, 580, 580, 580, 1147, 1147, 1147, 1147, 580, 710, 710, 1147, 710, 710, 710, 710, 1147, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 582, 582, 1147, 582, 1147, 1147, 1147, 1147, 582, 1147, 582, 582, 582, 310, 1147, 310, 310, 1147, 310, 1147, 1147, 1147, 310, 310, 1147, 310, 310, 310, 589, 1147, 1147, 589, 1147, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 589, 720, 720, 1147, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 608, 1147, 1147, 608, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 608, 1147, 608, 608, 608, 334, 1147, 1147, 334, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 334, 1147, 334, 334, 334, 732, 732, 1147, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 1147, 732, 732, 616, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 616, 1147, 616, 616, 616, 342, 1147, 1147, 342, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 342, 342, 342, 342, 342, 628, 1147, 1147, 1147, 1147, 1147, 628, 1147, 628, 628, 628, 628, 628, 1147, 1147, 628, 628, 628, 628, 628, 628, 1147, 1147, 1147, 1147, 628, 363, 1147, 1147, 1147, 1147, 1147, 363, 1147, 363, 363, 363, 363, 363, 1147, 1147, 363, 363, 363, 363, 363, 363, 1147, 1147, 1147, 1147, 363, 371, 1147, 371, 371, 371, 1147, 1147, 1147, 1147, 371, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 636, 1147, 636, 1147, 1147, 636, 1147, 636, 636, 636, 1147, 1147, 1147, 1147, 636, 637, 1147, 1147, 1147, 1147, 1147, 637, 1147, 637, 637, 637, 637, 637, 1147, 1147, 637, 637, 637, 637, 637, 637, 1147, 1147, 1147, 1147, 637, 395, 1147, 1147, 1147, 1147, 1147, 395, 1147, 395, 395, 395, 395, 395, 1147, 1147, 395, 395, 395, 395, 395, 395, 1147, 1147, 1147, 1147, 395, 746, 746, 1147, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 642, 642, 1147, 1147, 1147, 1147, 1147, 642, 1147, 642, 642, 642, 642, 642, 1147, 642, 642, 642, 642, 642, 642, 642, 1147, 1147, 1147, 1147, 642, 407, 407, 1147, 1147, 1147, 1147, 1147, 407, 1147, 407, 407, 407, 407, 407, 1147, 407, 407, 407, 407, 407, 407, 407, 1147, 1147, 1147, 1147, 407, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 647, 1147, 1147, 647, 1147, 1147, 1147, 1147, 647, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 647, 1147, 1147, 1147, 1147, 647, 1147, 647, 647, 647, 1147, 1147, 1147, 1147, 647, 651, 1147, 1147, 1147, 1147, 1147, 651, 1147, 651, 651, 651, 651, 651, 1147, 1147, 651, 651, 651, 651, 651, 651, 1147, 1147, 1147, 1147, 651, 443, 1147, 1147, 1147, 1147, 1147, 443, 1147, 443, 443, 443, 443, 443, 1147, 1147, 443, 443, 443, 443, 443, 443, 1147, 1147, 1147, 1147, 443, 756, 756, 756, 756, 1147, 1147, 756, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 756, 756, 1147, 1147, 1147, 756, 1147, 756, 756, 756, 1147, 1147, 1147, 1147, 756, 654, 654, 654, 654, 1147, 1147, 654, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 654, 1147, 1147, 1147, 654, 1147, 654, 654, 654, 1147, 1147, 1147, 1147, 654, 657, 657, 657, 657, 1147, 1147, 657, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 657, 657, 1147, 1147, 1147, 657, 1147, 657, 657, 657, 1147, 1147, 1147, 1147, 657, 660, 1147, 1147, 1147, 1147, 660, 1147, 660, 660, 660, 1147, 1147, 1147, 1147, 660, 662, 1147, 662, 662, 662, 1147, 1147, 1147, 1147, 662, 760, 1147, 760, 1147, 1147, 1147, 1147, 760, 1147, 760, 760, 760, 1147, 1147, 1147, 1147, 760, 669, 1147, 669, 669, 669, 1147, 1147, 1147, 1147, 669, 766, 1147, 1147, 1147, 1147, 766, 1147, 766, 766, 766, 1147, 1147, 1147, 1147, 766, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 777, 1147, 777, 777, 777, 777, 1147, 777, 1147, 1147, 777, 777, 777, 777, 777, 777, 551, 1147, 551, 551, 551, 1147, 1147, 1147, 1147, 551, 556, 1147, 556, 556, 556, 1147, 1147, 1147, 1147, 556, 797, 1147, 797, 797, 797, 797, 797, 1147, 1147, 1147, 797, 1147, 797, 797, 797, 1147, 1147, 1147, 1147, 797, 710, 710, 1147, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 802, 1147, 1147, 802, 1147, 1147, 1147, 1147, 802, 1147, 802, 802, 802, 317, 1147, 317, 1147, 317, 317, 1147, 317, 1147, 1147, 1147, 317, 317, 1147, 317, 317, 317, 720, 720, 1147, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 720, 334, 1147, 1147, 334, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 334, 1147, 334, 334, 334, 732, 732, 1147, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 732, 733, 733, 733, 733, 733, 342, 1147, 1147, 342, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 342, 342, 342, 342, 342, 310, 310, 1147, 310, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 310, 1147, 310, 310, 1147, 310, 310, 1147, 1147, 310, 310, 1147, 310, 310, 310, 1147, 310, 363, 1147, 1147, 1147, 1147, 1147, 363, 1147, 363, 363, 363, 363, 363, 1147, 1147, 363, 363, 363, 363, 363, 363, 1147, 1147, 1147, 1147, 363, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 633, 395, 1147, 1147, 1147, 1147, 1147, 395, 1147, 395, 395, 395, 395, 395, 1147, 1147, 395, 395, 395, 395, 395, 395, 1147, 1147, 1147, 1147, 395, 746, 746, 1147, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 746, 407, 407, 1147, 1147, 1147, 1147, 1147, 407, 1147, 407, 407, 407, 407, 407, 1147, 407, 407, 407, 407, 407, 407, 407, 1147, 1147, 1147, 1147, 407, 443, 1147, 1147, 1147, 1147, 1147, 443, 1147, 443, 443, 443, 443, 443, 1147, 1147, 443, 443, 443, 443, 443, 443, 1147, 1147, 1147, 1147, 443, 829, 1147, 829, 829, 829, 1147, 1147, 1147, 1147, 829, 756, 756, 756, 756, 1147, 1147, 756, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 756, 756, 1147, 1147, 1147, 756, 1147, 756, 756, 756, 1147, 1147, 1147, 1147, 756, 654, 654, 654, 654, 1147, 1147, 654, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 654, 1147, 1147, 1147, 654, 1147, 654, 654, 654, 1147, 1147, 1147, 1147, 654, 760, 1147, 760, 1147, 1147, 1147, 1147, 760, 1147, 760, 760, 760, 1147, 1147, 1147, 1147, 760, 766, 1147, 1147, 1147, 1147, 766, 1147, 766, 766, 766, 1147, 1147, 1147, 1147, 766, 875, 875, 1147, 875, 1147, 1147, 1147, 1147, 875, 1147, 875, 875, 875, 882, 882, 1147, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 882, 900, 900, 900, 900, 1147, 1147, 900, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 900, 900, 1147, 1147, 1147, 900, 1147, 900, 900, 900, 1147, 1147, 1147, 1147, 900, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 926, 1147, 926, 926, 926, 926, 1147, 926, 1147, 926, 1147, 926, 926, 926, 926, 926, 954, 954, 1147, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 954, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 995, 1147, 995, 995, 995, 995, 1147, 995, 1147, 1147, 1147, 995, 995, 995, 995, 995, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 996, 1147, 996, 996, 996, 996, 1147, 996, 1147, 1147, 1147, 996, 996, 996, 996, 996, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1044, 1147, 1044, 1044, 1044, 1044, 1147, 1044, 1147, 1147, 1147, 1044, 1044, 1044, 1044, 1044, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1055, 1147, 1055, 1055, 1055, 1055, 1147, 1055, 1147, 1147, 1147, 1055, 1055, 1055, 1055, 1055, 1099, 1099, 1147, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 1099, 87, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147 } ; static yyconst flex_int16_t yy_chk[9819] = { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 21, 22, 4, 23, 21, 22, 24, 23, 49, 1142, 24, 4, 4, 37, 4, 4, 38, 41, 4, 4, 4, 42, 50, 102, 37, 59, 102, 38, 41, 239, 322, 119, 42, 239, 45, 45, 119, 45, 60, 45, 41, 1140, 21, 22, 42, 23, 46, 46, 24, 46, 49, 46, 322, 53, 53, 37, 53, 65, 38, 41, 66, 83, 84, 42, 50, 54, 54, 59, 54, 4, 5, 5, 5, 5, 5, 5, 5, 45, 5, 5, 60, 5, 5, 5, 47, 5, 47, 5, 5, 46, 288, 857, 5, 5, 5, 47, 53, 1138, 857, 65, 47, 222, 66, 83, 84, 265, 222, 47, 54, 48, 265, 48, 95, 5, 5, 5, 55, 288, 55, 85, 48, 95, 77, 1135, 173, 48, 47, 173, 85, 85, 95, 56, 48, 56, 91, 91, 77, 91, 173, 55, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 48, 6, 6, 56, 6, 6, 6, 55, 6, 71, 6, 6, 57, 77, 57, 6, 6, 6, 58, 63, 58, 86, 56, 1132, 103, 324, 91, 103, 63, 63, 86, 86, 71, 1131, 270, 57, 6, 6, 6, 270, 1102, 58, 63, 129, 129, 129, 129, 324, 103, 227, 129, 71, 227, 1102, 57, 151, 151, 151, 151, 227, 58, 63, 151, 6, 6, 6, 6, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 72, 13, 13, 64, 13, 13, 13, 73, 13, 74, 13, 13, 64, 64, 78, 13, 13, 13, 79, 212, 80, 1127, 212, 72, 212, 528, 64, 528, 78, 79, 73, 80, 74, 1124, 111, 111, 13, 13, 13, 111, 402, 79, 72, 80, 106, 64, 106, 106, 106, 73, 90, 74, 106, 90, 112, 112, 78, 1123, 402, 112, 79, 111, 80, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 90, 14, 14, 1122, 14, 14, 14, 112, 14, 312, 14, 14, 312, 535, 203, 14, 14, 14, 96, 90, 96, 96, 96, 96, 313, 203, 325, 535, 1121, 120, 120, 96, 120, 313, 133, 133, 14, 14, 14, 133, 99, 318, 99, 99, 318, 99, 99, 99, 325, 240, 96, 99, 128, 128, 240, 128, 203, 323, 240, 155, 155, 133, 155, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 120, 15, 15, 323, 15, 15, 15, 912, 15, 230, 15, 15, 230, 1137, 327, 15, 15, 15, 104, 230, 1137, 104, 912, 128, 104, 323, 107, 134, 134, 107, 155, 300, 134, 104, 300, 327, 15, 15, 15, 104, 328, 107, 104, 233, 233, 347, 233, 107, 347, 159, 159, 1120, 159, 1119, 134, 300, 163, 163, 352, 163, 333, 352, 328, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 300, 16, 16, 563, 16, 16, 16, 333, 16, 567, 16, 16, 233, 1115, 104, 16, 16, 16, 105, 105, 159, 105, 107, 122, 122, 122, 122, 163, 567, 105, 563, 105, 105, 105, 105, 320, 16, 16, 16, 122, 349, 349, 105, 349, 122, 187, 187, 187, 187, 1141, 244, 371, 187, 1141, 244, 1114, 371, 320, 320, 320, 244, 105, 244, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 25, 25, 25, 25, 25, 25, 25, 449, 25, 25, 449, 25, 25, 25, 718, 25, 364, 25, 25, 337, 364, 449, 25, 25, 25, 123, 123, 123, 123, 1112, 1111, 124, 124, 124, 124, 167, 167, 718, 124, 593, 167, 123, 364, 25, 25, 25, 123, 124, 125, 125, 125, 125, 124, 373, 337, 125, 178, 178, 373, 178, 1110, 593, 167, 350, 125, 350, 350, 350, 844, 125, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 337, 26, 26, 844, 26, 26, 26, 1109, 26, 342, 26, 26, 342, 1108, 1107, 26, 26, 26, 303, 303, 178, 303, 124, 1106, 127, 127, 127, 127, 145, 145, 145, 145, 146, 146, 146, 146, 26, 26, 26, 125, 127, 597, 245, 1117, 145, 127, 127, 245, 146, 145, 1105, 245, 342, 146, 1117, 355, 355, 245, 355, 245, 1104, 303, 597, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 113, 113, 51, 113, 1099, 640, 51, 51, 51, 51, 168, 168, 321, 551, 140, 168, 113, 113, 551, 366, 366, 113, 366, 640, 321, 140, 140, 51, 51, 51, 140, 596, 140, 321, 553, 186, 186, 168, 186, 553, 1096, 192, 192, 113, 192, 113, 321, 583, 195, 195, 583, 195, 140, 596, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 136, 136, 52, 136, 1095, 186, 52, 52, 52, 52, 1093, 192, 375, 375, 141, 375, 136, 136, 195, 504, 357, 136, 504, 357, 504, 141, 141, 52, 52, 52, 141, 341, 141, 341, 341, 556, 341, 341, 341, 1092, 556, 1091, 341, 136, 357, 136, 383, 383, 383, 383, 1090, 1089, 141, 383, 52, 52, 52, 52, 52, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 142, 861, 1088, 81, 81, 81, 81, 150, 150, 150, 150, 142, 142, 1087, 1086, 861, 142, 150, 142, 180, 180, 180, 180, 150, 81, 81, 81, 1085, 150, 147, 147, 147, 147, 1084, 450, 180, 147, 450, 142, 1082, 180, 198, 198, 1075, 198, 147, 207, 207, 450, 207, 147, 81, 81, 81, 81, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 1074, 1061, 1060, 82, 82, 82, 82, 181, 181, 181, 181, 602, 198, 144, 144, 207, 144, 207, 144, 185, 185, 185, 185, 181, 82, 82, 82, 147, 181, 144, 144, 1144, 558, 602, 144, 185, 144, 558, 363, 363, 185, 225, 225, 363, 225, 386, 386, 386, 386, 1144, 1058, 82, 82, 82, 82, 97, 144, 1057, 144, 148, 148, 148, 148, 1051, 426, 363, 148, 426, 97, 182, 182, 182, 182, 1050, 426, 148, 182, 396, 97, 97, 148, 396, 1049, 97, 97, 182, 225, 1129, 97, 97, 182, 97, 97, 1048, 452, 231, 231, 452, 231, 97, 97, 1047, 1129, 396, 97, 97, 169, 169, 452, 169, 97, 97, 97, 97, 97, 97, 98, 98, 98, 98, 724, 343, 169, 169, 343, 98, 408, 169, 1046, 599, 408, 148, 98, 98, 98, 1045, 177, 177, 177, 177, 231, 182, 724, 177, 1043, 248, 248, 603, 248, 169, 599, 169, 408, 98, 177, 177, 177, 177, 1021, 1020, 98, 98, 252, 252, 343, 252, 365, 365, 603, 258, 258, 365, 258, 183, 183, 183, 183, 343, 1018, 98, 183, 98, 98, 100, 100, 100, 100, 604, 608, 183, 248, 608, 100, 365, 183, 206, 206, 206, 206, 100, 100, 100, 261, 261, 1017, 261, 598, 252, 604, 598, 715, 206, 206, 206, 258, 304, 304, 1016, 304, 1015, 100, 344, 100, 1014, 344, 395, 395, 100, 100, 598, 395, 715, 206, 345, 326, 611, 345, 326, 611, 348, 345, 621, 348, 1013, 621, 183, 100, 261, 100, 100, 101, 444, 395, 101, 348, 444, 1012, 326, 304, 326, 348, 206, 101, 101, 344, 101, 101, 1011, 719, 101, 101, 101, 1010, 326, 101, 345, 345, 444, 600, 344, 326, 600, 351, 353, 722, 351, 353, 387, 387, 719, 387, 354, 354, 101, 354, 326, 627, 351, 353, 627, 493, 600, 345, 351, 353, 722, 354, 398, 398, 348, 398, 493, 354, 397, 397, 354, 359, 1009, 397, 359, 101, 139, 139, 1008, 139, 139, 139, 139, 1007, 139, 139, 359, 139, 139, 139, 1006, 139, 359, 139, 139, 397, 1005, 493, 139, 139, 139, 358, 808, 358, 358, 358, 1004, 351, 353, 358, 360, 411, 411, 360, 411, 1003, 354, 368, 368, 139, 139, 139, 368, 808, 812, 360, 390, 390, 390, 390, 1002, 360, 879, 390, 953, 391, 391, 391, 391, 1001, 701, 359, 391, 701, 368, 812, 139, 139, 139, 139, 301, 301, 301, 301, 879, 1000, 953, 368, 378, 378, 378, 378, 428, 428, 998, 428, 301, 301, 301, 379, 379, 379, 379, 997, 378, 713, 379, 993, 713, 378, 360, 381, 381, 381, 381, 379, 517, 301, 381, 517, 379, 992, 991, 990, 301, 301, 517, 381, 433, 433, 728, 433, 381, 728, 989, 382, 382, 382, 382, 385, 385, 385, 385, 301, 988, 301, 301, 302, 302, 302, 302, 382, 987, 443, 443, 385, 382, 382, 443, 612, 385, 385, 612, 302, 302, 302, 414, 414, 414, 414, 985, 379, 384, 384, 384, 384, 400, 400, 984, 384, 443, 400, 414, 381, 302, 983, 721, 414, 384, 721, 982, 302, 302, 384, 419, 419, 419, 419, 980, 438, 438, 419, 438, 400, 424, 424, 424, 424, 612, 721, 302, 424, 302, 302, 316, 794, 400, 316, 794, 316, 316, 316, 316, 316, 316, 316, 316, 316, 316, 316, 316, 316, 316, 979, 407, 978, 316, 316, 316, 316, 425, 425, 425, 425, 384, 407, 407, 425, 446, 446, 407, 446, 407, 409, 977, 445, 445, 316, 316, 316, 445, 976, 975, 413, 409, 409, 974, 459, 459, 409, 459, 409, 407, 519, 413, 413, 519, 470, 470, 413, 470, 413, 445, 519, 316, 316, 316, 316, 316, 334, 646, 409, 334, 646, 973, 334, 334, 334, 334, 972, 646, 413, 448, 448, 971, 479, 479, 448, 479, 970, 968, 334, 334, 334, 413, 415, 415, 415, 415, 967, 966, 963, 415, 417, 417, 417, 417, 962, 957, 448, 417, 415, 334, 956, 484, 484, 415, 484, 954, 417, 488, 488, 448, 488, 417, 952, 951, 418, 418, 418, 418, 950, 453, 453, 453, 453, 949, 418, 334, 453, 334, 334, 346, 418, 948, 346, 499, 499, 418, 499, 453, 453, 453, 453, 346, 346, 847, 346, 346, 847, 947, 346, 346, 346, 946, 933, 346, 415, 933, 945, 420, 420, 420, 420, 944, 417, 943, 420, 421, 421, 421, 421, 942, 941, 619, 346, 420, 619, 421, 514, 514, 420, 514, 940, 421, 520, 520, 647, 520, 421, 647, 939, 454, 454, 454, 454, 938, 647, 467, 467, 467, 467, 346, 403, 403, 467, 403, 403, 403, 403, 937, 403, 403, 454, 403, 403, 403, 619, 403, 1059, 403, 403, 1059, 619, 936, 403, 403, 403, 423, 423, 423, 423, 420, 456, 456, 456, 456, 935, 423, 934, 456, 932, 537, 537, 423, 537, 403, 403, 403, 423, 930, 456, 456, 456, 456, 473, 473, 473, 473, 927, 925, 924, 473, 462, 462, 462, 462, 523, 523, 683, 523, 923, 683, 403, 403, 403, 403, 404, 404, 462, 404, 404, 404, 404, 462, 404, 404, 922, 404, 404, 404, 921, 404, 817, 404, 404, 817, 920, 919, 404, 404, 404, 918, 917, 916, 458, 458, 458, 458, 915, 523, 914, 458, 466, 466, 466, 466, 913, 911, 910, 404, 404, 404, 458, 458, 458, 458, 683, 909, 466, 463, 463, 463, 463, 466, 908, 817, 463, 465, 465, 465, 465, 907, 817, 906, 465, 463, 404, 404, 404, 404, 463, 905, 903, 465, 468, 468, 468, 468, 465, 708, 902, 468, 469, 469, 469, 469, 474, 474, 474, 474, 468, 541, 541, 474, 541, 468, 545, 545, 469, 545, 901, 548, 548, 469, 548, 897, 609, 896, 622, 609, 622, 622, 622, 609, 708, 620, 620, 895, 620, 623, 623, 463, 623, 618, 1023, 1023, 618, 1023, 723, 465, 620, 723, 731, 892, 623, 731, 620, 891, 885, 884, 623, 708, 886, 882, 878, 886, 468, 588, 609, 877, 588, 723, 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 618, 1023, 875, 588, 588, 588, 588, 625, 625, 609, 625, 618, 626, 626, 874, 626, 628, 628, 873, 620, 731, 628, 625, 623, 588, 588, 588, 626, 625, 629, 629, 625, 872, 626, 629, 630, 630, 637, 637, 886, 630, 871, 637, 628, 633, 633, 633, 633, 870, 869, 868, 588, 588, 588, 588, 588, 629, 634, 634, 634, 634, 867, 630, 642, 637, 638, 638, 633, 866, 865, 638, 639, 639, 630, 642, 642, 639, 625, 864, 642, 634, 642, 626, 863, 1022, 651, 651, 1022, 643, 862, 651, 860, 638, 859, 741, 741, 741, 741, 639, 643, 643, 642, 652, 652, 643, 734, 643, 652, 734, 639, 641, 641, 651, 641, 641, 641, 641, 741, 641, 641, 858, 641, 641, 641, 644, 641, 643, 641, 641, 652, 856, 855, 641, 641, 641, 644, 644, 854, 653, 653, 644, 853, 644, 653, 1101, 1022, 852, 1101, 734, 654, 654, 654, 654, 641, 641, 641, 654, 655, 655, 655, 655, 851, 644, 734, 655, 653, 850, 654, 654, 654, 654, 735, 1113, 644, 735, 1113, 653, 849, 655, 848, 641, 641, 641, 641, 656, 656, 656, 656, 846, 845, 1101, 656, 657, 657, 657, 657, 712, 843, 712, 657, 712, 712, 656, 656, 656, 656, 842, 841, 840, 712, 657, 657, 657, 657, 735, 736, 736, 839, 736, 737, 737, 838, 737, 738, 738, 735, 738, 739, 739, 837, 736, 836, 739, 835, 737, 834, 736, 833, 738, 832, 737, 745, 745, 831, 738, 830, 745, 738, 743, 743, 743, 743, 827, 826, 739, 755, 755, 755, 755, 753, 753, 825, 755, 822, 753, 821, 748, 809, 745, 739, 809, 743, 816, 755, 755, 755, 755, 748, 748, 814, 813, 807, 748, 745, 748, 736, 753, 806, 815, 737, 809, 815, 805, 738, 746, 746, 802, 746, 746, 746, 746, 753, 746, 746, 748, 746, 746, 746, 800, 746, 1126, 746, 746, 1126, 799, 798, 746, 746, 746, 748, 797, 796, 756, 756, 756, 756, 795, 820, 820, 756, 793, 803, 820, 803, 792, 803, 803, 746, 746, 746, 756, 756, 756, 756, 803, 1080, 815, 791, 1080, 757, 757, 757, 757, 790, 820, 810, 757, 818, 810, 880, 818, 820, 880, 789, 746, 746, 746, 746, 747, 747, 757, 747, 747, 747, 747, 788, 747, 747, 810, 747, 747, 747, 880, 747, 958, 747, 747, 958, 770, 770, 747, 747, 747, 770, 823, 823, 770, 770, 787, 823, 818, 770, 786, 1080, 770, 770, 883, 770, 785, 883, 784, 747, 747, 747, 824, 818, 819, 819, 783, 819, 782, 823, 828, 828, 780, 824, 824, 828, 823, 883, 824, 819, 824, 888, 958, 779, 888, 819, 747, 747, 747, 747, 778, 829, 829, 829, 829, 776, 889, 828, 829, 889, 824, 775, 955, 1128, 828, 955, 1128, 824, 774, 829, 829, 829, 829, 890, 890, 893, 893, 773, 890, 894, 893, 898, 898, 772, 888, 955, 898, 771, 888, 1133, 894, 894, 1133, 959, 819, 894, 959, 894, 1136, 889, 890, 1136, 893, 769, 890, 768, 893, 960, 898, 767, 960, 765, 898, 899, 899, 899, 899, 894, 764, 889, 899, 894, 900, 900, 900, 900, 763, 1024, 762, 900, 1024, 899, 899, 899, 899, 1019, 959, 761, 1019, 760, 900, 900, 900, 900, 961, 961, 964, 964, 965, 961, 960, 964, 1139, 1143, 959, 1139, 1143, 960, 1019, 965, 965, 759, 1076, 758, 965, 1076, 965, 969, 969, 752, 1024, 961, 969, 964, 1025, 1025, 1028, 1028, 751, 1025, 750, 1028, 1033, 1033, 1029, 1076, 965, 1033, 1024, 961, 1100, 964, 744, 1100, 969, 1029, 1029, 740, 733, 732, 1029, 1025, 1029, 1028, 965, 1081, 1081, 1083, 1081, 1033, 1083, 1103, 969, 1100, 1103, 1116, 1118, 1130, 1116, 1118, 1130, 1307, 1029, 1146, 1146, 726, 1146, 725, 720, 1307, 717, 716, 1307, 1307, 1319, 710, 1319, 1319, 1319, 1323, 709, 1323, 1323, 1323, 1350, 707, 706, 705, 1081, 704, 1083, 702, 1350, 700, 1103, 1350, 1350, 1103, 699, 1118, 1130, 695, 693, 691, 690, 1083, 1146, 689, 688, 687, 686, 1116, 1118, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1148, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1149, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1150, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1151, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1152, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1153, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1154, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1155, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1156, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1157, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1158, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1160, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1162, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1163, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1164, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1165, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1166, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1167, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1168, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1169, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1170, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1171, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1172, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1173, 1174, 1174, 685, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1174, 1175, 1356, 684, 1356, 1356, 1356, 1383, 682, 1383, 1383, 1383, 681, 680, 679, 678, 1175, 677, 1175, 1175, 1175, 676, 675, 674, 673, 1175, 1176, 672, 1176, 1176, 671, 1176, 670, 667, 666, 1176, 1176, 665, 1176, 1176, 1176, 1177, 664, 1177, 1177, 1177, 1177, 663, 1177, 662, 659, 658, 1177, 1177, 1177, 1177, 1177, 1177, 1178, 1178, 1178, 650, 649, 648, 645, 636, 1178, 635, 632, 607, 606, 1178, 1178, 1178, 1178, 1178, 1178, 1178, 1178, 1178, 605, 1178, 1178, 1179, 595, 1179, 1179, 594, 1179, 592, 590, 589, 1179, 1179, 587, 1179, 1179, 1179, 1180, 1180, 1180, 584, 582, 580, 579, 578, 1180, 576, 574, 572, 571, 1180, 1180, 1180, 1180, 1180, 1180, 1180, 1180, 1180, 568, 1180, 1180, 1181, 1181, 565, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1181, 1182, 562, 560, 559, 557, 555, 1182, 554, 1182, 1182, 1182, 1182, 1182, 552, 550, 1182, 1182, 1182, 1182, 1182, 1182, 547, 543, 539, 536, 1182, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1183, 1184, 534, 1184, 1184, 1184, 533, 532, 530, 529, 1184, 1185, 526, 1185, 1185, 525, 522, 516, 1185, 513, 1185, 1185, 1185, 512, 508, 506, 505, 1185, 1186, 1186, 1186, 1186, 503, 501, 1186, 498, 496, 495, 492, 490, 486, 483, 1186, 482, 481, 1186, 478, 477, 476, 1186, 472, 1186, 1186, 1186, 464, 461, 457, 1186, 1186, 1187, 1187, 1187, 1187, 441, 440, 436, 435, 431, 430, 416, 410, 405, 401, 1187, 393, 1187, 1187, 1187, 392, 389, 1187, 380, 1187, 1187, 1187, 377, 374, 372, 369, 1187, 1188, 1188, 1188, 1188, 361, 336, 1188, 335, 332, 330, 329, 319, 317, 310, 309, 306, 305, 295, 292, 291, 287, 1188, 283, 1188, 1188, 1188, 282, 279, 275, 274, 1188, 1189, 1189, 271, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1189, 1190, 266, 235, 221, 220, 219, 1190, 215, 1190, 1190, 1190, 1190, 1190, 214, 210, 1190, 1190, 1190, 1190, 1190, 1190, 205, 202, 194, 191, 1190, 1191, 1191, 184, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1191, 1192, 1192, 166, 162, 158, 149, 135, 1192, 132, 1192, 1192, 1192, 1192, 1192, 126, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 114, 110, 94, 93, 1192, 1193, 1193, 1193, 1193, 92, 87, 1193, 8, 7, 0, 0, 0, 0, 0, 1193, 0, 0, 1193, 0, 0, 0, 1193, 0, 1193, 1193, 1193, 0, 0, 0, 1193, 1193, 1194, 1194, 1194, 1194, 0, 0, 0, 0, 1194, 0, 0, 0, 0, 0, 1194, 0, 1194, 1194, 0, 0, 0, 1194, 0, 1194, 1194, 1194, 0, 0, 0, 0, 1194, 1195, 1195, 1195, 1195, 0, 0, 1195, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1195, 0, 1195, 1195, 1195, 0, 0, 0, 0, 1195, 1196, 0, 0, 1196, 0, 0, 0, 0, 1196, 0, 1196, 1196, 1196, 0, 0, 0, 0, 1196, 1197, 1197, 0, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1198, 1198, 0, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1198, 1199, 1199, 0, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1199, 1200, 0, 0, 0, 0, 0, 1200, 0, 1200, 1200, 1200, 1200, 1200, 0, 0, 1200, 1200, 1200, 1200, 1200, 1200, 0, 0, 0, 0, 1200, 1201, 0, 1201, 1201, 1201, 0, 0, 0, 0, 1201, 1202, 0, 0, 1202, 0, 0, 0, 0, 0, 0, 0, 0, 1202, 0, 0, 0, 1202, 0, 0, 0, 0, 1202, 0, 1202, 1202, 1202, 0, 0, 0, 0, 1202, 1203, 0, 1203, 1203, 1203, 0, 0, 0, 0, 1203, 1204, 1204, 1204, 1204, 0, 0, 1204, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1204, 1204, 0, 0, 0, 1204, 0, 1204, 1204, 1204, 0, 0, 0, 0, 1204, 1205, 1205, 1205, 1205, 0, 0, 1205, 0, 0, 0, 0, 0, 0, 0, 1205, 0, 0, 1205, 0, 0, 0, 1205, 0, 1205, 1205, 1205, 0, 0, 0, 1205, 1205, 1206, 1206, 1206, 1206, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1206, 0, 1206, 1206, 0, 0, 0, 1206, 0, 1206, 1206, 1206, 0, 0, 0, 0, 1206, 1207, 1207, 1207, 1207, 0, 0, 1207, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1207, 0, 1207, 1207, 1207, 0, 0, 0, 0, 1207, 1208, 0, 1208, 1208, 1208, 0, 0, 0, 0, 1208, 1209, 0, 1209, 0, 0, 0, 0, 1209, 0, 1209, 1209, 1209, 0, 0, 0, 0, 1209, 1210, 1210, 0, 1210, 0, 0, 0, 0, 1210, 0, 1210, 1210, 1210, 0, 0, 0, 0, 1210, 1211, 1211, 0, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 0, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 0, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1211, 1212, 0, 0, 1212, 0, 0, 0, 0, 1212, 0, 1212, 1212, 1212, 0, 0, 0, 0, 1212, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 0, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1214, 1214, 0, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 0, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1214, 1215, 1215, 0, 1215, 0, 1215, 1215, 1215, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1215, 1215, 1215, 0, 1215, 1215, 0, 0, 0, 0, 0, 1215, 1216, 0, 0, 1216, 0, 0, 0, 0, 1216, 0, 1216, 1216, 1216, 0, 0, 0, 0, 1216, 1217, 1217, 0, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1217, 1218, 1218, 0, 1218, 0, 1218, 1218, 1218, 1218, 1218, 1218, 0, 1218, 1218, 1218, 1218, 0, 1218, 1218, 1218, 1218, 0, 1218, 0, 1218, 1218, 1218, 1218, 1218, 1218, 1218, 1218, 1219, 0, 0, 1219, 0, 0, 0, 0, 1219, 0, 0, 0, 0, 1219, 1219, 0, 1219, 0, 0, 0, 0, 1219, 0, 1219, 1219, 1219, 1220, 1220, 0, 1220, 0, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 0, 1220, 0, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1220, 1221, 1221, 0, 1221, 0, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 0, 1221, 0, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1221, 1222, 0, 0, 1222, 0, 0, 0, 0, 1222, 0, 1222, 1222, 1222, 0, 0, 0, 0, 1222, 1223, 1223, 0, 1223, 1223, 1223, 1223, 1223, 1223, 0, 0, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 0, 1223, 0, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1223, 1224, 0, 1224, 1224, 1224, 0, 0, 0, 0, 1224, 1225, 0, 1225, 1225, 0, 0, 0, 1225, 0, 1225, 1225, 1225, 0, 0, 0, 0, 1225, 1226, 0, 1226, 1226, 1226, 0, 0, 0, 0, 1226, 1227, 0, 1227, 1227, 0, 0, 0, 1227, 0, 1227, 1227, 1227, 0, 0, 0, 0, 1227, 1228, 1228, 0, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 0, 1228, 0, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1228, 1229, 0, 0, 1229, 0, 0, 0, 0, 1229, 0, 1229, 1229, 1229, 0, 0, 0, 0, 1229, 1230, 1230, 0, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 0, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 0, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 1230, 1231, 1231, 0, 1231, 1231, 1231, 1231, 1231, 1231, 1231, 1231, 0, 1231, 1231, 1231, 1231, 1231, 1231, 1231, 1231, 1231, 0, 1231, 0, 1231, 1231, 1231, 1231, 1231, 1231, 1231, 1231, 1232, 0, 1232, 1232, 1232, 1232, 1232, 0, 0, 0, 1232, 0, 1232, 1232, 1232, 0, 0, 0, 0, 1232, 1233, 1233, 0, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 0, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1233, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 0, 0, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1234, 1235, 1235, 1235, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1235, 1235, 1235, 1235, 1235, 1235, 1235, 1235, 1235, 0, 1235, 1235, 1236, 1236, 0, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1236, 1237, 0, 1237, 1237, 1237, 0, 0, 0, 0, 1237, 1238, 1238, 0, 0, 0, 1238, 0, 1238, 1238, 1238, 0, 0, 0, 0, 1238, 1239, 0, 1239, 1239, 0, 1239, 0, 0, 0, 1239, 1239, 0, 1239, 1239, 1239, 1240, 0, 0, 1240, 0, 0, 0, 0, 1240, 0, 1240, 1240, 1240, 1241, 0, 0, 1241, 0, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1241, 1242, 0, 1242, 1242, 1242, 0, 0, 0, 1242, 1243, 0, 0, 0, 0, 0, 0, 0, 1243, 0, 1243, 1243, 1243, 1244, 0, 1244, 1244, 0, 1244, 0, 0, 0, 1244, 1244, 0, 1244, 1244, 1244, 1245, 0, 0, 1245, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1245, 1245, 1245, 1245, 1245, 1246, 1246, 0, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1246, 1247, 0, 0, 0, 0, 0, 1247, 0, 1247, 1247, 1247, 1247, 1247, 0, 0, 1247, 1247, 1247, 1247, 1247, 1247, 0, 0, 0, 0, 1247, 1248, 0, 0, 0, 0, 0, 1248, 0, 1248, 0, 1248, 1248, 1248, 0, 0, 1248, 1248, 1248, 1248, 1248, 1248, 0, 0, 0, 0, 1248, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1249, 1250, 0, 1250, 1250, 0, 0, 0, 1250, 0, 1250, 1250, 1250, 0, 0, 0, 0, 1250, 1251, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1251, 0, 1251, 1251, 1251, 0, 0, 0, 0, 1251, 1252, 1252, 1252, 1252, 0, 0, 1252, 0, 0, 0, 0, 0, 0, 0, 1252, 0, 0, 1252, 0, 0, 0, 1252, 0, 1252, 1252, 1252, 0, 0, 0, 1252, 1252, 1253, 1253, 1253, 1253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1253, 0, 1253, 1253, 1253, 0, 0, 1253, 0, 1253, 1253, 1253, 0, 0, 0, 0, 1253, 1254, 1254, 1254, 1254, 0, 0, 1254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1254, 0, 1254, 1254, 1254, 0, 0, 0, 0, 1254, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 0, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1255, 1256, 0, 1256, 0, 0, 1256, 0, 1256, 1256, 1256, 0, 0, 0, 0, 1256, 1257, 1257, 0, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1257, 1258, 0, 0, 0, 0, 0, 1258, 0, 1258, 1258, 1258, 1258, 1258, 0, 0, 1258, 1258, 1258, 1258, 1258, 1258, 0, 0, 0, 0, 1258, 1259, 0, 0, 0, 0, 0, 1259, 0, 1259, 0, 1259, 1259, 1259, 0, 0, 1259, 1259, 1259, 1259, 1259, 1259, 0, 0, 0, 0, 1259, 1260, 1260, 0, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1260, 1261, 1261, 0, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1261, 1262, 1262, 0, 0, 0, 0, 0, 1262, 0, 1262, 1262, 1262, 1262, 1262, 0, 1262, 1262, 1262, 1262, 1262, 1262, 1262, 0, 0, 0, 0, 1262, 1263, 0, 0, 0, 0, 0, 1263, 0, 1263, 0, 1263, 1263, 1263, 0, 0, 1263, 1263, 1263, 1263, 1263, 1263, 0, 0, 0, 0, 1263, 1264, 1264, 1264, 1264, 0, 0, 1264, 0, 0, 0, 0, 0, 0, 0, 1264, 0, 0, 1264, 0, 0, 0, 1264, 0, 1264, 1264, 1264, 0, 0, 0, 1264, 1264, 1265, 1265, 1265, 1265, 0, 0, 0, 0, 1265, 0, 0, 0, 0, 0, 1265, 0, 1265, 1265, 0, 0, 0, 1265, 0, 1265, 1265, 1265, 0, 0, 0, 0, 1265, 1266, 1266, 1266, 1266, 0, 0, 1266, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1266, 0, 1266, 1266, 1266, 0, 0, 0, 0, 1266, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 0, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1267, 1268, 0, 0, 1268, 0, 0, 0, 0, 1268, 0, 0, 0, 0, 0, 0, 0, 1268, 0, 0, 0, 0, 1268, 0, 1268, 1268, 1268, 0, 0, 0, 0, 1268, 1269, 0, 0, 1269, 0, 0, 0, 0, 1269, 0, 1269, 1269, 1269, 0, 0, 0, 0, 1269, 1270, 1270, 0, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1270, 1271, 1271, 0, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1271, 1272, 1272, 0, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1272, 1273, 0, 0, 0, 0, 0, 1273, 0, 1273, 1273, 1273, 1273, 1273, 0, 0, 1273, 1273, 1273, 1273, 1273, 1273, 0, 0, 0, 0, 1273, 1274, 0, 0, 0, 0, 0, 1274, 0, 1274, 0, 1274, 1274, 1274, 0, 0, 1274, 1274, 1274, 1274, 1274, 1274, 0, 0, 0, 0, 1274, 1275, 0, 0, 1275, 0, 0, 0, 0, 0, 0, 0, 0, 1275, 0, 0, 0, 1275, 0, 0, 0, 0, 1275, 0, 1275, 1275, 1275, 0, 0, 0, 0, 1275, 1276, 1276, 1276, 1276, 0, 0, 1276, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1276, 1276, 0, 0, 0, 1276, 0, 1276, 1276, 1276, 0, 0, 0, 0, 1276, 1277, 0, 1277, 1277, 1277, 0, 0, 0, 0, 1277, 1278, 1278, 1278, 1278, 0, 0, 1278, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1278, 1278, 0, 0, 0, 1278, 0, 1278, 1278, 1278, 0, 0, 0, 0, 1278, 1279, 1279, 1279, 1279, 0, 0, 1279, 0, 0, 0, 0, 0, 0, 0, 1279, 0, 0, 1279, 0, 0, 0, 1279, 0, 1279, 1279, 1279, 0, 0, 0, 1279, 1279, 1280, 1280, 1280, 1280, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1280, 0, 1280, 1280, 0, 0, 0, 1280, 0, 1280, 1280, 1280, 0, 0, 0, 0, 1280, 1281, 1281, 1281, 1281, 0, 0, 1281, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1281, 0, 1281, 1281, 1281, 0, 0, 0, 0, 1281, 1282, 0, 0, 0, 0, 1282, 0, 1282, 1282, 1282, 0, 0, 0, 0, 1282, 1283, 0, 1283, 0, 0, 0, 0, 1283, 0, 1283, 1283, 1283, 0, 0, 0, 0, 1283, 1284, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1284, 0, 1284, 1284, 1284, 0, 0, 0, 0, 1284, 1285, 1285, 0, 1285, 0, 0, 0, 0, 1285, 0, 1285, 1285, 1285, 0, 0, 0, 0, 1285, 1286, 1286, 0, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 0, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 0, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 1286, 1287, 0, 0, 1287, 0, 0, 0, 0, 1287, 0, 1287, 1287, 1287, 0, 0, 0, 0, 1287, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 0, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1288, 1289, 1289, 0, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 0, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1289, 1290, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1290, 0, 1290, 1290, 1290, 0, 0, 0, 0, 1290, 1291, 0, 0, 1291, 0, 0, 0, 0, 1291, 0, 1291, 1291, 1291, 0, 0, 0, 0, 1291, 1292, 1292, 0, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1292, 1293, 1293, 0, 1293, 0, 1293, 1293, 1293, 1293, 1293, 1293, 0, 1293, 1293, 1293, 1293, 0, 1293, 1293, 1293, 1293, 0, 1293, 0, 1293, 1293, 1293, 1293, 1293, 1293, 1293, 1293, 1294, 0, 0, 1294, 0, 0, 0, 0, 1294, 0, 0, 0, 0, 1294, 1294, 0, 1294, 0, 0, 0, 0, 1294, 0, 1294, 1294, 1294, 1295, 1295, 0, 1295, 0, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 0, 1295, 0, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1295, 1296, 1296, 0, 1296, 0, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 0, 1296, 0, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1296, 1297, 0, 0, 1297, 0, 0, 0, 0, 1297, 0, 1297, 1297, 1297, 0, 0, 0, 0, 1297, 1298, 1298, 0, 1298, 1298, 1298, 1298, 1298, 1298, 0, 0, 1298, 1298, 1298, 1298, 1298, 1298, 1298, 1298, 1298, 1298, 0, 1298, 0, 1298, 1298, 1298, 1298, 1298, 1298, 1298, 1298, 1299, 0, 1299, 1299, 0, 0, 0, 1299, 0, 1299, 1299, 1299, 0, 0, 0, 0, 1299, 1300, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1300, 0, 1300, 1300, 1300, 0, 0, 0, 0, 1300, 1301, 0, 1301, 1301, 0, 0, 0, 1301, 0, 1301, 1301, 1301, 0, 0, 0, 0, 1301, 1302, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1302, 0, 1302, 1302, 1302, 0, 0, 0, 0, 1302, 1303, 1303, 0, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 0, 1303, 0, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1304, 0, 0, 1304, 0, 0, 0, 0, 1304, 0, 1304, 1304, 1304, 0, 0, 0, 0, 1304, 1305, 1305, 0, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 0, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 0, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1306, 1306, 0, 1306, 1306, 1306, 1306, 1306, 1306, 1306, 1306, 0, 1306, 1306, 1306, 1306, 1306, 1306, 1306, 1306, 1306, 0, 1306, 0, 1306, 1306, 1306, 1306, 1306, 1306, 1306, 1306, 1308, 0, 1308, 1308, 1308, 1308, 1308, 0, 0, 0, 1308, 0, 1308, 1308, 1308, 0, 0, 0, 0, 1308, 1309, 0, 0, 0, 0, 1309, 0, 1309, 1309, 1309, 0, 0, 0, 0, 1309, 1310, 1310, 0, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 0, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1310, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 0, 0, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1311, 1312, 1312, 0, 0, 0, 1312, 0, 1312, 1312, 1312, 0, 0, 0, 0, 1312, 1313, 1313, 0, 1313, 1313, 1313, 1313, 0, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1313, 1314, 1314, 0, 1314, 0, 0, 0, 0, 1314, 0, 1314, 1314, 1314, 1315, 0, 1315, 1315, 0, 1315, 0, 0, 0, 1315, 1315, 0, 1315, 1315, 1315, 1316, 0, 0, 1316, 0, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1316, 1317, 1317, 0, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1317, 1318, 0, 0, 1318, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1318, 0, 1318, 1318, 1318, 1320, 0, 0, 1320, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1320, 0, 1320, 1320, 1320, 1321, 1321, 0, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 1321, 0, 1321, 1321, 1322, 0, 0, 0, 0, 0, 0, 0, 1322, 0, 1322, 1322, 1322, 1324, 0, 0, 1324, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1324, 1324, 1324, 1324, 1324, 1325, 0, 0, 0, 0, 0, 1325, 0, 1325, 1325, 1325, 1325, 1325, 0, 0, 1325, 1325, 1325, 1325, 1325, 1325, 0, 0, 0, 0, 1325, 1326, 0, 0, 0, 0, 0, 1326, 0, 1326, 1326, 1326, 1326, 1326, 0, 0, 1326, 1326, 1326, 1326, 1326, 1326, 0, 0, 0, 0, 1326, 1327, 0, 1327, 1327, 1327, 0, 0, 0, 0, 1327, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1328, 1329, 0, 1329, 0, 0, 1329, 0, 1329, 1329, 1329, 0, 0, 0, 0, 1329, 1330, 0, 0, 0, 0, 0, 1330, 0, 1330, 1330, 1330, 1330, 1330, 0, 0, 1330, 1330, 1330, 1330, 1330, 1330, 0, 0, 0, 0, 1330, 1331, 0, 0, 0, 0, 0, 1331, 0, 1331, 1331, 1331, 1331, 1331, 0, 0, 1331, 1331, 1331, 1331, 1331, 1331, 0, 0, 0, 0, 1331, 1332, 1332, 0, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1333, 1333, 0, 0, 0, 0, 0, 1333, 0, 1333, 1333, 1333, 1333, 1333, 0, 1333, 1333, 1333, 1333, 1333, 1333, 1333, 0, 0, 0, 0, 1333, 1334, 1334, 0, 0, 0, 0, 0, 1334, 0, 1334, 1334, 1334, 1334, 1334, 0, 1334, 1334, 1334, 1334, 1334, 1334, 1334, 0, 0, 0, 0, 1334, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1335, 1336, 0, 0, 1336, 0, 0, 0, 0, 1336, 0, 0, 0, 0, 0, 0, 0, 1336, 0, 0, 0, 0, 1336, 0, 1336, 1336, 1336, 0, 0, 0, 0, 1336, 1337, 0, 0, 0, 0, 0, 1337, 0, 1337, 1337, 1337, 1337, 1337, 0, 0, 1337, 1337, 1337, 1337, 1337, 1337, 0, 0, 0, 0, 1337, 1338, 0, 0, 0, 0, 0, 1338, 0, 1338, 1338, 1338, 1338, 1338, 0, 0, 1338, 1338, 1338, 1338, 1338, 1338, 0, 0, 0, 0, 1338, 1339, 1339, 1339, 1339, 0, 0, 1339, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1339, 1339, 0, 0, 0, 1339, 0, 1339, 1339, 1339, 0, 0, 0, 0, 1339, 1340, 1340, 1340, 1340, 0, 0, 1340, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1340, 0, 0, 0, 1340, 0, 1340, 1340, 1340, 0, 0, 0, 0, 1340, 1341, 1341, 1341, 1341, 0, 0, 1341, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1341, 1341, 0, 0, 0, 1341, 0, 1341, 1341, 1341, 0, 0, 0, 0, 1341, 1342, 0, 0, 0, 0, 1342, 0, 1342, 1342, 1342, 0, 0, 0, 0, 1342, 1343, 0, 1343, 1343, 1343, 0, 0, 0, 0, 1343, 1344, 0, 1344, 0, 0, 0, 0, 1344, 0, 1344, 1344, 1344, 0, 0, 0, 0, 1344, 1345, 0, 1345, 1345, 1345, 0, 0, 0, 0, 1345, 1346, 0, 0, 0, 0, 1346, 0, 1346, 1346, 1346, 0, 0, 0, 0, 1346, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 0, 1347, 1347, 1347, 1347, 0, 1347, 0, 0, 1347, 1347, 1347, 1347, 1347, 1347, 1348, 0, 1348, 1348, 1348, 0, 0, 0, 0, 1348, 1349, 0, 1349, 1349, 1349, 0, 0, 0, 0, 1349, 1351, 0, 1351, 1351, 1351, 1351, 1351, 0, 0, 0, 1351, 0, 1351, 1351, 1351, 0, 0, 0, 0, 1351, 1352, 1352, 0, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1353, 0, 0, 1353, 0, 0, 0, 0, 1353, 0, 1353, 1353, 1353, 1354, 0, 1354, 0, 1354, 1354, 0, 1354, 0, 0, 0, 1354, 1354, 0, 1354, 1354, 1354, 1355, 1355, 0, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1355, 1357, 0, 0, 1357, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1357, 0, 1357, 1357, 1357, 1358, 1358, 0, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1359, 1359, 1359, 1359, 1359, 1360, 0, 0, 1360, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1360, 1360, 1360, 1360, 1360, 1361, 1361, 0, 1361, 0, 0, 0, 0, 0, 0, 0, 1361, 0, 1361, 1361, 0, 1361, 1361, 0, 0, 1361, 1361, 0, 1361, 1361, 1361, 0, 1361, 1362, 0, 0, 0, 0, 0, 1362, 0, 1362, 1362, 1362, 1362, 1362, 0, 0, 1362, 1362, 1362, 1362, 1362, 1362, 0, 0, 0, 0, 1362, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1363, 1364, 0, 0, 0, 0, 0, 1364, 0, 1364, 1364, 1364, 1364, 1364, 0, 0, 1364, 1364, 1364, 1364, 1364, 1364, 0, 0, 0, 0, 1364, 1365, 1365, 0, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1366, 1366, 0, 0, 0, 0, 0, 1366, 0, 1366, 1366, 1366, 1366, 1366, 0, 1366, 1366, 1366, 1366, 1366, 1366, 1366, 0, 0, 0, 0, 1366, 1367, 0, 0, 0, 0, 0, 1367, 0, 1367, 1367, 1367, 1367, 1367, 0, 0, 1367, 1367, 1367, 1367, 1367, 1367, 0, 0, 0, 0, 1367, 1368, 0, 1368, 1368, 1368, 0, 0, 0, 0, 1368, 1369, 1369, 1369, 1369, 0, 0, 1369, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1369, 1369, 0, 0, 0, 1369, 0, 1369, 1369, 1369, 0, 0, 0, 0, 1369, 1370, 1370, 1370, 1370, 0, 0, 1370, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1370, 0, 0, 0, 1370, 0, 1370, 1370, 1370, 0, 0, 0, 0, 1370, 1371, 0, 1371, 0, 0, 0, 0, 1371, 0, 1371, 1371, 1371, 0, 0, 0, 0, 1371, 1372, 0, 0, 0, 0, 1372, 0, 1372, 1372, 1372, 0, 0, 0, 0, 1372, 1373, 1373, 0, 1373, 0, 0, 0, 0, 1373, 0, 1373, 1373, 1373, 1374, 1374, 0, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1374, 1375, 1375, 1375, 1375, 0, 0, 1375, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1375, 1375, 0, 0, 0, 1375, 0, 1375, 1375, 1375, 0, 0, 0, 0, 1375, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 1376, 0, 1376, 1376, 1376, 1376, 0, 1376, 0, 1376, 0, 1376, 1376, 1376, 1376, 1376, 1377, 1377, 0, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1377, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 1378, 0, 1378, 1378, 1378, 1378, 0, 1378, 0, 0, 0, 1378, 1378, 1378, 1378, 1378, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 1379, 0, 1379, 1379, 1379, 1379, 0, 1379, 0, 0, 0, 1379, 1379, 1379, 1379, 1379, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 1380, 0, 1380, 1380, 1380, 1380, 0, 1380, 0, 0, 0, 1380, 1380, 1380, 1380, 1380, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 1381, 0, 1381, 1381, 1381, 1381, 0, 1381, 0, 0, 0, 1381, 1381, 1381, 1381, 1381, 1382, 1382, 0, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1382, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147, 1147 } ; extern int commentscanYY_flex_debug; int commentscanYY_flex_debug = 0; static yy_state_type *yy_state_buf=0, *yy_state_ptr=0; static char *yy_full_match; static int yy_lp; static int yy_looking_for_trail_begin = 0; static int yy_full_lp; static int *yy_full_state; #define YY_TRAILING_MASK 0x2000 #define YY_TRAILING_HEAD_MASK 0x4000 #define REJECT \ { \ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ \ yy_cp = (yy_full_match); /* restore poss. backed-over text */ \ (yy_lp) = (yy_full_lp); /* restore orig. accepting pos. */ \ (yy_state_ptr) = (yy_full_state); /* restore orig. state */ \ yy_current_state = *(yy_state_ptr); /* restore curr. state */ \ ++(yy_lp); \ goto find_rule; \ } #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *commentscanYYtext; #line 1 "commentscan.l" /***************************************************************************** * * Copyright (C) 1997-2015 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ #line 20 "commentscan.l" /* * includes */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <ctype.h> #include <qarray.h> #include <qstack.h> #include <qregexp.h> #include <qfile.h> #include "scanner.h" #include "entry.h" #include "doxygen.h" #include "message.h" #include "config.h" #include "util.h" #include "index.h" #include "defargs.h" #include "language.h" #include "outputlist.h" #include "membergroup.h" #include "reflist.h" #include "debug.h" #include "parserintf.h" #include "cite.h" #include "markdown.h" #include "condparser.h" #include "formula.h" #define YY_NO_INPUT 1 #define YY_NO_UNISTD_H 1 // forward declarations static bool handleBrief(const QCString &); static bool handleFn(const QCString &); static bool handleDef(const QCString &); static bool handleOverload(const QCString &); static bool handleEnum(const QCString &); static bool handleDefGroup(const QCString &); static bool handleAddToGroup(const QCString &); static bool handleWeakGroup(const QCString &); static bool handleNamespace(const QCString &); static bool handlePackage(const QCString &); static bool handleClass(const QCString &); static bool handleHeaderFile(const QCString &); static bool handleProtocol(const QCString &); static bool handleCategory(const QCString &); static bool handleUnion(const QCString &); static bool handleStruct(const QCString &); static bool handleInterface(const QCString &); static bool handleIdlException(const QCString &); static bool handlePage(const QCString &); static bool handleMainpage(const QCString &); static bool handleFile(const QCString &); static bool handleDir(const QCString &); static bool handleExample(const QCString &); static bool handleDetails(const QCString &); static bool handleName(const QCString &); static bool handleTodo(const QCString &); static bool handleTest(const QCString &); static bool handleBug(const QCString &); static bool handleSubpage(const QCString &s); static bool handleDeprecated(const QCString &); static bool handleXRefItem(const QCString &); static bool handleRelated(const QCString &); static bool handleRelatedAlso(const QCString &); static bool handleMemberOf(const QCString &); static bool handleRefItem(const QCString &); static bool handleSection(const QCString &); static bool handleAnchor(const QCString &); static bool handleCite(const QCString &); static bool handleFormatBlock(const QCString &); static bool handleAddIndex(const QCString &); static bool handleIf(const QCString &); static bool handleIfNot(const QCString &); static bool handleElseIf(const QCString &); static bool handleElse(const QCString &); static bool handleEndIf(const QCString &); static bool handleIngroup(const QCString &); static bool handleNoSubGrouping(const QCString &); static bool handleShowInitializer(const QCString &); static bool handleHideInitializer(const QCString &); static bool handleCallgraph(const QCString &); static bool handleHideCallgraph(const QCString &); static bool handleCallergraph(const QCString &); static bool handleHideCallergraph(const QCString &); static bool handleInternal(const QCString &); static bool handleLineBr(const QCString &); static bool handleStatic(const QCString &); static bool handlePure(const QCString &); static bool handlePrivate(const QCString &); static bool handlePrivateSection(const QCString &); static bool handleProtected(const QCString &); static bool handleProtectedSection(const QCString &); static bool handlePublic(const QCString &s); static bool handlePublicSection(const QCString &s); static bool handleToc(const QCString &s); static bool handleInherit(const QCString &); static bool handleExtends(const QCString &); static bool handleCopyDoc(const QCString &); static bool handleCopyBrief(const QCString &); static bool handleCopyDetails(const QCString &); static bool handleParBlock(const QCString &); static bool handleEndParBlock(const QCString &); static bool handleParam(const QCString &); static bool handleRetval(const QCString &); typedef bool (*DocCmdFunc)(const QCString &name); struct DocCmdMap { const char *cmdName; DocCmdFunc handler; bool endsBrief; }; // map of command to handler function static DocCmdMap docCmdMap[] = { // command name handler function ends brief description { "brief", &handleBrief, FALSE }, { "short", &handleBrief, FALSE }, { "fn", &handleFn, FALSE }, { "var", &handleFn, FALSE }, { "typedef", &handleFn, FALSE }, { "property", &handleFn, FALSE }, { "def", &handleDef, FALSE }, { "overload", &handleOverload, FALSE }, { "enum", &handleEnum, FALSE }, { "defgroup", &handleDefGroup, FALSE }, { "addtogroup", &handleAddToGroup, FALSE }, { "weakgroup", &handleWeakGroup, FALSE }, { "namespace", &handleNamespace, FALSE }, { "package", &handlePackage, FALSE }, { "class", &handleClass, FALSE }, { "headerfile", &handleHeaderFile, FALSE }, { "protocol", &handleProtocol, FALSE }, { "category", &handleCategory, FALSE }, { "union", &handleUnion, FALSE }, { "struct", &handleStruct, FALSE }, { "interface", &handleInterface, FALSE }, { "idlexcept", &handleIdlException, FALSE }, { "page", &handlePage, FALSE }, { "mainpage", &handleMainpage, FALSE }, { "file", &handleFile, FALSE }, { "dir", &handleDir, FALSE }, { "example", &handleExample, FALSE }, { "details", &handleDetails, TRUE }, { "name", &handleName, FALSE }, { "todo", &handleTodo, FALSE }, // end brief will be done differently { "test", &handleTest, FALSE }, // end brief will be done differently { "bug", &handleBug, FALSE }, // end brief will be done differently { "deprecated", &handleDeprecated, FALSE }, // end brief will be done differently { "xrefitem", &handleXRefItem, FALSE }, // end brief will be done differently { "related", &handleRelated, TRUE }, { "relates", &handleRelated, TRUE }, { "relatedalso", &handleRelatedAlso, TRUE }, { "relatesalso", &handleRelatedAlso, TRUE }, { "parblock", &handleParBlock, TRUE }, { "endparblock", &handleEndParBlock, TRUE }, { "refitem", &handleRefItem, TRUE }, { "cite", &handleCite, FALSE }, { "subpage", &handleSubpage, TRUE }, { "section", &handleSection, TRUE }, { "subsection", &handleSection, TRUE }, { "subsubsection", &handleSection, TRUE }, { "paragraph", &handleSection, TRUE }, { "anchor", &handleAnchor, TRUE }, { "verbatim", &handleFormatBlock, TRUE }, { "latexonly", &handleFormatBlock, FALSE }, { "htmlonly", &handleFormatBlock, FALSE }, { "xmlonly", &handleFormatBlock, FALSE }, { "docbookonly", &handleFormatBlock, FALSE }, { "rtfonly", &handleFormatBlock, FALSE }, { "manonly", &handleFormatBlock, FALSE }, { "dot", &handleFormatBlock, TRUE }, { "msc", &handleFormatBlock, TRUE }, { "startuml", &handleFormatBlock, TRUE }, { "code", &handleFormatBlock, TRUE }, { "addindex", &handleAddIndex, FALSE }, { "if", &handleIf, FALSE }, { "ifnot", &handleIfNot, FALSE }, { "elseif", &handleElseIf, FALSE }, { "else", &handleElse, FALSE }, { "endif", &handleEndIf, FALSE }, { "ingroup", &handleIngroup, FALSE }, { "nosubgrouping", &handleNoSubGrouping, FALSE }, { "showinitializer", &handleShowInitializer, FALSE }, { "hideinitializer", &handleHideInitializer, FALSE }, { "callgraph", &handleCallgraph, FALSE }, { "hidecallgraph", &handleHideCallgraph, FALSE }, { "callergraph", &handleCallergraph, FALSE }, { "hidecallergraph", &handleHideCallergraph, FALSE }, { "internal", &handleInternal, TRUE }, { "_linebr", &handleLineBr, FALSE }, { "static", &handleStatic, FALSE }, { "pure", &handlePure, FALSE }, { "private", &handlePrivate, FALSE }, { "privatesection", &handlePrivateSection, FALSE }, { "protected", &handleProtected, FALSE }, { "protectedsection",&handleProtectedSection, FALSE }, { "public", &handlePublic, FALSE }, { "publicsection", &handlePublicSection, FALSE }, { "tableofcontents", &handleToc, FALSE }, { "inherit", &handleInherit, TRUE }, { "extends", &handleExtends, TRUE }, { "implements", &handleExtends, TRUE }, { "memberof", &handleMemberOf, TRUE }, { "arg", 0, TRUE }, { "attention", 0, TRUE }, { "author", 0, TRUE }, { "authors", 0, TRUE }, { "copydoc", &handleCopyDoc, TRUE }, { "copybrief", &handleCopyBrief, FALSE }, { "copydetails", &handleCopyDetails, TRUE }, { "copyright", 0, TRUE }, { "date", 0, TRUE }, { "dotfile", 0, TRUE }, { "htmlinclude", 0, FALSE }, { "image", 0, TRUE }, { "include", 0, TRUE }, { "includelineno", 0, TRUE }, { "invariant", 0, TRUE }, { "latexinclude", 0, FALSE }, { "li", 0, TRUE }, { "line", 0, TRUE }, { "note", 0, TRUE }, { "par", 0, TRUE }, { "param", &handleParam, TRUE }, { "tparam", 0, TRUE }, { "post", 0, TRUE }, { "pre", 0, TRUE }, { "remark", 0, TRUE }, { "remarks", 0, TRUE }, { "result", 0, TRUE }, { "return", 0, TRUE }, { "returns", 0, TRUE }, { "exception", 0, TRUE }, { "retval", &handleRetval, TRUE }, { "sa", 0, TRUE }, { "see", 0, TRUE }, { "since", 0, TRUE }, { "throw", 0, TRUE }, { "throws", 0, TRUE }, { "until", 0, TRUE }, { "verbinclude", 0, FALSE }, { "version", 0, TRUE }, { "warning", 0, TRUE }, { 0, 0, FALSE } }; /** @brief Command mapper. * * Maps a command name (as found in a comment block) onto a * specific handler function. */ class DocCmdMapper { public: struct Cmd { DocCmdFunc func; bool endsBrief; }; /** maps a command name to a handler function */ static Cmd *map(const char *name) { return instance()->find(name); } /** release the singleton */ static void freeInstance() { delete s_instance; s_instance=0; } private: static DocCmdMapper *instance() { if (s_instance==0) s_instance = new DocCmdMapper; return s_instance; } DocCmdMapper() : m_map(113) { m_map.setAutoDelete(TRUE); DocCmdMap *p = docCmdMap; while (p->cmdName) { if (m_map.find(p->cmdName)!=0) { err("DocCmdMapper: command %s already added\n",p->cmdName); exit(1); } Cmd *cmd = new Cmd; cmd->func = p->handler; cmd->endsBrief = p->endsBrief; m_map.insert(p->cmdName,cmd); p++; } } Cmd *find(const char *name) { return m_map.find(name); } QDict<Cmd> m_map; static DocCmdMapper *s_instance; }; DocCmdMapper *DocCmdMapper::s_instance=0; bool inInternalDocs = FALSE; #define YY_NEVER_INTERACTIVE 1 enum XRefKind { XRef_Item, XRef_Todo, XRef_Test, XRef_Bug, XRef_Deprecated, XRef_None }; enum OutputContext { OutputDoc, OutputBrief, OutputXRef, OutputInbody }; enum GuardType { Guard_If, Guard_IfNot, Guard_Skip }; class GuardedSection { public: GuardedSection(bool enabled,bool parentVisible) : m_enabled(enabled),m_parentVisible(parentVisible) {} bool isEnabled() const { return m_enabled; } bool parentVisible() const { return m_parentVisible; } private: bool m_enabled; bool m_parentVisible; }; void openGroup(Entry *e,const char *file,int line); void closeGroup(Entry *e,const char *file,int line,bool foundInline=FALSE); void initGroupInfo(Entry *e); static void groupAddDocs(Entry *e); /* ----------------------------------------------------------------- * * statics */ static ParserInterface *langParser; // the language parser that is calling us static QCString inputString; // input string static int inputPosition; // read pointer static QCString yyFileName; // file name that is read from static int yyLineNr; // line number in the input static bool inBody; // was the comment found inside the body of a function? static OutputContext inContext; // are we inside the brief, details or xref part static bool briefEndsAtDot; // does the brief description stop at a dot? static QCString formulaText; // Running text of a formula static QCString formulaEnv; // environment name static int formulaNewLines; // amount of new lines in the formula static QCString *pOutputString; // pointer to string to which the output is appended. static QCString outputXRef; // temp argument of todo/test/../xrefitem commands static QCString blockName; // preformatted block name (e.g. verbatim, latexonly,...) static XRefKind xrefKind; // kind of cross-reference command static XRefKind newXRefKind; // static GuardType guardType; // kind of guard for conditional section static bool enabledSectionFound; static QCString functionProto; // function prototype static QStack<GuardedSection> guards; // tracks nested conditional sections (if,ifnot,..) static Entry* current = 0 ; // working entry //static Entry* current_root = 0 ; // parent of working entry //static Entry* previous = 0 ; // TODO: remove need for this static bool needNewEntry; static QCString g_sectionLabel; static QCString g_sectionTitle; static int g_sectionLevel; static QCString xrefItemKey; static QCString newXRefItemKey; static QCString xrefItemTitle; static QCString xrefListTitle; static Protection protection; static bool xrefAppendFlag; static bool inGroupParamFound; static int braceCount; static bool insidePre; static bool parseMore; static int g_condCount; static int g_commentCount; static QCString g_spaceBeforeCmd; static QCString g_spaceBeforeIf; static QCString g_copyDocArg; static QCString g_guardExpr; static int g_roundCount; static bool g_insideParBlock; //----------------------------------------------------------------------------- static QStack<Grouping> g_autoGroupStack; static int g_memberGroupId = DOX_NOGROUP; static QCString g_memberGroupHeader; static QCString g_memberGroupDocs; static QCString g_memberGroupRelates; static QCString g_compoundName; //----------------------------------------------------------------------------- static void initParser() { g_sectionLabel.resize(0); g_sectionTitle.resize(0); g_memberGroupHeader.resize(0); g_insideParBlock = FALSE; } //----------------------------------------------------------------------------- static bool getDocSectionName(int s) { switch(s) { case Entry::CLASSDOC_SEC: case Entry::STRUCTDOC_SEC: case Entry::UNIONDOC_SEC: case Entry::EXCEPTIONDOC_SEC: case Entry::NAMESPACEDOC_SEC: case Entry::PROTOCOLDOC_SEC: case Entry::CATEGORYDOC_SEC: case Entry::ENUMDOC_SEC: case Entry::PAGEDOC_SEC: case Entry::VARIABLEDOC_SEC: case Entry::MEMBERDOC_SEC: case Entry::OVERLOADDOC_SEC: case Entry::FILEDOC_SEC: case Entry::DEFINEDOC_SEC: case Entry::GROUPDOC_SEC: case Entry::MAINPAGEDOC_SEC: case Entry::PACKAGEDOC_SEC: case Entry::DIRDOC_SEC: case Entry::EXAMPLE_SEC: case Entry::MEMBERGRP_SEC: return TRUE; default: return FALSE; } } //----------------------------------------------------------------------------- static bool makeStructuralIndicator(Entry::Sections s) { //printf("current->section=%x\n",current->section); if (getDocSectionName(current->section)) { return TRUE; } else { needNewEntry = TRUE; current->section = s; current->fileName = yyFileName; current->startLine = yyLineNr; return FALSE; } } static void lineCount() { for( const char* c = commentscanYYtext ; *c ; ++c ) yyLineNr += (*c == '\n') ; } static QCString stripQuotes(const char *s) { QCString name; if (s==0 || *s==0) return name; name=s; if (name.at(0)=='"' && name.at(name.length()-1)=='"') { name=name.mid(1,name.length()-2); } return name; } //----------------------------------------------------------------- static void addXRefItem(const char *listName,const char *itemTitle, const char *listTitle,bool append) { Entry *docEntry = current; // inBody && previous ? previous : current; if (listName==0) return; //printf("addXRefItem(%s,%s,%s,%d)\n",listName,itemTitle,listTitle,append); ListItemInfo *lii=0; RefList *refList = Doxygen::xrefLists->find(listName); if (refList==0) // new list { refList = new RefList(listName,listTitle,itemTitle); Doxygen::xrefLists->insert(listName,refList); //printf("new list!\n"); } if (docEntry->sli) { QListIterator<ListItemInfo> slii(*docEntry->sli); for (slii.toFirst();(lii=slii.current());++slii) { if (qstrcmp(lii->type,listName)==0) { //printf("found %s lii->type=%s\n",listName,lii->type); break; } } } if (lii && append) // already found item of same type just before this one { //printf("listName=%s item id = %d existing\n",listName,lii->itemId); RefItem *item = refList->getRefItem(lii->itemId); ASSERT(item!=0); item->text += " <p>"; if (Doxygen::markdownSupport) { item->text += processMarkdown(yyFileName,yyLineNr,current,outputXRef); } else { item->text += outputXRef; } //printf("%s: text +=%s\n",listName,item->text.data()); } else // new item { int itemId = refList->addRefItem(); //printf("listName=%s item id = %d new current=%p\n",listName,itemId,current); // if we have already an item from the same list type (e.g. a second @todo) // in the same Entry (i.e. lii!=0) then we reuse its link anchor. char anchorLabel[1024]; //sprintf(anchorLabel,"_%s%06d",listName,lii ? lii->itemId : itemId); sprintf(anchorLabel,"_%s%06d",listName,itemId); RefItem *item = refList->getRefItem(itemId); ASSERT(item!=0); if (Doxygen::markdownSupport) { item->text = processMarkdown(yyFileName,yyLineNr,current,outputXRef); } else { item->text = outputXRef; } item->listAnchor = anchorLabel; docEntry->addSpecialListItem(listName,itemId); QCString cmdString; cmdString.sprintf("\\xrefitem %s %d.",listName,itemId); if (inBody) { docEntry->inbodyDocs += cmdString; } else { docEntry->doc += cmdString; } SectionInfo *si = Doxygen::sectionDict->find(anchorLabel); if (si) { if (si->lineNr != -1) { warn(listName,yyLineNr,"multiple use of section label '%s', (first occurrence: %s, line %d)",anchorLabel,si->fileName.data(),si->lineNr); } else { warn(listName,yyLineNr,"multiple use of section label '%s', (first occurrence: %s)",anchorLabel,si->fileName.data()); } } else { si=new SectionInfo(listName,yyLineNr,anchorLabel, g_sectionTitle,SectionInfo::Anchor, g_sectionLevel); Doxygen::sectionDict->append(anchorLabel,si); docEntry->anchors->append(si); } } outputXRef.resize(0); } //----------------------------------------------------------------------------- // Adds a formula text to the list/dictionary of formulas if it was // not already added. Returns the label of the formula. static QCString addFormula() { QCString formLabel; QCString fText=formulaText.simplifyWhiteSpace(); Formula *f=0; if ((f=Doxygen::formulaDict->find(fText))==0) { f = new Formula(fText); Doxygen::formulaList->append(f); Doxygen::formulaDict->insert(fText,f); formLabel.sprintf("\\form#%d",f->getId()); Doxygen::formulaNameDict->insert(formLabel,f); } else { formLabel.sprintf("\\form#%d",f->getId()); } int i; for (i=0;i<formulaNewLines;i++) formLabel+="@_fakenl"; // add fake newlines to // keep the warnings // correctly aligned. return formLabel; } //----------------------------------------------------------------------------- static void checkFormula(); //----------------------------------------------------------------------------- static SectionInfo::SectionType sectionLevelToType(int level) { if (level>=0 && level<5) return (SectionInfo::SectionType)level; return SectionInfo::Anchor; } static void addSection() { SectionInfo *si = Doxygen::sectionDict->find(g_sectionLabel); if (si) { if (si->lineNr != -1) { warn(yyFileName,yyLineNr,"multiple use of section label '%s' while adding section, (first occurrence: %s, line %d)",g_sectionLabel.data(),si->fileName.data(),si->lineNr); } else { warn(yyFileName,yyLineNr,"multiple use of section label '%s' while adding section, (first occurrence: %s)",g_sectionLabel.data(),si->fileName.data()); } } else { // create a new section element g_sectionTitle+=commentscanYYtext; g_sectionTitle=g_sectionTitle.stripWhiteSpace(); si = new SectionInfo(yyFileName,yyLineNr,g_sectionLabel, g_sectionTitle,sectionLevelToType(g_sectionLevel),g_sectionLevel); // add section to this entry current->anchors->append(si); // add section to the global dictionary Doxygen::sectionDict->append(g_sectionLabel,si); } } //----------------------------------------------------------------------------- static void addCite() { Doxygen::citeDict->insert(commentscanYYtext); } //----------------------------------------------------------------------------- // strip trailing whitespace (excluding newlines) from string s static void stripTrailingWhiteSpace(QCString &s) { uint len = s.length(); int i = (int)len-1; char c; while (i>=0 && ((c = s.at(i))==' ' || c=='\t' || c=='\r')) i--; if (i!=(int)len-1) { s.resize(i+2); // string up to and including char at pos i and \0 terminator } } // selects the output to write to static inline void setOutput(OutputContext ctx) { bool xrefAppendToPrev = xrefAppendFlag; // determine append flag for the next item (i.e. the end of this item) xrefAppendFlag = !inBody && inContext==OutputXRef && ctx==OutputXRef && // two consecutive xref items newXRefKind==xrefKind && // of the same kind (xrefKind!=XRef_Item || newXRefItemKey==xrefItemKey); // with the same key if \xrefitem //printf("%d && %d && %d && (%d || %d)\n", // inContext==OutputXRef, // ctx==OutputXRef, // newXRefKind==xrefKind, // xrefKind!=XRef_Item, // newXRefItemKey==xrefItemKey); //printf("refKind=%d newXRefKind=%d xrefAppendToPrev=%d xrefAppendFlag=%d\n", // xrefKind,newXRefKind,xrefAppendToPrev,xrefAppendFlag); //printf("setOutput(inContext=%d ctx=%d)\n",inContext,ctx); if (inContext==OutputXRef) // end of XRef section => add the item { // See if we can append this new xref item to the previous one. // We know this at the start of the next item of the same // type and need to remember this until the end of that item. switch(xrefKind) { case XRef_Todo: addXRefItem("todo", theTranslator->trTodo(), theTranslator->trTodoList(), xrefAppendToPrev ); break; case XRef_Test: addXRefItem("test", theTranslator->trTest(), theTranslator->trTestList(), xrefAppendToPrev ); break; case XRef_Bug: addXRefItem("bug", theTranslator->trBug(), theTranslator->trBugList(), xrefAppendToPrev ); break; case XRef_Deprecated: addXRefItem("deprecated", theTranslator->trDeprecated(), theTranslator->trDeprecatedList(), xrefAppendToPrev ); break; case XRef_Item: // user defined list addXRefItem(xrefItemKey, xrefItemTitle, xrefListTitle, xrefAppendToPrev ); break; case XRef_None: ASSERT(0); break; } } xrefItemKey = newXRefItemKey; int oldContext = inContext; inContext = ctx; if (inContext!=OutputXRef && inBody) inContext=OutputInbody; switch(inContext) { case OutputDoc: if (oldContext!=inContext) { stripTrailingWhiteSpace(current->doc); if (current->docFile.isEmpty()) { current->docFile = yyFileName; current->docLine = yyLineNr; } } pOutputString = &current->doc; break; case OutputBrief: if (oldContext!=inContext) { if (current->briefFile.isEmpty()) { current->briefFile = yyFileName; current->briefLine = yyLineNr; } } if (current->brief.stripWhiteSpace().isEmpty()) // we only want one brief // description even if multiple // are given... { pOutputString = &current->brief; } else { pOutputString = &current->doc; inContext = OutputDoc; // need to switch to detailed docs, see bug 631380 } break; case OutputXRef: pOutputString = &outputXRef; // first item found, so can't append to previous //xrefAppendFlag = FALSE; break; case OutputInbody: pOutputString = &current->inbodyDocs; break; } } static void addAnchor(const char *anchor) { SectionInfo *si = Doxygen::sectionDict->find(anchor); if (si) { if (si->lineNr != -1) { warn(yyFileName,yyLineNr,"multiple use of section label '%s' while adding anchor, (first occurrence: %s, line %d)",anchor,si->fileName.data(),si->lineNr); } else { warn(yyFileName,yyLineNr,"multiple use of section label '%s' while adding anchor, (first occurrence: %s)",anchor,si->fileName.data()); } } else { si = new SectionInfo(yyFileName,yyLineNr,anchor,0,SectionInfo::Anchor,0); Doxygen::sectionDict->append(anchor,si); current->anchors->append(si); } } // add a string to the output static inline void addOutput(const char *s) { //printf("addOutput(%s)\n",s); *pOutputString+=s; } // add a character to the output static inline void addOutput(char c) { *pOutputString+=c; } static void endBrief(bool addToOutput=TRUE) { if (!current->brief.stripWhiteSpace().isEmpty()) { // only go to the detailed description if we have // found some brief description and not just whitespace briefEndsAtDot=FALSE; setOutput(OutputDoc); if (addToOutput) addOutput(commentscanYYtext); } } static void handleGuard(const QCString &expr); /* ----------------------------------------------------------------- */ #undef YY_INPUT #define YY_INPUT(buf,result,max_size) result=yyread(buf,max_size); static int prevPosition=0; static int yyread(char *buf,int max_size) { prevPosition=inputPosition; int c=0; while( c < max_size && inputString[inputPosition] ) { *buf = inputString[inputPosition++] ; //printf("%d (%c)\n",*buf,*buf); c++; buf++; } return c; } /* start command character */ /* comment parsing states. */ #line 4122 "/home/localguest/Documents/SVIII/Neurone/gtest/doxygen/build/generated_src/commentscan.cpp" #define INITIAL 0 #define Comment 1 #define PageDocArg1 2 #define PageDocArg2 3 #define RelatesParam1 4 #define ClassDocArg1 5 #define ClassDocArg2 6 #define ClassDocArg3 7 #define CategoryDocArg1 8 #define XRefItemParam1 9 #define XRefItemParam2 10 #define XRefItemParam3 11 #define FileDocArg1 12 #define ParamArg1 13 #define EnumDocArg1 14 #define NameSpaceDocArg1 15 #define PackageDocArg1 16 #define GroupDocArg1 17 #define GroupDocArg2 18 #define SectionLabel 19 #define SectionTitle 20 #define SubpageLabel 21 #define SubpageTitle 22 #define FormatBlock 23 #define LineParam 24 #define GuardParam 25 #define GuardParamEnd 26 #define SkipGuardedSection 27 #define SkipInternal 28 #define NameParam 29 #define InGroupParam 30 #define FnParam 31 #define OverloadParam 32 #define InheritParam 33 #define ExtendsParam 34 #define ReadFormulaShort 35 #define ReadFormulaLong 36 #define AnchorLabel 37 #define HtmlComment 38 #define SkipLang 39 #define CiteLabel 40 #define CopyDoc 41 #define GuardExpr 42 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int commentscanYYlex_destroy (void ); int commentscanYYget_debug (void ); void commentscanYYset_debug (int debug_flag ); YY_EXTRA_TYPE commentscanYYget_extra (void ); void commentscanYYset_extra (YY_EXTRA_TYPE user_defined ); FILE *commentscanYYget_in (void ); void commentscanYYset_in (FILE * in_str ); FILE *commentscanYYget_out (void ); void commentscanYYset_out (FILE * out_str ); int commentscanYYget_leng (void ); char *commentscanYYget_text (void ); int commentscanYYget_lineno (void ); void commentscanYYset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int commentscanYYwrap (void ); #else extern int commentscanYYwrap (void ); #endif #endif static void yyunput (int c,char *buf_ptr ); #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( commentscanYYtext, commentscanYYleng, 1, commentscanYYout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( commentscanYYin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( commentscanYYin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, commentscanYYin))==0 && ferror(commentscanYYin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(commentscanYYin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int commentscanYYlex (void); #define YY_DECL int commentscanYYlex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after commentscanYYtext and commentscanYYleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ if ( commentscanYYleng > 0 ) \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \ (commentscanYYtext[commentscanYYleng - 1] == '\n'); \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 1007 "commentscan.l" /* What can happen in while parsing a comment block: * commands (e.g. @page, or \page) * escaped commands (e.g. @@page or \\page). * formulas (e.g. \f$ \f[ \f{..) * directories (e.g. \doxygen\src\) * autolist end. (e.g. a dot on an otherwise empty line) * newlines. * end of brief description due to blank line. * end of brief description due to some command (@command, or <command>). * words and whitespace and other characters (#,?!, etc). * grouping commands (e.g. @{ and @}) * language switch (e.g. \~english or \~). * mail address (e.g. dimitri@stack.nl). * quoted text, such as "foo@bar" * XML commands, <summary></summary><remarks></remarks> */ #line 4374 "/home/localguest/Documents/SVIII/Neurone/gtest/doxygen/build/generated_src/commentscan.cpp" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif /* Create the reject buffer large enough to save one state per allowed character. */ if ( ! (yy_state_buf) ) (yy_state_buf) = (yy_state_type *)commentscanYYalloc(YY_STATE_BUF_SIZE ); if ( ! (yy_state_buf) ) YY_FATAL_ERROR( "out of dynamic memory in commentscanYYlex()" ); if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! commentscanYYin ) commentscanYYin = stdin; if ( ! commentscanYYout ) commentscanYYout = stdout; if ( ! YY_CURRENT_BUFFER ) { commentscanYYensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = commentscanYY_create_buffer(commentscanYYin,YY_BUF_SIZE ); } commentscanYY_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of commentscanYYtext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_current_state += YY_AT_BOL(); (yy_state_ptr) = (yy_state_buf); *(yy_state_ptr)++ = yy_current_state; yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1148 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; *(yy_state_ptr)++ = yy_current_state; ++yy_cp; } while ( yy_current_state != 1147 ); yy_find_action: yy_current_state = *--(yy_state_ptr); (yy_lp) = yy_accept[yy_current_state]; find_rule: /* we branch to this label when backing up */ for ( ; ; ) /* until we find what rule we matched */ { if ( (yy_lp) && (yy_lp) < yy_accept[yy_current_state + 1] ) { yy_act = yy_acclist[(yy_lp)]; if ( yy_act & YY_TRAILING_HEAD_MASK || (yy_looking_for_trail_begin) ) { if ( yy_act == (yy_looking_for_trail_begin) ) { (yy_looking_for_trail_begin) = 0; yy_act &= ~YY_TRAILING_HEAD_MASK; break; } } else if ( yy_act & YY_TRAILING_MASK ) { (yy_looking_for_trail_begin) = yy_act & ~YY_TRAILING_MASK; (yy_looking_for_trail_begin) |= YY_TRAILING_HEAD_MASK; (yy_full_match) = yy_cp; (yy_full_state) = (yy_state_ptr); (yy_full_lp) = (yy_lp); } else { (yy_full_match) = yy_cp; (yy_full_state) = (yy_state_ptr); (yy_full_lp) = (yy_lp); break; } ++(yy_lp); goto find_rule; } --yy_cp; yy_current_state = *--(yy_state_ptr); (yy_lp) = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 1: YY_RULE_SETUP #line 1026 "commentscan.l" { // escaped command addOutput(commentscanYYtext); } YY_BREAK case 2: YY_RULE_SETUP #line 1029 "commentscan.l" { // escaped command addOutput(commentscanYYtext); } YY_BREAK case 3: YY_RULE_SETUP #line 1032 "commentscan.l" { // mail address addOutput(commentscanYYtext); } YY_BREAK case 4: YY_RULE_SETUP #line 1035 "commentscan.l" { // quoted text addOutput(commentscanYYtext); } YY_BREAK case 5: YY_RULE_SETUP #line 1038 "commentscan.l" { // directory (or chain of commands!) addOutput(commentscanYYtext); } YY_BREAK case 6: YY_RULE_SETUP #line 1041 "commentscan.l" { // HTML command that ends a brief description setOutput(OutputDoc); // continue with the same input REJECT; } YY_BREAK case 7: YY_RULE_SETUP #line 1046 "commentscan.l" { // HTML command that ends a brief description if (current->lang==SrcLangExt_CSharp) { setOutput(OutputDoc); } // continue with the same input REJECT; } YY_BREAK case 8: YY_RULE_SETUP #line 1054 "commentscan.l" { // start of a .NET XML style brief description setOutput(OutputBrief); addOutput(commentscanYYtext); } YY_BREAK case 9: YY_RULE_SETUP #line 1058 "commentscan.l" { // start of a .NET XML style detailed description setOutput(OutputDoc); addOutput(commentscanYYtext); } YY_BREAK case 10: YY_RULE_SETUP #line 1062 "commentscan.l" { // start of a .NET XML style detailed description addOutput(commentscanYYtext); setOutput(OutputDoc); } YY_BREAK case 11: YY_RULE_SETUP #line 1066 "commentscan.l" { // end of a brief or detailed description addOutput(commentscanYYtext); } YY_BREAK case 12: YY_RULE_SETUP #line 1069 "commentscan.l" { QCString tag=commentscanYYtext; int s=tag.find("id="); if (s!=-1) // command has id attribute { char c=tag[s+3]; if (c=='\'' || c=='"') // valid start { int e=tag.find(c,s+4); if (e!=-1) // found matching end { QCString id=tag.mid(s+4,e-s-4); // extract id addAnchor(id); } } } addOutput(commentscanYYtext); } YY_BREAK case 13: YY_RULE_SETUP #line 1087 "commentscan.l" { insidePre=TRUE; addOutput(commentscanYYtext); } YY_BREAK case 14: YY_RULE_SETUP #line 1091 "commentscan.l" { insidePre=FALSE; addOutput(commentscanYYtext); } YY_BREAK case 15: YY_RULE_SETUP #line 1095 "commentscan.l" { // RCS tag which end a brief description setOutput(OutputDoc); REJECT; } YY_BREAK case 16: YY_RULE_SETUP #line 1099 "commentscan.l" { BEGIN(HtmlComment); } YY_BREAK case 17: YY_RULE_SETUP #line 1102 "commentscan.l" { addOutput("\\endinternal "); if (!inInternalDocs) warn(yyFileName,yyLineNr, "found \\endinternal without matching \\internal" ); inInternalDocs = FALSE; } YY_BREAK case 18: YY_RULE_SETUP #line 1110 "commentscan.l" { // potentially interesting command // the {B}* in the front was added for bug620924 QCString cmdName = QCString(commentscanYYtext).stripWhiteSpace().data()+1; DocCmdMapper::Cmd *cmdPtr = DocCmdMapper::map(cmdName); if (cmdPtr) // special action is required { int i=0; while (commentscanYYtext[i]==' ' || commentscanYYtext[i]=='\t') i++; g_spaceBeforeCmd = QCString(commentscanYYtext).left(i); if (cmdPtr->endsBrief && !(inContext==OutputXRef && cmdName=="parblock")) { briefEndsAtDot=FALSE; // this command forces the end of brief description setOutput(OutputDoc); } //if (i>0) addOutput(QCString(commentscanYYtext).left(i)); // removed for bug 689341 if (cmdPtr->func && cmdPtr->func(cmdName)) { // implicit split of the comment block into two // entries. Restart the next block at the start // of this command. parseMore=TRUE; // yuk, this is probably not very portable across lex implementations, // but we need to know the position in the input buffer where this // rule matched. // for flex 2.5.33+ we should use YY_CURRENT_BUFFER_LVALUE #if YY_FLEX_MAJOR_VERSION>=2 && (YY_FLEX_MINOR_VERSION>5 || (YY_FLEX_MINOR_VERSION==5 && YY_FLEX_SUBMINOR_VERSION>=33)) inputPosition=prevPosition + (int)(yy_bp - YY_CURRENT_BUFFER_LVALUE->yy_ch_buf); #else inputPosition=prevPosition + (int)(yy_bp - yy_current_buffer->yy_ch_buf); #endif yyterminate(); } else if (cmdPtr->func==0) { // command without handler, to be processed // later by parsedoc.cpp addOutput(commentscanYYtext); } } else // command not relevant { addOutput(commentscanYYtext); } } YY_BREAK case 19: YY_RULE_SETUP #line 1156 "commentscan.l" { // escaped formula command addOutput(commentscanYYtext); } YY_BREAK case 20: YY_RULE_SETUP #line 1159 "commentscan.l" { // language switch command QCString langId = QString(commentscanYYtext).stripWhiteSpace().data()+2; if (!langId.isEmpty() && qstricmp(Config_getEnum(OUTPUT_LANGUAGE),langId)!=0) { // enable language specific section BEGIN(SkipLang); } } YY_BREAK case 21: YY_RULE_SETUP #line 1167 "commentscan.l" { // start of a formula with custom environment formulaText="\\begin"; formulaEnv=QString(commentscanYYtext).stripWhiteSpace().data()+2; if (formulaEnv.at(formulaEnv.length()-1)=='{') { // remove trailing open brace formulaEnv=formulaEnv.left(formulaEnv.length()-1); } formulaText+=formulaEnv; formulaNewLines=0; BEGIN(ReadFormulaLong); } YY_BREAK case 22: YY_RULE_SETUP #line 1179 "commentscan.l" { // start of a inline formula formulaText="$"; formulaNewLines=0; BEGIN(ReadFormulaShort); } YY_BREAK case 23: YY_RULE_SETUP #line 1184 "commentscan.l" { // start of a block formula formulaText="\\["; formulaNewLines=0; BEGIN(ReadFormulaLong); } YY_BREAK case 24: YY_RULE_SETUP #line 1189 "commentscan.l" { // begin of a group //langParser->handleGroupStartCommand(g_memberGroupHeader); openGroup(current,yyFileName,yyLineNr); } YY_BREAK case 25: YY_RULE_SETUP #line 1193 "commentscan.l" { // end of a group //langParser->handleGroupEndCommand(); closeGroup(current,yyFileName,yyLineNr,TRUE); g_memberGroupHeader.resize(0); parseMore=TRUE; needNewEntry = TRUE; #if YY_FLEX_MAJOR_VERSION>=2 && (YY_FLEX_MINOR_VERSION>5 || (YY_FLEX_MINOR_VERSION==5 && YY_FLEX_SUBMINOR_VERSION>=33)) inputPosition=prevPosition + (int)(yy_bp - YY_CURRENT_BUFFER_LVALUE->yy_ch_buf) + strlen(commentscanYYtext); #else inputPosition=prevPosition + (int)(yy_bp - yy_current_buffer->yy_ch_buf) + strlen(commentscanYYtext); #endif yyterminate(); } YY_BREAK case 26: YY_RULE_SETUP #line 1206 "commentscan.l" { // escaped character addOutput(commentscanYYtext); } YY_BREAK case 27: YY_RULE_SETUP #line 1209 "commentscan.l" { // normal word addOutput(commentscanYYtext); } YY_BREAK case 28: /* rule 28 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1212 "commentscan.l" { // explicit end autolist: e.g " ." addOutput(commentscanYYtext); } YY_BREAK case 29: #line 1216 "commentscan.l" case 30: YY_RULE_SETUP #line 1216 "commentscan.l" { // start of autolist if (!Doxygen::markdownSupport) { REJECT; } else { if (inContext!=OutputXRef) { briefEndsAtDot=FALSE; setOutput(OutputDoc); } addOutput(commentscanYYtext); } } YY_BREAK case 31: YY_RULE_SETUP #line 1231 "commentscan.l" { // start of autolist if (inContext!=OutputXRef) { briefEndsAtDot=FALSE; setOutput(OutputDoc); } addOutput(commentscanYYtext); } YY_BREAK case 32: /* rule 32 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1239 "commentscan.l" { // horizontal line (dashed) addOutput(commentscanYYtext); } YY_BREAK case 33: YY_RULE_SETUP #line 1242 "commentscan.l" { // escaped mdash addOutput(commentscanYYtext); } YY_BREAK case 34: YY_RULE_SETUP #line 1245 "commentscan.l" { // escaped mdash addOutput(commentscanYYtext); } YY_BREAK case 35: YY_RULE_SETUP #line 1248 "commentscan.l" { // mdash addOutput(insidePre || Doxygen::markdownSupport ? commentscanYYtext : "&mdash;"); } YY_BREAK case 36: YY_RULE_SETUP #line 1251 "commentscan.l" { // ndash addOutput(insidePre || Doxygen::markdownSupport ? commentscanYYtext : "&ndash;"); } YY_BREAK case 37: YY_RULE_SETUP #line 1254 "commentscan.l" { // numbered item addOutput(commentscanYYtext); } YY_BREAK case 38: YY_RULE_SETUP #line 1257 "commentscan.l" { // . at start or in the middle of a word, or ellipsis addOutput(commentscanYYtext); } YY_BREAK case 39: YY_RULE_SETUP #line 1260 "commentscan.l" { // . with escaped space. addOutput(commentscanYYtext[0]); addOutput(commentscanYYtext[2]); } YY_BREAK case 40: YY_RULE_SETUP #line 1264 "commentscan.l" { // . with comma such as "e.g.," addOutput(commentscanYYtext); } YY_BREAK case 41: YY_RULE_SETUP #line 1267 "commentscan.l" { // ellipsis with escaped space. addOutput("... "); } YY_BREAK case 42: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1270 "commentscan.l" { // internal ellipsis addOutput(commentscanYYtext); } YY_BREAK case 43: /* rule 43 can match eol */ YY_RULE_SETUP #line 1273 "commentscan.l" { // at least one blank line (or blank line command) if (inContext==OutputXRef) { // see bug 613024, we need to put the newlines after ending the XRef section. if (!g_insideParBlock) setOutput(OutputDoc); int i; for (i=0;i<commentscanYYleng;) { if (commentscanYYtext[i]=='\n') addOutput('\n'),i++; else if (strcmp(commentscanYYtext+i,"\\_linebr")==0) addOutput('\n'),i+=8; else i++; } } else if (inContext!=OutputBrief) { int i; for (i=0;i<commentscanYYleng;) { if (commentscanYYtext[i]=='\n') addOutput('\n'),i++; else if (strcmp(commentscanYYtext+i,"\\_linebr")==0) addOutput('\n'),i+=8; else i++; } setOutput(OutputDoc); } else // inContext==OutputBrief { // only go to the detailed description if we have // found some brief description and not just whitespace endBrief(FALSE); } lineCount(); } YY_BREAK case 44: YY_RULE_SETUP #line 1304 "commentscan.l" { // potential end of a JavaDoc style comment addOutput(*commentscanYYtext); if (briefEndsAtDot) { setOutput(OutputDoc); briefEndsAtDot=FALSE; } } YY_BREAK case 45: /* rule 45 can match eol */ YY_RULE_SETUP #line 1312 "commentscan.l" { // newline addOutput(*commentscanYYtext); yyLineNr++; } YY_BREAK case 46: YY_RULE_SETUP #line 1316 "commentscan.l" { // catch-all for anything else addOutput(*commentscanYYtext); } YY_BREAK /* -------------- Rules for handling HTML comments ----------- */ case 47: YY_RULE_SETUP #line 1323 "commentscan.l" { BEGIN( Comment ); } YY_BREAK case 48: /* rule 48 can match eol */ YY_RULE_SETUP #line 1324 "commentscan.l" { if (*commentscanYYtext=='\n') yyLineNr++; } YY_BREAK case 49: YY_RULE_SETUP #line 1327 "commentscan.l" { // ignore unimportant characters } YY_BREAK case 50: YY_RULE_SETUP #line 1329 "commentscan.l" { // ignore every else } YY_BREAK /* -------------- Rules for handling formulas ---------------- */ case 51: YY_RULE_SETUP #line 1334 "commentscan.l" { // end of inline formula formulaText+="$"; addOutput(" "+addFormula()); BEGIN(Comment); } YY_BREAK case 52: YY_RULE_SETUP #line 1339 "commentscan.l" { // end of block formula formulaText+="\\]"; addOutput(" "+addFormula()); BEGIN(Comment); } YY_BREAK case 53: YY_RULE_SETUP #line 1344 "commentscan.l" { // end of custom env formula formulaText+="\\end"; formulaText+=formulaEnv; addOutput(" "+addFormula()); BEGIN(Comment); } YY_BREAK case 54: YY_RULE_SETUP #line 1350 "commentscan.l" { // any non-special character formulaText+=commentscanYYtext; } YY_BREAK case 55: /* rule 55 can match eol */ YY_RULE_SETUP #line 1353 "commentscan.l" { // new line formulaNewLines++; formulaText+=*commentscanYYtext; yyLineNr++; } YY_BREAK case 56: YY_RULE_SETUP #line 1358 "commentscan.l" { // any othe character formulaText+=*commentscanYYtext; } YY_BREAK /* ------------ handle argument of enum command --------------- */ case 57: /* rule 57 can match eol */ YY_RULE_SETUP #line 1364 "commentscan.l" { // handle argument current->name = commentscanYYtext; BEGIN( Comment ); } YY_BREAK case 58: /* rule 58 can match eol */ YY_RULE_SETUP #line 1368 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 59: /* rule 59 can match eol */ YY_RULE_SETUP #line 1372 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "missing argument after \\enum." ); addOutput('\n'); if (*commentscanYYtext=='\n') yyLineNr++; BEGIN( Comment ); } YY_BREAK case 60: YY_RULE_SETUP #line 1380 "commentscan.l" { // ignore other stuff } YY_BREAK /* ------------ handle argument of namespace command --------------- */ case 61: /* rule 61 can match eol */ YY_RULE_SETUP #line 1385 "commentscan.l" { // handle argument current->name = substitute(commentscanYYtext,".","::"); BEGIN( Comment ); } YY_BREAK case 62: /* rule 62 can match eol */ YY_RULE_SETUP #line 1389 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 63: /* rule 63 can match eol */ YY_RULE_SETUP #line 1393 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "missing argument after " "\\namespace." ); addOutput('\n'); if (*commentscanYYtext=='\n') yyLineNr++; BEGIN( Comment ); } YY_BREAK case 64: YY_RULE_SETUP #line 1402 "commentscan.l" { // ignore other stuff } YY_BREAK /* ------------ handle argument of package command --------------- */ case 65: YY_RULE_SETUP #line 1407 "commentscan.l" { // handle argument current->name = commentscanYYtext; BEGIN( Comment ); } YY_BREAK case 66: /* rule 66 can match eol */ YY_RULE_SETUP #line 1411 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 67: /* rule 67 can match eol */ YY_RULE_SETUP #line 1415 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "missing argument after " "\\package." ); addOutput('\n'); if (*commentscanYYtext=='\n') yyLineNr++; BEGIN( Comment ); } YY_BREAK case 68: YY_RULE_SETUP #line 1424 "commentscan.l" { // ignore other stuff } YY_BREAK /* ------ handle argument of class/struct/union command --------------- */ case 69: /* rule 69 can match eol */ YY_RULE_SETUP #line 1429 "commentscan.l" { current->name = substitute(removeRedundantWhiteSpace(commentscanYYtext),".","::"); BEGIN( ClassDocArg2 ); } YY_BREAK case 70: /* rule 70 can match eol */ YY_RULE_SETUP #line 1433 "commentscan.l" { // first argument current->name = substitute(commentscanYYtext,".","::"); if (current->section==Entry::PROTOCOLDOC_SEC) { current->name+="-p"; } // prepend outer scope name BEGIN( ClassDocArg2 ); } YY_BREAK case 71: /* rule 71 can match eol */ YY_RULE_SETUP #line 1442 "commentscan.l" { current->name = substitute(commentscanYYtext,".","::"); BEGIN( ClassDocArg2 ); } YY_BREAK case 72: /* rule 72 can match eol */ YY_RULE_SETUP #line 1446 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 73: /* rule 73 can match eol */ YY_RULE_SETUP #line 1450 "commentscan.l" { warn(yyFileName,yyLineNr, "missing argument after " "\\%s.",YY_START==ClassDocArg1?"class":"category" ); addOutput('\n'); if (*commentscanYYtext=='\n') yyLineNr++; BEGIN( Comment ); } YY_BREAK case 74: YY_RULE_SETUP #line 1459 "commentscan.l" { // ignore other stuff } YY_BREAK case 75: YY_RULE_SETUP #line 1462 "commentscan.l" { // second argument; include file current->includeFile = commentscanYYtext; BEGIN( ClassDocArg3 ); } YY_BREAK case 76: /* rule 76 can match eol */ YY_RULE_SETUP #line 1466 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 77: /* rule 77 can match eol */ YY_RULE_SETUP #line 1470 "commentscan.l" { addOutput('\n'); if (*commentscanYYtext=='\n') yyLineNr++; BEGIN( Comment ); } YY_BREAK case 78: YY_RULE_SETUP #line 1475 "commentscan.l" { // ignore other stuff } YY_BREAK case 79: YY_RULE_SETUP #line 1478 "commentscan.l" { // third argument; include file name current->includeName = commentscanYYtext; BEGIN( Comment ); } YY_BREAK case 80: /* rule 80 can match eol */ YY_RULE_SETUP #line 1482 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 81: /* rule 81 can match eol */ YY_RULE_SETUP #line 1486 "commentscan.l" { if (*commentscanYYtext=='\n') yyLineNr++; BEGIN( Comment ); } YY_BREAK case 82: YY_RULE_SETUP #line 1490 "commentscan.l" { // ignore other stuff } YY_BREAK /* --------- handle arguments of {def,add,weak}group commands --------- */ case 83: YY_RULE_SETUP #line 1495 "commentscan.l" { // group name current->name = commentscanYYtext; //lastDefGroup.groupname = commentscanYYtext; //lastDefGroup.pri = current->groupingPri(); // the .html stuff is for Qt compatibility if (current->name.right(5)==".html") { current->name=current->name.left(current->name.length()-5); } current->type.resize(0); BEGIN(GroupDocArg2); } YY_BREAK case 84: /* rule 84 can match eol */ YY_RULE_SETUP #line 1507 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 85: /* rule 85 can match eol */ YY_RULE_SETUP #line 1511 "commentscan.l" { // missing argument! warn(yyFileName,yyLineNr, "missing group name after %s", current->groupDocCmd() ); addOutput('\n'); if (*commentscanYYtext=='\n') yyLineNr++; BEGIN( Comment ); } YY_BREAK case 86: /* rule 86 can match eol */ YY_RULE_SETUP #line 1520 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 87: YY_RULE_SETUP #line 1524 "commentscan.l" { // title (stored in type) current->type += commentscanYYtext; current->type = current->type.stripWhiteSpace(); } YY_BREAK case 88: /* rule 88 can match eol */ YY_RULE_SETUP #line 1528 "commentscan.l" { if ( current->groupDocType==Entry::GROUPDOC_NORMAL && current->type.isEmpty() ) // defgroup requires second argument { warn(yyFileName,yyLineNr, "missing title after " "\\defgroup %s", current->name.data() ); } if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK /* --------- handle arguments of page/mainpage command ------------------- */ case 89: YY_RULE_SETUP #line 1545 "commentscan.l" { // first argument; page name current->name = stripQuotes(commentscanYYtext); BEGIN( PageDocArg2 ); } YY_BREAK case 90: /* rule 90 can match eol */ YY_RULE_SETUP #line 1549 "commentscan.l" { yyLineNr++; addOutput('\n'); } YY_BREAK case 91: /* rule 91 can match eol */ YY_RULE_SETUP #line 1552 "commentscan.l" { warn(yyFileName,yyLineNr, "missing argument after " "\\page." ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 92: YY_RULE_SETUP #line 1561 "commentscan.l" { // ignore other stuff } YY_BREAK case 93: /* rule 93 can match eol */ YY_RULE_SETUP #line 1563 "commentscan.l" { // second argument; page title yyLineNr++; current->args = commentscanYYtext; addOutput('\n'); BEGIN( Comment ); } YY_BREAK /* --------- handle arguments of the param command ------------ */ case 94: YY_RULE_SETUP #line 1571 "commentscan.l" { if (commentscanYYtext[0]=='_' && Config_getBool(MARKDOWN_SUPPORT)) { addOutput('\\'); } addOutput(commentscanYYtext); } YY_BREAK case 95: YY_RULE_SETUP #line 1578 "commentscan.l" { addOutput(" , "); } YY_BREAK case 96: YY_RULE_SETUP #line 1581 "commentscan.l" { if (commentscanYYtext[0]=='_' && Config_getBool(MARKDOWN_SUPPORT)) { addOutput('\\'); } addOutput(commentscanYYtext); BEGIN( Comment ); } YY_BREAK case 97: YY_RULE_SETUP #line 1589 "commentscan.l" { unput(commentscanYYtext[0]); BEGIN( Comment ); } YY_BREAK /* --------- handle arguments of the file/dir/example command ------------ */ case 98: /* rule 98 can match eol */ YY_RULE_SETUP #line 1596 "commentscan.l" { // no file name specfied if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 99: YY_RULE_SETUP #line 1601 "commentscan.l" { // first argument; name current->name = stripQuotes(commentscanYYtext); BEGIN( Comment ); } YY_BREAK case 100: /* rule 100 can match eol */ YY_RULE_SETUP #line 1605 "commentscan.l" { yyLineNr++; addOutput('\n'); } YY_BREAK case 101: YY_RULE_SETUP #line 1608 "commentscan.l" { // ignore other stuff } YY_BREAK /* --------- handle arguments of the xrefitem command ------------ */ case 102: YY_RULE_SETUP #line 1613 "commentscan.l" { // first argument newXRefItemKey=commentscanYYtext; setOutput(OutputXRef); BEGIN(XRefItemParam2); } YY_BREAK case 103: /* rule 103 can match eol */ YY_RULE_SETUP #line 1618 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 104: /* rule 104 can match eol */ YY_RULE_SETUP #line 1622 "commentscan.l" { // missing arguments warn(yyFileName,yyLineNr, "Missing first argument of \\xrefitem" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); inContext = OutputDoc; BEGIN( Comment ); } YY_BREAK case 105: YY_RULE_SETUP #line 1631 "commentscan.l" { // ignore other stuff } YY_BREAK case 106: YY_RULE_SETUP #line 1634 "commentscan.l" { // second argument xrefItemTitle = stripQuotes(commentscanYYtext); BEGIN(XRefItemParam3); } YY_BREAK case 107: /* rule 107 can match eol */ YY_RULE_SETUP #line 1638 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 108: /* rule 108 can match eol */ YY_RULE_SETUP #line 1642 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "Missing second argument of \\xrefitem" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); inContext = OutputDoc; BEGIN( Comment ); } YY_BREAK case 109: YY_RULE_SETUP #line 1651 "commentscan.l" { // ignore other stuff } YY_BREAK case 110: YY_RULE_SETUP #line 1654 "commentscan.l" { // third argument xrefListTitle = stripQuotes(commentscanYYtext); xrefKind = XRef_Item; BEGIN( Comment ); } YY_BREAK case 111: /* rule 111 can match eol */ YY_RULE_SETUP #line 1659 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 112: /* rule 112 can match eol */ YY_RULE_SETUP #line 1663 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "Missing third argument of \\xrefitem" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); inContext = OutputDoc; BEGIN( Comment ); } YY_BREAK case 113: YY_RULE_SETUP #line 1672 "commentscan.l" { // ignore other stuff } YY_BREAK /* ----- handle arguments of the relates(also)/memberof command ------- */ case 114: YY_RULE_SETUP #line 1678 "commentscan.l" { // argument current->relates = commentscanYYtext; //if (current->mGrpId!=DOX_NOGROUP) //{ // memberGroupRelates = commentscanYYtext; //} BEGIN( Comment ); } YY_BREAK case 115: /* rule 115 can match eol */ YY_RULE_SETUP #line 1686 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 116: /* rule 116 can match eol */ YY_RULE_SETUP #line 1690 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "Missing argument of \\relates or \\memberof command" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 117: YY_RULE_SETUP #line 1698 "commentscan.l" { // ignore other stuff } YY_BREAK /* ----- handle arguments of the relates(also)/addindex commands ----- */ case 118: /* rule 118 can match eol */ YY_RULE_SETUP #line 1704 "commentscan.l" { // end of argument if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 119: /* rule 119 can match eol */ YY_RULE_SETUP #line 1709 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 120: YY_RULE_SETUP #line 1713 "commentscan.l" { // ignore other stuff addOutput(*commentscanYYtext); } YY_BREAK /* ----- handle arguments of the section/subsection/.. commands ------- */ case 121: YY_RULE_SETUP #line 1719 "commentscan.l" { // first argyment g_sectionLabel=commentscanYYtext; addOutput(commentscanYYtext); g_sectionTitle.resize(0); BEGIN(SectionTitle); } YY_BREAK case 122: /* rule 122 can match eol */ YY_RULE_SETUP #line 1725 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "\\section command has no label" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 123: YY_RULE_SETUP #line 1733 "commentscan.l" { // invalid character for section label warn(yyFileName,yyLineNr, "Invalid or missing section label" ); BEGIN(Comment); } YY_BREAK case 124: /* rule 124 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1739 "commentscan.l" { // end of section title addSection(); addOutput(commentscanYYtext); BEGIN( Comment ); } YY_BREAK case 125: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 8; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1744 "commentscan.l" { // end of section title addSection(); addOutput(commentscanYYtext); BEGIN( Comment ); } YY_BREAK case 126: /* rule 126 can match eol */ YY_RULE_SETUP #line 1749 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 127: YY_RULE_SETUP #line 1753 "commentscan.l" { // any character without special meaning g_sectionTitle+=commentscanYYtext; addOutput(commentscanYYtext); } YY_BREAK case 128: YY_RULE_SETUP #line 1757 "commentscan.l" { // unescape escaped command g_sectionTitle+=&commentscanYYtext[1]; addOutput(commentscanYYtext); } YY_BREAK case 129: YY_RULE_SETUP #line 1761 "commentscan.l" { // unescape escaped character g_sectionTitle+=commentscanYYtext[1]; addOutput(commentscanYYtext); } YY_BREAK case 130: YY_RULE_SETUP #line 1765 "commentscan.l" { // anything else g_sectionTitle+=commentscanYYtext; addOutput(*commentscanYYtext); } YY_BREAK /* ----- handle arguments of the subpage command ------- */ case 131: YY_RULE_SETUP #line 1772 "commentscan.l" { // first argument addOutput(commentscanYYtext); // we add subpage labels as a kind of "inheritance" relation to prevent // needing to add another list to the Entry class. current->extends->append(new BaseInfo(commentscanYYtext,Public,Normal)); BEGIN(SubpageTitle); } YY_BREAK case 132: /* rule 132 can match eol */ YY_RULE_SETUP #line 1779 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "\\subpage command has no label" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 133: /* rule 133 can match eol */ YY_RULE_SETUP #line 1787 "commentscan.l" { // no title, end command addOutput(commentscanYYtext); BEGIN( Comment ); } YY_BREAK case 134: YY_RULE_SETUP #line 1791 "commentscan.l" { // add title, end of command addOutput(commentscanYYtext); BEGIN( Comment ); } YY_BREAK case 135: YY_RULE_SETUP #line 1795 "commentscan.l" { // no title, end of command unput(*commentscanYYtext); BEGIN( Comment ); } YY_BREAK /* ----- handle arguments of the anchor command ------- */ case 136: YY_RULE_SETUP #line 1802 "commentscan.l" { // found argument addAnchor(commentscanYYtext); addOutput(commentscanYYtext); BEGIN( Comment ); } YY_BREAK case 137: /* rule 137 can match eol */ YY_RULE_SETUP #line 1807 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "\\anchor command has no label" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 138: YY_RULE_SETUP #line 1815 "commentscan.l" { // invalid character for anchor label warn(yyFileName,yyLineNr, "Invalid or missing anchor label" ); BEGIN(Comment); } YY_BREAK /* ----- handle arguments of the preformatted block commands ------- */ case 139: /* rule 139 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1825 "commentscan.l" { // possible ends addOutput(commentscanYYtext); if (&commentscanYYtext[4]==blockName) // found end of the block { BEGIN(Comment); } } YY_BREAK case 140: YY_RULE_SETUP #line 1832 "commentscan.l" { addOutput(commentscanYYtext); if (blockName=="startuml") // found end of the block { BEGIN(Comment); } } YY_BREAK case 141: YY_RULE_SETUP #line 1839 "commentscan.l" { // some word addOutput(commentscanYYtext); } YY_BREAK case 142: /* rule 142 can match eol */ YY_RULE_SETUP #line 1842 "commentscan.l" { // new line if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); } YY_BREAK case 143: YY_RULE_SETUP #line 1846 "commentscan.l" { // start of a C-comment g_commentCount++; addOutput(commentscanYYtext); } YY_BREAK case 144: YY_RULE_SETUP #line 1850 "commentscan.l" { // end of a C-comment addOutput(commentscanYYtext); g_commentCount--; if (g_commentCount<0 && blockName!="verbatim") { warn(yyFileName,yyLineNr, "found */ without matching /* while inside a \\%s block! Perhaps a missing \\end%s?\n",blockName.data(),blockName.data()); } } YY_BREAK case 145: YY_RULE_SETUP #line 1859 "commentscan.l" { addOutput(*commentscanYYtext); } YY_BREAK case YY_STATE_EOF(FormatBlock): #line 1862 "commentscan.l" { QCString endTag = "@end"+blockName; if (blockName=="startuml") endTag="enduml"; warn(yyFileName,yyLineNr, "reached end of comment while inside a @%s block; check for missing @%s tag!", blockName.data(),endTag.data() ); yyterminate(); } YY_BREAK /* ----- handle arguments of if/ifnot commands ------- */ case 146: YY_RULE_SETUP #line 1874 "commentscan.l" { g_guardExpr=commentscanYYtext; g_roundCount=1; BEGIN(GuardExpr); } YY_BREAK case 147: /* rule 147 can match eol */ YY_RULE_SETUP #line 1879 "commentscan.l" { g_guardExpr+=commentscanYYtext; } YY_BREAK case 148: YY_RULE_SETUP #line 1882 "commentscan.l" { g_guardExpr+=commentscanYYtext; g_roundCount++; } YY_BREAK case 149: YY_RULE_SETUP #line 1886 "commentscan.l" { g_guardExpr+=commentscanYYtext; g_roundCount--; if (g_roundCount==0) { handleGuard(g_guardExpr); } } YY_BREAK case 150: /* rule 150 can match eol */ YY_RULE_SETUP #line 1894 "commentscan.l" { warn(yyFileName,yyLineNr, "invalid expression '%s' for guard",g_guardExpr.data()); unput(*commentscanYYtext); BEGIN(GuardParam); } YY_BREAK case 151: YY_RULE_SETUP #line 1900 "commentscan.l" { // parameter of if/ifnot guard handleGuard(commentscanYYtext); } YY_BREAK case 152: /* rule 152 can match eol */ YY_RULE_SETUP #line 1903 "commentscan.l" { // end of argument if (*commentscanYYtext=='\n') yyLineNr++; //next line is commented out due to bug620924 //addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 153: /* rule 153 can match eol */ YY_RULE_SETUP #line 1909 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 154: YY_RULE_SETUP #line 1913 "commentscan.l" { // ignore other stuff addOutput(*commentscanYYtext); } YY_BREAK case 155: /* rule 155 can match eol */ YY_RULE_SETUP #line 1916 "commentscan.l" { g_spaceBeforeIf.resize(0); BEGIN(Comment); } YY_BREAK case 156: YY_RULE_SETUP #line 1920 "commentscan.l" { if (!g_spaceBeforeIf.isEmpty()) // needed for 665313 in combation with bug620924 { addOutput(g_spaceBeforeIf); } g_spaceBeforeIf.resize(0); BEGIN(Comment); } YY_BREAK case 157: YY_RULE_SETUP #line 1928 "commentscan.l" { unput(*commentscanYYtext); BEGIN(Comment); } YY_BREAK /* ----- handle skipping of conditional sections ------- */ case 158: /* rule 158 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1935 "commentscan.l" { guardType = Guard_IfNot; BEGIN( GuardParam ); } YY_BREAK case 159: /* rule 159 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1939 "commentscan.l" { guardType = Guard_If; BEGIN( GuardParam ); } YY_BREAK case 160: /* rule 160 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1943 "commentscan.l" { if (guards.isEmpty()) { warn(yyFileName,yyLineNr, "found @endif without matching start command"); } else { GuardedSection *s = guards.pop(); bool parentVisible = s->parentVisible(); delete s; if (parentVisible) { enabledSectionFound=TRUE; BEGIN( GuardParamEnd ); } } } YY_BREAK case 161: /* rule 161 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1961 "commentscan.l" { if (guards.isEmpty()) { warn(yyFileName,yyLineNr, "found @else without matching start command"); } else { if (!enabledSectionFound && guards.top()->parentVisible()) { delete guards.pop(); guards.push(new GuardedSection(TRUE,TRUE)); enabledSectionFound=TRUE; BEGIN( GuardParamEnd ); } } } YY_BREAK case 162: /* rule 162 can match eol */ *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 1978 "commentscan.l" { if (guards.isEmpty()) { warn(yyFileName,yyLineNr, "found @elseif without matching start command"); } else { if (!enabledSectionFound && guards.top()->parentVisible()) { guardType=Guard_If; delete guards.pop(); BEGIN( GuardParam ); } } } YY_BREAK case 163: /* rule 163 can match eol */ YY_RULE_SETUP #line 1994 "commentscan.l" { // skip line if (*commentscanYYtext=='\n') yyLineNr++; //addOutput('\n'); } YY_BREAK case 164: YY_RULE_SETUP #line 1998 "commentscan.l" { // skip non-special characters } YY_BREAK case 165: YY_RULE_SETUP #line 2000 "commentscan.l" { // any other character } YY_BREAK /* ----- handle skipping of internal section ------- */ case 166: /* rule 166 can match eol */ YY_RULE_SETUP #line 2006 "commentscan.l" { // skip line if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); } YY_BREAK case 167: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 2010 "commentscan.l" { g_condCount++; } YY_BREAK case 168: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 2013 "commentscan.l" { g_condCount++; } YY_BREAK case 169: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 2016 "commentscan.l" { g_condCount--; if (g_condCount<0) // handle conditional section around of \internal, see bug607743 { unput('\\'); BEGIN(Comment); } } YY_BREAK case 170: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 2024 "commentscan.l" { if (g_sectionLevel>0) { unput('\\'); BEGIN(Comment); } } YY_BREAK case 171: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 2031 "commentscan.l" { if (g_sectionLevel>1) { unput('\\'); BEGIN(Comment); } } YY_BREAK case 172: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 2038 "commentscan.l" { if (g_sectionLevel>2) { unput('\\'); BEGIN(Comment); } } YY_BREAK case 173: *yy_cp = (yy_hold_char); /* undo effects of setting up commentscanYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up commentscanYYtext again */ YY_RULE_SETUP #line 2045 "commentscan.l" { if (g_sectionLevel>3) { unput('\\'); BEGIN(Comment); } } YY_BREAK case 174: YY_RULE_SETUP #line 2052 "commentscan.l" { addOutput("\\endinternal "); BEGIN(Comment); } YY_BREAK case 175: YY_RULE_SETUP #line 2056 "commentscan.l" { // skip non-special characters } YY_BREAK case 176: YY_RULE_SETUP #line 2058 "commentscan.l" { // any other character } YY_BREAK /* ----- handle argument of name command ------- */ case 177: /* rule 177 can match eol */ YY_RULE_SETUP #line 2064 "commentscan.l" { // end of argument if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 178: /* rule 178 can match eol */ YY_RULE_SETUP #line 2069 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); g_memberGroupHeader+=' '; } YY_BREAK case 179: YY_RULE_SETUP #line 2074 "commentscan.l" { // ignore other stuff g_memberGroupHeader+=*commentscanYYtext; current->name+=*commentscanYYtext; } YY_BREAK /* ----- handle argument of ingroup command ------- */ case 180: YY_RULE_SETUP #line 2081 "commentscan.l" { // group id current->groups->append( new Grouping(commentscanYYtext, Grouping::GROUPING_INGROUP) ); inGroupParamFound=TRUE; } YY_BREAK case 181: /* rule 181 can match eol */ YY_RULE_SETUP #line 2087 "commentscan.l" { // missing argument if (!inGroupParamFound) { warn(yyFileName,yyLineNr, "Missing group name for \\ingroup command" ); } if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 182: /* rule 182 can match eol */ YY_RULE_SETUP #line 2098 "commentscan.l" { // line continuation yyLineNr++; addOutput('\n'); } YY_BREAK case 183: YY_RULE_SETUP #line 2102 "commentscan.l" { // ignore other stuff addOutput(*commentscanYYtext); } YY_BREAK /* ----- handle argument of fn command ------- */ case 184: /* rule 184 can match eol */ YY_RULE_SETUP #line 2108 "commentscan.l" { // end of argument if (braceCount==0) { if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); langParser->parsePrototype(functionProto); BEGIN( Comment ); } } YY_BREAK case 185: /* rule 185 can match eol */ YY_RULE_SETUP #line 2117 "commentscan.l" { // line continuation yyLineNr++; functionProto+=' '; } YY_BREAK case 186: YY_RULE_SETUP #line 2121 "commentscan.l" { // non-special characters functionProto+=commentscanYYtext; } YY_BREAK case 187: YY_RULE_SETUP #line 2124 "commentscan.l" { functionProto+=commentscanYYtext; braceCount++; } YY_BREAK case 188: YY_RULE_SETUP #line 2128 "commentscan.l" { functionProto+=commentscanYYtext; braceCount--; } YY_BREAK case 189: YY_RULE_SETUP #line 2132 "commentscan.l" { // add other stuff functionProto+=*commentscanYYtext; } YY_BREAK /* ----- handle argument of overload command ------- */ case 190: /* rule 190 can match eol */ YY_RULE_SETUP #line 2140 "commentscan.l" { // end of argument if (*commentscanYYtext=='\n') yyLineNr++; if (functionProto.stripWhiteSpace().isEmpty()) { // plain overload command addOutput(getOverloadDocs()); addOutput('\n'); } else // overload declaration { makeStructuralIndicator(Entry::OVERLOADDOC_SEC); langParser->parsePrototype(functionProto); } BEGIN( Comment ); } YY_BREAK case 191: /* rule 191 can match eol */ YY_RULE_SETUP #line 2154 "commentscan.l" { // line continuation yyLineNr++; functionProto+=' '; } YY_BREAK case 192: YY_RULE_SETUP #line 2158 "commentscan.l" { // add other stuff functionProto+=*commentscanYYtext; } YY_BREAK /* ----- handle argument of inherit command ------- */ case 193: YY_RULE_SETUP #line 2164 "commentscan.l" { // found argument current->extends->append( new BaseInfo(removeRedundantWhiteSpace(commentscanYYtext),Public,Normal) ); BEGIN( Comment ); } YY_BREAK case 194: /* rule 194 can match eol */ YY_RULE_SETUP #line 2170 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "\\inherit command has no argument" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 195: YY_RULE_SETUP #line 2178 "commentscan.l" { // invalid character for anchor label warn(yyFileName,yyLineNr, "Invalid or missing name for \\inherit command" ); BEGIN(Comment); } YY_BREAK /* ----- handle argument of extends and implements commands ------- */ case 196: YY_RULE_SETUP #line 2187 "commentscan.l" { // found argument current->extends->append( new BaseInfo(removeRedundantWhiteSpace(commentscanYYtext),Public,Normal) ); BEGIN( Comment ); } YY_BREAK case 197: /* rule 197 can match eol */ YY_RULE_SETUP #line 2193 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "\\extends or \\implements command has no argument" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 198: YY_RULE_SETUP #line 2201 "commentscan.l" { // ignore other stuff } YY_BREAK /* ----- handle language specific sections ------- */ case 199: YY_RULE_SETUP #line 2206 "commentscan.l" { /* language switch */ QCString langId = &commentscanYYtext[2]; if (langId.isEmpty() || qstricmp(Config_getEnum(OUTPUT_LANGUAGE),langId)==0) { // enable language specific section BEGIN(Comment); } } YY_BREAK case 200: YY_RULE_SETUP #line 2214 "commentscan.l" { /* any character not a *, @, backslash or new line */ } YY_BREAK case 201: /* rule 201 can match eol */ YY_RULE_SETUP #line 2216 "commentscan.l" { /* new line in verbatim block */ if (*commentscanYYtext=='\n') yyLineNr++; } YY_BREAK case 202: YY_RULE_SETUP #line 2219 "commentscan.l" { /* any other character */ } YY_BREAK /* ----- handle arguments of the cite command ------- */ case 203: YY_RULE_SETUP #line 2224 "commentscan.l" { // found argyment addCite(); addOutput(commentscanYYtext); BEGIN(Comment); } YY_BREAK case 204: /* rule 204 can match eol */ YY_RULE_SETUP #line 2229 "commentscan.l" { // missing argument warn(yyFileName,yyLineNr, "\\cite command has no label" ); if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); BEGIN( Comment ); } YY_BREAK case 205: YY_RULE_SETUP #line 2237 "commentscan.l" { // invalid character for cite label warn(yyFileName,yyLineNr, "Invalid or missing cite label" ); BEGIN(Comment); } YY_BREAK /* ----- handle argument of the copydoc command ------- */ case YY_STATE_EOF(CopyDoc): #line 2246 "commentscan.l" case 206: /* rule 206 can match eol */ YY_RULE_SETUP #line 2247 "commentscan.l" { if (*commentscanYYtext=='\n') yyLineNr++; addOutput('\n'); setOutput(OutputDoc); addOutput("\\copydetails "); addOutput(g_copyDocArg); addOutput("\n"); BEGIN(Comment); } YY_BREAK case 207: YY_RULE_SETUP #line 2256 "commentscan.l" { g_copyDocArg+=commentscanYYtext; addOutput(commentscanYYtext); } YY_BREAK case 208: YY_RULE_SETUP #line 2260 "commentscan.l" { g_copyDocArg+=commentscanYYtext; addOutput(commentscanYYtext); } YY_BREAK case 209: YY_RULE_SETUP #line 2266 "commentscan.l" ECHO; YY_BREAK #line 6626 "/home/localguest/Documents/SVIII/Neurone/gtest/doxygen/build/generated_src/commentscan.cpp" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(Comment): case YY_STATE_EOF(PageDocArg1): case YY_STATE_EOF(PageDocArg2): case YY_STATE_EOF(RelatesParam1): case YY_STATE_EOF(ClassDocArg1): case YY_STATE_EOF(ClassDocArg2): case YY_STATE_EOF(ClassDocArg3): case YY_STATE_EOF(CategoryDocArg1): case YY_STATE_EOF(XRefItemParam1): case YY_STATE_EOF(XRefItemParam2): case YY_STATE_EOF(XRefItemParam3): case YY_STATE_EOF(FileDocArg1): case YY_STATE_EOF(ParamArg1): case YY_STATE_EOF(EnumDocArg1): case YY_STATE_EOF(NameSpaceDocArg1): case YY_STATE_EOF(PackageDocArg1): case YY_STATE_EOF(GroupDocArg1): case YY_STATE_EOF(GroupDocArg2): case YY_STATE_EOF(SectionLabel): case YY_STATE_EOF(SectionTitle): case YY_STATE_EOF(SubpageLabel): case YY_STATE_EOF(SubpageTitle): case YY_STATE_EOF(LineParam): case YY_STATE_EOF(GuardParam): case YY_STATE_EOF(GuardParamEnd): case YY_STATE_EOF(SkipGuardedSection): case YY_STATE_EOF(SkipInternal): case YY_STATE_EOF(NameParam): case YY_STATE_EOF(InGroupParam): case YY_STATE_EOF(FnParam): case YY_STATE_EOF(OverloadParam): case YY_STATE_EOF(InheritParam): case YY_STATE_EOF(ExtendsParam): case YY_STATE_EOF(ReadFormulaShort): case YY_STATE_EOF(ReadFormulaLong): case YY_STATE_EOF(AnchorLabel): case YY_STATE_EOF(HtmlComment): case YY_STATE_EOF(SkipLang): case YY_STATE_EOF(CiteLabel): case YY_STATE_EOF(GuardExpr): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed commentscanYYin at a new source and called * commentscanYYlex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = commentscanYYin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( commentscanYYwrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * commentscanYYtext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of commentscanYYlex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ YY_FATAL_ERROR( "input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; commentscanYYrestart(commentscanYYin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) commentscanYYrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); yy_current_state += YY_AT_BOL(); (yy_state_ptr) = (yy_state_buf); *(yy_state_ptr)++ = yy_current_state; for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1148 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; *(yy_state_ptr)++ = yy_current_state; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register YY_CHAR yy_c = 1; while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 1148 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 1147); if ( ! yy_is_jam ) *(yy_state_ptr)++ = yy_current_state; return yy_is_jam ? 0 : yy_current_state; } static void yyunput (int c, register char * yy_bp ) { register char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up commentscanYYtext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register int number_to_move = (yy_n_chars) + 2; register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; register char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ commentscanYYrestart(commentscanYYin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( commentscanYYwrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve commentscanYYtext */ (yy_hold_char) = *++(yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n'); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void commentscanYYrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ commentscanYYensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = commentscanYY_create_buffer(commentscanYYin,YY_BUF_SIZE ); } commentscanYY_init_buffer(YY_CURRENT_BUFFER,input_file ); commentscanYY_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void commentscanYY_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * commentscanYYpop_buffer_state(); * commentscanYYpush_buffer_state(new_buffer); */ commentscanYYensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; commentscanYY_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (commentscanYYwrap()) processing, but the only time this flag * is looked at is after commentscanYYwrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void commentscanYY_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; commentscanYYin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE commentscanYY_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) commentscanYYalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in commentscanYY_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) commentscanYYalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in commentscanYY_create_buffer()" ); b->yy_is_our_buffer = 1; commentscanYY_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with commentscanYY_create_buffer() * */ void commentscanYY_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) commentscanYYfree((void *) b->yy_ch_buf ); commentscanYYfree((void *) b ); } /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a commentscanYYrestart() or at EOF. */ static void commentscanYY_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; commentscanYY_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then commentscanYY_init_buffer was _probably_ * called from commentscanYYrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void commentscanYY_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) commentscanYY_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void commentscanYYpush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; commentscanYYensure_buffer_stack(); /* This block is copied from commentscanYY_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from commentscanYY_switch_to_buffer. */ commentscanYY_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void commentscanYYpop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; commentscanYY_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { commentscanYY_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void commentscanYYensure_buffer_stack (void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)commentscanYYalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in commentscanYYensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)commentscanYYrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in commentscanYYensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE commentscanYY_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) commentscanYYalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in commentscanYY_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; commentscanYY_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to commentscanYYlex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * commentscanYY_scan_bytes() instead. */ YY_BUFFER_STATE commentscanYY_scan_string (yyconst char * yystr ) { return commentscanYY_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to commentscanYYlex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE commentscanYY_scan_bytes (yyconst char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) commentscanYYalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in commentscanYY_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = commentscanYY_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in commentscanYY_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up commentscanYYtext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ commentscanYYtext[commentscanYYleng] = (yy_hold_char); \ (yy_c_buf_p) = commentscanYYtext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ commentscanYYleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int commentscanYYget_lineno (void) { return commentscanYYlineno; } /** Get the input stream. * */ FILE *commentscanYYget_in (void) { return commentscanYYin; } /** Get the output stream. * */ FILE *commentscanYYget_out (void) { return commentscanYYout; } /** Get the length of the current token. * */ int commentscanYYget_leng (void) { return commentscanYYleng; } /** Get the current token. * */ char *commentscanYYget_text (void) { return commentscanYYtext; } /** Set the current line number. * @param line_number * */ void commentscanYYset_lineno (int line_number ) { commentscanYYlineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see commentscanYY_switch_to_buffer */ void commentscanYYset_in (FILE * in_str ) { commentscanYYin = in_str ; } void commentscanYYset_out (FILE * out_str ) { commentscanYYout = out_str ; } int commentscanYYget_debug (void) { return commentscanYY_flex_debug; } void commentscanYYset_debug (int bdebug ) { commentscanYY_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from commentscanYYlex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; (yy_state_buf) = 0; (yy_state_ptr) = 0; (yy_full_match) = 0; (yy_lp) = 0; /* Defined in main.c */ #ifdef YY_STDINIT commentscanYYin = stdin; commentscanYYout = stdout; #else commentscanYYin = (FILE *) 0; commentscanYYout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * commentscanYYlex_init() */ return 0; } /* commentscanYYlex_destroy is for both reentrant and non-reentrant scanners. */ int commentscanYYlex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ commentscanYY_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; commentscanYYpop_buffer_state(); } /* Destroy the stack itself. */ commentscanYYfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; commentscanYYfree ( (yy_state_buf) ); (yy_state_buf) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * commentscanYYlex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *commentscanYYalloc (yy_size_t size ) { return (void *) malloc( size ); } void *commentscanYYrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void commentscanYYfree (void * ptr ) { free( (char *) ptr ); /* see commentscanYYrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 2266 "commentscan.l" //---------------------------------------------------------------------------- static bool handleBrief(const QCString &) { //printf("handleBrief\n"); setOutput(OutputBrief); return FALSE; } static bool handleFn(const QCString &) { bool stop=makeStructuralIndicator(Entry::MEMBERDOC_SEC); functionProto.resize(0); braceCount=0; BEGIN(FnParam); return stop; } static bool handleDef(const QCString &) { bool stop=makeStructuralIndicator(Entry::DEFINEDOC_SEC); functionProto.resize(0); BEGIN(FnParam); return stop; } static bool handleOverload(const QCString &) { functionProto.resize(0); BEGIN(OverloadParam); return FALSE; } static bool handleEnum(const QCString &) { bool stop=makeStructuralIndicator(Entry::ENUMDOC_SEC); BEGIN(EnumDocArg1); return stop; } static bool handleDefGroup(const QCString &) { bool stop=makeStructuralIndicator(Entry::GROUPDOC_SEC); current->groupDocType = Entry::GROUPDOC_NORMAL; BEGIN( GroupDocArg1 ); return stop; } static bool handleAddToGroup(const QCString &) { bool stop=makeStructuralIndicator(Entry::GROUPDOC_SEC); current->groupDocType = Entry::GROUPDOC_ADD; BEGIN( GroupDocArg1 ); return stop; } static bool handleWeakGroup(const QCString &) { bool stop=makeStructuralIndicator(Entry::GROUPDOC_SEC); current->groupDocType = Entry::GROUPDOC_WEAK; BEGIN( GroupDocArg1 ); return stop; } static bool handleNamespace(const QCString &) { bool stop=makeStructuralIndicator(Entry::NAMESPACEDOC_SEC); BEGIN( NameSpaceDocArg1 ); return stop; } static bool handlePackage(const QCString &) { bool stop=makeStructuralIndicator(Entry::PACKAGEDOC_SEC); BEGIN( PackageDocArg1 ); return stop; } static bool handleClass(const QCString &) { bool stop=makeStructuralIndicator(Entry::CLASSDOC_SEC); BEGIN( ClassDocArg1 ); return stop; } static bool handleHeaderFile(const QCString &) { BEGIN( ClassDocArg2 ); return FALSE; } static bool handleProtocol(const QCString &) { // Obj-C protocol bool stop=makeStructuralIndicator(Entry::PROTOCOLDOC_SEC); BEGIN( ClassDocArg1 ); return stop; } static bool handleCategory(const QCString &) { // Obj-C category bool stop=makeStructuralIndicator(Entry::CATEGORYDOC_SEC); BEGIN( CategoryDocArg1 ); return stop; } static bool handleUnion(const QCString &) { bool stop=makeStructuralIndicator(Entry::UNIONDOC_SEC); BEGIN( ClassDocArg1 ); return stop; } static bool handleStruct(const QCString &) { bool stop=makeStructuralIndicator(Entry::STRUCTDOC_SEC); BEGIN( ClassDocArg1 ); return stop; } static bool handleInterface(const QCString &) { bool stop=makeStructuralIndicator(Entry::INTERFACEDOC_SEC); BEGIN( ClassDocArg1 ); return stop; } static bool handleIdlException(const QCString &) { bool stop=makeStructuralIndicator(Entry::EXCEPTIONDOC_SEC); BEGIN( ClassDocArg1 ); return stop; } static bool handlePage(const QCString &) { bool stop=makeStructuralIndicator(Entry::PAGEDOC_SEC); BEGIN( PageDocArg1 ); return stop; } static bool handleMainpage(const QCString &) { bool stop=makeStructuralIndicator(Entry::MAINPAGEDOC_SEC); if (!stop) { current->name = "mainpage"; } BEGIN( PageDocArg2 ); return stop; } static bool handleFile(const QCString &) { bool stop=makeStructuralIndicator(Entry::FILEDOC_SEC); if (!stop) { current->name = yyFileName; } BEGIN( FileDocArg1 ); return stop; } static bool handleParam(const QCString &) { // we need process param and retval arguments to escape leading underscores in case of // markdown processing, see bug775493 addOutput("@param "); BEGIN( ParamArg1 ); return FALSE; } static bool handleRetval(const QCString &) { addOutput("@retval "); BEGIN( ParamArg1 ); return FALSE; } static bool handleDir(const QCString &) { bool stop=makeStructuralIndicator(Entry::DIRDOC_SEC); if (!stop) current->name = yyFileName; BEGIN( FileDocArg1 ); return stop; } static bool handleExample(const QCString &) { bool stop=makeStructuralIndicator(Entry::EXAMPLE_SEC); if (!stop) current->name = yyFileName; BEGIN( FileDocArg1 ); return stop; } static bool handleDetails(const QCString &) { if (inContext!=OutputBrief) { addOutput("\n\n"); // treat @details outside brief description // as a new paragraph } setOutput(OutputDoc); return FALSE; } static bool handleName(const QCString &) { bool stop=makeStructuralIndicator(Entry::MEMBERGRP_SEC); if (!stop) { g_memberGroupHeader.resize(0); BEGIN( NameParam ); if (g_memberGroupId!=DOX_NOGROUP) // end of previous member group { closeGroup(current,yyFileName,yyLineNr,TRUE); } } return stop; } static bool handleTodo(const QCString &) { newXRefKind = XRef_Todo; setOutput(OutputXRef); xrefKind = XRef_Todo; return FALSE; } static bool handleTest(const QCString &) { newXRefKind = XRef_Test; setOutput(OutputXRef); xrefKind = XRef_Test; return FALSE; } static bool handleBug(const QCString &) { newXRefKind = XRef_Bug; setOutput(OutputXRef); xrefKind = XRef_Bug; return FALSE; } static bool handleDeprecated(const QCString &) { newXRefKind = XRef_Deprecated; setOutput(OutputXRef); xrefKind = XRef_Deprecated; return FALSE; } static bool handleXRefItem(const QCString &) { newXRefKind = XRef_Item; BEGIN(XRefItemParam1); return FALSE; } static bool handleParBlock(const QCString &) { if (g_insideParBlock) { warn(yyFileName,yyLineNr, "found \\parblock command while already in a parblock!"); } if (!g_spaceBeforeCmd.isEmpty()) { addOutput(g_spaceBeforeCmd); g_spaceBeforeCmd.resize(0); } addOutput("@parblock "); g_insideParBlock = TRUE; return FALSE; } static bool handleEndParBlock(const QCString &) { if (!g_insideParBlock) { warn(yyFileName,yyLineNr, "found \\endparblock command without matching \\parblock!"); } addOutput("@endparblock"); setOutput(OutputDoc); // to end a parblock inside a xrefitem like context g_insideParBlock = FALSE; return FALSE; } static bool handleRelated(const QCString &) { BEGIN(RelatesParam1); return FALSE; } static bool handleRelatedAlso(const QCString &) { current->relatesType = Duplicate; BEGIN(RelatesParam1); return FALSE; } static bool handleMemberOf(const QCString &) { current->relatesType = MemberOf; BEGIN(RelatesParam1); return FALSE; } static bool handleRefItem(const QCString &) { addOutput("@refitem "); BEGIN(LineParam); return FALSE; } static bool handleSection(const QCString &s) { setOutput(OutputDoc); addOutput("@"+s+" "); BEGIN(SectionLabel); if (s=="section") g_sectionLevel=1; else if (s=="subsection") g_sectionLevel=2; else if (s=="subsubsection") g_sectionLevel=3; else if (s=="paragraph") g_sectionLevel=4; return FALSE; } static bool handleSubpage(const QCString &s) { if (current->section!=Entry::EMPTY_SEC && current->section!=Entry::PAGEDOC_SEC && current->section!=Entry::MAINPAGEDOC_SEC ) { warn(yyFileName,yyLineNr, "found \\subpage command in a comment block that is not marked as a page!"); } if (!g_spaceBeforeCmd.isEmpty()) { addOutput(g_spaceBeforeCmd); g_spaceBeforeCmd.resize(0); } addOutput("@"+s+" "); BEGIN(SubpageLabel); return FALSE; } static bool handleAnchor(const QCString &s) { addOutput("@"+s+" "); BEGIN(AnchorLabel); return FALSE; } static bool handleCite(const QCString &s) { if (!g_spaceBeforeCmd.isEmpty()) { addOutput(g_spaceBeforeCmd); g_spaceBeforeCmd.resize(0); } addOutput("@"+s+" "); BEGIN(CiteLabel); return FALSE; } static bool handleFormatBlock(const QCString &s) { addOutput("@"+s+" "); //printf("handleFormatBlock(%s)\n",s.data()); blockName=s; g_commentCount=0; BEGIN(FormatBlock); return FALSE; } static bool handleAddIndex(const QCString &) { addOutput("@addindex "); BEGIN(LineParam); return FALSE; } static bool handleIf(const QCString &) { enabledSectionFound=FALSE; guardType = Guard_If; g_spaceBeforeIf = g_spaceBeforeCmd; BEGIN(GuardParam); return FALSE; } static bool handleIfNot(const QCString &) { enabledSectionFound=FALSE; guardType = Guard_IfNot; g_spaceBeforeIf = g_spaceBeforeCmd; BEGIN(GuardParam); return FALSE; } static bool handleElseIf(const QCString &) { if (guards.isEmpty()) { warn(yyFileName,yyLineNr, "found \\else without matching start command"); } else { guardType = enabledSectionFound ? Guard_Skip : Guard_If; BEGIN(GuardParam); } return FALSE; } static bool handleElse(const QCString &) { if (guards.isEmpty()) { warn(yyFileName,yyLineNr, "found \\else without matching start command"); } else { BEGIN( SkipGuardedSection ); } return FALSE; } static bool handleEndIf(const QCString &) { if (guards.isEmpty()) { warn(yyFileName,yyLineNr, "found \\endif without matching start command"); } else { delete guards.pop(); } enabledSectionFound=FALSE; if (!g_spaceBeforeCmd.isEmpty()) { addOutput(g_spaceBeforeCmd); g_spaceBeforeCmd.resize(0); } BEGIN( GuardParamEnd ); return FALSE; } static bool handleIngroup(const QCString &) { inGroupParamFound=FALSE; BEGIN( InGroupParam ); return FALSE; } static bool handleNoSubGrouping(const QCString &) { current->subGrouping = FALSE; return FALSE; } static bool handleShowInitializer(const QCString &) { current->initLines = 100000; // ON return FALSE; } static bool handleHideInitializer(const QCString &) { current->initLines = 0; // OFF return FALSE; } static bool handleCallgraph(const QCString &) { current->callGraph = TRUE; // ON return FALSE; } static bool handleHideCallgraph(const QCString &) { current->callGraph = FALSE; // OFF return FALSE; } static bool handleCallergraph(const QCString &) { current->callerGraph = TRUE; // ON return FALSE; } static bool handleHideCallergraph(const QCString &) { current->callerGraph = FALSE; // OFF return FALSE; } static bool handleInternal(const QCString &) { if (!Config_getBool(INTERNAL_DOCS)) { // make sure some whitespace before a \internal command // is not treated as "documentation" if (current->doc.stripWhiteSpace().isEmpty()) { current->doc.resize(0); } g_condCount=0; BEGIN( SkipInternal ); } else { // re-enabled for bug640828 addOutput("\\internal "); inInternalDocs = TRUE; } return FALSE; } static bool handleLineBr(const QCString &) { addOutput('\n'); return FALSE; } static bool handleStatic(const QCString &) { endBrief(); current->stat = TRUE; return FALSE; } static bool handlePure(const QCString &) { endBrief(); current->virt = Pure; return FALSE; } static bool handlePrivate(const QCString &) { current->protection = Private; return FALSE; } static bool handlePrivateSection(const QCString &) { current->protection = protection = Private; return FALSE; } static bool handleProtected(const QCString &) { current->protection = Protected; return FALSE; } static bool handleProtectedSection(const QCString &) { current->protection = protection = Protected ; return FALSE; } static bool handlePublic(const QCString &) { current->protection = Public; return FALSE; } static bool handlePublicSection(const QCString &) { current->protection = protection = Public; return FALSE; } static bool handleToc(const QCString &) { if (current->section==Entry::PAGEDOC_SEC || current->section==Entry::MAINPAGEDOC_SEC) { current->stat=TRUE; // we 'abuse' stat to pass whether or the TOC is enabled } return FALSE; } static bool handleInherit(const QCString &) { BEGIN(InheritParam); return FALSE; } static bool handleExtends(const QCString &) { BEGIN(ExtendsParam); return FALSE; } static bool handleCopyBrief(const QCString &) { if (current->brief.isEmpty() && current->doc.isEmpty()) { // if we don't have a brief or detailed description yet, // then the @copybrief should end up in the brief description. // otherwise it will be copied inline (see bug691315 & bug700788) setOutput(OutputBrief); } if (!g_spaceBeforeCmd.isEmpty()) { addOutput(g_spaceBeforeCmd); g_spaceBeforeCmd.resize(0); } addOutput("\\copybrief "); return FALSE; } static bool handleCopyDetails(const QCString &) { setOutput(OutputDoc); if (!g_spaceBeforeCmd.isEmpty()) { addOutput(g_spaceBeforeCmd); g_spaceBeforeCmd.resize(0); } addOutput("\\copydetails "); return FALSE; } static bool handleCopyDoc(const QCString &) { setOutput(OutputBrief); if (!g_spaceBeforeCmd.isEmpty()) { addOutput(g_spaceBeforeCmd); g_spaceBeforeCmd.resize(0); } addOutput("\\copybrief "); g_copyDocArg.resize(0); BEGIN(CopyDoc); return FALSE; } //---------------------------------------------------------------------------- static void checkFormula() { if (YY_START==ReadFormulaShort || YY_START==ReadFormulaLong) { warn(yyFileName,yyLineNr,"End of comment block while inside formula."); } } //---------------------------------------------------------------------------- bool parseCommentBlock(/* in */ ParserInterface *parser, /* in */ Entry *curEntry, /* in */ const QCString &comment, /* in */ const QCString &fileName, /* in,out */ int &lineNr, /* in */ bool isBrief, /* in */ bool isAutoBriefOn, /* in */ bool isInbody, /* in,out */ Protection &prot, /* in,out */ int &position, /* out */ bool &newEntryNeeded ) { //printf("parseCommentBlock() isBrief=%d isAutoBriefOn=%d lineNr=%d\n", // isBrief,isAutoBriefOn,lineNr); initParser(); guards.setAutoDelete(TRUE); guards.clear(); langParser = parser; current = curEntry; if (comment.isEmpty()) return FALSE; // avoid empty strings inputString = comment; inputString.append(" "); inputPosition = position; yyLineNr = lineNr; yyFileName = fileName; protection = prot; needNewEntry = FALSE; xrefKind = XRef_None; xrefAppendFlag = FALSE; insidePre = FALSE; parseMore = FALSE; inBody = isInbody; outputXRef.resize(0); setOutput( isBrief || isAutoBriefOn ? OutputBrief : OutputDoc ); briefEndsAtDot = isAutoBriefOn; g_condCount = 0; g_sectionLevel = 0; g_spaceBeforeCmd.resize(0); g_spaceBeforeIf.resize(0); printlex(commentscanYY_flex_debug, TRUE, __FILE__, fileName ? fileName.data(): NULL); if (!current->inbodyDocs.isEmpty() && isInbody) // separate in body fragments { current->inbodyDocs+="\n\n"; } Debug::print(Debug::CommentScan,0,"-----------\nCommentScanner: %s:%d\n" "input=[\n%s]\n",qPrint(fileName),lineNr,qPrint(comment) ); commentscanYYrestart( commentscanYYin ); BEGIN( Comment ); commentscanYYlex(); setOutput( OutputDoc ); if (YY_START==OverloadParam) // comment ended with \overload { addOutput(getOverloadDocs()); } if (!guards.isEmpty()) { warn(yyFileName,yyLineNr,"Documentation block ended in the middle of a conditional section!"); } if (g_insideParBlock) { warn(yyFileName,yyLineNr, "Documentation block ended while inside a \\parblock. Missing \\endparblock"); } current->doc=stripLeadingAndTrailingEmptyLines(current->doc,current->docLine); if (current->section==Entry::FILEDOC_SEC && current->doc.isEmpty()) { // to allow a comment block with just a @file command. current->doc="\n\n"; } if (current->section==Entry::MEMBERGRP_SEC && g_memberGroupId==DOX_NOGROUP) // @name section but no group started yet { openGroup(current,yyFileName,yyLineNr); } if (Doxygen::markdownSupport) { current->brief = processMarkdown(fileName,lineNr,current,current->brief); current->doc = processMarkdown(fileName,lineNr,current,current->doc); current->inbodyDocs = processMarkdown(fileName,lineNr,current,current->inbodyDocs); } Debug::print(Debug::CommentScan,0, "brief=[line=%d\n%s]\ndocs=[line=%d\n%s]\ninbody=[line=%d\n%s]\n===========\n", current->briefLine,qPrint(current->brief), current->docLine,qPrint(current->doc), current->inbodyLine,qPrint(current->inbodyDocs) ); checkFormula(); prot = protection; groupAddDocs(curEntry); newEntryNeeded = needNewEntry; // if we did not proceed during this call, it does not make // sense to continue, since we get stuck. See bug 567346 for situations // were this happens if (parseMore && position==inputPosition) parseMore=FALSE; if (parseMore) position=inputPosition; else position=0; lineNr = yyLineNr; //printf("position=%d parseMore=%d newEntryNeeded=%d\n", // position,parseMore,newEntryNeeded); printlex(commentscanYY_flex_debug, FALSE, __FILE__, fileName ? fileName.data(): NULL); return parseMore; } //--------------------------------------------------------------------------- void groupEnterFile(const char *fileName,int) { g_autoGroupStack.setAutoDelete(TRUE); g_autoGroupStack.clear(); g_memberGroupId = DOX_NOGROUP; g_memberGroupDocs.resize(0); g_memberGroupRelates.resize(0); g_compoundName=fileName; } void groupLeaveFile(const char *fileName,int line) { //if (g_memberGroupId!=DOX_NOGROUP) //{ // warn(fileName,line,"end of file while inside a member group\n"); //} g_memberGroupId=DOX_NOGROUP; g_memberGroupRelates.resize(0); g_memberGroupDocs.resize(0); if (!g_autoGroupStack.isEmpty()) { warn(fileName,line,"end of file while inside a group\n"); } } void groupEnterCompound(const char *fileName,int line,const char *name) { if (g_memberGroupId!=DOX_NOGROUP) { warn(fileName,line,"try to put compound %s inside a member group\n",name); } g_memberGroupId=DOX_NOGROUP; g_memberGroupRelates.resize(0); g_memberGroupDocs.resize(0); g_compoundName = name; int i = g_compoundName.find('('); if (i!=-1) { g_compoundName=g_compoundName.left(i); // strip category (Obj-C) } if (g_compoundName.isEmpty()) { g_compoundName=fileName; } //printf("groupEnterCompound(%s)\n",name); } void groupLeaveCompound(const char *,int,const char * /*name*/) { //printf("groupLeaveCompound(%s)\n",name); //if (g_memberGroupId!=DOX_NOGROUP) //{ // warn(fileName,line,"end of compound %s while inside a member group\n",name); //} g_memberGroupId=DOX_NOGROUP; g_memberGroupRelates.resize(0); g_memberGroupDocs.resize(0); g_compoundName.resize(0); } static int findExistingGroup(int &groupId,const MemberGroupInfo *info) { //printf("findExistingGroup %s:%s\n",info->header.data(),info->compoundName.data()); QIntDictIterator<MemberGroupInfo> di(Doxygen::memGrpInfoDict); MemberGroupInfo *mi; for (di.toFirst();(mi=di.current());++di) { if (g_compoundName==mi->compoundName && // same file or scope !mi->header.isEmpty() && // not a nameless group qstricmp(mi->header,info->header)==0 // same header name ) { //printf("Found it!\n"); return (int)di.currentKey(); // put the item in this group } } groupId++; // start new group return groupId; } void openGroup(Entry *e,const char *,int) { //printf("==> openGroup(name=%s,sec=%x) g_autoGroupStack=%d\n", // e->name.data(),e->section,g_autoGroupStack.count()); if (e->section==Entry::GROUPDOC_SEC) // auto group { g_autoGroupStack.push(new Grouping(e->name,e->groupingPri())); } else // start of a member group { //printf(" membergroup id=%d %s\n",g_memberGroupId,g_memberGroupHeader.data()); if (g_memberGroupId==DOX_NOGROUP) // no group started yet { static int curGroupId=0; MemberGroupInfo *info = new MemberGroupInfo; info->header = g_memberGroupHeader.stripWhiteSpace(); info->compoundName = g_compoundName; g_memberGroupId = findExistingGroup(curGroupId,info); //printf(" use membergroup %d\n",g_memberGroupId); Doxygen::memGrpInfoDict.insert(g_memberGroupId,info); g_memberGroupRelates = e->relates; e->mGrpId = g_memberGroupId; } } } void closeGroup(Entry *e,const char *fileName,int line,bool foundInline) { //printf("==> closeGroup(name=%s,sec=%x,file=%s,line=%d) g_autoGroupStack=%d\n", // e->name.data(),e->section,fileName,line,g_autoGroupStack.count()); if (g_memberGroupId!=DOX_NOGROUP) // end of member group { MemberGroupInfo *info=Doxygen::memGrpInfoDict.find(g_memberGroupId); if (info) // known group { info->doc = g_memberGroupDocs; info->docFile = fileName; info->docLine = line; } g_memberGroupId=DOX_NOGROUP; g_memberGroupRelates.resize(0); g_memberGroupDocs.resize(0); if (!foundInline) e->mGrpId=DOX_NOGROUP; //printf("new group id=%d\n",g_memberGroupId); } else if (!g_autoGroupStack.isEmpty()) // end of auto group { Grouping *grp = g_autoGroupStack.pop(); // see bug577005: we should not remove the last group for e if (!foundInline) e->groups->removeLast(); //printf("Removing %s e=%p\n",grp->groupname.data(),e); delete grp; if (!foundInline) initGroupInfo(e); } } void initGroupInfo(Entry *e) { //printf("==> initGroup(id=%d,related=%s,e=%p)\n",g_memberGroupId, // g_memberGroupRelates.data(),e); e->mGrpId = g_memberGroupId; e->relates = g_memberGroupRelates; if (!g_autoGroupStack.isEmpty()) { //printf("Appending group %s to %s: count=%d entry=%p\n", // g_autoGroupStack.top()->groupname.data(), // e->name.data(),e->groups->count(),e); e->groups->append(new Grouping(*g_autoGroupStack.top())); } } static void groupAddDocs(Entry *e) { if (e->section==Entry::MEMBERGRP_SEC) { g_memberGroupDocs=e->brief.stripWhiteSpace(); e->doc = stripLeadingAndTrailingEmptyLines(e->doc,e->docLine); if (!g_memberGroupDocs.isEmpty() && !e->doc.isEmpty()) { g_memberGroupDocs+="\n\n"; } g_memberGroupDocs+=e->doc; MemberGroupInfo *info=Doxygen::memGrpInfoDict.find(g_memberGroupId); if (info) { info->doc = g_memberGroupDocs; info->docFile = e->docFile; info->docLine = e->docLine; info->setRefItems(e->sli); } e->doc.resize(0); e->brief.resize(0); } } static void handleGuard(const QCString &expr) { CondParser prs; bool sectionEnabled=prs.parse(yyFileName,yyLineNr,expr.stripWhiteSpace()); bool parentEnabled = TRUE; if (!guards.isEmpty()) parentEnabled = guards.top()->isEnabled(); if (parentEnabled) { if ( (sectionEnabled && guardType==Guard_If) || (!sectionEnabled && guardType==Guard_IfNot) ) // section is visible { guards.push(new GuardedSection(TRUE,TRUE)); enabledSectionFound=TRUE; BEGIN( GuardParamEnd ); } else // section is invisible { if (guardType!=Guard_Skip) { guards.push(new GuardedSection(FALSE,TRUE)); } BEGIN( SkipGuardedSection ); } } else // invisible because of parent { guards.push(new GuardedSection(FALSE,FALSE)); BEGIN( SkipGuardedSection ); } } #if !defined(YY_FLEX_SUBMINOR_VERSION) //---------------------------------------------------------------------------- extern "C" { // some bogus code to keep the compiler happy void commentscanYYdummy() { yy_flex_realloc(0,0); } } #endif
[ "audrey.bender@epfl.ch" ]
audrey.bender@epfl.ch
ddbcd91b5d73966b3f73e16763e7ec48558990c9
292827a33c60bdba5643a19a58b0add3d8f7bd1e
/Project_Dependant/IOinputBlocked.hpp
1a2ee06a66ea8f9ae88484cf5f3c2e93c9a67fac
[]
no_license
artcampo/2012_3D_96k_Procedural_game
143c9a6ca351fca127f8b00d2ebb8a461a002e9c
ae33e17c795457d777a0569762a3d157de4774b1
refs/heads/master
2021-01-12T04:27:50.727862
2016-12-29T14:01:49
2016-12-29T14:01:49
77,615,952
0
0
null
null
null
null
UTF-8
C++
false
false
828
hpp
#ifndef _IO_INPUT_BLOCKED_HPP #define _IO_INPUT_BLOCKED_HPP #include "dx_misc.hpp" #include "Camera/Camera.hpp" #include "Camera/CameraThidPerson.hpp" #include "Camera/CameraFirstPerson.hpp" #include "physics/Physics.hpp" #include "GameBall/Game.hpp" #include "Project_Dependant/IOAbstract.hpp" class GameBpApp; class IoInputBlocked : public IoAbstract { public: IoInputBlocked( Camera* aCam, Game *aGame, GameBpApp* aGameApp ); ~IoInputBlocked(); void Move ( unsigned int key ); void MouseMove ( D3DXVECTOR3* inc_mouse ); void initIoReading( float aDeltaT ); void finishIoReading( D3DXVECTOR3* aMouseIncrement ); private: Camera* mCam; /*!< Camera*/ Game* mGame; //for callbacks GameBpApp* mGameApp; //for callbacks }; #endif
[ "arturocampos82@gmail.com" ]
arturocampos82@gmail.com
d5af8dc9d5f6415ce88dee5c6ee5fddbc9eda3ee
2f7e428c916aedc7e227b0f093cd11f906f7e3f7
/c++/Builder/UserBuilder/UserBuilder.hpp
13e5be3dc8c3fedeb4c4b00cc584e9343eec220a
[ "MIT" ]
permissive
Om4ar/Design-Patterns
2b8c290f635260a12ea1e5f482c2eb83af5abf55
210553651660072bad3a6b954b581742c5501ec0
refs/heads/master
2020-07-21T13:37:52.248416
2019-06-26T13:42:28
2019-06-26T13:42:28
206,883,388
1
0
MIT
2019-09-06T22:31:57
2019-09-06T22:31:57
null
UTF-8
C++
false
false
440
hpp
#ifndef __USER_BUILDER_H_ #define __USER_BUILDER_H_ #include <string> #include "../User/User.hpp" class UserBuilder { private: string _firstName; string _lastName; int _age; string _street; public: UserBuilder(); UserBuilder& withFirstName(string name); UserBuilder& withLastName(string name); UserBuilder& withAge(int age); UserBuilder& liveInStreet(string street); User& build(); }; #endif
[ "fastercodingtutorial@gmail.com" ]
fastercodingtutorial@gmail.com
d0bc83c09fc6e294450adb7981767a8edf493d71
f02534d5d190c1f239b6d3bc7f37740f36d24069
/LQCore/Selection/include/BaseSelection.h
ea220c8e7bd565a12f69aea10ec17609f696ab0c
[]
no_license
sungbinoh/LQanalyzer
c8d7031df94d7f4ebca541b6f93cdfb5aafbd61a
43844b72271f2b9fb862a608e5c4270796625b7b
refs/heads/CatAnalyzer_13TeV
2020-01-23T21:52:56.054920
2016-11-17T16:11:11
2016-11-17T16:11:11
74,735,602
0
1
null
2016-11-25T07:30:16
2016-11-25T07:30:15
null
UTF-8
C++
false
false
4,315
h
#ifndef BaseSelection_h #define BaseSelection_h #include <iostream> using namespace std; #include <TROOT.h> #include <TChain.h> #include <TFile.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include "TLorentzVector.h" #include "TH1F.h" #include "TH2F.h" #include "TH3F.h" #include "AnalysisBase.h" #include "LQEvent.h" class BaseSelection { public: enum ID { ELECTRON_POG_VETO = 0, ELECTRON_POG_LOOSE = 1, ELECTRON_POG_MEDIUM = 2, ELECTRON_POG_TIGHT = 3, ELECTRON_POG_MVATrig = 4, ELECTRON_POG_MVANonTrig = 5, ELECTRON_ECAL_FIDUCIAL = 6, ELECTRON_HN_VETO = 7, ELECTRON_HN_TIGHT = 8, ELECTRON_HN_FAKELOOSE = 9, ELECTRON_HN_FAKELOOSE_NOD0 = 10, ELECTRON_TOP_VETO = 11, ELECTRON_TOP_LOOSE = 12, ELECTRON_TOP_TIGHT = 13, ELECTRON_PTETA = 14, ELECTRON_NOCUT = 15, MUON_POG_LOOSE = 16, MUON_POG_MEDIUM = 17, MUON_POG_TIGHT = 18, MUON_HN_VETO = 19, MUON_HN_FAKELOOSE = 20, MUON_HN_TIGHT = 21, MUON_FAKELOOSE = 22, MUON_TOP_VETO = 23, MUON_TOP_LOOSE = 24, MUON_TOP_TIGHT = 25, MUON_PTETA = 26, MUON_NOCUT = 27, PFJET_LOOSE = 28, PFJET_MEDIUM = 29, PFJET_TIGHT = 30, JET_HN = 31, JET_HN_TChannel = 32, JET_NOLEPTONVETO = 33, JET_LOOSE = 34, JET_TIGHT = 35, PHOTON_POG_LOOSE = 36, PHOTON_POG_MEDIUM = 37, PHOTON_POG_TIGHT = 38, }; Int_t ifid; //// Selection cuts Bool_t etaPt,RelIsod0Chi2,DepositVeto,individual,RelIsod0;//fiducial;//muonid,pTcut,isIso; //// variables to make cuts Double_t LeptonRelIso,dxy,dz,D0,D0Error,D0Significance,Vxy, Vz; Double_t LeptonchiNdof; Int_t numlep; Bool_t jetIsOK; /// variables to set cuts Double_t pt_cut_min, pt_cut_max, eta_cut_min, eta_cut, jpt_cut_min, jpt_cut_max, jeta_cut_min, jeta_cut, relIso_cut, relIsoMIN_cut, chiNdof_cut, chiNdofMIN_cut, dxy_cut, dxyMIN_cut, dz_cut; Int_t casediscriminator,simpleselection; /// LQEvent class object. Stores all vectors LQEvent k_lqevent; TString AccessStringMap(TString label, TString id); float AccessFloatMap(TString label, TString id); bool CheckCutFloat(TString label, TString id); bool CheckCutString(TString label, TString id); TString GetString(ID id); map<TString,vector<pair<TString,TString> > > k_stringmap; map<TString,vector<pair<TString,float> > > k_floatmap; void SetIDSMap(std::map<TString, vector<pair<TString,TString> > > smap); void SetIDFMap(std::map<TString, vector<pair<TString,float> > > smap); void PrintSIDMap(); void PrintFIDMap(); BaseSelection(); BaseSelection& operator= (const BaseSelection& obj); BaseSelection(const BaseSelection& bs); ~BaseSelection(); /// bools to tell selector to apply cuts Bool_t apply_ptcut,apply_etacut, apply_jptcut,apply_jetacut, apply_relisocut, apply_chi2cut, apply_dxycut, apply_dzcut, apply_general, apply_deposit; Bool_t apply_ID, apply_convcut, apply_chargeconst, applypileuptool; ID k_id; /// SetCut functions void reset(); void SetPt(Double_t minPt, Double_t maxPt); void SetPt(Double_t minPt); void SetJetPt(Double_t minPt); void SetEta(Double_t Eta); void SetUseJetPileUp(bool use); void SetJetEta(Double_t Eta); void SetEta(Double_t minEta, Double_t Eta); void SetRelIso(Double_t RelIso); void SetRelIso(Double_t RelIsoMIN, Double_t RelIso); void SetChiNdof(Double_t ChiNdof); void SetChiNdof(Double_t ChiNdofMIN, Double_t ChiNdof); void SetBSdxy(Double_t dxy); void SetBSdxy(Double_t dxyMIN, Double_t dxy); void SetBSdz(Double_t dz); void SetID(ID id); void SetCheckCharge(bool check); void SetApplyConvVeto(bool apply); }; #endif
[ "jalmond@cern.ch" ]
jalmond@cern.ch
d23509795a8724fdf12e3e5e4744ae9e470c38ee
3b59884fb983fc78ec34a1ae82003b2c95a0b34e
/src/behavior/valuefunction/Q_provider.h
3f50aba050d0f1eb9e10aeff06fbb48407aeb6f4
[ "Apache-2.0" ]
permissive
MarkieMark/fastrl
8b0704d498b2a7a5378abfbceef2cd2d6c2f10cb
e4f0b9b60a7ecb6f13bbb79936ea82acb8adae0e
refs/heads/master
2021-01-23T00:25:57.964522
2019-03-10T13:17:18
2019-03-27T09:12:48
92,812,155
6
0
null
null
null
null
UTF-8
C++
false
false
695
h
// // Mark Benjamin 6/1/17. // Copyright (c) 2017 Mark Benjamin // #ifndef FASTRL_BEHAVIOR_VALUEFUNCTION_Q_PROVIDER_H #define FASTRL_BEHAVIOR_VALUEFUNCTION_Q_PROVIDER_H #include "Q_function.hpp" #include "../policy/enumerable_policy.hpp" #include "Q_value.hpp" class QProvider : public QFunction { public: virtual vector<QValue *> qValues(State *s) { throw runtime_error("QProvider::qValues() Not Implemented"); } }; class QProviderHelper { private: QProviderHelper() = default; public: static double maxQ(QProvider * qSource, State *s); static double policyValue(QProvider * qSource, State *s, EnumerablePolicy * p); }; #endif // FASTRL_BEHAVIOR_VALUEFUNCTION_Q_PROVIDER_H
[ "MarkBenjamin1@gatech.edu" ]
MarkBenjamin1@gatech.edu
5bf3dfb0656b8fd54cf738f9ad8bbdfcb6066702
ebad70e7b3228b10b2d277462da2f7a37c93c26e
/src/osdep/gui/EditFilesysVirtual.cpp
2df16339f495b07f6fed01e6b915bfa991061dc0
[]
no_license
03stevensmi/uae4arm
a6390bc4bcb33c7ef30015efc592aa785434d3b0
0689cf926bbc2e8643af7302f789161e79179581
refs/heads/master
2020-03-29T12:42:52.218305
2018-07-08T17:11:09
2018-07-08T17:11:09
149,914,199
0
0
null
null
null
null
UTF-8
C++
false
false
10,828
cpp
#ifdef USE_SDL2 #include <guisan.hpp> #include <SDL_ttf.h> #include <guisan/sdl.hpp> #include <guisan/sdl/sdltruetypefont.hpp> #else #include <guichan.hpp> #include <SDL/SDL_ttf.h> #include <guichan/sdl.hpp> #include "sdltruetypefont.hpp" #endif #include "SelectorEntry.hpp" #include "UaeRadioButton.hpp" #include "UaeDropDown.hpp" #include "UaeCheckBox.hpp" #include "sysconfig.h" #include "sysdeps.h" #include "config.h" #include "options.h" #include "memory-uae.h" #include "uae.h" #include "autoconf.h" #include "filesys.h" #include "gui.h" #include "gui_handling.h" #ifdef ANDROIDSDL #include "androidsdl_event.h" #endif #define DIALOG_WIDTH 520 #define DIALOG_HEIGHT 202 extern std::string volName; static bool dialogResult = false; static bool dialogFinished = false; static gcn::Window *wndEditFilesysVirtual; static gcn::Button* cmdOK; static gcn::Button* cmdCancel; static gcn::Label *lblDevice; static gcn::TextField *txtDevice; static gcn::Label *lblVolume; static gcn::TextField *txtVolume; static gcn::Label *lblPath; static gcn::TextField *txtPath; static gcn::Button* cmdPath; static gcn::UaeCheckBox* chkReadWrite; static gcn::UaeCheckBox* chkAutoboot; static gcn::Label *lblBootPri; static gcn::TextField *txtBootPri; class FilesysVirtualActionListener : public gcn::ActionListener { public: void action(const gcn::ActionEvent& actionEvent) { if(actionEvent.getSource() == cmdPath) { char tmp[MAX_PATH]; strncpy(tmp, txtPath->getText().c_str(), MAX_PATH); wndEditFilesysVirtual->releaseModalFocus(); if(SelectFolder("Select folder", tmp)) { txtPath->setText(tmp); txtVolume->setText(volName); } wndEditFilesysVirtual->requestModalFocus(); cmdPath->requestFocus(); } else { if (actionEvent.getSource() == cmdOK) { if(txtDevice->getText().length() <= 0) { wndEditFilesysVirtual->setCaption("Please enter a device name."); return; } if(txtVolume->getText().length() <= 0) { wndEditFilesysVirtual->setCaption("Please enter a volume name."); return; } dialogResult = true; } dialogFinished = true; } } }; static FilesysVirtualActionListener* filesysVirtualActionListener; static void InitEditFilesysVirtual(void) { wndEditFilesysVirtual = new gcn::Window("Edit"); wndEditFilesysVirtual->setSize(DIALOG_WIDTH, DIALOG_HEIGHT); wndEditFilesysVirtual->setPosition((GUI_WIDTH - DIALOG_WIDTH) / 2, (GUI_HEIGHT - DIALOG_HEIGHT) / 2); wndEditFilesysVirtual->setBaseColor(gui_baseCol + 0x202020); wndEditFilesysVirtual->setCaption("Volume settings"); wndEditFilesysVirtual->setTitleBarHeight(TITLEBAR_HEIGHT); filesysVirtualActionListener = new FilesysVirtualActionListener(); cmdOK = new gcn::Button("Ok"); cmdOK->setSize(BUTTON_WIDTH, BUTTON_HEIGHT); cmdOK->setPosition(DIALOG_WIDTH - DISTANCE_BORDER - 2 * BUTTON_WIDTH - DISTANCE_NEXT_X, DIALOG_HEIGHT - 2 * DISTANCE_BORDER - BUTTON_HEIGHT - 10); cmdOK->setBaseColor(gui_baseCol + 0x202020); cmdOK->setId("virtOK"); cmdOK->addActionListener(filesysVirtualActionListener); cmdCancel = new gcn::Button("Cancel"); cmdCancel->setSize(BUTTON_WIDTH, BUTTON_HEIGHT); cmdCancel->setPosition(DIALOG_WIDTH - DISTANCE_BORDER - BUTTON_WIDTH, DIALOG_HEIGHT - 2 * DISTANCE_BORDER - BUTTON_HEIGHT - 10); cmdCancel->setBaseColor(gui_baseCol + 0x202020); cmdCancel->setId("virtCancel"); cmdCancel->addActionListener(filesysVirtualActionListener); lblDevice = new gcn::Label("Device Name:"); lblDevice->setSize(100, LABEL_HEIGHT); lblDevice->setAlignment(gcn::Graphics::RIGHT); txtDevice = new gcn::TextField(); txtDevice->setSize(80, TEXTFIELD_HEIGHT); txtDevice->setId("virtDev"); lblVolume = new gcn::Label("Volume Label:"); lblVolume->setSize(100, LABEL_HEIGHT); lblVolume->setAlignment(gcn::Graphics::RIGHT); txtVolume = new gcn::TextField(); txtVolume->setSize(80, TEXTFIELD_HEIGHT); txtVolume->setId("virtVol"); lblPath = new gcn::Label("Path:"); lblPath->setSize(100, LABEL_HEIGHT); lblPath->setAlignment(gcn::Graphics::RIGHT); txtPath = new gcn::TextField(); txtPath->setSize(338, TEXTFIELD_HEIGHT); txtPath->setEnabled(false); cmdPath = new gcn::Button("..."); cmdPath->setSize(SMALL_BUTTON_WIDTH, SMALL_BUTTON_HEIGHT); cmdPath->setBaseColor(gui_baseCol + 0x202020); cmdPath->setId("virtPath"); cmdPath->addActionListener(filesysVirtualActionListener); chkReadWrite = new gcn::UaeCheckBox("Read/Write", true); chkReadWrite->setId("virtRW"); chkAutoboot = new gcn::UaeCheckBox("Bootable", true); chkAutoboot->setId("virtAutoboot"); lblBootPri = new gcn::Label("Boot priority:"); lblBootPri->setSize(84, LABEL_HEIGHT); lblBootPri->setAlignment(gcn::Graphics::RIGHT); txtBootPri = new gcn::TextField(); txtBootPri->setSize(40, TEXTFIELD_HEIGHT); txtBootPri->setId("virtBootpri"); int posY = DISTANCE_BORDER; int posX = DISTANCE_BORDER; wndEditFilesysVirtual->add(lblDevice, DISTANCE_BORDER, posY); posX += lblDevice->getWidth() + 8; wndEditFilesysVirtual->add(txtDevice, posX, posY); posX += txtDevice->getWidth() + DISTANCE_BORDER * 2; wndEditFilesysVirtual->add(chkReadWrite, posX, posY + 1); posY += txtDevice->getHeight() + DISTANCE_NEXT_Y; wndEditFilesysVirtual->add(lblVolume, DISTANCE_BORDER, posY); wndEditFilesysVirtual->add(txtVolume, txtDevice->getX(), posY); wndEditFilesysVirtual->add(chkAutoboot, chkReadWrite->getX(), posY + 1); posX += chkAutoboot->getWidth() + DISTANCE_BORDER * 2; wndEditFilesysVirtual->add(lblBootPri, posX, posY); wndEditFilesysVirtual->add(txtBootPri, posX + lblBootPri->getWidth() + 8, posY); posY += txtDevice->getHeight() + DISTANCE_NEXT_Y; wndEditFilesysVirtual->add(lblPath, DISTANCE_BORDER, posY); wndEditFilesysVirtual->add(txtPath, DISTANCE_BORDER + lblDevice->getWidth() + 8, posY); wndEditFilesysVirtual->add(cmdPath, wndEditFilesysVirtual->getWidth() - DISTANCE_BORDER - SMALL_BUTTON_WIDTH, posY); posY += txtDevice->getHeight() + DISTANCE_NEXT_Y; wndEditFilesysVirtual->add(cmdOK); wndEditFilesysVirtual->add(cmdCancel); gui_top->add(wndEditFilesysVirtual); txtDevice->requestFocus(); wndEditFilesysVirtual->requestModalFocus(); } static void ExitEditFilesysVirtual(void) { wndEditFilesysVirtual->releaseModalFocus(); gui_top->remove(wndEditFilesysVirtual); delete lblDevice; delete txtDevice; delete lblVolume; delete txtVolume; delete lblPath; delete txtPath; delete cmdPath; delete chkReadWrite; delete chkAutoboot; delete lblBootPri; delete txtBootPri; delete cmdOK; delete cmdCancel; delete filesysVirtualActionListener; delete wndEditFilesysVirtual; } static void EditFilesysVirtualLoop(void) { #ifndef USE_SDL2 FocusBugWorkaround(wndEditFilesysVirtual); #endif while(!dialogFinished) { SDL_Event event; while(SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { switch(event.key.keysym.sym) { case VK_ESCAPE: dialogFinished = true; break; case VK_UP: if(HandleNavigation(DIRECTION_UP)) continue; // Don't change value when enter ComboBox -> don't send event to control break; case VK_DOWN: if(HandleNavigation(DIRECTION_DOWN)) continue; // Don't change value when enter ComboBox -> don't send event to control break; case VK_LEFT: if(HandleNavigation(DIRECTION_LEFT)) continue; // Don't change value when enter Slider -> don't send event to control break; case VK_RIGHT: if(HandleNavigation(DIRECTION_RIGHT)) continue; // Don't change value when enter Slider -> don't send event to control break; case VK_X: case VK_A: event.key.keysym.sym = SDLK_RETURN; gui_input->pushInput(event); // Fire key down event.type = SDL_KEYUP; // and the key up break; default: break; } } //------------------------------------------------- // Send event to guichan/guisan-controls //------------------------------------------------- #ifdef ANDROIDSDL androidsdl_event(event, gui_input); #else gui_input->pushInput(event); #endif } // Now we let the Gui object perform its logic. uae_gui->logic(); // Now we let the Gui object draw itself. uae_gui->draw(); // Finally we update the screen. wait_for_vsync(); #ifdef USE_SDL2 UpdateGuiScreen(); #else SDL_Flip(gui_screen); #endif } } bool EditFilesysVirtual(int unit_no) { struct mountedinfo mi; struct uaedev_config_data *uci; std::string strdevname, strvolname, strroot; char tmp[32]; dialogResult = false; dialogFinished = false; InitEditFilesysVirtual(); if(unit_no >= 0) { struct uaedev_config_info *ci; uci = &changed_prefs.mountconfig[unit_no]; ci = &uci->ci; get_filesys_unitconfig(&changed_prefs, unit_no, &mi); strdevname.assign(ci->devname); txtDevice->setText(strdevname); strvolname.assign(ci->volname); txtVolume->setText(strvolname); strroot.assign(ci->rootdir); txtPath->setText(strroot); chkReadWrite->setSelected(!ci->readonly); chkAutoboot->setSelected(ci->bootpri != BOOTPRI_NOAUTOBOOT); snprintf(tmp, sizeof (tmp), "%d", ci->bootpri >= -127 ? ci->bootpri : -127); txtBootPri->setText(tmp); } else { CreateDefaultDevicename(tmp); txtDevice->setText(tmp); txtVolume->setText(tmp); strroot.assign(currentDir); txtPath->setText(strroot); chkReadWrite->setSelected(true); txtBootPri->setText("0"); } EditFilesysVirtualLoop(); if(dialogResult) { struct uaedev_config_info ci; int bp = tweakbootpri(atoi(txtBootPri->getText().c_str()), chkAutoboot->isSelected() ? 1 : 0, 0); extractPath((char *) txtPath->getText().c_str(), currentDir); uci_set_defaults(&ci, true); strncpy(ci.devname, (char *) txtDevice->getText().c_str(), MAX_DPATH); strncpy(ci.volname, (char *) txtVolume->getText().c_str(), MAX_DPATH); strncpy(ci.rootdir, (char *) txtPath->getText().c_str(), MAX_DPATH); ci.type = UAEDEV_DIR; ci.readonly = !chkReadWrite->isSelected(); ci.bootpri = bp; uci = add_filesys_config(&changed_prefs, unit_no, &ci); if (uci) { struct hardfiledata *hfd = get_hardfile_data (uci->configoffset); hardfile_media_change (hfd, &ci, true, false); } } ExitEditFilesysVirtual(); return dialogResult; }
[ "lubomyr31@gmail.com" ]
lubomyr31@gmail.com
a37949a39891d9b4f5103e8b796372b676da8062
59dfb4acc4a58b7e6332254a604a40c365d3d114
/Excises/Horton Beginning Visual C++ 2012 - 副本/Ivor Horton Website Code & Exercises/368084 Code from the Book/Chapter 09/Ex9_13/Ex9_13.cpp
4dacca03f4dff16e670d234dbd2c9e8bd1d58e1b
[]
no_license
JerCaptain39/my_cpp_project
2f227c7095bd4f73d4da5abf9768359e32b28b80
87b4afc52ecce6f5133739951ec0409d7acee16e
refs/heads/master
2021-05-11T17:23:21.553971
2018-01-19T09:29:20
2018-01-19T09:29:20
117,798,030
0
0
null
null
null
null
UTF-8
C++
false
false
1,268
cpp
// Ex9_13.cpp // Using a nested class to define a stack #include "Box.h" // For CBox and CContainer #include "GlassBox.h" // For CGlassBox (and CBox and CContainer) #include "Stack.h" // For the stack class with nested struct CItem #include <iostream> // For stream I/O using std::cout; using std::endl; int main() { CBox* pBoxes[] = { new CBox(2.0, 3.0, 4.0), new CGlassBox(2.0, 3.0, 4.0), new CBox(4.0, 5.0, 6.0), new CGlassBox(4.0, 5.0, 6.0) }; cout << "The array of boxes have the following volumes:"; for (CBox* pBox : pBoxes) pBox->ShowVolume(); // Output the volume of a box cout << endl << endl << "Now pushing the boxes on the stack..." << endl; CStack stack; // Create the stack for (CBox* pBox : pBoxes) // Store box pointers in the stack stack.Push(pBox); cout << "Popping the boxes off the stack presents them in reverse order:"; CBox* pTemp(nullptr); while(pTemp = stack.Pop()) pTemp->ShowVolume(); cout << endl; for (CBox* pBox : pBoxes) // Delete the boxes delete pBox; return 0; }
[ "JerCaptain39@outlook.com" ]
JerCaptain39@outlook.com
0c8dede94a63c7c7af9a91060a4fa2d16178d8a7
5d8c71b1b580517fb807efdfd673a46944b9957b
/znRender/DepthStencilState.h
376f4c6509224972d0f7e2d8f30413d25d4fec68
[]
no_license
bmjoy/ZenonEngine
abe2c4c47d1930f343dadcaed7d3c360660aa1bf
c7d1564246157abfa84b7028817bedff6993693b
refs/heads/master
2020-05-23T03:12:21.586899
2019-04-22T10:52:31
2019-04-22T10:52:31
186,611,748
1
1
null
2019-05-14T11:51:37
2019-05-14T11:51:37
null
UTF-8
C++
false
false
7,378
h
#pragma once class DepthStencilState : public Object { public: /** * Used to enable or disable depth buffer writes. */ enum class DepthWrite { Enable, Disable }; /** * Compare function determines if a pixel is written to the back buffer. * This enumerator is used for both depth and stencil operations but * depth and stencil compare functions are set independently. * @see DepthStencilState::DepthMode::DepthFunction * @see DepthStencilState::StencilMode::StencilFunction */ enum class CompareFunction { Never, // Never pass the comparison operation. Less, // Pass if the source pixel's depth or stencil reference value is less than the value stored in the depth/stencil buffer ( DSs < DSd ). Equal, // Pass if the source pixel's depth or stencil reference value is equal to the value stored in the depth/stencil buffer ( DSs == DSd ). LessOrEqual, // Pass if the source pixel's depth or stencil reference value is less than or equal to the value stored in the depth/stencil buffer ( DSs <= DSd ). Greater, // Pass if the source pixel's depth or stencil reference value is greater than the value stored in the depth/stencil buffer ( DSs > DSd ). NotEqual, // Pass if the source pixel's depth or stencil reference value is not equal to teh value stored in the depth/stencil buffer ( DSs != DSd ). GreaterOrEqual, // Pass if the source pixel's depth or stencil reference value is greater than or equal to the value stored in the depth/stencil buffer ( DSs >= DSd ). Always // Always pass the comparison operation. }; /** * The stencil operation determines what happens to the stencil buffer if * either a comparison function passes, or fails. You can specify the operation * depending on the result of the comparison function in the StencilMode structure. * @see DepthStencilState::StencilMode. */ enum class StencilOperation { Keep, // Keep the existing value in the stencil buffer unmodified. Zero, // Set the value in the stencil buffer to 0. Reference, // Set the value in the stencil buffer to the reference value. @see DepthStencilState::StencilMode::StencilReference. IncrementClamp, // Increment the value in the stencil buffer by 1 and clamp the result if it is out of range. DecrementClamp, // Decrement the value in the stencil buffer by 1 and clamp the result if it is out of range. Invert, // Invert the value in the stencil value. IncrementWrap, // Increment the value in the stencil buffer by 1 and wrap the result if it is out of range. DecrementWrap, // Decrement the value in the stencil buffer by 1 and wrap the result if it is out of range. }; struct DepthMode { /** * Set to true to enable depth testing. * If enabled, the DepthFunction will be used to check if a pixel should * be written to the back buffer or discarded. * Default: True * @see DepthStencilState::DepthMode::DepthFunction */ bool DepthEnable; /** * Enable or disable writing to the depth buffer. * This should be enabled for opaque geometry and disabled * for partially transparent objects. * Default: Enabled. */ DepthWrite DepthWriteMask; /** * If the depth comparison function evaluates to TRUE then the pixel * is rasterized. If the depth comparison function evaluates to FALSE then * the pixel is discarded and not written to the back buffer. * The default value is CompareFunc::Less which means that source pixels * that are closer to the camera will pass the compare function and source * pixels that appear further away from the camera are discarded. */ CompareFunction DepthFunction; explicit DepthMode(bool depthEnable = true, DepthWrite depthWrite = DepthWrite::Enable, CompareFunction depthFunction = CompareFunction::Less) : DepthEnable(depthEnable) , DepthWriteMask(depthWrite) , DepthFunction(depthFunction) {} }; /** * The operation to perform on the stencil buffer can be specified * depending on whether the primitive that is being tested is front-facing * or back facing (according to the value of RasterizerState::FrontFacing). */ struct FaceOperation { /** * The operation to perform on the value in the stencil buffer if the * stencil comparision function (specified by FaceOperation::StencilFunction) * returns FALSE. * Default: StencilOperation::Keep */ StencilOperation StencilFail; /** * The operation to perform on the value in the stencil buffer if the * stencil comparision function (specified by FaceOperation::StencilFunction) * returns TRUE and depth comparision function (determined by DepthMode::DepthFunction) * returns FALSE. * Default: StencilOperation::Keep */ StencilOperation StencilPassDepthFail; /** * The operation to perform if both depth comparison function * (determined by DepthMode::DepthFunction) and stencil comparision * function (specified by FaceOperation::StencilFunction) returns TRUE. * Default: StencilOperation::Keep */ StencilOperation StencilDepthPass; /** * The the comparison method to use for stencil operations. * Default: CompareFunction::Always (Tests always passes). * @see DepthStencilState::CompareFunction */ CompareFunction StencilFunction; explicit FaceOperation(StencilOperation stencilFail = StencilOperation::Keep, StencilOperation stencilPassDepthFail = StencilOperation::Keep, StencilOperation stencilDepthPass = StencilOperation::Keep, CompareFunction stencilFunction = CompareFunction::Always) : StencilFail(stencilFail) , StencilPassDepthFail(stencilPassDepthFail) , StencilDepthPass(stencilDepthPass) , StencilFunction(stencilFunction) {} }; struct StencilMode { /** * Set to true to enable stencil testing. * Default: false. */ bool StencilEnabled; /** * A mask that is AND'd to the value in the stencil buffer before it is read. * Default: 0xff */ uint8_t ReadMask; /** * A mask that is AND'd to the value in the stencil buffer before it is written. * Default: 0xff */ uint8_t WriteMask; /** * The value to set the stencil buffer to if any of the StencilOperation * members of the FaceOperation struct is set to StencilOperation::Reference. * Default: 0 */ uint32_t StencilReference; /** * The compare function and pass/fail operations to perform on the stencil * buffer for front-facing polygons. */ FaceOperation FrontFace; /** * The compare function and pass/fail operations to perform on the stencil * buffer for back-facing polygons. */ FaceOperation BackFace; StencilMode(bool stencilEnabled = false, uint8_t readMask = 0xff, uint8_t writeMask = 0xff, uint32_t stencilReference = 0, FaceOperation frontFace = FaceOperation(), FaceOperation backFace = FaceOperation()) : StencilEnabled(stencilEnabled) , ReadMask(readMask) , WriteMask(writeMask) , StencilReference(stencilReference) , FrontFace(frontFace) , BackFace(backFace) {} }; virtual void SetDepthMode(const DepthMode& depthMode) = 0; virtual const DepthMode& GetDepthMode() const = 0; virtual void SetStencilMode(const StencilMode& stencilMode) = 0; virtual const StencilMode& GetStencilMode() const = 0; virtual void Bind() = 0; };
[ "alexstenfard@gmail.com" ]
alexstenfard@gmail.com
b045fe55b45d94cc206e9adbaaa847ca4944424f
8b69c522ad35e68100b0f70b12a7c8671560e882
/2-05-01-multimaps.cpp
12ec4d386aaf4005b5527c76440c595bc3977879
[]
no_license
zarev/stl-course
8dc2ff530f05f8cb693f328565810e5f5527c266
b626d55198b766af46b61b9c92db0965c9527138
refs/heads/master
2021-04-14T17:58:43.109941
2020-04-01T10:19:50
2020-04-01T10:19:50
249,252,596
0
0
null
null
null
null
UTF-8
C++
false
false
1,182
cpp
#include <iostream> #include <map> #include <string> #include <fstream> #include <sstream> #include <utility> using namespace std; int main(){ ifstream in("illiad.txt"); multimap<string, pair<int, int>> wordPositions; int lineNumber, wordInLine = 0; string line = " "; while(!in.eof()){ lineNumber++; getline(in,line); istringstream iss(line); string word = ""; while (!iss.eof()){ wordInLine++; iss >> word; wordPositions.insert(make_pair(word, make_pair(lineNumber,wordInLine))); } wordInLine = 0; } cout << "lines of text: " << lineNumber << endl; for (auto it = wordPositions.cbegin(), it2=it; it !=wordPositions.cend(); it=it2){ unsigned int count = wordPositions.count(it->first); cout << "\"" << it->first << "\" occurs " << count << " times, and is on: \n"; cout << "\n" << it->second.first << endl; for (; it2 != wordPositions.cend() && it2->first == it->first; it2++){ auto [line, word] = it2->second; cout << "\tline " << line << ", position " << word << "\n"; } } in.close(); return 0; } //go through word map, print each word and its positions
[ "21259114+zarev@users.noreply.github.com" ]
21259114+zarev@users.noreply.github.com
0f397227adb2351cf3c0330269c519e2a87b7d1e
5c7f35bf82a69da68e2cde58ed792a61c8f6d923
/PWG/DevNanoAOD/AliAnalysisTaskNanoAODnormalisation.h
67ba21aec1724dffc7fd5bf4376fdac4a11f7ce7
[]
permissive
novitzky/AliPhysics
a4b2cae5000da04c66227e57db30adef618e50c8
093f9cb10313464cc527204eec9cc403c8c42443
refs/heads/master
2020-06-02T23:03:58.281372
2019-06-11T09:10:15
2019-06-11T09:20:45
191,334,338
0
0
BSD-3-Clause
2019-06-11T09:05:46
2019-06-11T09:05:45
null
UTF-8
C++
false
false
918
h
#ifndef AliAnalysisTaskNanoAODnormalisation_H #define AliAnalysisTaskNanoAODnormalisation_H #include "AliAnalysisCuts.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisNanoAODCuts.h" #include <TList.h> class AliAnalysisTaskNanoAODnormalisation : public AliAnalysisTaskSE { public: AliAnalysisTaskNanoAODnormalisation(std::string taskName = "AliAnalysisTaskNanoAODnormalisation"); virtual ~AliAnalysisTaskNanoAODnormalisation(); virtual void UserCreateOutputObjects(); virtual Bool_t UserNotify(); static AliAnalysisTaskNanoAODnormalisation* AddTask(std::string name = "AliAnalysisTaskNanoAODnormalisation"); private: bool fFirst; //!<! Current filke name TList* fOutputList; //!<! Output list TH2D* fCandidateEvents[2]; //!<! TH2D* fSelectedEvents[2]; //!<! ClassDef(AliAnalysisTaskNanoAODnormalisation,1); }; #endif
[ "maximiliano.puccio@cern.ch" ]
maximiliano.puccio@cern.ch
5ad6e6c9ba354d1891d796f1a4b3a9808afdffe2
d4c6151c86413dfd0881706a08aff5953a4aa28b
/src/ui/scenic/lib/gfx/tests/vk_session_test.cc
4e77d3916a33d6c1dcb5c11970ed64551f57aaca
[ "BSD-3-Clause" ]
permissive
opensource-assist/fuschia
64e0494fe0c299cf19a500925e115a75d6347a10
66646c55b3d0b36aae90a4b6706b87f1a6261935
refs/heads/master
2022-11-02T02:11:41.392221
2019-12-27T00:43:47
2019-12-27T00:43:47
230,425,920
0
1
BSD-3-Clause
2022-10-03T10:28:51
2019-12-27T10:43:28
C++
UTF-8
C++
false
false
3,756
cc
// Copyright 2018 The Fuchsia 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 "src/ui/scenic/lib/gfx/tests/vk_session_test.h" #include "src/ui/lib/escher/impl/vulkan_utils.h" #include "src/ui/lib/escher/test/gtest_escher.h" #include "src/ui/lib/escher/test/vk_debug_report_collector.h" using namespace escher; namespace scenic_impl { namespace gfx { namespace test { VulkanDeviceQueuesPtr VkSessionTest::CreateVulkanDeviceQueues(bool use_protected_memory) { auto vulkan_instance = escher::test::EscherEnvironment::GetGlobalTestEnvironment()->GetVulkanInstance(); // This extension is necessary to support exporting Vulkan memory to a VMO. VulkanDeviceQueues::Params::Flags flags = use_protected_memory ? VulkanDeviceQueues::Params::kAllowProtectedMemory : 0; auto vulkan_queues = VulkanDeviceQueues::New( vulkan_instance, {{VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, VK_FUCHSIA_EXTERNAL_MEMORY_EXTENSION_NAME}, {}, vk::SurfaceKHR(), flags}); // Some devices might not be capable of using protected memory. if (use_protected_memory && !vulkan_queues->caps().allow_protected_memory) { return nullptr; } return vulkan_queues; } void VkSessionTest::SetUp() { vk_debug_report_callback_registry_.RegisterDebugReportCallbacks(); SessionTest::SetUp(); sysmem_ = std::make_unique<Sysmem>(); display_manager_ = std::make_unique<display::DisplayManager>(); constexpr float display_width = 1024; constexpr float display_height = 768; display_manager_->SetDefaultDisplayForTests(std::make_unique<display::Display>( /*id*/ 0, /*px-width*/ display_width, /*px-height*/ display_height)); } void VkSessionTest::TearDown() { EXPECT_VULKAN_VALIDATION_OK(); vk_debug_report_callback_registry_.DeregisterDebugReportCallbacks(); SessionTest::TearDown(); image_factory_.reset(); release_fence_signaller_.reset(); escher_.reset(); sysmem_.reset(); display_manager_.reset(); } VkSessionTest::VkSessionTest() : SessionTest(), vk_debug_report_callback_registry_( escher::test::EscherEnvironment::GetGlobalTestEnvironment()->GetVulkanInstance(), std::make_optional<VulkanInstance::DebugReportCallback>( escher::test::impl::VkDebugReportCollector::HandleDebugReport, &vk_debug_report_collector_), {}), vk_debug_report_collector_() {} SessionContext VkSessionTest::CreateSessionContext() { auto session_context = SessionTest::CreateSessionContext(); auto vulkan_device = CreateVulkanDeviceQueues(); FXL_DCHECK(!escher_); FXL_DCHECK(!release_fence_signaller_); FXL_DCHECK(!image_factory_); escher_ = std::make_unique<Escher>(vulkan_device); release_fence_signaller_ = std::make_unique<ReleaseFenceSignaller>(escher_->command_buffer_sequencer()); image_factory_ = std::make_unique<ImageFactoryAdapter>(escher_->gpu_allocator(), escher_->resource_recycler()); session_context.vk_device = escher_->vk_device(); session_context.escher = escher_.get(); session_context.escher_resource_recycler = escher_->resource_recycler(); session_context.escher_image_factory = image_factory_.get(); session_context.release_fence_signaller = release_fence_signaller_.get(); return session_context; } CommandContext VkSessionTest::CreateCommandContext() { return CommandContext(escher::BatchGpuUploader::New(escher_->GetWeakPtr(), /* trace_id = */ 0), sysmem_.get(), display_manager_.get(), fxl::WeakPtr<SceneGraph>(/*empty*/)); } } // namespace test } // namespace gfx } // namespace scenic_impl
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d3cc58634adc86263df2004a9007ee749569df6d
502e207c832ef269a011e65f564925efa78ffa4f
/MicroSTL/MicroSTL/micro_iterator.h
0241bb41be8093a9b8da55a3d50ff1c596676806
[]
no_license
Maxmengt/MicroSTL
57b8254d79706183d4a495048e602c66a67ad730
23b9124d27f35b0ede07171facfdbe7cfe65d0c4
refs/heads/master
2021-01-11T19:51:46.397010
2017-03-03T13:07:22
2017-03-03T13:07:22
79,409,450
0
1
null
null
null
null
UTF-8
C++
false
false
3,516
h
#ifndef _MICRO_ITERATOR_H_ #define _MICRO_ITERATOR_H_ #include <cstddef> namespace MicroSTL { struct input_iterator_tag {}; struct output_iterator_tag {}; struct forward_iterator_tag : public input_iterator_tag {}; struct bidirectional_iterator_tag : public forward_iterator_tag {}; struct random_access_iterator_tag : public bidirectional_iterator_tag {}; template<class I> struct iterator_traits { typedef typename I::iterator_category iterator_category; typedef typename I::value_type value_type; typedef typename I::difference_type difference_type; typedef typename I::pointer pointer; typedef typename I::reference reference; }; template<class T> struct iterator_traits<T*> { typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T& reference; }; template<class T> struct iterator_traits<const T*> { typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef const T* pointer; typedef const T& reference; }; template<class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T&> struct iterator { typedef Category iterator_category; typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; }; template<class Iterator> inline typename iterator_traits<Iterator>::iterator_category iterator_category(const Iterator&) { typedef typename iterator_traits<Iterator>::iterator_categoty category; return category(); } template<class Iterator> inline typename iterator_traits<Iterator>::difference_type* difference_type(const Iterator&) { return static_cast<typename iterator_traits<Iterator>::difference_type*>(0); } template<class Iterator> inline typename iterator_traits<Iterator>::value_type* value_type(const Iterator&) { return static_cast<typename iterator_traits<Iterator>::value_type*>(0); } template<class InputIterator> inline typename iterator_traits<InputIterator>::difference_type __distance(InputIterator first, InputIterator last, input_iterator_tag) { iterator_traits<InputIterator>::difference_type n = 0; while (first != last) { ++first; ++n; } return n; } template<class RandomAccessIterator> inline typename iterator_traits<RandomAccessIterator>::difference_type __distance(RandomAccessIterator first, RandomAccessIterator last, random_access_iterator_tag) { return last - first; } template<class InputIterator> inline typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last) { return __distance(first, last, iterator_category()); } template<class InputIterator, class Distance> inline void __advance(InputIterator& i, Distance n, input_iterator_tag) { while( n-- ) ++i; } template<class BidirectionalIterator, class Distance> inline void __advance(BidirectionalIterator& i, Distance n, bidirectional_iterator_tag) { if( n >= 0 ) { while( n-- ) ++i; } else { while( n++ ) --i; } } template<class RandomAccessIterator, class Distance> inline void __advance(RandomAccessIterator& i, Distance n, random_access_iterator_tag) { i += n; } template<class InputIterator, class Distance> inline void advance(InputIterator& i, Distance n) { __advance(i, n, iterator_category()); } } #endif // !_MICRO_ITERATOR_H_
[ "mengt2012@gmail.com" ]
mengt2012@gmail.com
05c755eb1aecbd151cdcd0d7379e19a27adff014
b452fdfb6a8667b6523d630cc46eaf25c9ff81f9
/cmake_policy/src/cmake_policy.cpp
8d3d38a66c6c9f982c2202c91d402d15390a55c1
[]
no_license
dpinol/ros_tests
8446984a7428b179ee7d9e2633869ba259113b82
8adda2cf544b319bdcfef2db7a650e3067081fee
refs/heads/master
2021-01-20T08:47:25.580025
2014-02-26T16:59:48
2014-02-26T16:59:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
94
cpp
#include<iostream> #include <ros/console.h> int main() { ROS_ERROR("hello"); return 0; }
[ "github@dpinol.com" ]
github@dpinol.com
f7ac0c342586eec130b794cda64a5bcad7405b05
498a5610ddc171858f0f9764c2aff258adf53b7d
/1408.cpp
d5135b37a9bb264747e3cdc82c076c30b315b3ad
[]
no_license
banje/acmcpp
b317bbfd3d6b58b205c516ae4127d4ac56635c9c
617b77984356c0a3a625525d21fbd66e7e30cbae
refs/heads/master
2022-11-03T10:52:00.404774
2020-06-16T17:35:21
2020-06-16T17:35:21
260,918,744
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include <stdio.h> int main(){ int a,b=0,c=0,d; scanf("%d:",&a); b=b+3600*a; scanf("%d:",&a); b=b+60*a; scanf("%d:\n",&a); b=b+a; scanf("%d:",&a); c=c+3600*a; scanf("%d:",&a); c=c+60*a; scanf("%d:\n",&a); c=c+a; d=c-b; if(d<0){ d=d+86400; } printf("%02d:%02d:%02d",d/3600,d/60-d/3600*60,d%60); }
[ "pak2t@naver.com" ]
pak2t@naver.com
e51a22a3afb87fd76ecd0267418b5d8986cb04a6
48a70d93e92961a32c4d0e5f9b6c1799bbd73b46
/datamover/production/syn/systemc/dataflow_in_loop.cpp
5168a22110d089bec843bafcafd5dd13219fa891
[]
no_license
OpenMRI/snickerdoodle-hls-data-mover
fa476ced1bd8c1696beacf37709c12eb9440f292
56768618f64a756bbca5f445431f042835065c2c
refs/heads/master
2023-03-22T02:11:58.011884
2018-06-17T07:47:59
2018-06-17T07:47:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,569
cpp
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2018.1 // Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved. // // =========================================================== #include "dataflow_in_loop.h" #include "AESL_pkg.h" using namespace std; namespace ap_rtl { const sc_logic dataflow_in_loop::ap_const_logic_1 = sc_dt::Log_1; const sc_logic dataflow_in_loop::ap_const_logic_0 = sc_dt::Log_0; const sc_lv<64> dataflow_in_loop::ap_const_lv64_0 = "0000000000000000000000000000000000000000000000000000000000000000"; const sc_lv<64> dataflow_in_loop::ap_const_lv64_1 = "1"; const sc_lv<1> dataflow_in_loop::ap_const_lv1_0 = "0"; const sc_lv<1> dataflow_in_loop::ap_const_lv1_1 = "1"; const sc_lv<2> dataflow_in_loop::ap_const_lv2_0 = "00"; const sc_lv<2> dataflow_in_loop::ap_const_lv2_1 = "1"; const sc_lv<32> dataflow_in_loop::ap_const_lv32_0 = "00000000000000000000000000000000"; const sc_lv<3> dataflow_in_loop::ap_const_lv3_0 = "000"; const sc_lv<4> dataflow_in_loop::ap_const_lv4_0 = "0000"; const bool dataflow_in_loop::ap_const_boolean_1 = true; dataflow_in_loop::dataflow_in_loop(sc_module_name name) : sc_module(name), mVcdFile(0) { cache_V_U = new dataflow_in_loop_cud("cache_V_U"); cache_V_U->clk(ap_clk); cache_V_U->reset(ap_rst); cache_V_U->i_address0(rx_axis_words7131_U0_cache_V1_address0); cache_V_U->i_ce0(rx_axis_words7131_U0_cache_V1_ce0); cache_V_U->i_we0(rx_axis_words7131_U0_cache_V1_we0); cache_V_U->i_d0(rx_axis_words7131_U0_cache_V1_d0); cache_V_U->i_q0(cache_V_i_q0); cache_V_U->t_address0(write_burst_U0_cache_V_address0); cache_V_U->t_ce0(write_burst_U0_cache_V_ce0); cache_V_U->t_we0(ap_var_for_const0); cache_V_U->t_d0(ap_var_for_const1); cache_V_U->t_q0(cache_V_t_q0); cache_V_U->i_ce(ap_var_for_const2); cache_V_U->t_ce(ap_var_for_const2); cache_V_U->i_full_n(cache_V_i_full_n); cache_V_U->i_write(ap_channel_done_cache_V); cache_V_U->t_empty_n(cache_V_t_empty_n); cache_V_U->t_read(write_burst_U0_ap_ready); rx_axis_words7131_U0 = new rx_axis_words7131("rx_axis_words7131_U0"); rx_axis_words7131_U0->ap_clk(ap_clk); rx_axis_words7131_U0->ap_rst(ap_rst); rx_axis_words7131_U0->ap_start(rx_axis_words7131_U0_ap_start); rx_axis_words7131_U0->ap_done(rx_axis_words7131_U0_ap_done); rx_axis_words7131_U0->ap_continue(rx_axis_words7131_U0_ap_continue); rx_axis_words7131_U0->ap_idle(rx_axis_words7131_U0_ap_idle); rx_axis_words7131_U0->ap_ready(rx_axis_words7131_U0_ap_ready); rx_axis_words7131_U0->axis_V_V_TDATA(axis_V_V_TDATA); rx_axis_words7131_U0->axis_V_V_TVALID(axis_V_V_TVALID); rx_axis_words7131_U0->axis_V_V_TREADY(rx_axis_words7131_U0_axis_V_V_TREADY); rx_axis_words7131_U0->loop_count_V(loop_count_V); rx_axis_words7131_U0->final_burst_length_V(final_burst_length_V); rx_axis_words7131_U0->val_assign(val_assign); rx_axis_words7131_U0->cache_V1_address0(rx_axis_words7131_U0_cache_V1_address0); rx_axis_words7131_U0->cache_V1_ce0(rx_axis_words7131_U0_cache_V1_ce0); rx_axis_words7131_U0->cache_V1_we0(rx_axis_words7131_U0_cache_V1_we0); rx_axis_words7131_U0->cache_V1_d0(rx_axis_words7131_U0_cache_V1_d0); rx_axis_words7131_U0->rx_buffer_V_offset(rx_buffer_V_offset1); rx_axis_words7131_U0->rx_buffer_V_offset_out_din(rx_axis_words7131_U0_rx_buffer_V_offset_out_din); rx_axis_words7131_U0->rx_buffer_V_offset_out_full_n(rx_buffer_V_offset_c_full_n); rx_axis_words7131_U0->rx_buffer_V_offset_out_write(rx_axis_words7131_U0_rx_buffer_V_offset_out_write); rx_axis_words7131_U0->rx_buffer_V_offset1(rx_buffer_V_offset); rx_axis_words7131_U0->rx_buffer_V_offset1_out_din(rx_axis_words7131_U0_rx_buffer_V_offset1_out_din); rx_axis_words7131_U0->rx_buffer_V_offset1_out_full_n(rx_buffer_V_offset_c_2_full_n); rx_axis_words7131_U0->rx_buffer_V_offset1_out_write(rx_axis_words7131_U0_rx_buffer_V_offset1_out_write); rx_axis_words7131_U0->ap_return(rx_axis_words7131_U0_ap_return); write_burst_U0 = new write_burst("write_burst_U0"); write_burst_U0->ap_clk(ap_clk); write_burst_U0->ap_rst(ap_rst); write_burst_U0->ap_start(write_burst_U0_ap_start); write_burst_U0->ap_done(write_burst_U0_ap_done); write_burst_U0->ap_continue(write_burst_U0_ap_continue); write_burst_U0->ap_idle(write_burst_U0_ap_idle); write_burst_U0->ap_ready(write_burst_U0_ap_ready); write_burst_U0->cache_V_address0(write_burst_U0_cache_V_address0); write_burst_U0->cache_V_ce0(write_burst_U0_cache_V_ce0); write_burst_U0->cache_V_q0(cache_V_t_q0); write_burst_U0->buffer_offset_V(buffer_offset_V_dout); write_burst_U0->m_axi_rx_buffer_V_AWVALID(write_burst_U0_m_axi_rx_buffer_V_AWVALID); write_burst_U0->m_axi_rx_buffer_V_AWREADY(m_axi_rx_buffer_V_AWREADY); write_burst_U0->m_axi_rx_buffer_V_AWADDR(write_burst_U0_m_axi_rx_buffer_V_AWADDR); write_burst_U0->m_axi_rx_buffer_V_AWID(write_burst_U0_m_axi_rx_buffer_V_AWID); write_burst_U0->m_axi_rx_buffer_V_AWLEN(write_burst_U0_m_axi_rx_buffer_V_AWLEN); write_burst_U0->m_axi_rx_buffer_V_AWSIZE(write_burst_U0_m_axi_rx_buffer_V_AWSIZE); write_burst_U0->m_axi_rx_buffer_V_AWBURST(write_burst_U0_m_axi_rx_buffer_V_AWBURST); write_burst_U0->m_axi_rx_buffer_V_AWLOCK(write_burst_U0_m_axi_rx_buffer_V_AWLOCK); write_burst_U0->m_axi_rx_buffer_V_AWCACHE(write_burst_U0_m_axi_rx_buffer_V_AWCACHE); write_burst_U0->m_axi_rx_buffer_V_AWPROT(write_burst_U0_m_axi_rx_buffer_V_AWPROT); write_burst_U0->m_axi_rx_buffer_V_AWQOS(write_burst_U0_m_axi_rx_buffer_V_AWQOS); write_burst_U0->m_axi_rx_buffer_V_AWREGION(write_burst_U0_m_axi_rx_buffer_V_AWREGION); write_burst_U0->m_axi_rx_buffer_V_AWUSER(write_burst_U0_m_axi_rx_buffer_V_AWUSER); write_burst_U0->m_axi_rx_buffer_V_WVALID(write_burst_U0_m_axi_rx_buffer_V_WVALID); write_burst_U0->m_axi_rx_buffer_V_WREADY(m_axi_rx_buffer_V_WREADY); write_burst_U0->m_axi_rx_buffer_V_WDATA(write_burst_U0_m_axi_rx_buffer_V_WDATA); write_burst_U0->m_axi_rx_buffer_V_WSTRB(write_burst_U0_m_axi_rx_buffer_V_WSTRB); write_burst_U0->m_axi_rx_buffer_V_WLAST(write_burst_U0_m_axi_rx_buffer_V_WLAST); write_burst_U0->m_axi_rx_buffer_V_WID(write_burst_U0_m_axi_rx_buffer_V_WID); write_burst_U0->m_axi_rx_buffer_V_WUSER(write_burst_U0_m_axi_rx_buffer_V_WUSER); write_burst_U0->m_axi_rx_buffer_V_ARVALID(write_burst_U0_m_axi_rx_buffer_V_ARVALID); write_burst_U0->m_axi_rx_buffer_V_ARREADY(ap_var_for_const0); write_burst_U0->m_axi_rx_buffer_V_ARADDR(write_burst_U0_m_axi_rx_buffer_V_ARADDR); write_burst_U0->m_axi_rx_buffer_V_ARID(write_burst_U0_m_axi_rx_buffer_V_ARID); write_burst_U0->m_axi_rx_buffer_V_ARLEN(write_burst_U0_m_axi_rx_buffer_V_ARLEN); write_burst_U0->m_axi_rx_buffer_V_ARSIZE(write_burst_U0_m_axi_rx_buffer_V_ARSIZE); write_burst_U0->m_axi_rx_buffer_V_ARBURST(write_burst_U0_m_axi_rx_buffer_V_ARBURST); write_burst_U0->m_axi_rx_buffer_V_ARLOCK(write_burst_U0_m_axi_rx_buffer_V_ARLOCK); write_burst_U0->m_axi_rx_buffer_V_ARCACHE(write_burst_U0_m_axi_rx_buffer_V_ARCACHE); write_burst_U0->m_axi_rx_buffer_V_ARPROT(write_burst_U0_m_axi_rx_buffer_V_ARPROT); write_burst_U0->m_axi_rx_buffer_V_ARQOS(write_burst_U0_m_axi_rx_buffer_V_ARQOS); write_burst_U0->m_axi_rx_buffer_V_ARREGION(write_burst_U0_m_axi_rx_buffer_V_ARREGION); write_burst_U0->m_axi_rx_buffer_V_ARUSER(write_burst_U0_m_axi_rx_buffer_V_ARUSER); write_burst_U0->m_axi_rx_buffer_V_RVALID(ap_var_for_const0); write_burst_U0->m_axi_rx_buffer_V_RREADY(write_burst_U0_m_axi_rx_buffer_V_RREADY); write_burst_U0->m_axi_rx_buffer_V_RDATA(ap_var_for_const1); write_burst_U0->m_axi_rx_buffer_V_RLAST(ap_var_for_const0); write_burst_U0->m_axi_rx_buffer_V_RID(ap_var_for_const3); write_burst_U0->m_axi_rx_buffer_V_RUSER(ap_var_for_const3); write_burst_U0->m_axi_rx_buffer_V_RRESP(ap_var_for_const4); write_burst_U0->m_axi_rx_buffer_V_BVALID(m_axi_rx_buffer_V_BVALID); write_burst_U0->m_axi_rx_buffer_V_BREADY(write_burst_U0_m_axi_rx_buffer_V_BREADY); write_burst_U0->m_axi_rx_buffer_V_BRESP(m_axi_rx_buffer_V_BRESP); write_burst_U0->m_axi_rx_buffer_V_BID(m_axi_rx_buffer_V_BID); write_burst_U0->m_axi_rx_buffer_V_BUSER(m_axi_rx_buffer_V_BUSER); write_burst_U0->rx_buffer_V_offset_dout(rx_buffer_V_offset_c_2_dout); write_burst_U0->rx_buffer_V_offset_empty_n(rx_buffer_V_offset_c_2_empty_n); write_burst_U0->rx_buffer_V_offset_read(write_burst_U0_rx_buffer_V_offset_read); write_burst_U0->rx_buffer_V_offset_c_dout(rx_buffer_V_offset_c_dout); write_burst_U0->rx_buffer_V_offset_c_empty_n(rx_buffer_V_offset_c_empty_n); write_burst_U0->rx_buffer_V_offset_c_read(write_burst_U0_rx_buffer_V_offset_c_read); rx_buffer_V_offset_c_U = new fifo_w1_d2_A("rx_buffer_V_offset_c_U"); rx_buffer_V_offset_c_U->clk(ap_clk); rx_buffer_V_offset_c_U->reset(ap_rst); rx_buffer_V_offset_c_U->if_read_ce(ap_var_for_const2); rx_buffer_V_offset_c_U->if_write_ce(ap_var_for_const2); rx_buffer_V_offset_c_U->if_din(rx_axis_words7131_U0_rx_buffer_V_offset_out_din); rx_buffer_V_offset_c_U->if_full_n(rx_buffer_V_offset_c_full_n); rx_buffer_V_offset_c_U->if_write(rx_axis_words7131_U0_rx_buffer_V_offset_out_write); rx_buffer_V_offset_c_U->if_dout(rx_buffer_V_offset_c_dout); rx_buffer_V_offset_c_U->if_empty_n(rx_buffer_V_offset_c_empty_n); rx_buffer_V_offset_c_U->if_read(write_burst_U0_rx_buffer_V_offset_c_read); rx_buffer_V_offset_c_2_U = new fifo_w29_d2_A("rx_buffer_V_offset_c_2_U"); rx_buffer_V_offset_c_2_U->clk(ap_clk); rx_buffer_V_offset_c_2_U->reset(ap_rst); rx_buffer_V_offset_c_2_U->if_read_ce(ap_var_for_const2); rx_buffer_V_offset_c_2_U->if_write_ce(ap_var_for_const2); rx_buffer_V_offset_c_2_U->if_din(rx_axis_words7131_U0_rx_buffer_V_offset1_out_din); rx_buffer_V_offset_c_2_U->if_full_n(rx_buffer_V_offset_c_2_full_n); rx_buffer_V_offset_c_2_U->if_write(rx_axis_words7131_U0_rx_buffer_V_offset1_out_write); rx_buffer_V_offset_c_2_U->if_dout(rx_buffer_V_offset_c_2_dout); rx_buffer_V_offset_c_2_U->if_empty_n(rx_buffer_V_offset_c_2_empty_n); rx_buffer_V_offset_c_2_U->if_read(write_burst_U0_rx_buffer_V_offset_read); buffer_offset_V_U = new fifo_w20_d2_A("buffer_offset_V_U"); buffer_offset_V_U->clk(ap_clk); buffer_offset_V_U->reset(ap_rst); buffer_offset_V_U->if_read_ce(ap_var_for_const2); buffer_offset_V_U->if_write_ce(ap_var_for_const2); buffer_offset_V_U->if_din(rx_axis_words7131_U0_ap_return); buffer_offset_V_U->if_full_n(buffer_offset_V_full_n); buffer_offset_V_U->if_write(ap_channel_done_buffer_offset_V); buffer_offset_V_U->if_dout(buffer_offset_V_dout); buffer_offset_V_U->if_empty_n(buffer_offset_V_empty_n); buffer_offset_V_U->if_read(write_burst_U0_ap_ready); SC_METHOD(thread_ap_clk_no_reset_); dont_initialize(); sensitive << ( ap_clk.pos() ); SC_METHOD(thread_ap_channel_done_buffer_offset_V); sensitive << ( rx_axis_words7131_U0_ap_done ); sensitive << ( ap_sync_reg_channel_write_buffer_offset_V ); SC_METHOD(thread_ap_channel_done_cache_V); sensitive << ( rx_axis_words7131_U0_ap_done ); sensitive << ( ap_sync_reg_channel_write_cache_V ); SC_METHOD(thread_ap_done); sensitive << ( write_burst_U0_ap_done ); SC_METHOD(thread_ap_idle); sensitive << ( rx_axis_words7131_U0_ap_idle ); sensitive << ( write_burst_U0_ap_idle ); sensitive << ( cache_V_t_empty_n ); sensitive << ( buffer_offset_V_empty_n ); SC_METHOD(thread_ap_ready); sensitive << ( rx_axis_words7131_U0_ap_ready ); SC_METHOD(thread_ap_sync_channel_write_buffer_offset_V); sensitive << ( ap_channel_done_buffer_offset_V ); sensitive << ( buffer_offset_V_full_n ); sensitive << ( ap_sync_reg_channel_write_buffer_offset_V ); SC_METHOD(thread_ap_sync_channel_write_cache_V); sensitive << ( ap_channel_done_cache_V ); sensitive << ( rx_axis_words7131_U0_cache_V1_full_n ); sensitive << ( ap_sync_reg_channel_write_cache_V ); SC_METHOD(thread_ap_sync_continue); sensitive << ( ap_continue ); SC_METHOD(thread_ap_sync_done); sensitive << ( write_burst_U0_ap_done ); SC_METHOD(thread_ap_sync_ready); sensitive << ( rx_axis_words7131_U0_ap_ready ); SC_METHOD(thread_axis_V_V_TREADY); sensitive << ( rx_axis_words7131_U0_axis_V_V_TREADY ); SC_METHOD(thread_m_axi_rx_buffer_V_ARADDR); SC_METHOD(thread_m_axi_rx_buffer_V_ARBURST); SC_METHOD(thread_m_axi_rx_buffer_V_ARCACHE); SC_METHOD(thread_m_axi_rx_buffer_V_ARID); SC_METHOD(thread_m_axi_rx_buffer_V_ARLEN); SC_METHOD(thread_m_axi_rx_buffer_V_ARLOCK); SC_METHOD(thread_m_axi_rx_buffer_V_ARPROT); SC_METHOD(thread_m_axi_rx_buffer_V_ARQOS); SC_METHOD(thread_m_axi_rx_buffer_V_ARREGION); SC_METHOD(thread_m_axi_rx_buffer_V_ARSIZE); SC_METHOD(thread_m_axi_rx_buffer_V_ARUSER); SC_METHOD(thread_m_axi_rx_buffer_V_ARVALID); SC_METHOD(thread_m_axi_rx_buffer_V_AWADDR); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWADDR ); SC_METHOD(thread_m_axi_rx_buffer_V_AWBURST); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWBURST ); SC_METHOD(thread_m_axi_rx_buffer_V_AWCACHE); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWCACHE ); SC_METHOD(thread_m_axi_rx_buffer_V_AWID); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWID ); SC_METHOD(thread_m_axi_rx_buffer_V_AWLEN); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWLEN ); SC_METHOD(thread_m_axi_rx_buffer_V_AWLOCK); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWLOCK ); SC_METHOD(thread_m_axi_rx_buffer_V_AWPROT); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWPROT ); SC_METHOD(thread_m_axi_rx_buffer_V_AWQOS); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWQOS ); SC_METHOD(thread_m_axi_rx_buffer_V_AWREGION); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWREGION ); SC_METHOD(thread_m_axi_rx_buffer_V_AWSIZE); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWSIZE ); SC_METHOD(thread_m_axi_rx_buffer_V_AWUSER); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWUSER ); SC_METHOD(thread_m_axi_rx_buffer_V_AWVALID); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_AWVALID ); SC_METHOD(thread_m_axi_rx_buffer_V_BREADY); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_BREADY ); SC_METHOD(thread_m_axi_rx_buffer_V_RREADY); SC_METHOD(thread_m_axi_rx_buffer_V_WDATA); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_WDATA ); SC_METHOD(thread_m_axi_rx_buffer_V_WID); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_WID ); SC_METHOD(thread_m_axi_rx_buffer_V_WLAST); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_WLAST ); SC_METHOD(thread_m_axi_rx_buffer_V_WSTRB); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_WSTRB ); SC_METHOD(thread_m_axi_rx_buffer_V_WUSER); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_WUSER ); SC_METHOD(thread_m_axi_rx_buffer_V_WVALID); sensitive << ( write_burst_U0_m_axi_rx_buffer_V_WVALID ); SC_METHOD(thread_rx_axis_words7131_U0_ap_continue); sensitive << ( ap_sync_channel_write_buffer_offset_V ); sensitive << ( ap_sync_channel_write_cache_V ); SC_METHOD(thread_rx_axis_words7131_U0_ap_start); sensitive << ( ap_start ); SC_METHOD(thread_rx_axis_words7131_U0_cache_V1_full_n); sensitive << ( cache_V_i_full_n ); SC_METHOD(thread_rx_axis_words7131_U0_start_full_n); SC_METHOD(thread_rx_axis_words7131_U0_start_write); SC_METHOD(thread_write_burst_U0_ap_continue); sensitive << ( ap_continue ); SC_METHOD(thread_write_burst_U0_ap_start); sensitive << ( cache_V_t_empty_n ); sensitive << ( buffer_offset_V_empty_n ); SC_METHOD(thread_write_burst_U0_start_full_n); SC_METHOD(thread_write_burst_U0_start_write); SC_THREAD(thread_ap_var_for_const2); SC_THREAD(thread_ap_var_for_const0); SC_THREAD(thread_ap_var_for_const1); SC_THREAD(thread_ap_var_for_const3); SC_THREAD(thread_ap_var_for_const4); ap_sync_reg_channel_write_buffer_offset_V = SC_LOGIC_0; ap_sync_reg_channel_write_cache_V = SC_LOGIC_0; static int apTFileNum = 0; stringstream apTFilenSS; apTFilenSS << "dataflow_in_loop_sc_trace_" << apTFileNum ++; string apTFn = apTFilenSS.str(); mVcdFile = sc_create_vcd_trace_file(apTFn.c_str()); mVcdFile->set_time_unit(1, SC_PS); if (1) { #ifdef __HLS_TRACE_LEVEL_PORT_HIER__ sc_trace(mVcdFile, ap_clk, "(port)ap_clk"); sc_trace(mVcdFile, ap_rst, "(port)ap_rst"); sc_trace(mVcdFile, axis_V_V_TDATA, "(port)axis_V_V_TDATA"); sc_trace(mVcdFile, loop_count_V, "(port)loop_count_V"); sc_trace(mVcdFile, final_burst_length_V, "(port)final_burst_length_V"); sc_trace(mVcdFile, val_assign, "(port)val_assign"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWVALID, "(port)m_axi_rx_buffer_V_AWVALID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWREADY, "(port)m_axi_rx_buffer_V_AWREADY"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWADDR, "(port)m_axi_rx_buffer_V_AWADDR"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWID, "(port)m_axi_rx_buffer_V_AWID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWLEN, "(port)m_axi_rx_buffer_V_AWLEN"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWSIZE, "(port)m_axi_rx_buffer_V_AWSIZE"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWBURST, "(port)m_axi_rx_buffer_V_AWBURST"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWLOCK, "(port)m_axi_rx_buffer_V_AWLOCK"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWCACHE, "(port)m_axi_rx_buffer_V_AWCACHE"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWPROT, "(port)m_axi_rx_buffer_V_AWPROT"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWQOS, "(port)m_axi_rx_buffer_V_AWQOS"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWREGION, "(port)m_axi_rx_buffer_V_AWREGION"); sc_trace(mVcdFile, m_axi_rx_buffer_V_AWUSER, "(port)m_axi_rx_buffer_V_AWUSER"); sc_trace(mVcdFile, m_axi_rx_buffer_V_WVALID, "(port)m_axi_rx_buffer_V_WVALID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_WREADY, "(port)m_axi_rx_buffer_V_WREADY"); sc_trace(mVcdFile, m_axi_rx_buffer_V_WDATA, "(port)m_axi_rx_buffer_V_WDATA"); sc_trace(mVcdFile, m_axi_rx_buffer_V_WSTRB, "(port)m_axi_rx_buffer_V_WSTRB"); sc_trace(mVcdFile, m_axi_rx_buffer_V_WLAST, "(port)m_axi_rx_buffer_V_WLAST"); sc_trace(mVcdFile, m_axi_rx_buffer_V_WID, "(port)m_axi_rx_buffer_V_WID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_WUSER, "(port)m_axi_rx_buffer_V_WUSER"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARVALID, "(port)m_axi_rx_buffer_V_ARVALID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARREADY, "(port)m_axi_rx_buffer_V_ARREADY"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARADDR, "(port)m_axi_rx_buffer_V_ARADDR"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARID, "(port)m_axi_rx_buffer_V_ARID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARLEN, "(port)m_axi_rx_buffer_V_ARLEN"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARSIZE, "(port)m_axi_rx_buffer_V_ARSIZE"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARBURST, "(port)m_axi_rx_buffer_V_ARBURST"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARLOCK, "(port)m_axi_rx_buffer_V_ARLOCK"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARCACHE, "(port)m_axi_rx_buffer_V_ARCACHE"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARPROT, "(port)m_axi_rx_buffer_V_ARPROT"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARQOS, "(port)m_axi_rx_buffer_V_ARQOS"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARREGION, "(port)m_axi_rx_buffer_V_ARREGION"); sc_trace(mVcdFile, m_axi_rx_buffer_V_ARUSER, "(port)m_axi_rx_buffer_V_ARUSER"); sc_trace(mVcdFile, m_axi_rx_buffer_V_RVALID, "(port)m_axi_rx_buffer_V_RVALID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_RREADY, "(port)m_axi_rx_buffer_V_RREADY"); sc_trace(mVcdFile, m_axi_rx_buffer_V_RDATA, "(port)m_axi_rx_buffer_V_RDATA"); sc_trace(mVcdFile, m_axi_rx_buffer_V_RLAST, "(port)m_axi_rx_buffer_V_RLAST"); sc_trace(mVcdFile, m_axi_rx_buffer_V_RID, "(port)m_axi_rx_buffer_V_RID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_RUSER, "(port)m_axi_rx_buffer_V_RUSER"); sc_trace(mVcdFile, m_axi_rx_buffer_V_RRESP, "(port)m_axi_rx_buffer_V_RRESP"); sc_trace(mVcdFile, m_axi_rx_buffer_V_BVALID, "(port)m_axi_rx_buffer_V_BVALID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_BREADY, "(port)m_axi_rx_buffer_V_BREADY"); sc_trace(mVcdFile, m_axi_rx_buffer_V_BRESP, "(port)m_axi_rx_buffer_V_BRESP"); sc_trace(mVcdFile, m_axi_rx_buffer_V_BID, "(port)m_axi_rx_buffer_V_BID"); sc_trace(mVcdFile, m_axi_rx_buffer_V_BUSER, "(port)m_axi_rx_buffer_V_BUSER"); sc_trace(mVcdFile, rx_buffer_V_offset, "(port)rx_buffer_V_offset"); sc_trace(mVcdFile, rx_buffer_V_offset1, "(port)rx_buffer_V_offset1"); sc_trace(mVcdFile, axis_V_V_TVALID, "(port)axis_V_V_TVALID"); sc_trace(mVcdFile, axis_V_V_TREADY, "(port)axis_V_V_TREADY"); sc_trace(mVcdFile, loop_count_V_ap_vld, "(port)loop_count_V_ap_vld"); sc_trace(mVcdFile, final_burst_length_V_ap_vld, "(port)final_burst_length_V_ap_vld"); sc_trace(mVcdFile, val_assign_ap_vld, "(port)val_assign_ap_vld"); sc_trace(mVcdFile, rx_buffer_V_offset1_ap_vld, "(port)rx_buffer_V_offset1_ap_vld"); sc_trace(mVcdFile, rx_buffer_V_offset_ap_vld, "(port)rx_buffer_V_offset_ap_vld"); sc_trace(mVcdFile, ap_done, "(port)ap_done"); sc_trace(mVcdFile, ap_start, "(port)ap_start"); sc_trace(mVcdFile, ap_ready, "(port)ap_ready"); sc_trace(mVcdFile, ap_idle, "(port)ap_idle"); sc_trace(mVcdFile, ap_continue, "(port)ap_continue"); #endif #ifdef __HLS_TRACE_LEVEL_INT__ sc_trace(mVcdFile, cache_V_i_q0, "cache_V_i_q0"); sc_trace(mVcdFile, cache_V_t_q0, "cache_V_t_q0"); sc_trace(mVcdFile, rx_axis_words7131_U0_ap_start, "rx_axis_words7131_U0_ap_start"); sc_trace(mVcdFile, rx_axis_words7131_U0_ap_done, "rx_axis_words7131_U0_ap_done"); sc_trace(mVcdFile, rx_axis_words7131_U0_ap_continue, "rx_axis_words7131_U0_ap_continue"); sc_trace(mVcdFile, rx_axis_words7131_U0_ap_idle, "rx_axis_words7131_U0_ap_idle"); sc_trace(mVcdFile, rx_axis_words7131_U0_ap_ready, "rx_axis_words7131_U0_ap_ready"); sc_trace(mVcdFile, rx_axis_words7131_U0_axis_V_V_TREADY, "rx_axis_words7131_U0_axis_V_V_TREADY"); sc_trace(mVcdFile, rx_axis_words7131_U0_cache_V1_address0, "rx_axis_words7131_U0_cache_V1_address0"); sc_trace(mVcdFile, rx_axis_words7131_U0_cache_V1_ce0, "rx_axis_words7131_U0_cache_V1_ce0"); sc_trace(mVcdFile, rx_axis_words7131_U0_cache_V1_we0, "rx_axis_words7131_U0_cache_V1_we0"); sc_trace(mVcdFile, rx_axis_words7131_U0_cache_V1_d0, "rx_axis_words7131_U0_cache_V1_d0"); sc_trace(mVcdFile, rx_axis_words7131_U0_rx_buffer_V_offset_out_din, "rx_axis_words7131_U0_rx_buffer_V_offset_out_din"); sc_trace(mVcdFile, rx_axis_words7131_U0_rx_buffer_V_offset_out_write, "rx_axis_words7131_U0_rx_buffer_V_offset_out_write"); sc_trace(mVcdFile, rx_axis_words7131_U0_rx_buffer_V_offset1_out_din, "rx_axis_words7131_U0_rx_buffer_V_offset1_out_din"); sc_trace(mVcdFile, rx_axis_words7131_U0_rx_buffer_V_offset1_out_write, "rx_axis_words7131_U0_rx_buffer_V_offset1_out_write"); sc_trace(mVcdFile, rx_axis_words7131_U0_ap_return, "rx_axis_words7131_U0_ap_return"); sc_trace(mVcdFile, ap_channel_done_buffer_offset_V, "ap_channel_done_buffer_offset_V"); sc_trace(mVcdFile, buffer_offset_V_full_n, "buffer_offset_V_full_n"); sc_trace(mVcdFile, ap_sync_reg_channel_write_buffer_offset_V, "ap_sync_reg_channel_write_buffer_offset_V"); sc_trace(mVcdFile, ap_sync_channel_write_buffer_offset_V, "ap_sync_channel_write_buffer_offset_V"); sc_trace(mVcdFile, ap_channel_done_cache_V, "ap_channel_done_cache_V"); sc_trace(mVcdFile, rx_axis_words7131_U0_cache_V1_full_n, "rx_axis_words7131_U0_cache_V1_full_n"); sc_trace(mVcdFile, ap_sync_reg_channel_write_cache_V, "ap_sync_reg_channel_write_cache_V"); sc_trace(mVcdFile, ap_sync_channel_write_cache_V, "ap_sync_channel_write_cache_V"); sc_trace(mVcdFile, write_burst_U0_ap_start, "write_burst_U0_ap_start"); sc_trace(mVcdFile, write_burst_U0_ap_done, "write_burst_U0_ap_done"); sc_trace(mVcdFile, write_burst_U0_ap_continue, "write_burst_U0_ap_continue"); sc_trace(mVcdFile, write_burst_U0_ap_idle, "write_burst_U0_ap_idle"); sc_trace(mVcdFile, write_burst_U0_ap_ready, "write_burst_U0_ap_ready"); sc_trace(mVcdFile, write_burst_U0_cache_V_address0, "write_burst_U0_cache_V_address0"); sc_trace(mVcdFile, write_burst_U0_cache_V_ce0, "write_burst_U0_cache_V_ce0"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWVALID, "write_burst_U0_m_axi_rx_buffer_V_AWVALID"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWADDR, "write_burst_U0_m_axi_rx_buffer_V_AWADDR"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWID, "write_burst_U0_m_axi_rx_buffer_V_AWID"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWLEN, "write_burst_U0_m_axi_rx_buffer_V_AWLEN"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWSIZE, "write_burst_U0_m_axi_rx_buffer_V_AWSIZE"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWBURST, "write_burst_U0_m_axi_rx_buffer_V_AWBURST"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWLOCK, "write_burst_U0_m_axi_rx_buffer_V_AWLOCK"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWCACHE, "write_burst_U0_m_axi_rx_buffer_V_AWCACHE"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWPROT, "write_burst_U0_m_axi_rx_buffer_V_AWPROT"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWQOS, "write_burst_U0_m_axi_rx_buffer_V_AWQOS"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWREGION, "write_burst_U0_m_axi_rx_buffer_V_AWREGION"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_AWUSER, "write_burst_U0_m_axi_rx_buffer_V_AWUSER"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_WVALID, "write_burst_U0_m_axi_rx_buffer_V_WVALID"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_WDATA, "write_burst_U0_m_axi_rx_buffer_V_WDATA"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_WSTRB, "write_burst_U0_m_axi_rx_buffer_V_WSTRB"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_WLAST, "write_burst_U0_m_axi_rx_buffer_V_WLAST"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_WID, "write_burst_U0_m_axi_rx_buffer_V_WID"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_WUSER, "write_burst_U0_m_axi_rx_buffer_V_WUSER"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARVALID, "write_burst_U0_m_axi_rx_buffer_V_ARVALID"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARADDR, "write_burst_U0_m_axi_rx_buffer_V_ARADDR"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARID, "write_burst_U0_m_axi_rx_buffer_V_ARID"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARLEN, "write_burst_U0_m_axi_rx_buffer_V_ARLEN"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARSIZE, "write_burst_U0_m_axi_rx_buffer_V_ARSIZE"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARBURST, "write_burst_U0_m_axi_rx_buffer_V_ARBURST"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARLOCK, "write_burst_U0_m_axi_rx_buffer_V_ARLOCK"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARCACHE, "write_burst_U0_m_axi_rx_buffer_V_ARCACHE"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARPROT, "write_burst_U0_m_axi_rx_buffer_V_ARPROT"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARQOS, "write_burst_U0_m_axi_rx_buffer_V_ARQOS"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARREGION, "write_burst_U0_m_axi_rx_buffer_V_ARREGION"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_ARUSER, "write_burst_U0_m_axi_rx_buffer_V_ARUSER"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_RREADY, "write_burst_U0_m_axi_rx_buffer_V_RREADY"); sc_trace(mVcdFile, write_burst_U0_m_axi_rx_buffer_V_BREADY, "write_burst_U0_m_axi_rx_buffer_V_BREADY"); sc_trace(mVcdFile, write_burst_U0_rx_buffer_V_offset_read, "write_burst_U0_rx_buffer_V_offset_read"); sc_trace(mVcdFile, write_burst_U0_rx_buffer_V_offset_c_read, "write_burst_U0_rx_buffer_V_offset_c_read"); sc_trace(mVcdFile, ap_sync_continue, "ap_sync_continue"); sc_trace(mVcdFile, cache_V_i_full_n, "cache_V_i_full_n"); sc_trace(mVcdFile, cache_V_t_empty_n, "cache_V_t_empty_n"); sc_trace(mVcdFile, rx_buffer_V_offset_c_full_n, "rx_buffer_V_offset_c_full_n"); sc_trace(mVcdFile, rx_buffer_V_offset_c_dout, "rx_buffer_V_offset_c_dout"); sc_trace(mVcdFile, rx_buffer_V_offset_c_empty_n, "rx_buffer_V_offset_c_empty_n"); sc_trace(mVcdFile, rx_buffer_V_offset_c_2_full_n, "rx_buffer_V_offset_c_2_full_n"); sc_trace(mVcdFile, rx_buffer_V_offset_c_2_dout, "rx_buffer_V_offset_c_2_dout"); sc_trace(mVcdFile, rx_buffer_V_offset_c_2_empty_n, "rx_buffer_V_offset_c_2_empty_n"); sc_trace(mVcdFile, buffer_offset_V_dout, "buffer_offset_V_dout"); sc_trace(mVcdFile, buffer_offset_V_empty_n, "buffer_offset_V_empty_n"); sc_trace(mVcdFile, ap_sync_done, "ap_sync_done"); sc_trace(mVcdFile, ap_sync_ready, "ap_sync_ready"); sc_trace(mVcdFile, rx_axis_words7131_U0_start_full_n, "rx_axis_words7131_U0_start_full_n"); sc_trace(mVcdFile, rx_axis_words7131_U0_start_write, "rx_axis_words7131_U0_start_write"); sc_trace(mVcdFile, write_burst_U0_start_full_n, "write_burst_U0_start_full_n"); sc_trace(mVcdFile, write_burst_U0_start_write, "write_burst_U0_start_write"); #endif } } dataflow_in_loop::~dataflow_in_loop() { if (mVcdFile) sc_close_vcd_trace_file(mVcdFile); delete cache_V_U; delete rx_axis_words7131_U0; delete write_burst_U0; delete rx_buffer_V_offset_c_U; delete rx_buffer_V_offset_c_2_U; delete buffer_offset_V_U; } void dataflow_in_loop::thread_ap_var_for_const2() { ap_var_for_const2 = ap_const_logic_1; } void dataflow_in_loop::thread_ap_var_for_const0() { ap_var_for_const0 = ap_const_logic_0; } void dataflow_in_loop::thread_ap_var_for_const1() { ap_var_for_const1 = ap_const_lv64_0; } void dataflow_in_loop::thread_ap_var_for_const3() { ap_var_for_const3 = ap_const_lv1_0; } void dataflow_in_loop::thread_ap_var_for_const4() { ap_var_for_const4 = ap_const_lv2_0; } void dataflow_in_loop::thread_ap_clk_no_reset_() { if ( ap_rst.read() == ap_const_logic_1) { ap_sync_reg_channel_write_buffer_offset_V = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_const_logic_1, (rx_axis_words7131_U0_ap_done.read() & rx_axis_words7131_U0_ap_continue.read()))) { ap_sync_reg_channel_write_buffer_offset_V = ap_const_logic_0; } else { ap_sync_reg_channel_write_buffer_offset_V = ap_sync_channel_write_buffer_offset_V.read(); } } if ( ap_rst.read() == ap_const_logic_1) { ap_sync_reg_channel_write_cache_V = ap_const_logic_0; } else { if (esl_seteq<1,1,1>(ap_const_logic_1, (rx_axis_words7131_U0_ap_done.read() & rx_axis_words7131_U0_ap_continue.read()))) { ap_sync_reg_channel_write_cache_V = ap_const_logic_0; } else { ap_sync_reg_channel_write_cache_V = ap_sync_channel_write_cache_V.read(); } } } void dataflow_in_loop::thread_ap_channel_done_buffer_offset_V() { ap_channel_done_buffer_offset_V = (rx_axis_words7131_U0_ap_done.read() & (ap_sync_reg_channel_write_buffer_offset_V.read() ^ ap_const_logic_1)); } void dataflow_in_loop::thread_ap_channel_done_cache_V() { ap_channel_done_cache_V = (rx_axis_words7131_U0_ap_done.read() & (ap_sync_reg_channel_write_cache_V.read() ^ ap_const_logic_1)); } void dataflow_in_loop::thread_ap_done() { ap_done = write_burst_U0_ap_done.read(); } void dataflow_in_loop::thread_ap_idle() { ap_idle = (rx_axis_words7131_U0_ap_idle.read() & write_burst_U0_ap_idle.read() & (cache_V_t_empty_n.read() ^ ap_const_logic_1) & (buffer_offset_V_empty_n.read() ^ ap_const_logic_1)); } void dataflow_in_loop::thread_ap_ready() { ap_ready = rx_axis_words7131_U0_ap_ready.read(); } void dataflow_in_loop::thread_ap_sync_channel_write_buffer_offset_V() { ap_sync_channel_write_buffer_offset_V = ((ap_channel_done_buffer_offset_V.read() & buffer_offset_V_full_n.read()) | ap_sync_reg_channel_write_buffer_offset_V.read()); } void dataflow_in_loop::thread_ap_sync_channel_write_cache_V() { ap_sync_channel_write_cache_V = ((ap_channel_done_cache_V.read() & rx_axis_words7131_U0_cache_V1_full_n.read()) | ap_sync_reg_channel_write_cache_V.read()); } void dataflow_in_loop::thread_ap_sync_continue() { ap_sync_continue = ap_continue.read(); } void dataflow_in_loop::thread_ap_sync_done() { ap_sync_done = write_burst_U0_ap_done.read(); } void dataflow_in_loop::thread_ap_sync_ready() { ap_sync_ready = rx_axis_words7131_U0_ap_ready.read(); } void dataflow_in_loop::thread_axis_V_V_TREADY() { axis_V_V_TREADY = rx_axis_words7131_U0_axis_V_V_TREADY.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARADDR() { m_axi_rx_buffer_V_ARADDR = ap_const_lv32_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARBURST() { m_axi_rx_buffer_V_ARBURST = ap_const_lv2_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARCACHE() { m_axi_rx_buffer_V_ARCACHE = ap_const_lv4_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARID() { m_axi_rx_buffer_V_ARID = ap_const_lv1_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARLEN() { m_axi_rx_buffer_V_ARLEN = ap_const_lv32_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARLOCK() { m_axi_rx_buffer_V_ARLOCK = ap_const_lv2_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARPROT() { m_axi_rx_buffer_V_ARPROT = ap_const_lv3_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARQOS() { m_axi_rx_buffer_V_ARQOS = ap_const_lv4_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARREGION() { m_axi_rx_buffer_V_ARREGION = ap_const_lv4_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARSIZE() { m_axi_rx_buffer_V_ARSIZE = ap_const_lv3_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARUSER() { m_axi_rx_buffer_V_ARUSER = ap_const_lv1_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_ARVALID() { m_axi_rx_buffer_V_ARVALID = ap_const_logic_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWADDR() { m_axi_rx_buffer_V_AWADDR = write_burst_U0_m_axi_rx_buffer_V_AWADDR.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWBURST() { m_axi_rx_buffer_V_AWBURST = write_burst_U0_m_axi_rx_buffer_V_AWBURST.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWCACHE() { m_axi_rx_buffer_V_AWCACHE = write_burst_U0_m_axi_rx_buffer_V_AWCACHE.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWID() { m_axi_rx_buffer_V_AWID = write_burst_U0_m_axi_rx_buffer_V_AWID.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWLEN() { m_axi_rx_buffer_V_AWLEN = write_burst_U0_m_axi_rx_buffer_V_AWLEN.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWLOCK() { m_axi_rx_buffer_V_AWLOCK = write_burst_U0_m_axi_rx_buffer_V_AWLOCK.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWPROT() { m_axi_rx_buffer_V_AWPROT = write_burst_U0_m_axi_rx_buffer_V_AWPROT.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWQOS() { m_axi_rx_buffer_V_AWQOS = write_burst_U0_m_axi_rx_buffer_V_AWQOS.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWREGION() { m_axi_rx_buffer_V_AWREGION = write_burst_U0_m_axi_rx_buffer_V_AWREGION.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWSIZE() { m_axi_rx_buffer_V_AWSIZE = write_burst_U0_m_axi_rx_buffer_V_AWSIZE.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWUSER() { m_axi_rx_buffer_V_AWUSER = write_burst_U0_m_axi_rx_buffer_V_AWUSER.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_AWVALID() { m_axi_rx_buffer_V_AWVALID = write_burst_U0_m_axi_rx_buffer_V_AWVALID.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_BREADY() { m_axi_rx_buffer_V_BREADY = write_burst_U0_m_axi_rx_buffer_V_BREADY.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_RREADY() { m_axi_rx_buffer_V_RREADY = ap_const_logic_0; } void dataflow_in_loop::thread_m_axi_rx_buffer_V_WDATA() { m_axi_rx_buffer_V_WDATA = write_burst_U0_m_axi_rx_buffer_V_WDATA.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_WID() { m_axi_rx_buffer_V_WID = write_burst_U0_m_axi_rx_buffer_V_WID.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_WLAST() { m_axi_rx_buffer_V_WLAST = write_burst_U0_m_axi_rx_buffer_V_WLAST.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_WSTRB() { m_axi_rx_buffer_V_WSTRB = write_burst_U0_m_axi_rx_buffer_V_WSTRB.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_WUSER() { m_axi_rx_buffer_V_WUSER = write_burst_U0_m_axi_rx_buffer_V_WUSER.read(); } void dataflow_in_loop::thread_m_axi_rx_buffer_V_WVALID() { m_axi_rx_buffer_V_WVALID = write_burst_U0_m_axi_rx_buffer_V_WVALID.read(); } void dataflow_in_loop::thread_rx_axis_words7131_U0_ap_continue() { rx_axis_words7131_U0_ap_continue = (ap_sync_channel_write_buffer_offset_V.read() & ap_sync_channel_write_cache_V.read()); } void dataflow_in_loop::thread_rx_axis_words7131_U0_ap_start() { rx_axis_words7131_U0_ap_start = ap_start.read(); } void dataflow_in_loop::thread_rx_axis_words7131_U0_cache_V1_full_n() { rx_axis_words7131_U0_cache_V1_full_n = cache_V_i_full_n.read(); } void dataflow_in_loop::thread_rx_axis_words7131_U0_start_full_n() { rx_axis_words7131_U0_start_full_n = ap_const_logic_1; } void dataflow_in_loop::thread_rx_axis_words7131_U0_start_write() { rx_axis_words7131_U0_start_write = ap_const_logic_0; } void dataflow_in_loop::thread_write_burst_U0_ap_continue() { write_burst_U0_ap_continue = ap_continue.read(); } void dataflow_in_loop::thread_write_burst_U0_ap_start() { write_burst_U0_ap_start = (cache_V_t_empty_n.read() & buffer_offset_V_empty_n.read()); } void dataflow_in_loop::thread_write_burst_U0_start_full_n() { write_burst_U0_start_full_n = ap_const_logic_1; } void dataflow_in_loop::thread_write_burst_U0_start_write() { write_burst_U0_start_write = ap_const_logic_0; } }
[ "weatherbee@krtkl.com" ]
weatherbee@krtkl.com
b9631992cde96f43d1c923455faadb6582ed2fb4
5f345205d03f55364b4c7e476b34ced8e8d8ed60
/include/okapi/api/device/button/abstractButton.hpp
4e75f2ebd79b4e1218f5053a3692656b1cd877c3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "MPL-2.0" ]
permissive
Discobots-1104A/2020-2021-bionic-beaver
e660563815237a8d0e243de308ea729c3c04f7da
cd2245a65cad7884c87900d4625f4d5c5f6ad703
refs/heads/master
2023-02-14T05:16:16.955760
2020-12-14T23:44:22
2020-12-14T23:44:22
291,755,615
1
5
MIT
2021-01-08T23:35:25
2020-08-31T15:38:38
C++
UTF-8
C++
false
false
1,290
hpp
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "okapi/api/control/controllerInput.hpp" namespace okapi { class AbstractButton : public ControllerInput<bool> { public: virtual ~AbstractButton(); /** * Return whether the button is currently pressed. **/ virtual bool isPressed() = 0; /** * Return whether the state of the button changed since the last time this method was * called. **/ virtual bool changed() = 0; /** * Return whether the state of the button changed to being pressed since the last time this method * was called. **/ virtual bool changedToPressed() = 0; /** * Return whether the state of the button to being not pressed changed since the last time this * method was called. **/ virtual bool changedToReleased() = 0; /** * Get the sensor value for use in a control loop. This method might be automatically called in * another thread by the controller. * * @return the current sensor value. This is the same as the output of the pressed() method. */ virtual bool controllerGet() override; }; } // namespace okapi
[ "marco.tan.200405@gmail.com" ]
marco.tan.200405@gmail.com
ba644b30b20da07143e939735b4cd0349a32779b
70a3a722d31619e6a7c5a37644a707d595254616
/codefoce/cf1323d.cc
a4897625aa2b951f5e8b25abc29dd5e55da4ecf1
[]
no_license
yaoyaowd/competitivecoding
bed58601ae12cfa7768c5fd91bfb61293dc10545
b626e75ffc593390e4e5cf1ed53f396b62df418c
refs/heads/master
2022-05-04T03:44:20.313924
2022-04-04T20:33:18
2022-04-04T20:33:18
184,917,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,285
cc
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 400010; const int inf = 1e8; const int mod = 1000000007; int n; vector<int> a; int b[maxn]; int check(int bit) { for (int i =0 ; i < n; ++i) { b[i] = a[i] & ((bit << 1) - 1); } sort(b, b + n); int tot = 0; int l = n, r = n; for (int i = 0; i < n; ++i) { while (l > 0 && b[l - 1] + b[i] >= bit) l--; while (r < n && b[r] + b[i] >= bit + bit) r--; if (l < r) { tot += r - l + 1; if (i >= l && i < r) tot -= 1; } } cout << bit << " " << l << " " << r << endl; l = n, r = n; for (int i = 0; i < n; ++i) { while (l > 0 && b[l - 1] + b[i] >= bit + bit + bit) l--; while (r < n && b[r] + b[i] >= bit + bit + bit + bit - 2) r--; if (l < r) { tot += r - l + 1; if (i >= l && i < r) tot -= 1; } } cout << bit << " " << l << " " << r << endl; return tot; } int main() { freopen("in.txt", "r", stdin); ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n; a.resize(n); for (int i = 0; i < n; ++i) cin >> a[i]; sort(a.begin(), a.end()); int ans = 0; for (int i = 1; i <= a[n - 1] * 2; i += i) { ans += (check(i) % 2) * i; } cout << ans << endl; return 0; }
[ "dongw89@gmail.com" ]
dongw89@gmail.com
6591a870b70708cd2a713bc618436f4de996b29a
623a8be7e988b4006c82f25874e7570312089b96
/dpse2/src/dpseapp/simu/CSimulatorBase.cpp
d211d8240be2657cb4d390ab730b1dd2ed1d9b46
[ "MIT" ]
permissive
ArsMasiuk/DPSE
c8f30779bbff823c42552fe23bd0c867e122d314
f04446545d73d19a130eb3a565ad46bf7008eb27
refs/heads/master
2021-01-19T04:08:22.592215
2019-11-07T22:18:57
2019-11-07T22:18:57
84,427,904
2
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
#include "CSimulatorBase.h" #include "ILogger.h" #include <qvge/CNodeEditorScene.h> CSimulatorBase::CSimulatorBase(QObject *parent) : QObject(parent) { } void CSimulatorBase::setLogger(ILogger &logger) { m_logger = &logger; } void CSimulatorBase::logInfo(const QString& text) { if (m_logger) m_logger->write(text, ILogger::LOG_INFO); } void CSimulatorBase::logOk(const QString& text) { if (m_logger) m_logger->write(text, ILogger::LOG_OK); } void CSimulatorBase::logWarning(const QString& text) { if (m_logger) m_logger->write(text, ILogger::LOG_WARN); } void CSimulatorBase::logError(const QString& text) { if (m_logger) m_logger->write(text, ILogger::LOG_ERROR); } // ISimulator void CSimulatorBase::setGraph(const IGraphInterface& scene) { m_scene = &scene; }
[ "ars.masiuk@gmail.com" ]
ars.masiuk@gmail.com
202872017c318a480bf1ff28940da728789c4a4f
e204913fed67f1dfac2d338592fd0929359f1577
/components/Common/Slices/.svn/text-base/ReuseDistanceSlice.cpp.svn-base
9f5f39476233abcfa7fb856316744b4c1c73c67c
[]
no_license
javpicorel/memory_tool
33371dc778b2a1c4351661887444570265808356
f88ea71a26c94a368675740205779d971ae510f5
refs/heads/master
2021-01-11T03:52:40.234629
2017-03-26T23:23:24
2017-03-26T23:23:24
71,281,348
1
0
null
null
null
null
UTF-8
C++
false
false
3,252
// DO-NOT-REMOVE begin-copyright-block // // Redistributions of any form whatsoever must retain and/or include the // following acknowledgment, notices and disclaimer: // // This product includes software developed by Carnegie Mellon University. // // Copyright 2006 - 2008 by Eric Chung, Michael Ferdman, Brian Gold, Nikos // Hardavellas, Jangwoo Kim, Ippokratis Pandis, Minglong Shao, Jared Smolens, // Stephen Somogyi, Evangelos Vlachos, Tom Wenisch, Anastassia Ailamaki, // Babak Falsafi and James C. Hoe for the SimFlex Project, Computer // Architecture Lab at Carnegie Mellon, Carnegie Mellon University. // // For more information, see the SimFlex project website at: // http://www.ece.cmu.edu/~simflex // // You may not use the name 'Carnegie Mellon University' or derivations // thereof to endorse or promote products derived from this software. // // If you modify the software you must place a notice on or within any // modified version provided or made available to any third party stating // that you have modified the software. The notice shall include at least // your name, address, phone number, email address and the date and purpose // of the modification. // // THE SOFTWARE IS PROVIDED 'AS-IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER // EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO ANY WARRANTY // THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS OR BE ERROR-FREE AND ANY // IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, OR NON-INFRINGEMENT. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY // BE LIABLE FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO DIRECT, INDIRECT, // SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN // ANY WAY CONNECTED WITH THIS SOFTWARE (WHETHER OR NOT BASED UPON WARRANTY, // CONTRACT, TORT OR OTHERWISE). // // DO-NOT-REMOVE end-copyright-block #include <components/Common/Slices/ReuseDistanceSlice.hpp> namespace Flexus { namespace SharedTypes { std::ostream & operator << (std::ostream & s, ReuseDistanceSlice & aReuseDistanceSlice) { char const * reuseDistSlice_types[] = { "Process Memory Message", "Get Mean Reuse Distance [Data]" }; return s << "ReuseDistanceSlice[" << reuseDistSlice_types[aReuseDistanceSlice.type()] << "]: Addr:0x" << std::hex << aReuseDistanceSlice.address() << " Msg: " << aReuseDistanceSlice.memMsg(); } } //namespace SharedTypes } //namespace Flexus
[ "javier.picorel@epfl.ch" ]
javier.picorel@epfl.ch
523a2e1eb61ba3dd1d15806f394040429ecde539
a3bf8ac1d3070a4a2a6b264307286af38f68a9cb
/kolko i krzyz/PodajPole.cpp
0a5e87125c0bccb2e87468b7bb2ccaf19ffea3ad
[]
no_license
Kacpi12/TIC-TAC-TOE
27cff7ac9f36c12c9d469ca447d256081aee50eb
402c93f01bb652a9f59957bd4887b26914c0660a
refs/heads/master
2022-12-04T06:31:22.383726
2020-08-30T10:48:28
2020-08-30T10:48:28
291,451,311
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
#include <iostream> #include <fstream> #include <cstdlib> template<typename T> void PodajXY(T& x, T& y) { std::cout << "Podaj wspolrzedne pion: "; while ((std::cin >> x) && (x > 2)); std::cout << std::endl; std::cout << "Podaj wspolrzedne poziom: "; while ((std::cin >> y) && (y > 2)); }
[ "kapisztuka1@gmail.com" ]
kapisztuka1@gmail.com
1787757485638ca6f4c0fa2ad03b607243ab4c7e
35b929181f587c81ad507c24103d172d004ee911
/SrcLib/core/fwAtoms/include/fwAtoms/Blob.hpp
b56e155b8036d01a6dc335f9fa0946b152d62e62
[]
no_license
hamalawy/fw4spl
7853aa46ed5f96660123e88d2ba8b0465bd3f58d
680376662bf3fad54b9616d1e9d4c043d9d990df
refs/heads/master
2021-01-10T11:33:53.571504
2015-07-23T08:01:59
2015-07-23T08:01:59
50,699,438
2
1
null
null
null
null
UTF-8
C++
false
false
1,899
hpp
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2009-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef __FWATOMS_BASE_BLOB_HPP__ #define __FWATOMS_BASE_BLOB_HPP__ #include <fwMemory/BufferObject.hpp> #include "fwAtoms/config.hpp" #include "fwAtoms/Base.hpp" #include "fwAtoms/factory/new.hpp" namespace fwAtoms { /** * @brief Representation of a buffer * * A blob wraps a buffer */ class FWATOMS_CLASS_API Blob : public Base { public: fwCoreClassDefinitionsWithFactoryMacro( (Blob)(::fwAtoms::Base), (()), ::fwAtoms::factory::New< Blob >) ; /** * @brief Constructor * @param key Private construction key */ Blob(::fwAtoms::Base::Key key) {} /** * @brief Destructor */ virtual ~Blob() {} /** * @brief create a new Blob shared ptr. * @param buffer the buffer object */ FWATOMS_API static Blob::sptr New(::fwMemory::BufferObject::sptr buffer); /** * @brief create a new Blob shared ptr. * @param buffer the buffer * @param size the buffer size */ FWATOMS_API static Blob::sptr New(void* buffer, unsigned int size); /** * @brief buffer accessor. * @return the a pointer to the first buffer element. * @{ */ FWATOMS_API ::fwMemory::BufferObject::sptr getBufferObject() const; FWATOMS_API void setBufferObject(const ::fwMemory::BufferObject::sptr &bo); /// @} /** * @brief Returns a clone object */ FWATOMS_API virtual Base::sptr clone() const; /** * @brief returns Atom type */ ::fwAtoms::Base::AtomType type() const {return ::fwAtoms::Base::BLOB;}; protected: ::fwMemory::BufferObject::sptr m_bufferObject; }; } #endif /* _FWATOMS_BASE_BLOB_HPP_ */
[ "fbridault@IRCAD.FR" ]
fbridault@IRCAD.FR
64e101bf2f8407782bf7c2135431ac00a60551ec
32ffbbbffef195ee4a87aa066499349bdf613e40
/day02/bag.cpp
6cf739c24e2ef16788c91bbf41b3cb14e89b1a74
[]
no_license
webturing/2020NOIPWinterCamp
d4655fcdf537a33f8684a867b9cab9916b0f1d94
a5becac8e18872f3b88550cc2f7961c6f7797604
refs/heads/master
2020-12-09T16:57:02.351834
2020-01-17T09:47:29
2020-01-17T09:47:29
233,363,866
3
1
null
null
null
null
UTF-8
C++
false
false
677
cpp
#include<bits/stdc++.h> using namespace std; int dp[20010]; int w[100],v[100]; int n, m; int main() { //freopen("test.in.c", "r", stdin); while(cin >> m >> n) { for (int i = 1;i <= n;i++) cin >> v[i] >> w[i]; memset(dp, 0x3f3f3f3f, sizeof(dp)); dp[0] = 0; for (int i = 1;i <= n;i++) { for (int j = 1;j <= w[i];j++) for (int k = m;k >= v[i];k--) { dp[k] = min(dp[k], dp[k-v[i]]+1); } } if (dp[m] != 0x3f3f3f3f) cout << dp[m] << endl; else cout << "><" << endl; } return 0; }
[ "zj@webturing" ]
zj@webturing
38c9819641dc2c9314aa3bea7dbeb79d1a52af1e
64b35e1a9e8e720d7d0fb31a9e85548bfef330c9
/List/DoubleTable.cpp
de757f7f7348e0b0154d76aa2c446f34ef762441
[]
no_license
bigJiaLuo/DataStructureStudy
32395fce5c62f928f0bc145e0ce9b5da6d634dec
5ed9d2b20605dca8b5532de63f12eaa64c2f4447
refs/heads/master
2022-12-13T01:45:48.041509
2020-09-17T06:08:13
2020-09-17T06:08:13
269,287,153
2
0
null
null
null
null
GB18030
C++
false
false
14,139
cpp
// 2020年5月25日09:34:53 //双向链表 #include <stdio.h> #include <malloc.h> #define ERROR 0; #define OK 1; #define TRUE 1; #define FALSE 0; typedef int ElemType; typedef int Status; typedef struct Node { ElemType data; struct Node * prior;//上一结点 地址 struct Node * next; //下一结点 地址 } doubleList, *pdoubleList; Status getElem(doubleList L, int i, ElemType *e); Status listInsert(pdoubleList pL, int i, ElemType e); Status isEmpty(int i, int j, pdoubleList *p); void initList(pdoubleList *pL); void createListF(pdoubleList pL, ElemType a[], int n); /* 判断 第i-j个结点是否 存在,并且 保存第i结点的地址,*p 返回 TRUE,代表第i个元素为空,FALSE 不为空 */ Status isEmpty(int i, int j, pdoubleList *p) { while (j < i && *p) { j++; *p = (*p)->next; } if (j > i || !*p) return TRUE; return FALSE; } /* 获取链表中第i个数据 思路: 1.声明一个结点p指向链表头结点,初始化j 从1开始 2.当 j < i时,就遍历链表,让p的指针向后移动,不断指向下一结点,j累加 3.若链表末尾p为空,则说明第i个元素不存在 4.否则查找成功,返回结点p的数据域 时间复杂度 为 O(n) */ Status getElem(doubleList L, int i, ElemType *e) { int j = 1; //初始 开始位置 pdoubleList p = L.next; //p指向头结点 if (isEmpty(i, j, &p)) // p 循环 i-1次 p = p->next,最后会指向 第i个元素的前一个 return ERROR; //没有找到第i个元素 *e = p->data; return OK; } /* 单链表的第i个数据插入结点 pL为 单链表的头结点的指针变量,i为插入元素位置,e为待插入的数据 思路: 1.声明结点p指向链表的头结点,初始化j = 1 2.当j < i时,就遍历链表,让p的指针不断后移,j累加 3.若链表末尾p为空,则说明第i个元素不存在 4.否则查找成功,在系统中生成一段动态存储空间 s 5.将数据元素e 赋值为 s->data 6.双链表的插入标准语句 s->next = p->next;//新节点后继连接第i个结点 s->prior = p;//新节点前驱连接 第i-1个结点 p->next->prior = s;//第i个结点前驱链接 新节点s p->next = s;//第i-1个结点后继连接 新节点s 7.完毕 */ Status listInsert(pdoubleList *pL, int i, ElemType e) { int j = 1; pdoubleList p = (*pL), s; //p指向 头结点 //查找 第i个元素是否存在 if (isEmpty(i, j, &p)) return ERROR; //没有找到第i个元素 s = (pdoubleList)malloc(sizeof(doubleList)); //创建新的动态结点 s->data = e; //插入新节点 s->next = p->next;//新节点后继连接第i个结点 s->prior = p;//新节点前驱连接 第i-1个结点 p->next->prior = s;//第i个结点前驱链接 新节点s p->next = s;//第i-1个结点后继连接 新节点s return OK; } /* 单链表删除第i个元素 pL为 头结点,i为 第几个元素,e返回删除的数据 思路: 1.声明一结点指向 第一个结点,初始化 j = 1 2.查找 第i-1个元素是否存在,并且 用p 保存第i-1个元素的地址 3.进行单链表删除。保存待删除的结点 q = p->next; p = q->next; 4.释放 q结点 内存空间 5.完毕 */ Status listDelete(pdoubleList *pL, int i, ElemType *e) { int j = 1; pdoubleList p = (*pL), q; // 第一个结点 if (isEmpty(i, j, &p)) return ERROR; //删除元素 不存在 //删除 第i个结点 q = p->next;//保存 删除结点 p->next = q->next;//第i-1结点后驱 连接 第i+1结点 q->next->prior = p;//第i+1结点前驱连接 第i-1结点 free(q); q = NULL; return OK; } /* 初始化一个头结点 */ void initList(pdoubleList *pL) { *pL = (pdoubleList)malloc(sizeof(doubleList)); (*pL)->prior = *pL;//上一结点指向自身 (*pL)->next = *pL;//下一个结点指向其自身 } /* 根据数组,建立 单链表(头插法) pL头结点,a 为数组首地址,n为 数组长度 思路: 1.创建一个头结点 给 pL,和i =1, 2.循环 遍历 i<n 3.循环 ·生成一个新结点 p ·将本次循环的 数组中的值给 p->data[i] ·将 p插入到头结点 与上一新节点之间 */ void createListF(pdoubleList *pL, ElemType a[], int n) { initList(&(*pL)); pdoubleList p; for (int i = 0; i < n; i++) { //生成新的结点p p = (pdoubleList)malloc(sizeof(doubleList)); //赋值 p->data = a[i]; p->prior = (*pL);//p的前驱指向头结点 p->next = (*pL)->next;//p的后继指向第一个结点 (*pL)->next->prior = p;//旧首节点结点前驱指向 p (*pL)->next = p; // p称为新的首节点 } } /* 创建线性表。(尾插法) 注意结尾时,将头结点的 prior 更换为 最后一个结点 */ // void createListR(pdoubleList &pL, ElemType a[], int n) // { // pL = (pdoubleList)malloc(sizeof(doubleList)); // pL->next = pL; // pL->prior = pL; // pdoubleList p, r = pL,L = pL; //p保存新节点,r指向最后结点,pre指向第一结点 // for (int i = 0; i < n; i++) // { // //生成新的结点 // p = (pdoubleList)malloc(sizeof(doubleList)); // p->data = a[i]; // // p->next = NULL; // // p->prior = NULL; // //新节点插入到最后一位,r重新指向最后一位 // r->next = p; // p->prior = r; // r = p;//重新指向最后一位结点 // } // //尾指针next为头结点 // r->next = pL; // pL->prior = r; // } void createListR(pdoubleList *pL, ElemType a[], int n) { initList(&(*pL)); pdoubleList p, r = *pL,L = *pL; //p保存新节点,r指向最后结点,pre指向第一结点 for (int i = 0; i < n; i++) { //生成新的结点 p = (pdoubleList)malloc(sizeof(doubleList)); p->data = a[i]; // p->next = NULL; // p->prior = NULL; //新节点插入到最后一位,r重新指向最后一位 r->next = p; p->prior = r; r = p;//重新指向最后一位结点,且下一次循环将p-next域赋值 } //尾指针next为头结点,头结点的前驱为 尾结点 r->next = *pL; (*pL)->prior = r; } /* 打印线性表 L为头指针 */ void displayList(pdoubleList L) { pdoubleList p = L->next; printf("顺序遍历!\n"); while (p != L) { printf("%d\t", p->data); p = p->next; } printf("\n"); } void displayList1(pdoubleList L) { printf("逆序遍历!\n"); pdoubleList p = L->prior; while (p != L) { printf("%d\t", p->data); p = p->prior; } printf("\n"); } /* 释放pL所指向的单链表 思路: 1.声明p,q。p存放待释放结点,q存放下一结点 2.将第一结点给p 3.循环: ·将下一节点赋给q ·释放p ·将q 赋给p */ Status clearList(pdoubleList *pL) { pdoubleList p, q; //p存放待释放的结点,q存放下一结点 p = (*pL)->next; //当p为空时停止 while (p) { /* code */ q = p->next; free(p); p = q; } (*pL)->next = *pL; return OK; } // 双链表应用示例 /* 1.有一带头结点的单链表L = {a1,b1,a2,b2...an,bn},设计一个算法将其 拆分为两个带头结点的单链表L1和L2,L1={a1,a2,an},L2={b1,b2,..bn}. 要求L1沿用L的头结点 思路: 1.L1表 元素为顺序插入,采用尾插法,L2表逆序插入,采用头插法 */ void split(pdoubleList * L,pdoubleList * L1,pdoubleList * L2){ pdoubleList p = (*L)->next,r1,q;//p 用于循环L表,指向第一个结点,r1用于始终指向L1的尾结点,q用来保存 头插法修改p->next *L1 = *L;//L1沿用L的头结点 r1 = *L1;//始终指向L1尾结点 *L2 = (pdoubleList)malloc(sizeof(doubleList));//L2建立头结点 (*L2)->next = NULL; while(p != *L){ //不要写成*L1, 这样尾插法 的话,会使结点一直插在第一元素, 最后也只有一个结点 r1->next = p;//尾插法 插入元素p ai r1 = p;//指向 L1尾结点 p = p->next;//移动p指针, data值为 bi q = p->next;// 保存因头插法 失去的p->next, data为 ai p->next = (*L2)->next;//头插法,将p插入第一位结点 (*L2)->next = p;//L2头结点,始终指向新插入结点 p = q;//p重新指向 ai + 1的结点 } r1->next = NULL;//循环结束后,为尾结点next域赋NULL } /* 删除一个双链表中最大的元素 思路: 1.删除一个元素,需要获取其前一位的元素 2.将第一结点赋给max,p; maxpre 保存max前一结点,pre 保存 p前一结点 3.循环 ·依次遍历链表,将max与后每一结点p进行比较,大的结点存入max中 ·判断是否需要对max赋值,要-》maxpre = pre; ·pre = p,p = p->next */ void listDeleteMax(pdoubleList * pL){ pdoubleList maxpre = *pL,max = (*pL)->next,p = (*pL)->next,pre = *pL; while(p != *pL){ //比较大小 if(max->data < p->data){ max = p; maxpre = pre; } //将 p指针后移,重置pre pre = p; p = p->next; } maxpre->next=maxpre->next->next; free(max); max = NULL; } /* 双链表由递增排序 思路: 1.由于双链表L中有一个以上的数据结点,先构造只含一个数据结点的有序表。 2.扫描双链表L余下的结点 p( 直到p = NULL) pre始终指向 排好序的有序表的头结点,与原单链表中的 p指向的结点比较 有序表中小于 p结点 则 继续移动指针到下一个,直到大于p结点,或 pre->next == *pL 3.在有序表中通过比较找插入 p结点的前驱结点 pre 4.在pre结点之后插入 p结点,直接插入排序法 2020年5月24日16:32:58, 需要重点复习,初步理解 头插法,pre相当于移动的头结点,p结点插在其之后 */ void sort(pdoubleList * pL){ pdoubleList p,pre,q,L = *pL; p = L->next->next;//p指向 L的第二个数据结点 L->next->next = *pL;//构造只含 一个数据结点的有序表 while(p != *pL){ q = p->next;// q保存 p结点后继结点的指针 pre = L;// 从有序表开头进行比较,pre指向插入 p的前驱结点 while(pre->next != *pL && pre->next->data < p->data)//循环结束 ,说明 已经找到比p大的结点,pre保存其前驱结点,或者 pre所指有序表均小于p所指结点 pre = pre->next;//后移pre指针 //插入动作,p结点大于 pre->next,p结点插入到 pre->next 位置上, pre->next 后移一位,头插法,pre相当于移动的头结点,p结点插在其之后 //pre->next 必大于 p->next,将其插入到 p结点next域中,pre作为前驱结点链接 p p->next = pre->next;//将p插入到 pre之后 p->prior = pre;//插入元素指向 插入位置元素的前驱 pre->next->prior = p;//后移结点前驱指向 p pre->next = p; p = q;//扫描原双链表余下的结点 // printf("地址:%p",p); } } //双链表的应用示例 /* 1.有一双链表L, 设计一算法,将L中所有元素的顺序逆序 思路: 1.先构造一个只包含头结点的双链表(沿用L的头结点)L 1.1 变量p 指向L的开始结点 2.通过遍历原链表,使用头插法重新插入 */ void reverse(pdoubleList * L){ pdoubleList p = (*L)->next,q;//p指向 L的开始结点,q保存头插法丢失的下一结点 (*L)->next = *L;//构造一个空结点 while(p != *L){//扫描L q = p->next;//保存下一结点 //头插法 p->next = (*L)->next;//将p插入到L的开始结点处 if((*L)->next != *L){ } (*L)->next->prior = p;//将 原先开始结点前驱指向 新开始结点 p->prior = *L;//新开始节点前驱指向 头结点 (*L)->next = p;//头结点后继 指向新开始结点 p = q;//指向下一结点 } } /* 2.有一双链表L, 删除 第一个值为 x的 结点 思路: 1.寻找 删除结点的前驱结点 2.删除 */ Status delElem1(pdoubleList * L,ElemType x){ pdoubleList p = *L,q; while (p->next != (*L) && p->next->data != x) { /* code */ p = p->next;//寻找 第一个元素为x的前驱结点 } if(p->next != (*L)){ q = p->next;//保留 删除结点 p->next->next->prior = p; p->next = q->next; free(q); q = NULL; return OK; } return ERROR; } Status delElem2(pdoubleList * L,ElemType x){ pdoubleList p = (*L)->next; while (p != (*L) && p->data != x) { /* code */ p = p->next;//寻找 第一个元素为x的结点 } if (p != *L) { /* code */ p->next->prior = p->prior; p->prior->next = p->next; free(p); p = NULL; return OK; } return ERROR; } int main(void) { pdoubleList L,L1,L2; pdoubleList& L3 = L; ElemType a[] = {11, 20, 33, 4, 5,6,7,8,9,10}; createListR(&L, a, 10); // initList(&L1); // initList(&L2); // split(&L,&L1,&L2); displayList(L); reverse(&L); // sort(&L); // delElem2(&L,10); // listDeleteMax(&L); // int e; // listDelete(&L,10,&e); // listInsert(&L, 1, 100); displayList(L); // displayList(L2); getchar(); return 0; }
[ "2458681060@qq.com" ]
2458681060@qq.com
6d928ebc0c725b216167f68feeecd173575fed71
92453dcf4b3f89285236fddb52033c800898819d
/include/camera.h
7a879ef4d33ed21067057757e98932ce45f26f1d
[]
no_license
splatpope/JuliaExplorer
ca48ffa90b864efafaa81010640fed3ec856b6ce
ad2a9bb075da7f8a9db5ad86f8955bbee35f0d22
refs/heads/master
2020-06-12T00:59:13.239813
2019-07-25T23:46:27
2019-07-25T23:46:27
194,143,650
0
0
null
null
null
null
UTF-8
C++
false
false
4,612
h
#ifndef CAMERA_H #define CAMERA_H #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <vector> // Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods enum Camera_Movement { CAM_RESET = -1, CAM_FORWARD, CAM_BACKWARD, CAM_LEFT, CAM_RIGHT }; // Default camera values const float YAW = -90.0f; const float PITCH = 0.0f; const float SPEED = 2.5f; const float SENSITIVITY = 0.1f; const float ZOOM = 45.0f; // holy shit put all this crap in a namespace please // An abstract camera class that processes input and calculates the corresponding Euler Angles, Vectors and Matrices for use in OpenGL class Camera { public: // Camera Attributes glm::vec3 Position; glm::vec3 Front; glm::vec3 Up; glm::vec3 Right; glm::vec3 WorldUp; // Euler Angles float Yaw; float Pitch; // Camera options float MovementSpeed; float MouseSensitivity; float Zoom; // Constructor with vectors Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM) { Position = position; WorldUp = up; Yaw = yaw; Pitch = pitch; updateCameraVectors(); } // Constructor with scalar values Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM) { Position = glm::vec3(posX, posY, posZ); WorldUp = glm::vec3(upX, upY, upZ); Yaw = yaw; Pitch = pitch; updateCameraVectors(); } // Returns the view matrix calculated using Euler Angles and the LookAt Matrix glm::mat4 GetViewMatrix() { return glm::lookAt(Position, Position + Front, Up); } // Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems) void ProcessKeyboard(Camera_Movement direction, float deltaTime) { float velocity = MovementSpeed * deltaTime; if (direction == CAM_FORWARD) Position += Up * velocity; //Position += Front * velocity; //use Up (pan) instead of Front (zoom) if (direction == CAM_BACKWARD) Position -= Up * velocity; //Position -= Front * velocity; if (direction == CAM_LEFT) Position -= Right * velocity; if (direction == CAM_RIGHT) Position += Right * velocity; } // Processes input received from a mouse input system. Expects the offset value in both the x and y direction. void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true) { xoffset *= MouseSensitivity; yoffset *= MouseSensitivity; Yaw += xoffset; Pitch += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (Pitch > 89.0f) Pitch = 89.0f; if (Pitch < -89.0f) Pitch = -89.0f; } // Update Front, Right and Up Vectors using the updated Euler angles updateCameraVectors(); } // Processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis void ProcessMouseScroll(float yoffset) { if (Zoom >= 1.0f && Zoom <= 45.0f) Zoom -= yoffset; if (Zoom <= 1.0f) Zoom = 1.0f; if (Zoom >= 45.0f) Zoom = 45.0f; } private: // Calculates the front vector from the Camera's (updated) Euler Angles void updateCameraVectors() { // Calculate the new Front vector glm::vec3 front; front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch)); front.y = sin(glm::radians(Pitch)); front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch)); Front = glm::normalize(front); // Also re-calculate the Right and Up vector Right = glm::normalize(glm::cross(Front, WorldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. Up = glm::normalize(glm::cross(Right, Front)); } }; #endif
[ "prdrdecroly@gmail.com" ]
prdrdecroly@gmail.com
b37035a5731bca8183e8a91acfea5e2b5585aed4
04b1803adb6653ecb7cb827c4f4aa616afacf629
/components/offline_pages/core/prefetch/store/prefetch_downloader_quota.h
7abb7915bc261c8a156a4e21c58b2a0c02adc781
[ "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
1,538
h
// Copyright 2017 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_DOWNLOADER_QUOTA_H_ #define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_DOWNLOADER_QUOTA_H_ #include <cstdint> #include "base/macros.h" namespace base { class Clock; } // namespace base namespace sql { class Database; } // namespace sql namespace offline_pages { // Handles retrieval, storage and calculation of quota for |PrefetchDownloader|. class PrefetchDownloaderQuota { public: // Public for unit tests. static const int64_t kDefaultMaxDailyQuotaBytes; PrefetchDownloaderQuota(sql::Database* db, base::Clock* clock); ~PrefetchDownloaderQuota(); // Gets the max daily quota from Finch. static int64_t GetMaxDailyQuotaBytes(); // Gets the currently available quota, as read from the DB and adjusted for // time elapsed since quota was last updated. int64_t GetAvailableQuotaBytes(); // Sets available quota to the provided |quota| value, capped by // [0, max daily quota]. bool SetAvailableQuotaBytes(int64_t quota); private: // DB connection. Not owned. sql::Database* db_; // Clock used for time related calculation and quota updates in DB. Not owned. base::Clock* clock_; DISALLOW_COPY_AND_ASSIGN(PrefetchDownloaderQuota); }; } // namespace offline_pages #endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_DOWNLOADER_QUOTA_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
d6b939251651b57e68d1c5d99eb4789049eddec7
3dd2bdff943f707ee24cb7bbed371283af085d44
/day08/ex03/CloseBracket.cpp
b143243915d7d2a298bc4bd5e988516ab78bde54
[]
no_license
terngkub/piscine_cpp
255ff5663b47013952e47ef4d38fbedcea8c14b4
7d61d49fd010a8f4ed365242dc6edb2ca0fa3aa9
refs/heads/master
2020-03-11T21:22:41.532592
2019-03-11T20:23:47
2019-03-11T20:23:47
130,263,263
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
#include "CloseBracket.hpp" #include <iostream> CloseBracket::CloseBracket() { _type = ']'; } CloseBracket::~CloseBracket() { } void CloseBracket::execute(iterator & it, iterator & itb, iterator & ite, char * memory, int & index) { static_cast<void>(ite); if (memory[index] == 0) { while (it != itb && (*it)->getType() != '[' ) { --it; } } }
[ "terngnattapol@gmail.com" ]
terngnattapol@gmail.com
af4c13f2c7eb24b874cd924fa48eed3f3080251d
82ac4b610c34e2830ca7870b459ccd804839620f
/src/solver.cpp
da1054f0427b8cb203b6e5e550116ec1ee96122e
[]
no_license
mfkiwl/GNSS_Navi
440a5c5624bfeb4455124f4c990d88ddf3d8d319
cf625933fff1abd1be13a450e7baf619dfec3f45
refs/heads/master
2021-06-22T16:24:16.993016
2017-08-25T21:39:04
2017-08-25T21:39:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,116
cpp
/* * solver.cpp * * Created on: 16 Aug 2017 * Author: Sokol */ #include <math.h> #include <iostream> #include <iomanip> #include "Observations.h" #include "OrbProp.h" #include "Matrix.h" #include "solver.h" using namespace std; Matrix solverLS(const Observations& obsAll, const Orbits& orbsAll, const Matrix& RecXYZapriori) { set<int> commonSV = intersect(obsAll, orbsAll, "R"); Observations obs = select(obsAll, commonSV, "R"); Orbits orbs = select(orbsAll, commonSV); vector<int> sats = orbs.sats; int numberOfSats = sats.size(); if (numberOfSats < 4) { return Matrix(4, 1, 0.0); } // constants, all units in SI !!! const double c = 299792458; // [m/s] const double Omega_E_rate = 0.000072921151467; //[rad/s] const double Tzpd = 2.3; // [m] Matrix RecXYZ(3, 1, 0); RecXYZ = RecXYZapriori; Matrix Range = getRanges(obs); Matrix Xs(3, 1, 0); Matrix Vs(3, 1, 0); Orbits orbs_cor = orbs; for (int iSat = 0; iSat < numberOfSats; ++iSat) { Xs(0) = orbs.StateVector.at(sats[iSat])(0); Xs(1) = orbs.StateVector.at(sats[iSat])(1); Xs(2) = orbs.StateVector.at(sats[iSat])(2); Vs(0) = orbs.StateVector.at(sats[iSat])(3); Vs(1) = orbs.StateVector.at(sats[iSat])(4); Vs(2) = orbs.StateVector.at(sats[iSat])(5); // Correction for Satellite motion during signal travel time double dt_rs = Range(iSat) / c; Xs -= Vs * dt_rs; // Correction for Earth rotation during signal travel time double dOmega = Omega_E_rate * dt_rs; Xs(0) = cos(dOmega) * Xs(0) + sin(dOmega) * Xs(1); Xs(1) = -sin(dOmega) * Xs(0) + cos(dOmega) * Xs(1); // propagate Ephemeris from Tsv to Tuts double TauN = orbs_cor.SVClockBias.at(sats[iSat]); double GammaN = orbs_cor.SVRelativeFrequencyBias.at(sats[iSat]); double TauC = orbs_cor.SystemCorrectiontTme; double tSV = orbs_cor.epoch.toSeconds(); double SVtoUT = (TauN - GammaN * tSV + TauC); Matrix dXs_dts(3, 1, 0); dXs_dts = Vs * SVtoUT; Xs -= dXs_dts; orbs_cor.StateVector.at(sats[iSat])(0) = Xs(0); orbs_cor.StateVector.at(sats[iSat])(1) = Xs(1); orbs_cor.StateVector.at(sats[iSat])(2) = Xs(2); } // dummies Matrix PRangeTilde(numberOfSats, 1, 0.0); Matrix A(numberOfSats, 4, 1); //designMatrix Matrix Residuals(numberOfSats, 1, 0); Matrix rec_est(4, 1, 0); int maxIter = 1; if (norm(RecXYZ) == 0) { maxIter = 5; } for (int iteration = 0; iteration < maxIter; ++iteration) { for (int iSat = 0; iSat < numberOfSats; ++iSat) { Xs(0) = orbs_cor.StateVector.at(sats[iSat])(0); Xs(1) = orbs_cor.StateVector.at(sats[iSat])(1); Xs(2) = orbs_cor.StateVector.at(sats[iSat])(2); // unit vectors Matrix e_sr = (RecXYZ - Xs) / norm(Xs - RecXYZ); A(iSat, 0) = e_sr(0); A(iSat, 1) = e_sr(1); A(iSat, 2) = e_sr(2); // Troposphere correction Matrix e_rec(3, 1, 0); double cos_z = 0; double T = Tzpd; if (norm(RecXYZ) != 0) { e_rec = RecXYZ / norm(RecXYZ); cos_z = (e_rec.transpose() * (e_sr * -1))(0, 0); T = Tzpd / cos_z; } // sat clock correction double TauN = orbs_cor.SVClockBias.at(sats[iSat]); double GammaN = orbs_cor.SVRelativeFrequencyBias.at(sats[iSat]); double TauC = orbs_cor.SystemCorrectiontTme; double tSV = orbs_cor.epoch.toSeconds(); // move known values to lhs PRangeTilde(iSat) = Range(iSat) + (e_sr.transpose() * Xs)(0, 0) + (TauN - GammaN * tSV + TauC) * c - T; } // LSE solution rec_est = (A.transpose() * A).inverse() * (A.transpose() * PRangeTilde); // A.print(); RecXYZ(0) = rec_est(0); RecXYZ(1) = rec_est(1); RecXYZ(2) = rec_est(2); printXYZT(rec_est); cout << endl; // cout << setw(5) << setprecision(0) << numberOfSats << endl; // Matrix Resuduals(numberOfSats,1,0); // Resuduals = PRangeTilde - A * rec_est; // cout << "Residuals" << endl; // Resuduals.print(); } return rec_est; } void printXYZT(const Matrix& rec_est) { const double c = 299792458; // [m/s] int w = 16; cout << fixed << setprecision(3) << setw(w) << rec_est(0) << " " << setw(w) << rec_est(1) << " " << setw(w) << rec_est(2) << " " << setw(w) << setprecision(9) << rec_est(3) / c; }
[ "sokolovalexv@gmail.com" ]
sokolovalexv@gmail.com
c462c8656d495e0a185cdec93579df7f97c701f0
db3b085d00c89ed16bd9e78e132c4558848e6866
/788_Rotated_Digits.cpp
49c946b33d38053c160c2e5aabca9c387134a043
[]
no_license
zkxshg/Test_of_LeetCode
23e4bcd814499c26940659614607f0782c764b09
8a3c2d43ed0b5815c5fb2d2bb4d59e586aae9dba
refs/heads/master
2023-08-22T16:08:04.801856
2023-08-09T22:43:56
2023-08-09T22:43:56
230,379,638
1
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
// string class Solution { public: int rotatedDigits(int N) { int res = 0; for (int i = 1; i <= N; i++) if (ifRo(i)) res++; return res; } bool ifRo(int n) { bool rot = false; while (n > 0) { int i = n % 10; if (i == 3 || i == 4 || i==7) return false; if (i == 2 || i == 5 || i == 6 || i == 9) rot = true; n /= 10; } return rot; } };
[ "zkxshg@126.com" ]
zkxshg@126.com
d00b4f91b0a2272546c92452475c137ea23ed62c
a67a806c481f403a29f4290d4772a361169d19db
/src/gallium/drivers/radeon/AMDILDeviceInfo.cpp
89b8312c294228bf6ca7033f9444499016f4fc91
[ "NCSA" ]
permissive
curro/mesa
4f77445a5b854c52192844020020322bde877753
4e86989a0334c6b6cbcd5291b3547657931f5ab7
refs/heads/master
2021-01-19T07:44:05.233166
2012-04-10T22:11:56
2012-05-01T15:18:03
2,745,131
5
0
null
null
null
null
UTF-8
C++
false
false
3,128
cpp
//===-- AMDILDeviceInfo.cpp - TODO: Add brief description -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //==-----------------------------------------------------------------------===// #include "AMDILDevices.h" #include "AMDILSubtarget.h" using namespace llvm; namespace llvm { AMDILDevice* getDeviceFromName(const std::string &deviceName, AMDILSubtarget *ptr, bool is64bit, bool is64on32bit) { if (deviceName.c_str()[2] == '7') { switch (deviceName.c_str()[3]) { case '1': return new AMDIL710Device(ptr); case '7': return new AMDIL770Device(ptr); default: return new AMDIL7XXDevice(ptr); }; } else if (deviceName == "cypress") { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDILCypressDevice(ptr); } else if (deviceName == "juniper") { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDILEvergreenDevice(ptr); } else if (deviceName == "redwood") { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDILRedwoodDevice(ptr); } else if (deviceName == "cedar") { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDILCedarDevice(ptr); } else if (deviceName == "barts" || deviceName == "turks") { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDILNIDevice(ptr); } else if (deviceName == "cayman") { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDILCaymanDevice(ptr); } else if (deviceName == "caicos") { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDILNIDevice(ptr); } else if (deviceName == "SI") { return new AMDILSIDevice(ptr); } else { #if DEBUG assert(!is64bit && "This device does not support 64bit pointers!"); assert(!is64on32bit && "This device does not support 64bit" " on 32bit pointers!"); #endif return new AMDIL7XXDevice(ptr); } } }
[ "thomas.stellard@amd.com" ]
thomas.stellard@amd.com
166012a60842bf8385c97cec48fbc377d30a984b
ead59468f0da63c830da5fb68dee75e83303ce9b
/obj_carre/carre.cpp
45b1e56c9489c740889cea76d8eb9ebe66f2a98e
[]
no_license
cvcarles/Cpp
532c6aeceaee58abb310a6036b07ac84ab3c3980
46eb5d510880b201bdae96a197144715be23b245
refs/heads/main
2023-03-14T06:14:58.261683
2021-03-08T16:44:10
2021-03-08T16:44:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
#include "carre.hpp" void carre::setCote(const double c) { super::setLargeur(c); super::setLongueur(c); } double carre::getCote() const{ return super::getLargeur(); } double carre::surface() const{ return super::surface(); } std::string carre::quiSuisJe() const { return "un carre"; } std::ostream &operator<<(std::ostream &f, const carre &c){ return f << "carre(" << c.getCote() << ")"; }
[ "43798006+Mr-Zygoto@users.noreply.github.com" ]
43798006+Mr-Zygoto@users.noreply.github.com
3313f017048fb7a60a49b58bd4013cafacc87cf9
b2d201172f4409a6d29080f9adb83b91a6d12e83
/assign-7/src/sscontroller.cpp
5a8649ae01998e070313fab7a085c4c20d555207
[]
no_license
WhiteCloudUU/cs106x
0f1a2fc37bfd41a90e15f9f306dec1f1e26ac18a
d7b1b9decfbdc7fb339162a133d3d4fa173191e4
refs/heads/master
2023-03-31T21:13:56.578932
2021-04-04T17:24:08
2021-04-04T17:24:08
349,921,609
1
0
null
null
null
null
UTF-8
C++
false
false
7,008
cpp
/** * File: sscontroller.cpp * ---------------------- * This file implements the command-line controller for the Stanford 1-2-3 program. * * Fall 2007 Julie Zelenski (all initial work) * Autumn 2009 Jerry Cain (upgrade to use new libraries) * Autumn 2012 Jerry Cain (upgrade to use even newer libraries) * Autumn 2018 Jerry Cain (upgrade to use even *newer* libraries) */ #include <iostream> #include <fstream> #include <iomanip> #include "simpio.h" #include "map.h" #include "tokenscanner.h" #include "error.h" #include "ssutil.h" #include "ssmodel.h" #include "ssview.h" #include "console.h" using namespace std; /** * General implementation notes * ---------------------------- * The controller module implements the command-line interface to the spreadsheet * program. The interface can easily be extended with additional * commands by writing a handler function for the command and then adding * an entry to the table. */ /** * Typedef: cmdFnT * --------------- * This typedef makes a shorthand name for the function prototype * so we can refer to it as cmdFnT instead of the long form */ typedef void (*cmdFnT)(TokenScanner& scanner, SSModel& model); /** * Function: helpAction, loadAction, saveAction, etc. * --------------------------------------------------------- * Each of these handles one specific command. In most cases, it is * simply a matter of using the scanner to read the following arguments and * then acting on the command by sending the appropriate message to the model. */ static const int kLeftColumnWidth = 22; static void helpAction(TokenScanner& /* scanner */, SSModel& /* model */) { cout << left << setw(kLeftColumnWidth) << "help" << "Print this menu of commands" << endl; cout << left << setw(kLeftColumnWidth) << "load <filename>" << "Read named file into spreadsheet" << endl; cout << left << setw(kLeftColumnWidth) << "save <filename>" << "Save current spreadsheet to named file" << endl; cout << left << setw(kLeftColumnWidth) << "set <cell> = <value>" << "Set cell to value. Value can be \"string\" or formula" << endl; cout << left << setw(kLeftColumnWidth) << "get <cell>" << "Print contents of cell" << endl; cout << left << setw(kLeftColumnWidth) << "quit" << "Quit the program" << endl; cout << endl; } static void loadAction(TokenScanner& scanner, SSModel& model) { if (!scanner.hasMoreTokens()) error("The load command requires a file name."); string filename; while (scanner.hasMoreTokens()) filename += scanner.nextToken(); ifstream infile(filename.c_str()); if (infile.fail()) error("Cannot open the file named \"" + filename + "\"."); model.readFromStream(infile); cout << "Loaded file \"" << filename << "\"." << endl; } static void saveAction(TokenScanner& scanner, SSModel& model) { if (!scanner.hasMoreTokens()) error("The save command requires a file name."); string filename; while (scanner.hasMoreTokens()) filename += scanner.nextToken(); ofstream out(filename.c_str()); if (out.fail()) error("Cannot open the file named \"" + filename + "\"."); model.writeToStream(out); cout << "Saved file \"" << filename << "\"." << endl; } static void setAction(TokenScanner& scanner, SSModel& model) { if (!scanner.hasMoreTokens()) error("The set command requires a cell name and a value."); string cellname = scanner.nextToken(); if (!model.nameIsValid(cellname)) error("Invalid cell name " + cellname); if (scanner.nextToken() != "=") error("= expected."); model.setCellFromScanner(cellname, scanner); } static void getAction(TokenScanner& scanner, SSModel& model) { if (!scanner.hasMoreTokens()) error("The get command requires a cell name."); string cellname = scanner.nextToken(); if (!model.nameIsValid(cellname)) error("Invalid cell name " + cellname); model.printCellInformation(cellname); } static const double kHaltTimeBeforeWindowClose = 3000; static void quitAction(TokenScanner& /* scanner */, SSModel& /* model */) { cout << "Thanks for using Stanford 1-2-3. " << "Closing window in " << kHaltTimeBeforeWindowClose/1000 << " " << "seconds...." << endl; pause(kHaltTimeBeforeWindowClose); exitGraphics(); } /** * Function: setUpCommandTable * --------------------------- * Adds all commands into the table. */ static void setUpCommandTable(Map<string, cmdFnT>& table) { // store map entries using lowercase, always use lowercase to lookup table["help"] = helpAction; table["load"] = loadAction; table["save"] = saveAction; table["set"] = setAction; table["get"] = getAction; table["quit"] = quitAction; } /********************************************************************************* * DO NOT EDIT FUNCTIONS BELOW THIS COMMENT. WE WILL BE USING THEM FOR GRADING * *********************************************************************************/ /** * Function: interpretCommands * --------------------------- * The loop in this function gets a command entered by the user and uses a * command dispatch table to determine how to act on the request. One of * the more unusual aspects is its use of a try-block around the attempt * to handle the command. Many things can go wrong in processing the command * (malformed arguments, parsing problem, unable to open a file, etc) and the * underlying functions call error() to report those problems. Usually this * would quit the entire program, which in this case is not desirable. * Instead, the try-block allows the call to error() to be "caught" and * control jumps to the exception handling statement here, which prints * the message and goes back into the loop to allow the user to try again. */ static void interpretCommands(Map<string, cmdFnT>& cmdTable) { SSView view; SSModel model(kNumRowsDisplayed, kNumColsDisplayed, &view); TokenScanner scanner; scanner.ignoreWhitespace(); scanner.scanNumbers(); scanner.scanStrings(); cout << "Welcome to Stanford 1-2-3. Type \"help\" for list of commands." << endl << endl; while (true) { string command = getLine("Enter command: "); scanner.setInput(command); string cmdName = toLowerCase(trim(scanner.nextToken())); if (!cmdTable.containsKey(cmdName)) { cout << "Unrecognized command \"" + cmdName << "\". Type \"help\" for list of commands." << endl; } else { try { cmdTable[cmdName](scanner, model); } catch (ErrorException ex) { cout << "Error in " << cmdName << " command: " << ex.getMessage() << endl; } } } } int main() { Map<string, cmdFnT> cmdTable; setUpCommandTable(cmdTable); interpretCommands(cmdTable); return 0; }
[ "jinzhao.chang.bayarea@gmail.com" ]
jinzhao.chang.bayarea@gmail.com
9948741a7f680b79eaee7af3f76ae6eb44bdabbf
741dafeb834dbca0e58ca1b393cc5bf12ba0da13
/codeforce/1315/A/main.cpp
f7a5610741d051094a272ad80a77beb0a5cee4be
[]
no_license
HoangViet144/Competitive-Programming
8c3a28f97b0de8ad9f501cbae9c0767d6a4b956f
19e9472545a10379511af3cf64ad0d4c1305dd8c
refs/heads/master
2021-07-15T14:11:45.515412
2020-11-09T01:45:54
2020-11-09T01:45:54
221,480,049
0
0
null
null
null
null
UTF-8
C++
false
false
600
cpp
#include <bits/stdc++.h> #define FOR(i,a,b) for(long long i = (a); i < (b); i++) #define FORD(i,a,b) for(int i = (a); i >= (b); i--) #define REP(i,a) for(int i = 0; i < (a); i++) #define REPD(i,a) for(int i = (a)-1; i >= 0; i--) #define sz(a) (int)a.size() #define ALL(a) a.begin(),a.end() #define ii pair<int,int> #define fi first #define se second #define ll long long #define N 1e5 using namespace std; int main() { int t; cin>>t; while(t--) { int a,b,x,y; cin>>a>>b>>x>>y; cout<<max(max(max(b*x,b*(a-x-1)),y*a),a*(b-y-1))<<endl;; } return 0; }
[ "viet14042000@gmail.com" ]
viet14042000@gmail.com
04ca866ff2595395aa91b9cf3b65fea3e207c9ed
22b31d2f6c0de8f7f35a8f1a927752a493418180
/src/readWav.cpp
258a80c5e6e5c2b7fb1df9e5a932e2ac43b869a3
[]
no_license
joshtbennett/readUltrasoundAudio
b6c5c4039a5877636ac5049bcc4c4315d63e1d50
02d98c46be51f00d4833027d9cece7c2102a6a8d
refs/heads/master
2020-03-30T02:20:34.568624
2018-09-27T17:56:00
2018-09-27T17:56:00
150,627,028
0
0
null
null
null
null
UTF-8
C++
false
false
3,283
cpp
#include <iostream> #include <string.h> #include <cstdint> using namespace std; typedef struct WAV_HEADER{ uint8_t riff[4]; uint32_t chunkSize; uint8_t wave[4]; uint8_t fmt[4]; uint32_t subChunk1Size; uint16_t audioFormat; uint16_t numOfChannels; uint32_t samplesPerSecond; uint32_t bytesPerSecond; uint16_t blockAlign; uint16_t bitsPerSample; uint8_t subChunk2ID[4]; uint32_t subChunk2Size; }wav_hdr; int main(int argc, char const *argv[]){ wav_hdr wavHeader; int headerSize = sizeof(wav_hdr), filelength = 0; char* filePath = "/home/josh/Documents/doppler.wav"; FILE *wavFile = fopen(filePath, "r"); if (wavFile == nullptr) { fprintf(stderr, "Unable to open wave file: %s\n", filePath); return 1; } //Read the header size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile); cout << "Header Read " << bytesRead << " bytes." << endl; if (bytesRead > 0) { //Read the data uint16_t bytesPerSample = wavHeader.bitsPerSample / 8; //Number of bytes per sample uint64_t numSamples = wavHeader.chunkSize / bytesPerSample; //How many samples are in the wav file? static const uint16_t BUFFER_SIZE = 4096; int8_t* buffer = new int8_t[BUFFER_SIZE]; while ((bytesRead = fread(buffer, sizeof buffer[0], BUFFER_SIZE / (sizeof buffer[0]), wavFile)) > 0) { /** DO SOMETHING WITH THE WAVE DATA HERE **/ cout << "Read " << bytesRead << " bytes." << endl; } delete [] buffer; buffer = nullptr; // filelength = getFileSize(wavFile); cout << "File is :" << filelength << " bytes." << endl; cout << "RIFF header :" << wavHeader.riff[0] << wavHeader.riff[1] << wavHeader.riff[2] << wavHeader.riff[3] << endl; cout << "WAVE header :" << wavHeader.wave[0] << wavHeader.wave[1] << wavHeader.wave[2] << wavHeader.wave[3] << endl; cout << "FMT :" << wavHeader.fmt[0] << wavHeader.fmt[1] << wavHeader.fmt[2] << wavHeader.fmt[3] << endl; cout << "Data size :" << wavHeader.chunkSize << endl; // Display the sampling Rate from the header cout << "Sampling Rate :" << wavHeader.samplesPerSecond << endl; cout << "Number of bits used :" << wavHeader.bitsPerSample << endl; cout << "Number of channels :" << wavHeader.numOfChannels << endl; cout << "Number of bytes per second :" << wavHeader.bytesPerSecond << endl; cout << "Data length :" << wavHeader.subChunk2Size << endl; cout << "Audio Format :" << wavHeader.audioFormat << endl; // Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM cout << "Block align :" << wavHeader.blockAlign << endl; cout << "Data string :" << wavHeader.subChunk2ID[0] << wavHeader.subChunk2ID[1] << wavHeader.subChunk2ID[2] << wavHeader.subChunk2ID[3] << endl; } fclose(wavFile); return 0; }
[ "josh.bennett@mun.ca" ]
josh.bennett@mun.ca
28c109835d81ac1f4d59306bfd634570d158cff8
af22d67edb7fc51c23c0c37cc33224302d9c7fe9
/cplusplus/output.cpp
7752965f808a4d7501fb910ea17e683ed2c1a7a0
[]
no_license
2011211242/test
a573b1a26481b1fddb67b3442efae9040cda24a8
2020f83e6c76edec50de5ed828e7f3e05b925d0b
refs/heads/master
2021-01-23T02:40:39.026087
2017-09-27T07:24:55
2017-09-27T07:24:55
86,017,882
0
0
null
null
null
null
UTF-8
C++
false
false
85
cpp
#include <cstdio> using namespace std; int main() { printf("%08x\n", 0x1000); }
[ "2990936748@qq.com" ]
2990936748@qq.com
2f2a9d7f8921c8208f2c8a5bd7600754daca0d94
9b0598175c6d6605ca1a8d5eaea829bf5d9f9c2f
/cpp/leetcode495.提莫攻击.cpp
f1272f56d76bdc30148a601649c34bc863014470
[]
no_license
xx502003587/LeetcodeExam
7de49193452c7156ef814a4a5a1bd8be011da10e
a8ec990d8970e45772efdb1eb8e927df7b025fd8
refs/heads/master
2021-07-21T19:17:17.767374
2021-07-18T14:35:01
2021-07-18T14:35:01
198,946,581
0
0
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
/* * 题意: * 在《英雄联盟》的世界中,有一个叫 “提莫” 的英雄,他的攻击可以让敌方英雄艾希进入中毒状态。 * 现在,给出提莫对艾希的攻击时间序列和提莫攻击的中毒持续时间,你需要输出艾希的中毒状态总时长。 * 你可以认为提莫在给定的时间点进行攻击,并立即使艾希处于中毒状态。 * * 思路: * 如果从 timeSeries[i] 开始攻击,加上持续时间 duration 后,还没达到 timeSeries[i+1] 的时间点 * 说明本次中毒的持续时间是满的 * * 如果从 timeSeries[i] 开始攻击,加上持续时间 duration 后,已经超过了 timeSeries[i+1] 的时间点 * 说明本次中毒的持续时间只从 timeSeries[i] 持续到 timeSeries[i+1] ,而 timeSeries[i+1] 重新攻击后,将刷新持续时间 * * 所以分这两种情况来进行累加求和即可 */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int findPoisonedDuration(vector<int>& timeSeries, int duration) { if (timeSeries.empty()) { return 0; } int res = 0; int len = timeSeries.size(); for (int i = 0; i < len - 1; ++i) { // 加上持续时间后没到达下一次攻击的时间,直接加上持续时间 if (timeSeries[i] + duration < timeSeries[i+1]) { res += duration; } // 超过了下一次攻击的时间点,直接加上时间差 else { res += timeSeries[i+1] - timeSeries[i]; } } return res + duration; } int main() { vector<int> timeSeries = {1,4}; int duration = 2; auto ret = findPoisonedDuration(timeSeries, duration); // 4 cout << ret; return 0; }
[ "1701210908@pku.edu.cn" ]
1701210908@pku.edu.cn
7096c3d1e3de8dfa762696222e03892c0d2ecb08
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/ui/views/examples/table_example.cc
f3bd42624c9ede8c5ce0fcbb25db85f1ea066c8d
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
5,739
cc
// 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. #include "ui/views/examples/table_example.h" #include <vector> #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/layout/grid_layout.h" using base::ASCIIToUTF16; namespace views { namespace examples { namespace { ui::TableColumn TestTableColumn(int id, const std::string& title) { ui::TableColumn column; column.id = id; column.title = ASCIIToUTF16(title.c_str()); column.sortable = true; return column; } } // namespace TableExample::TableExample() : ExampleBase("Table") , table_(NULL) { } TableExample::~TableExample() { // Delete the view before the model. delete table_; table_ = NULL; } void TableExample::CreateExampleView(View* container) { column1_visible_checkbox_ = new Checkbox( ASCIIToUTF16("Fruit column visible")); column1_visible_checkbox_->SetChecked(true); column1_visible_checkbox_->set_listener(this); column2_visible_checkbox_ = new Checkbox( ASCIIToUTF16("Color column visible")); column2_visible_checkbox_->SetChecked(true); column2_visible_checkbox_->set_listener(this); column3_visible_checkbox_ = new Checkbox( ASCIIToUTF16("Origin column visible")); column3_visible_checkbox_->SetChecked(true); column3_visible_checkbox_->set_listener(this); column4_visible_checkbox_ = new Checkbox( ASCIIToUTF16("Price column visible")); column4_visible_checkbox_->SetChecked(true); column4_visible_checkbox_->set_listener(this); GridLayout* layout = GridLayout::CreateAndInstall(container); std::vector<ui::TableColumn> columns; columns.push_back(TestTableColumn(0, "Fruit")); columns[0].percent = 1; columns.push_back(TestTableColumn(1, "Color")); columns.push_back(TestTableColumn(2, "Origin")); columns.push_back(TestTableColumn(3, "Price")); columns.back().alignment = ui::TableColumn::RIGHT; table_ = new TableView(this, columns, ICON_AND_TEXT, true); table_->SetGrouper(this); table_->set_observer(this); icon1_.allocN32Pixels(16, 16); SkCanvas canvas1(icon1_); canvas1.drawColor(SK_ColorRED); icon2_.allocN32Pixels(16, 16); SkCanvas canvas2(icon2_); canvas2.drawColor(SK_ColorBLUE); ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(1 /* expand */, 0); layout->AddView(table_->CreateParentIfNecessary()); column_set = layout->AddColumnSet(1); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0.5f, GridLayout::USE_PREF, 0, 0); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0.5f, GridLayout::USE_PREF, 0, 0); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0.5f, GridLayout::USE_PREF, 0, 0); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0.5f, GridLayout::USE_PREF, 0, 0); layout->StartRow(0 /* no expand */, 1); layout->AddView(column1_visible_checkbox_); layout->AddView(column2_visible_checkbox_); layout->AddView(column3_visible_checkbox_); layout->AddView(column4_visible_checkbox_); } int TableExample::RowCount() { return 10; } base::string16 TableExample::GetText(int row, int column_id) { if (row == -1) return base::string16(); const char* const cells[5][4] = { { "Orange", "Orange", "South america", "$5" }, { "Apple", "Green", "Canada", "$3" }, { "Blue berries", "Blue", "Mexico", "$10.3" }, { "Strawberries", "Red", "California", "$7" }, { "Cantaloupe", "Orange", "South america", "$5" }, }; return ASCIIToUTF16(cells[row % 5][column_id]); } gfx::ImageSkia TableExample::GetIcon(int row) { SkBitmap row_icon = row % 2 ? icon1_ : icon2_; return gfx::ImageSkia::CreateFrom1xBitmap(row_icon); } void TableExample::SetObserver(ui::TableModelObserver* observer) {} void TableExample::GetGroupRange(int model_index, GroupRange* range) { if (model_index < 2) { range->start = 0; range->length = 2; } else if (model_index > 6) { range->start = 7; range->length = 3; } else { range->start = model_index; range->length = 1; } } void TableExample::OnSelectionChanged() { PrintStatus("Selected: %s", base::UTF16ToASCII(GetText(table_->selection_model().active(), 0)).c_str()); } void TableExample::OnDoubleClick() { PrintStatus("Double Click: %s", base::UTF16ToASCII(GetText(table_->selection_model().active(), 0)).c_str()); } void TableExample::OnMiddleClick() {} void TableExample::OnKeyDown(ui::KeyboardCode virtual_keycode) {} void TableExample::ButtonPressed(Button* sender, const ui::Event& event) { int index = 0; bool show = true; if (sender == column1_visible_checkbox_) { index = 0; show = column1_visible_checkbox_->checked(); } else if (sender == column2_visible_checkbox_) { index = 1; show = column2_visible_checkbox_->checked(); } else if (sender == column3_visible_checkbox_) { index = 2; show = column3_visible_checkbox_->checked(); } else if (sender == column4_visible_checkbox_) { index = 3; show = column4_visible_checkbox_->checked(); } table_->SetColumnVisibility(index, show); } } // namespace examples } // namespace views
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
a5dd00915723b80ac920e74e079cd59e5e79cdfe
1212ca9c78bc4eb4f4f5c5ed3b15d109619b0d7a
/ash/multi_device_setup/multi_device_notification_presenter_unittest.cc
65bf5b6c9fb82ab798afcd66e39894ae5d860bd0
[ "BSD-3-Clause" ]
permissive
lierba64/chromium
de6cb1b18e920f32abe09ddad0228676f69c06ad
740df9ada67ff550a3c6dd51aed4d29fe3aea31f
refs/heads/master
2023-03-13T00:55:11.562148
2018-10-10T16:30:54
2018-10-10T16:30:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,815
cc
// Copyright 2018 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 "ash/multi_device_setup/multi_device_notification_presenter.h" #include <map> #include <memory> #include <utility> #include "ash/session/test_session_controller_client.h" #include "ash/strings/grit/ash_strings.h" #include "ash/test/ash_test_base.h" #include "ash/test/ash_test_helper.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup.h" #include "chromeos/services/multidevice_setup/public/mojom/constants.mojom.h" #include "chromeos/services/multidevice_setup/public/mojom/multidevice_setup.mojom.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/mojom/connector.mojom.h" #include "ui/base/l10n/l10n_util.h" #include "ui/message_center/fake_message_center.h" #include "ui/message_center/message_center.h" namespace ash { namespace { const char kTestUserEmail[] = "test@example.com"; const char kTestHostDeviceName[] = "Test Device"; // Note: Must be formatted as a GUID. const char kTestServiceUserId[] = "01234567-89ab-cdef-0123-456789abcdef"; class TestMessageCenter : public message_center::FakeMessageCenter { public: TestMessageCenter() = default; ~TestMessageCenter() override = default; // message_center::FakeMessageCenter: void AddNotification( std::unique_ptr<message_center::Notification> notification) override { EXPECT_FALSE(notification_); notification_ = std::move(notification); } void UpdateNotification( const std::string& id, std::unique_ptr<message_center::Notification> new_notification) override { EXPECT_TRUE(notification_); EXPECT_EQ(notification_->id(), id); EXPECT_EQ(new_notification->id(), id); notification_ = std::move(new_notification); } void RemoveNotification(const std::string& id, bool by_user) override { EXPECT_TRUE(notification_); EXPECT_EQ(notification_->id(), id); notification_.reset(); } message_center::Notification* FindVisibleNotificationById( const std::string& id) override { if (notification_) { EXPECT_EQ(notification_->id(), id); return notification_.get(); } return nullptr; } void ClickOnNotification(const std::string& id) override { EXPECT_TRUE(notification_); EXPECT_EQ(id, notification_->id()); notification_->delegate()->Click(base::nullopt, base::nullopt); } private: std::unique_ptr<message_center::Notification> notification_; DISALLOW_COPY_AND_ASSIGN(TestMessageCenter); }; } // namespace class MultiDeviceNotificationPresenterTest : public NoSessionAshTestBase { public: class TestOpenUiDelegate : public MultiDeviceNotificationPresenter::OpenUiDelegate { public: TestOpenUiDelegate() = default; ~TestOpenUiDelegate() override = default; int open_multi_device_setup_ui_count() const { return open_multi_device_setup_ui_count_; } int open_connected_devices_settings_count() const { return open_connected_devices_settings_count_; } // MultiDeviceNotificationPresenter::OpenUiDelegate: void OpenMultiDeviceSetupUi() override { ++open_multi_device_setup_ui_count_; } void OpenConnectedDevicesSettings() override { ++open_connected_devices_settings_count_; } private: int open_multi_device_setup_ui_count_ = 0; int open_connected_devices_settings_count_ = 0; }; protected: MultiDeviceNotificationPresenterTest() = default; void SetUp() override { NoSessionAshTestBase::SetUp(); std::unique_ptr<TestOpenUiDelegate> test_open_ui_delegate = std::make_unique<TestOpenUiDelegate>(); test_open_ui_delegate_ = test_open_ui_delegate.get(); service_manager::mojom::ConnectorRequest request; connector_ = service_manager::Connector::Create(&request); fake_multidevice_setup_ = std::make_unique<chromeos::multidevice_setup::FakeMultiDeviceSetup>(); service_manager::Connector::TestApi test_api(connector_.get()); test_api.OverrideBinderForTesting( service_manager::Identity( chromeos::multidevice_setup::mojom::kServiceName, kTestServiceUserId), chromeos::multidevice_setup::mojom::MultiDeviceSetup::Name_, base::BindRepeating( &chromeos::multidevice_setup::FakeMultiDeviceSetup::BindHandle, base::Unretained(fake_multidevice_setup_.get()))); notification_presenter_ = std::make_unique<MultiDeviceNotificationPresenter>( &test_message_center_, connector_.get()); notification_presenter_->open_ui_delegate_ = std::move(test_open_ui_delegate); } void TearDown() override { notification_presenter_.reset(); NoSessionAshTestBase::TearDown(); } void InvokePendingMojoCalls() { notification_presenter_->FlushForTesting(); } void SignIntoAccount() { TestSessionControllerClient* test_session_client = GetSessionControllerClient(); test_session_client->AddUserSession( kTestUserEmail, user_manager::USER_TYPE_REGULAR, true /* enable_settings */, true /* provide_pref_service */, false /* is_new_profile */, kTestServiceUserId); test_session_client->SetSessionState(session_manager::SessionState::ACTIVE); test_session_client->SwitchActiveUser( AccountId::FromUserEmail(kTestUserEmail)); InvokePendingMojoCalls(); EXPECT_TRUE(fake_multidevice_setup_->delegate().is_bound()); } void ShowNewUserNotification() { EXPECT_TRUE(fake_multidevice_setup_->delegate().is_bound()); fake_multidevice_setup_->delegate()->OnPotentialHostExistsForNewUser(); InvokePendingMojoCalls(); } void ShowExistingUserHostSwitchedNotification() { EXPECT_TRUE(fake_multidevice_setup_->delegate().is_bound()); fake_multidevice_setup_->delegate()->OnConnectedHostSwitchedForExistingUser( kTestHostDeviceName); InvokePendingMojoCalls(); } void ShowExistingUserNewChromebookNotification() { EXPECT_TRUE(fake_multidevice_setup_->delegate().is_bound()); fake_multidevice_setup_->delegate()->OnNewChromebookAddedForExistingUser( kTestHostDeviceName); InvokePendingMojoCalls(); } void ClickNotification() { test_message_center_.ClickOnNotification( MultiDeviceNotificationPresenter::kNotificationId); } void VerifyNewUserPotentialHostExistsNotificationIsVisible() { VerifyNotificationIsVisible( MultiDeviceNotificationPresenter::Status::kNewUserNotificationVisible); } void VerifyExistingUserHostSwitchedNotificationIsVisible() { VerifyNotificationIsVisible( MultiDeviceNotificationPresenter::Status:: kExistingUserHostSwitchedNotificationVisible); } void VerifyExistingUserNewChromebookAddedNotificationIsVisible() { VerifyNotificationIsVisible( MultiDeviceNotificationPresenter::Status:: kExistingUserNewChromebookNotificationVisible); } void VerifyNoNotificationIsVisible() { EXPECT_FALSE(test_message_center_.FindVisibleNotificationById( MultiDeviceNotificationPresenter::kNotificationId)); } void AssertPotentialHostBucketCount(std::string histogram, int count) { if (histogram_tester_.GetAllSamples(histogram).empty()) { EXPECT_EQ(count, 0); return; } histogram_tester_.ExpectBucketCount( histogram, MultiDeviceNotificationPresenter:: kNotificationTypeNewUserPotentialHostExists, count); } void AssertHostSwitchedBucketCount(std::string histogram, int count) { if (histogram_tester_.GetAllSamples(histogram).empty()) { EXPECT_EQ(count, 0); return; } histogram_tester_.ExpectBucketCount( histogram, MultiDeviceNotificationPresenter:: kNotificationTypeExistingUserHostSwitched, count); } void AssertNewChromebookBucketCount(std::string histogram, int count) { if (histogram_tester_.GetAllSamples(histogram).empty()) { EXPECT_EQ(count, 0); return; } histogram_tester_.ExpectBucketCount( histogram, MultiDeviceNotificationPresenter:: kNotificationTypeExistingUserNewChromebookAdded, count); } base::HistogramTester histogram_tester_; TestOpenUiDelegate* test_open_ui_delegate_; TestMessageCenter test_message_center_; std::unique_ptr<service_manager::Connector> connector_; std::unique_ptr<chromeos::multidevice_setup::FakeMultiDeviceSetup> fake_multidevice_setup_; std::unique_ptr<MultiDeviceNotificationPresenter> notification_presenter_; private: void VerifyNotificationIsVisible( MultiDeviceNotificationPresenter::Status notification_status) { const message_center::Notification* kVisibleNotification = test_message_center_.FindVisibleNotificationById( MultiDeviceNotificationPresenter::kNotificationId); base::string16 title; base::string16 message; switch (notification_status) { case MultiDeviceNotificationPresenter::Status:: kNewUserNotificationVisible: title = l10n_util::GetStringUTF16( IDS_ASH_MULTI_DEVICE_SETUP_NEW_USER_POTENTIAL_HOST_EXISTS_TITLE); message = l10n_util::GetStringUTF16( IDS_ASH_MULTI_DEVICE_SETUP_NEW_USER_POTENTIAL_HOST_EXISTS_MESSAGE); break; case MultiDeviceNotificationPresenter::Status:: kExistingUserHostSwitchedNotificationVisible: title = l10n_util::GetStringFUTF16( IDS_ASH_MULTI_DEVICE_SETUP_EXISTING_USER_HOST_SWITCHED_TITLE, base::ASCIIToUTF16(kTestHostDeviceName)); message = l10n_util::GetStringUTF16( IDS_ASH_MULTI_DEVICE_SETUP_EXISTING_USER_HOST_SWITCHED_MESSAGE); break; case MultiDeviceNotificationPresenter::Status:: kExistingUserNewChromebookNotificationVisible: title = l10n_util::GetStringFUTF16( IDS_ASH_MULTI_DEVICE_SETUP_EXISTING_USER_NEW_CHROMEBOOK_ADDED_TITLE, base::ASCIIToUTF16(kTestHostDeviceName)); message = l10n_util::GetStringUTF16( IDS_ASH_MULTI_DEVICE_SETUP_EXISTING_USER_NEW_CHROMEBOOK_ADDED_MESSAGE); break; case MultiDeviceNotificationPresenter::Status::kNoNotificationVisible: NOTREACHED(); } EXPECT_EQ(title, kVisibleNotification->title()); EXPECT_EQ(message, kVisibleNotification->message()); } DISALLOW_COPY_AND_ASSIGN(MultiDeviceNotificationPresenterTest); }; TEST_F(MultiDeviceNotificationPresenterTest, NotSignedIntoAccount) { static const session_manager::SessionState kNonActiveStates[] = { session_manager::SessionState::UNKNOWN, session_manager::SessionState::OOBE, session_manager::SessionState::LOGIN_PRIMARY, session_manager::SessionState::LOGGED_IN_NOT_ACTIVE, session_manager::SessionState::LOCKED, session_manager::SessionState::LOGIN_SECONDARY}; // For each of the states which is not ACTIVE, set the session state. None of // these should trigger a SetAccountStatusChangeDelegate() call. for (const auto state : kNonActiveStates) { GetSessionControllerClient()->SetSessionState(state); InvokePendingMojoCalls(); EXPECT_FALSE(fake_multidevice_setup_->delegate().is_bound()); } SignIntoAccount(); EXPECT_TRUE(fake_multidevice_setup_->delegate().is_bound()); } TEST_F(MultiDeviceNotificationPresenterTest, TestHostNewUserPotentialHostExistsNotification_RemoveProgrammatically) { SignIntoAccount(); ShowNewUserNotification(); VerifyNewUserPotentialHostExistsNotificationIsVisible(); notification_presenter_->RemoveMultiDeviceSetupNotification(); VerifyNoNotificationIsVisible(); EXPECT_EQ(test_open_ui_delegate_->open_multi_device_setup_ui_count(), 0); AssertPotentialHostBucketCount("MultiDeviceSetup_NotificationClicked", 0); AssertPotentialHostBucketCount("MultiDeviceSetup_NotificationShown", 1); } TEST_F(MultiDeviceNotificationPresenterTest, TestHostNewUserPotentialHostExistsNotification_TapNotification) { SignIntoAccount(); ShowNewUserNotification(); VerifyNewUserPotentialHostExistsNotificationIsVisible(); ClickNotification(); VerifyNoNotificationIsVisible(); EXPECT_EQ(test_open_ui_delegate_->open_multi_device_setup_ui_count(), 1); AssertPotentialHostBucketCount("MultiDeviceSetup_NotificationClicked", 1); AssertPotentialHostBucketCount("MultiDeviceSetup_NotificationShown", 1); } TEST_F(MultiDeviceNotificationPresenterTest, TestHostExistingUserHostSwitchedNotification_RemoveProgrammatically) { SignIntoAccount(); ShowExistingUserHostSwitchedNotification(); VerifyExistingUserHostSwitchedNotificationIsVisible(); notification_presenter_->RemoveMultiDeviceSetupNotification(); VerifyNoNotificationIsVisible(); EXPECT_EQ(test_open_ui_delegate_->open_connected_devices_settings_count(), 0); AssertHostSwitchedBucketCount("MultiDeviceSetup_NotificationClicked", 0); AssertHostSwitchedBucketCount("MultiDeviceSetup_NotificationShown", 1); } TEST_F(MultiDeviceNotificationPresenterTest, TestHostExistingUserHostSwitchedNotification_TapNotification) { SignIntoAccount(); ShowExistingUserHostSwitchedNotification(); VerifyExistingUserHostSwitchedNotificationIsVisible(); ClickNotification(); VerifyNoNotificationIsVisible(); EXPECT_EQ(test_open_ui_delegate_->open_connected_devices_settings_count(), 1); AssertHostSwitchedBucketCount("MultiDeviceSetup_NotificationClicked", 1); AssertHostSwitchedBucketCount("MultiDeviceSetup_NotificationShown", 1); } TEST_F( MultiDeviceNotificationPresenterTest, TestHostExistingUserNewChromebookAddedNotification_RemoveProgrammatically) { SignIntoAccount(); ShowExistingUserNewChromebookNotification(); VerifyExistingUserNewChromebookAddedNotificationIsVisible(); notification_presenter_->RemoveMultiDeviceSetupNotification(); VerifyNoNotificationIsVisible(); EXPECT_EQ(test_open_ui_delegate_->open_connected_devices_settings_count(), 0); AssertNewChromebookBucketCount("MultiDeviceSetup_NotificationClicked", 0); AssertNewChromebookBucketCount("MultiDeviceSetup_NotificationShown", 1); } TEST_F(MultiDeviceNotificationPresenterTest, TestHostExistingUserNewChromebookAddedNotification_TapNotification) { SignIntoAccount(); ShowExistingUserNewChromebookNotification(); VerifyExistingUserNewChromebookAddedNotificationIsVisible(); ClickNotification(); VerifyNoNotificationIsVisible(); EXPECT_EQ(test_open_ui_delegate_->open_connected_devices_settings_count(), 1); AssertNewChromebookBucketCount("MultiDeviceSetup_NotificationClicked", 1); AssertNewChromebookBucketCount("MultiDeviceSetup_NotificationShown", 1); } TEST_F(MultiDeviceNotificationPresenterTest, NotificationsReplaceOneAnother) { SignIntoAccount(); ShowNewUserNotification(); VerifyNewUserPotentialHostExistsNotificationIsVisible(); ShowExistingUserHostSwitchedNotification(); VerifyExistingUserHostSwitchedNotificationIsVisible(); ShowExistingUserNewChromebookNotification(); VerifyExistingUserNewChromebookAddedNotificationIsVisible(); ClickNotification(); VerifyNoNotificationIsVisible(); AssertPotentialHostBucketCount("MultiDeviceSetup_NotificationShown", 1); AssertHostSwitchedBucketCount("MultiDeviceSetup_NotificationShown", 1); AssertNewChromebookBucketCount("MultiDeviceSetup_NotificationShown", 1); } TEST_F(MultiDeviceNotificationPresenterTest, NotificationsReplaceThemselves) { SignIntoAccount(); ShowNewUserNotification(); VerifyNewUserPotentialHostExistsNotificationIsVisible(); ShowNewUserNotification(); VerifyNewUserPotentialHostExistsNotificationIsVisible(); notification_presenter_->RemoveMultiDeviceSetupNotification(); ShowExistingUserHostSwitchedNotification(); VerifyExistingUserHostSwitchedNotificationIsVisible(); ShowExistingUserHostSwitchedNotification(); VerifyExistingUserHostSwitchedNotificationIsVisible(); notification_presenter_->RemoveMultiDeviceSetupNotification(); ShowExistingUserNewChromebookNotification(); VerifyExistingUserNewChromebookAddedNotificationIsVisible(); ShowExistingUserNewChromebookNotification(); VerifyExistingUserNewChromebookAddedNotificationIsVisible(); notification_presenter_->RemoveMultiDeviceSetupNotification(); AssertPotentialHostBucketCount("MultiDeviceSetup_NotificationShown", 2); AssertHostSwitchedBucketCount("MultiDeviceSetup_NotificationShown", 2); AssertNewChromebookBucketCount("MultiDeviceSetup_NotificationShown", 2); } } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
91495dd4afdd3522e9476f6d6d793408b5a24338
3655b609205de8feb1ad0936943a538b81992681
/CSC8503 Framework/Game Technologies/GameTechNew/SphereCollisionShape.h
634b2a4d4c1539fbacc2a86cdcbec6b3b15004d0
[]
no_license
shaunno94/MCompTeamProject_2016
607237d136f6179fc7c048b912e3689050181796
c45d37e6cd736f4275ed56132333426cd0e0dbd9
refs/heads/master
2021-03-16T06:54:18.574410
2016-03-11T10:43:27
2016-03-11T10:43:27
50,836,215
1
0
null
null
null
null
UTF-8
C++
false
false
861
h
#pragma once #include "CollisionShape.h" class SphereCollisionShape : public CollisionShape { public: SphereCollisionShape(); SphereCollisionShape(float radius); ~SphereCollisionShape(); virtual Matrix3 BuildInverseInertia(float invMass) override; virtual void GetLocalCollisionAxes(PhysicsObject* currentObject, PhysicsObject* collidingObject, std::vector<Vector3>* out_axes) override; virtual void GetMinMaxVertexOnAxis(PhysicsObject* currentObject, const Vector3& axis, Vector3* out_min, Vector3* out_max) override; virtual void GetIncidentReferencePolygon(PhysicsObject* currentObject, const Vector3& axis, std::list<Vector3>* out_face, Vector3* out_normal, std::vector<Plane>* out_adjacent_planes) override; void SetRadius(float radius) { m_Radius = radius; } float GetRadius() { return m_Radius; } protected: float m_Radius; };
[ "julius.narvilas@gmail.com" ]
julius.narvilas@gmail.com
28791b9aa662c361bb8114d1007d48701da28549
14344ea4c081bbfb9639cc33dcf843b9134b7d5b
/mindspore/lite/c_ops/embedding_lookup_sparse.h
cf10c2d5559a3f0097268ffd01196d734eebf6e2
[ "Apache-2.0", "Libpng", "LGPL-2.1-only", "MIT", "IJG", "Zlib", "BSD-3-Clause-Open-MPI", "AGPL-3.0-only", "MPL-2.0-no-copyleft-exception", "MPL-1.0", "MPL-1.1", "MPL-2.0", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Unlicense", "LicenseRef-scancode-proprietary-lice...
permissive
Joejiong/mindspore
d06318e456c000f6368dbe648daa39d82ba6a2da
083fd6565cab1aa1d3114feeacccf1cba0d55e80
refs/heads/master
2022-12-05T07:17:28.737741
2020-08-18T07:51:33
2020-08-18T07:51:33
288,415,456
0
0
Apache-2.0
2020-08-18T09:43:35
2020-08-18T09:43:34
null
UTF-8
C++
false
false
1,633
h
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * 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 <vector> #include <set> #include <cmath> #include "ir/dtype/type_id.h" #include "mindspore/lite/c_ops/primitive_c.h" #ifdef PRIMITIVE_WRITEABLE #include "schema/inner/model_generated.h" #else #include "schema/model_generated.h" #endif #ifndef LITE_MINDSPORE_LITE_C_OPS_EMBEDDING_LOOKUP_SPARSE_H_ #define LITE_MINDSPORE_LITE_C_OPS_EMBEDDING_LOOKUP_SPARSE_H_ namespace mindspore { class EmbeddingLookupSparse : public PrimitiveC { public: #ifdef PRIMITIVE_WRITEABLE explicit EmbeddingLookupSparse(schema::PrimitiveT *primitive) : PrimitiveC(primitive) {} #else explicit EmbeddingLookupSparse(schema::Primitive *primitive) : PrimitiveC(primitive) {} #endif std::vector<int> GetSpIds() const; std::vector<float> GetSpWeights() const; float GetMaxNortm() const; void SetSpIds(const std::vector<int> &sp_ids); void SetSpWeights(const std::vector<float> &sp_weights); void SetMaxNortm(float max_nortm); }; } // namespace mindspore #endif // LITE_MINDSPORE_LITE_C_OPS_EMBEDDING_LOOKUP_SPARSE_H_
[ "yeyunpeng1@huawei.com" ]
yeyunpeng1@huawei.com
3fe63e6cdf99f9cafc370187984dca14bb03c183
0de3385199ae63184d7bb627f714dd749def2c2b
/[Algo 7] Binomial Heap/[Algo 7] Binomial Heap/stdafx.cpp
70dcf7ce0ee27adb896cd3cbdb24cbb4009133a0
[]
no_license
DharaHarsora/BinomialHeap
623b283fe83d84a28ca9f8189560719ab35fa76e
4c3d2342bc7d4f2f6a55d279dbbd51d595a24644
refs/heads/master
2021-12-14T21:52:57.661426
2017-06-08T18:33:19
2017-06-08T18:33:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
// stdafx.cpp : source file that includes just the standard includes // [Algo 7] Binomial Heap.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "wiblz123@gmail.com" ]
wiblz123@gmail.com
7d31aedb3c9152e0a9f0172c206986ef678abf26
34e89117d314c8d2b9c0d7ba633089b775b46c20
/src/Caribou/Topology/test/Grid/Grid_3D.h
fe22e127adc65b289db16f89e05cc27a1dd5af63
[]
no_license
hugtalbot/caribou
abd2c71e014ff368044f42ae26156c74f51810ae
c2a40b51238f1688404c2382bdce0bd1785efcf4
refs/heads/master
2022-07-14T02:50:20.589179
2020-03-24T15:17:14
2020-03-24T15:17:14
251,669,693
2
0
null
2022-06-29T13:16:39
2020-03-31T16:50:40
null
UTF-8
C++
false
false
14,719
h
#ifndef CARIBOU_TOPOLOGY_TEST_GRID_3D_H #define CARIBOU_TOPOLOGY_TEST_GRID_3D_H #include <Caribou/Geometry/Hexahedron.h> #include <vector> #include <chrono> #define BEGIN_CLOCK ;std::chrono::steady_clock::time_point __time_point_begin; #define TICK ;__time_point_begin = std::chrono::steady_clock::now(); #define TOCK (std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - __time_point_begin).count()) TEST(Topology_Grid_3D, Grid3D) { using namespace caribou::topology; using Grid = Grid<3>; using WorldCoordinates = Grid::WorldCoordinates; using Subdivisions = Grid::Subdivisions; using Dimensions = Grid::Dimensions; using GridCoordinates = Grid::GridCoordinates; using CellIndex = Grid::CellIndex; using Hexa = caribou::geometry::Hexahedron<caribou::geometry::interpolation::Hexahedron8>; Grid grid(WorldCoordinates{0.25, 0.5, 0.75}, Subdivisions{2, 2, 2}, Dimensions{100, 100, 100}); // General properties EXPECT_EQ(grid.number_of_nodes(), (unsigned) 27); // Cell numbering test EXPECT_EQ((CellIndex) 5, grid.cell_index_at(GridCoordinates(1, 0, 1))); EXPECT_EQ(GridCoordinates(1, 0, 1), grid.cell_coordinates_at((CellIndex) 5)); // Cell positioning EXPECT_FALSE(grid.contains(WorldCoordinates{0.24, 0.50, 0.75})); EXPECT_FALSE(grid.contains(WorldCoordinates{0.25, 0.49, 0.75})); EXPECT_FALSE(grid.contains(WorldCoordinates{0.25, 0.50, 0.74})); EXPECT_TRUE (grid.contains(WorldCoordinates{0.25, 0.50, 0.75})); EXPECT_TRUE (grid.contains(WorldCoordinates{50, 50, 50})); EXPECT_TRUE (grid.contains(WorldCoordinates{100.25, 100.50, 100.75})); EXPECT_FALSE(grid.contains(WorldCoordinates{100.26, 100.50, 100.75})); EXPECT_FALSE(grid.contains(WorldCoordinates{100.25, 100.51, 100.75})); EXPECT_FALSE(grid.contains(WorldCoordinates{100.25, 100.50, 100.76})); // Cells queries EXPECT_TRUE(list_are_equals({0, 2, 4, 6}, grid.cells_enclosing( WorldCoordinates({-50, 50, 50}), WorldCoordinates({25, 25, 25}), WorldCoordinates({25, 75, 75}) ))); EXPECT_TRUE(list_are_equals({0}, grid.cells_enclosing( WorldCoordinates({0.25, 0.5, 0.75}), WorldCoordinates({25, 25, 25}), WorldCoordinates({50.24, 50.49, 50.74}) ))); EXPECT_TRUE(list_are_equals({0, 1, 2, 3, 4, 5, 6, 7}, grid.cells_enclosing( WorldCoordinates({50.25, 50.5, 50.75}), WorldCoordinates({75, 75, 75}), WorldCoordinates({100.24, 100.49, 100.74}) ))); EXPECT_TRUE(list_are_equals({0, 1, 2, 3, 4, 5, 6, 7}, grid.cells_enclosing( WorldCoordinates({0.25, 0.5, 0.75}), WorldCoordinates({100.24, 100.49, 100.74}) ))); // Cells around nodes EXPECT_TRUE(list_are_equals({}, grid.cells_around(WorldCoordinates(-50, -50, -50)))); EXPECT_TRUE(list_are_equals({0}, grid.cells_around(WorldCoordinates(0.25, 0.50, 0.75)))); EXPECT_TRUE(list_are_equals({0, 1}, grid.cells_around(WorldCoordinates(50.25, 0.50, 0.75)))); EXPECT_TRUE(list_are_equals({1}, grid.cells_around(WorldCoordinates(100.25, 0.50, 0.75)))); EXPECT_TRUE(list_are_equals({0, 4, 2, 6, 1, 5, 3, 7}, grid.cells_around(WorldCoordinates(50.25, 50.50, 50.75)))); // Cells around faces EXPECT_TRUE(list_are_equals({0}, grid.cells_around(WorldCoordinates(0.25, 25.50, 25.75)))); EXPECT_TRUE(list_are_equals({0}, grid.cells_around(WorldCoordinates(25.25, 25.50, 0.75)))); EXPECT_TRUE(list_are_equals({0}, grid.cells_around(WorldCoordinates(25.25, 0.50, 25.75)))); EXPECT_TRUE(list_are_equals({0, 1}, grid.cells_around(WorldCoordinates(50.25, 25.50, 25.75)))); EXPECT_TRUE(list_are_equals({0, 2}, grid.cells_around(WorldCoordinates(25.25, 50.50, 25.75)))); EXPECT_TRUE(list_are_equals({0, 4}, grid.cells_around(WorldCoordinates(25.25, 25.50, 50.75)))); EXPECT_TRUE(list_are_equals({7}, grid.cells_around(WorldCoordinates(75.25, 100.50, 75.75)))); EXPECT_TRUE(list_are_equals({7}, grid.cells_around(WorldCoordinates(75.25, 75.50, 100.75)))); EXPECT_TRUE(list_are_equals({7}, grid.cells_around(WorldCoordinates(100.25, 75.50, 75.75)))); // Cells around edges EXPECT_TRUE(list_are_equals({0}, grid.cells_around(WorldCoordinates(25.25, 0.50, 0.75)))); EXPECT_TRUE(list_are_equals({7}, grid.cells_around(WorldCoordinates(75.25, 100.50, 100.75)))); EXPECT_TRUE(list_are_equals({0, 4, 2, 6}, grid.cells_around(WorldCoordinates(25.25, 50.50, 50.75)))); EXPECT_TRUE(list_are_equals({2, 6, 3, 7}, grid.cells_around(WorldCoordinates(50.25, 75.50, 50.75)))); EXPECT_TRUE(list_are_equals({0, 2, 1, 3}, grid.cells_around(WorldCoordinates(50.25, 50.50, 25.75)))); // Node position queries EXPECT_NODE_EQ(grid.node(0), WorldCoordinates({0.25, 0.5, 0.75})); EXPECT_NODE_EQ(grid.node(2), WorldCoordinates({100.25, 0.5, 0.75})); EXPECT_NODE_EQ(grid.node(6), WorldCoordinates({0.25, 100.5, 0.75})); EXPECT_NODE_EQ(grid.node(8), WorldCoordinates({100.25, 100.5, 0.75})); EXPECT_NODE_EQ(grid.node(18), WorldCoordinates({0.25, 0.5, 100.75})); EXPECT_NODE_EQ(grid.node(20), WorldCoordinates({100.25, 0.5, 100.75})); EXPECT_NODE_EQ(grid.node(24), WorldCoordinates({0.25, 100.5, 100.75})); EXPECT_NODE_EQ(grid.node(26), WorldCoordinates({100.25, 100.5, 100.75})); // Node indexing for (Grid::NodeIndex index = 0; index < (signed) grid.number_of_nodes(); ++index) { EXPECT_EQ(index, grid.node_index_at(grid.node_coordinates_at(index))); } // Edge queries EXPECT_EQ(grid.number_of_edges(), (unsigned) 3 * 12 + 2 * 9); // First slice (2D grid) EXPECT_EQ(grid.edge(0), Grid::EdgeNodes({{0, 1}})); EXPECT_EQ(grid.edge(0), Grid::EdgeNodes({{0, 1}})); EXPECT_EQ(grid.edge(1), Grid::EdgeNodes({{1, 2}})); EXPECT_EQ(grid.edge(2), Grid::EdgeNodes({{0, 3}})); EXPECT_EQ(grid.edge(3), Grid::EdgeNodes({{1, 4}})); EXPECT_EQ(grid.edge(4), Grid::EdgeNodes({{2, 5}})); EXPECT_EQ(grid.edge(5), Grid::EdgeNodes({{3, 4}})); EXPECT_EQ(grid.edge(6), Grid::EdgeNodes({{4, 5}})); EXPECT_EQ(grid.edge(7), Grid::EdgeNodes({{3, 6}})); EXPECT_EQ(grid.edge(8), Grid::EdgeNodes({{4, 7}})); EXPECT_EQ(grid.edge(9), Grid::EdgeNodes({{5, 8}})); EXPECT_EQ(grid.edge(10), Grid::EdgeNodes({{6, 7}})); EXPECT_EQ(grid.edge(11), Grid::EdgeNodes({{7, 8}})); // Between the slice 1 and slice 2 EXPECT_EQ(grid.edge(12), Grid::EdgeNodes({{0, 9}})); EXPECT_EQ(grid.edge(13), Grid::EdgeNodes({{1, 10}})); EXPECT_EQ(grid.edge(14), Grid::EdgeNodes({{2, 11}})); EXPECT_EQ(grid.edge(15), Grid::EdgeNodes({{3, 12}})); EXPECT_EQ(grid.edge(16), Grid::EdgeNodes({{4, 13}})); EXPECT_EQ(grid.edge(17), Grid::EdgeNodes({{5, 14}})); EXPECT_EQ(grid.edge(18), Grid::EdgeNodes({{6, 15}})); EXPECT_EQ(grid.edge(19), Grid::EdgeNodes({{7, 16}})); EXPECT_EQ(grid.edge(20), Grid::EdgeNodes({{8, 17}})); // second slice (2D grid) EXPECT_EQ(grid.edge(21), Grid::EdgeNodes({{9, 10}})); EXPECT_EQ(grid.edge(22), Grid::EdgeNodes({{10, 11}})); EXPECT_EQ(grid.edge(23), Grid::EdgeNodes({{9, 12}})); EXPECT_EQ(grid.edge(24), Grid::EdgeNodes({{10, 13}})); EXPECT_EQ(grid.edge(25), Grid::EdgeNodes({{11, 14}})); EXPECT_EQ(grid.edge(26), Grid::EdgeNodes({{12, 13}})); EXPECT_EQ(grid.edge(27), Grid::EdgeNodes({{13, 14}})); EXPECT_EQ(grid.edge(28), Grid::EdgeNodes({{12, 15}})); EXPECT_EQ(grid.edge(29), Grid::EdgeNodes({{13, 16}})); EXPECT_EQ(grid.edge(30), Grid::EdgeNodes({{14, 17}})); EXPECT_EQ(grid.edge(31), Grid::EdgeNodes({{15, 16}})); EXPECT_EQ(grid.edge(32), Grid::EdgeNodes({{16, 17}})); // Between the slice 2 and slice 3 EXPECT_EQ(grid.edge(33), Grid::EdgeNodes({{9, 18}})); EXPECT_EQ(grid.edge(34), Grid::EdgeNodes({{10, 19}})); EXPECT_EQ(grid.edge(35), Grid::EdgeNodes({{11, 20}})); EXPECT_EQ(grid.edge(36), Grid::EdgeNodes({{12, 21}})); EXPECT_EQ(grid.edge(37), Grid::EdgeNodes({{13, 22}})); EXPECT_EQ(grid.edge(38), Grid::EdgeNodes({{14, 23}})); EXPECT_EQ(grid.edge(39), Grid::EdgeNodes({{15, 24}})); EXPECT_EQ(grid.edge(40), Grid::EdgeNodes({{16, 25}})); EXPECT_EQ(grid.edge(41), Grid::EdgeNodes({{17, 26}})); // third slice (2D grid) EXPECT_EQ(grid.edge(42), Grid::EdgeNodes({{18, 19}})); EXPECT_EQ(grid.edge(43), Grid::EdgeNodes({{19, 20}})); EXPECT_EQ(grid.edge(44), Grid::EdgeNodes({{18, 21}})); EXPECT_EQ(grid.edge(45), Grid::EdgeNodes({{19, 22}})); EXPECT_EQ(grid.edge(46), Grid::EdgeNodes({{20, 23}})); EXPECT_EQ(grid.edge(47), Grid::EdgeNodes({{21, 22}})); EXPECT_EQ(grid.edge(48), Grid::EdgeNodes({{22, 23}})); EXPECT_EQ(grid.edge(49), Grid::EdgeNodes({{21, 24}})); EXPECT_EQ(grid.edge(50), Grid::EdgeNodes({{22, 25}})); EXPECT_EQ(grid.edge(51), Grid::EdgeNodes({{23, 26}})); EXPECT_EQ(grid.edge(52), Grid::EdgeNodes({{24, 25}})); EXPECT_EQ(grid.edge(53), Grid::EdgeNodes({{25, 26}})); // Cell Node indices for (UNSIGNED_INTEGER_TYPE i = 0; i < grid.number_of_cells(); ++i) { const auto node_indices = grid.node_indices_of((Grid::CellIndex) i); const Hexa h( grid.node(node_indices[0]), grid.node(node_indices[1]), grid.node(node_indices[2]), grid.node(node_indices[3]), grid.node(node_indices[4]), grid.node(node_indices[5]), grid.node(node_indices[6]), grid.node(node_indices[7])); EXPECT_ELEMENTS_EQ(h, grid.cell_at((Grid::CellIndex) i)); } // Face queries EXPECT_EQ(grid.number_of_faces(), (unsigned) 36); // First slice (2D grid) EXPECT_EQ(grid.face(0), Grid::FaceNodes({{0, 1, 4, 3}})); EXPECT_EQ(grid.face(1), Grid::FaceNodes({{1, 2, 5, 4}})); EXPECT_EQ(grid.face(2), Grid::FaceNodes({{3, 4, 7, 6}})); EXPECT_EQ(grid.face(3), Grid::FaceNodes({{4, 5, 8, 7}})); // Between the slice 1 and slice 2 // - xz axis EXPECT_EQ(grid.face(4), Grid::FaceNodes({{0, 1, 10, 9}})); EXPECT_EQ(grid.face(5), Grid::FaceNodes({{1, 2, 11, 10}})); EXPECT_EQ(grid.face(6), Grid::FaceNodes({{3, 4, 13, 12}})); EXPECT_EQ(grid.face(7), Grid::FaceNodes({{4, 5, 14, 13}})); EXPECT_EQ(grid.face(8), Grid::FaceNodes({{6, 7, 16, 15}})); EXPECT_EQ(grid.face(9), Grid::FaceNodes({{7, 8, 17, 16}})); // - yz axis EXPECT_EQ(grid.face(10), Grid::FaceNodes({{0, 3, 12, 9}})); EXPECT_EQ(grid.face(11), Grid::FaceNodes({{1, 4, 13, 10}})); EXPECT_EQ(grid.face(12), Grid::FaceNodes({{2, 5, 14, 11}})); EXPECT_EQ(grid.face(13), Grid::FaceNodes({{3, 6, 15, 12}})); EXPECT_EQ(grid.face(14), Grid::FaceNodes({{4, 7, 16, 13}})); EXPECT_EQ(grid.face(15), Grid::FaceNodes({{5, 8, 17, 14}})); // Second slice (2D grid) unsigned int s = 9; // slice_corner_node_index EXPECT_EQ(grid.face(16), Grid::FaceNodes({{s + 0, s + 1, s + 4, s + 3}})); EXPECT_EQ(grid.face(17), Grid::FaceNodes({{s + 1, s + 2, s + 5, s + 4}})); EXPECT_EQ(grid.face(18), Grid::FaceNodes({{s + 3, s + 4, s + 7, s + 6}})); EXPECT_EQ(grid.face(19), Grid::FaceNodes({{s + 4, s + 5, s + 8, s + 7}})); // Between the slice 2 and slice 3 // - xz axis EXPECT_EQ(grid.face(20), Grid::FaceNodes({{s + 0, s + 1, s + 10, s + 9}})); EXPECT_EQ(grid.face(21), Grid::FaceNodes({{s + 1, s + 2, s + 11, s + 10}})); EXPECT_EQ(grid.face(22), Grid::FaceNodes({{s + 3, s + 4, s + 13, s + 12}})); EXPECT_EQ(grid.face(23), Grid::FaceNodes({{s + 4, s + 5, s + 14, s + 13}})); EXPECT_EQ(grid.face(24), Grid::FaceNodes({{s + 6, s + 7, s + 16, s + 15}})); EXPECT_EQ(grid.face(25), Grid::FaceNodes({{s + 7, s + 8, s + 17, s + 16}})); // - yz axis EXPECT_EQ(grid.face(26), Grid::FaceNodes({{s + 0, s + 3, s + 12, s + 9}})); EXPECT_EQ(grid.face(27), Grid::FaceNodes({{s + 1, s + 4, s + 13, s + 10}})); EXPECT_EQ(grid.face(28), Grid::FaceNodes({{s + 2, s + 5, s + 14, s + 11}})); EXPECT_EQ(grid.face(29), Grid::FaceNodes({{s + 3, s + 6, s + 15, s + 12}})); EXPECT_EQ(grid.face(30), Grid::FaceNodes({{s + 4, s + 7, s + 16, s + 13}})); EXPECT_EQ(grid.face(31), Grid::FaceNodes({{s + 5, s + 8, s + 17, s + 14}})); // Third slice (2D grid) s = 18; // slice_corner_node_index EXPECT_EQ(grid.face(32), Grid::FaceNodes({{s + 0, s + 1, s + 4, s + 3}})); EXPECT_EQ(grid.face(33), Grid::FaceNodes({{s + 1, s + 2, s + 5, s + 4}})); EXPECT_EQ(grid.face(34), Grid::FaceNodes({{s + 3, s + 4, s + 7, s + 6}})); EXPECT_EQ(grid.face(35), Grid::FaceNodes({{s + 4, s + 5, s + 8, s + 7}})); } TEST(Topology_Grid_3D, BenchMark) { using namespace caribou::topology; using Grid = Grid<3>; using WorldCoordinates = Grid::WorldCoordinates; using Subdivisions = Grid::Subdivisions; using Dimensions = Grid::Dimensions; BEGIN_CLOCK; Grid grid(WorldCoordinates{0, 0, 0}, Subdivisions{100, 100, 1000}, Dimensions{100, 100, 100}); std::vector<WorldCoordinates> positions(grid.number_of_nodes()); std::vector<Grid::ElementNodes> hexahedrons(grid.number_of_cells()); for (UNSIGNED_INTEGER_TYPE i = 0; i < grid.number_of_nodes(); ++i) { positions[i] = grid.node(i); } for (UNSIGNED_INTEGER_TYPE i = 0; i < grid.number_of_cells(); ++i) { hexahedrons[i] = grid.node_indices_of(i); } // Memory-bound test FLOATING_POINT_TYPE volume_1 = 0; TICK; for (UNSIGNED_INTEGER_TYPE i = 0; i < hexahedrons.size(); ++i) { const auto & node_indices = hexahedrons[i]; std::array<WorldCoordinates, 8> nodes; for (UNSIGNED_INTEGER_TYPE j = 0; j < 8; ++j) { nodes[j] = positions[node_indices[j]]; } for (UNSIGNED_INTEGER_TYPE n = 0; n < 8; ++n) { for (UNSIGNED_INTEGER_TYPE m = 0; m < 8; ++m) { volume_1 += (nodes[n] - nodes[m]).norm(); } } } std::cout <<"Memory-bound grid 3d: " << TOCK / 1000. / 1000. << " [ms]" << std::endl; // CPU-bound test FLOATING_POINT_TYPE volume_2 = 0; const auto ncells = grid.number_of_cells(); TICK; for (UNSIGNED_INTEGER_TYPE i = 0; i < ncells; ++i) { Grid::ElementNodes node_indices = grid.node_indices_of(i); std::array<WorldCoordinates, 8> nodes; for (UNSIGNED_INTEGER_TYPE j = 0; j < 8; ++j) { nodes[j] = grid.node(node_indices[j]); } for (UNSIGNED_INTEGER_TYPE n = 0; n < 8; ++n) { for (UNSIGNED_INTEGER_TYPE m = 0; m < 8; ++m) { volume_2 += (nodes[n] - nodes[m]).norm(); } } } std::cout <<"CPU-bound grid 3d: " << TOCK / 1000. / 1000. << " [ms]" << std::endl; EXPECT_EQ(volume_1, volume_2); } #endif //CARIBOU_TOPOLOGY_TEST_GRID_3D_H
[ "jnbrunet2000@gmail.com" ]
jnbrunet2000@gmail.com
667cb9c345b00d16af34743477af6c8dbfaf1d87
49022e7430be70ab6880c28b759f9c68e1e2edf8
/Common/Matrix2D.inl
1d62ff69761225410aa1c5e9f9991819b8b58096
[]
no_license
f3db43f4g443/SimpleSample11
61a634afa664676f94bf51f58c38640ee7ee1b64
e6aa0ceb34843defd0433b09f42f2de036d443d7
refs/heads/master
2022-03-10T18:21:42.698566
2022-02-18T06:42:18
2022-02-18T06:42:18
68,726,252
0
1
null
2021-04-15T18:51:36
2016-09-20T15:30:41
C++
UTF-8
C++
false
false
6,568
inl
#include "Common.h" template <typename T> FORCE_INLINE TMatrix2D<T>::TMatrix2D () { } template <typename T> FORCE_INLINE TMatrix2D<T>::TMatrix2D (const TMatrix2D& mat):m00(mat.m00), m01(mat.m01), m02(mat.m02), m10(mat.m10), m11(mat.m11), m12(mat.m12), m20(mat.m20), m21(mat.m21), m22(mat.m22) { } template <typename T> FORCE_INLINE TMatrix2D<T>::TMatrix2D ( T m00, T m01, T m02, T m10, T m11, T m12, T m20, T m21, T m22):m00(m00), m01(m01), m02(m02), m10(m10), m11(m11), m12(m12), m20(m20), m21(m21), m22(m22) { } template <typename T> FORCE_INLINE TMatrix2D<T>& TMatrix2D<T>::operator= (const TMatrix2D<T>& mat) { memcpy(this, &mat, sizeof(TMatrix2D<T>)); return *this; } template <typename T> FORCE_INLINE TMatrix2D<T> TMatrix2D<T>::operator+ (const TMatrix2D<T>& mat) const { return TMatrix<T>(m00 + mat.m00, m01 + mat.m01, m02 + mat.m02, m10 + mat.m10, m11 + mat.m11, m12 + mat.m12, m20 + mat.m20, m21 + mat.m21, m22 + mat.m22); } template <typename T> FORCE_INLINE TMatrix2D<T> TMatrix2D<T>::operator- (const TMatrix2D<T>& mat) const { return TMatrix2D<T>(m00 - mat.m00, m01 - mat.m01, m02 - mat.m02, m10 - mat.m10, m11 - mat.m11, m12 - mat.m12, m20 - mat.m20, m21 - mat.m21, m22 - mat.m22); } template <typename T> FORCE_INLINE TMatrix2D<T> TMatrix2D<T>::operator* (T scalar) const { return TMatrix2D<T>(m00 * scalar, m01 * scalar, m02 * scalar, m10 * scalar, m11 * scalar, m12 * scalar, m20 * scalar, m21 * scalar, m22 * scalar); } template <typename T> FORCE_INLINE bool TMatrix2D<T>::operator== ( const TMatrix2D& mat ) { return m00 == mat.m00 && m01 == mat.m01 && m02 == mat.m02 && m10 == mat.m10 && m11 == mat.m11 && m12 == mat.m12 && m20 == mat.m20 && m21 == mat.m21 && m22 == mat.m22; } template <typename T> FORCE_INLINE bool TMatrix2D<T>::operator!= ( const TMatrix2D& mat ) { return !( *this == mat ); } template <typename T> FORCE_INLINE TVector3<T> TMatrix2D<T>::operator* (const TVector3<T>& vec) const { return TVector3<T>(vec.Dot(TVector3<T>(m00, m01, m02)), vec.Dot(TVector3<T>(m10, m11, m12)), vec.Dot(TVector3<T>(m20, m21, m22))); } template <typename T> FORCE_INLINE TMatrix2D<T> TMatrix2D<T>::operator* (const TMatrix2D<T>& mat) const { return TMatrix2D<T>(m00 * mat.m00 + m01 * mat.m10 + m02 * mat.m20, m00 * mat.m01 + m01 * mat.m11 + m02 * mat.m21, m00 * mat.m02 + m01 * mat.m12 + m02 * mat.m22, m10 * mat.m00 + m11 * mat.m10 + m12 * mat.m20, m10 * mat.m01 + m11 * mat.m11 + m12 * mat.m21, m10 * mat.m02 + m11 * mat.m12 + m12 * mat.m22, m20 * mat.m00 + m21 * mat.m10 + m22 * mat.m20, m20 * mat.m01 + m21 * mat.m11 + m22 * mat.m21, m20 * mat.m02 + m21 * mat.m12 + m22 * mat.m22); } template <typename T> FORCE_INLINE TVector2<T> TMatrix2D<T>::MulVector2Pos(const TVector2<T>& vec) const { TVector3<T> vec3(vec.x, vec.y, 1); TVector3<T> vec3a = *this * vec3; return TVector2<T>(vec3a.x, vec3a.y); } template <typename T> FORCE_INLINE TVector2<T> TMatrix2D<T>::MulVector2Dir(const TVector2<T>& vec) const { TVector3<T> vec3(vec.x, vec.y, 0); TVector3<T> vec3a = *this * vec3; return TVector2<T>(vec3a.x, vec3a.y); } template <typename T> FORCE_INLINE TVector2<T> TMatrix2D<T>::MulTVector2PosNoScale(const TVector2<T>& vec) const { TVector2<T> vec2( vec.x - m02, vec.y - m12 ); return TVector2<T>( vec2.Dot( TVector2<T>( m00, m10 ) ), vec2.Dot( TVector2<T>( m01, m11 ) ) ); } template <typename T> FORCE_INLINE TVector2<T> TMatrix2D<T>::MulTVector2DirNoScale(const TVector2<T>& vec) const { TVector2<T> vec2( vec.x, vec.y ); return TVector2<T>( vec2.Dot( TVector2<T>( m00, m10 ) ), vec2.Dot( TVector2<T>( m01, m11 ) ) ); } template <typename T> FORCE_INLINE TVector2<T> TMatrix2D<T>::MulTVector2Pos( const TVector2<T>& vec ) const { float l2 = m00 * m00 + m10 * m10; TVector2<T> vec2( vec.x - m02, vec.y - m12 ); return TVector2<T>( vec2.Dot( TVector2<T>( m00, m10 ) ), vec2.Dot( TVector2<T>( m01, m11 ) ) ) / l2; } template <typename T> FORCE_INLINE TVector2<T> TMatrix2D<T>::MulTVector2Dir( const TVector2<T>& vec ) const { float l2 = m00 * m00 + m10 * m10; TVector2<T> vec2( vec.x, vec.y ); return TVector2<T>( vec2.Dot( TVector2<T>( m00, m10 ) ), vec2.Dot( TVector2<T>( m01, m11 ) ) ) / l2; } template <typename T> FORCE_INLINE TVector2<T> TMatrix2D<T>::GetPosition() const { return TVector2<T>(m02, m12); } template <typename T> FORCE_INLINE void TMatrix2D<T>::SetPosition( TVector2<T> pos ) { m02 = pos.x; m12 = pos.y; } template <typename T> FORCE_INLINE void TMatrix2D<T>::Identity() { *this = TMatrix2D<T>( 1, 0, 0, 0, 1, 0, 0, 0, 1 ); } template <typename T> FORCE_INLINE void TMatrix2D<T>::Transform(T x, T y, T angle, T s) { T cs = cosf(angle); T sn = sinf(angle); m00 = s * cs; m01 = s * -sn; m02 = x; m10 = s * sn; m11 = s * cs; m12 = y; m20 = 0; m21 = 0; m22 = 1.0f; } template <typename T> FORCE_INLINE void TMatrix2D<T>::Decompose( T& x, T& y, T& angle, T& s ) const { x = m02; y = m12; s = sqrt( m00 * m00 + m01 * m01 ); angle = atan2( m10, m00 ); } template <typename T> FORCE_INLINE void TMatrix2D<T>::Decompose( T& x, T& y, T& angle, T& sx, T& sy ) const { x = m02; y = m12; sx = sqrt( m00 * m00 + m01 * m01 ); sy = sqrt( m10 * m10 + m11 * m11 ); angle = atan2( -m01, m00 ); } template <typename T> FORCE_INLINE void TMatrix2D<T>::Transform(T x, T y, T angle, T sx, T sy) { T cs = cosf(angle); T sn = sinf(angle); m00 = sx * cs; m01 = sy * -sn; m02 = x; m10 = sx * sn; m11 = sy * cs; m12 = y; m20 = 0; m21 = 0; m22 = 1.0f; } template <typename T> FORCE_INLINE void TMatrix2D<T>::Translate(T x, T y) { m00 = 1; m01 = 0; m02 = x; m10 = 0; m11 = 1; m12 = y; m20 = 0; m21 = 0; m22 = 1; } template <typename T> FORCE_INLINE void TMatrix2D<T>::Rotate(T angle) { T cs = cosf(angle); T sn = sinf(angle); m00 = cs; m01 = -sn; m02 = 0; m10 = sn; m11 = cs; m12 = 0; m20 = 0; m21 = 0; m22 = 1.0f; } template <typename T> FORCE_INLINE void TMatrix2D<T>::Scale(T s) { m00 = s; m01 = 0; m02 = 0; m10 = 0; m11 = s; m12 = 0; m20 = 0; m21 = 0; m22 = 1; } template <typename T> FORCE_INLINE TMatrix2D<T> TMatrix2D<T>::Inverse() const { TMatrix2D<T> invTrans; invTrans.Translate( -m02, -m12 ); float s2 = m00 * m00 + m01 * m01; TMatrix2D<T> invRot( m00 / s2, m10 / s2, 0, m01 / s2, m11 / s2, 0, 0, 0, 1 ); return invRot * invTrans; } template <typename T> FORCE_INLINE TMatrix2D<T> TMatrix2D<T>::InverseNoScale() const { TMatrix2D<T> invTrans; invTrans.Translate( -m02, -m12 ); TMatrix2D<T> invRot( m00, m10, 0, m01, m11, 0, 0, 0, 1 ); return invRot * invTrans; }
[ "654656040@qq.com" ]
654656040@qq.com
6a3b273253d66e09967595ed1a8552ee0f238ff7
5712a01bc06416cf32fb637e10b21b34b938961c
/Leetcode/Pascal's Triangle II.cpp
3841f286b3071c3554a40acff5c5bf211cbe3704
[]
no_license
WenShihKen/uva
654a9f5f3e56935625e061795f152609899b79e5
03a3d603941dd9b9ec13e76fb99d24da6749a81b
refs/heads/master
2021-01-10T14:34:29.580527
2020-06-25T15:34:23
2020-06-25T15:34:23
48,536,090
1
0
null
null
null
null
UTF-8
C++
false
false
382
cpp
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> ans(rowIndex + 1, 1); for (int i = 1; i <= rowIndex; i++) { int t1 = 1; for (int j = 1; j < i; j++) { int t2 = ans[j]; ans[j] += t1; t1 = t2; } } return ans; } };
[ "WenShihKen@users.noreply.github.com" ]
WenShihKen@users.noreply.github.com
bfb5366091cf387268d7bd4d27ef75b2f12251d7
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-iotanalytics/include/aws/iotanalytics/model/BatchPutMessageResult.h
00b476177304842920e65a078d1a606ba5044781
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
3,376
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/iotanalytics/IoTAnalytics_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/iotanalytics/model/BatchPutMessageErrorEntry.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace IoTAnalytics { namespace Model { class AWS_IOTANALYTICS_API BatchPutMessageResult { public: BatchPutMessageResult(); BatchPutMessageResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); BatchPutMessageResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>A list of any errors encountered when sending the messages to the * channel.</p> */ inline const Aws::Vector<BatchPutMessageErrorEntry>& GetBatchPutMessageErrorEntries() const{ return m_batchPutMessageErrorEntries; } /** * <p>A list of any errors encountered when sending the messages to the * channel.</p> */ inline void SetBatchPutMessageErrorEntries(const Aws::Vector<BatchPutMessageErrorEntry>& value) { m_batchPutMessageErrorEntries = value; } /** * <p>A list of any errors encountered when sending the messages to the * channel.</p> */ inline void SetBatchPutMessageErrorEntries(Aws::Vector<BatchPutMessageErrorEntry>&& value) { m_batchPutMessageErrorEntries = std::move(value); } /** * <p>A list of any errors encountered when sending the messages to the * channel.</p> */ inline BatchPutMessageResult& WithBatchPutMessageErrorEntries(const Aws::Vector<BatchPutMessageErrorEntry>& value) { SetBatchPutMessageErrorEntries(value); return *this;} /** * <p>A list of any errors encountered when sending the messages to the * channel.</p> */ inline BatchPutMessageResult& WithBatchPutMessageErrorEntries(Aws::Vector<BatchPutMessageErrorEntry>&& value) { SetBatchPutMessageErrorEntries(std::move(value)); return *this;} /** * <p>A list of any errors encountered when sending the messages to the * channel.</p> */ inline BatchPutMessageResult& AddBatchPutMessageErrorEntries(const BatchPutMessageErrorEntry& value) { m_batchPutMessageErrorEntries.push_back(value); return *this; } /** * <p>A list of any errors encountered when sending the messages to the * channel.</p> */ inline BatchPutMessageResult& AddBatchPutMessageErrorEntries(BatchPutMessageErrorEntry&& value) { m_batchPutMessageErrorEntries.push_back(std::move(value)); return *this; } private: Aws::Vector<BatchPutMessageErrorEntry> m_batchPutMessageErrorEntries; }; } // namespace Model } // namespace IoTAnalytics } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
b66ba09593e642a672d8d7c125d2d17daa2ca61c
85dd89fb0b3e89df45ce35cd9d54dd94a2d0bf06
/AtCoderProblems/ARC/042/a.cpp
95e926f458d959c99898eace0828310e77e35e0c
[]
no_license
Kourin1996/CompetitiveProgramming
c0a29f256ecc6d270357ca3b563ba57bbcb0e4be
be2bc9388b7ef63599b668827f7acb86908d02d5
refs/heads/main
2021-06-10T14:00:54.224708
2018-06-25T10:30:34
2018-06-25T10:30:34
114,212,139
0
0
null
null
null
null
UTF-8
C++
false
false
552
cpp
#include <iostream> #include <vector> #include <utility> #include <algorithm> int N = 0, M = 0; std::vector< std::pair<int,int> > thread; int main(void){ int i; std::cin >> N >> M; thread.resize(N); for(i=0; i<N; ++i){ thread[i].first = 0; thread[i].second = i+1; } int x = 0; int top = 0; for(i=0; i<M; ++i){ std::cin >> x; thread[x-1].first = --top; } std::sort(thread.begin(), thread.end()); for(i=0; i<N; ++i){ std::cout << thread[i].second << "\n"; } }
[ "kourin1996@gmail.com" ]
kourin1996@gmail.com
182942063a304f5c6ae0d0485d8d09916515d4d9
52a9241361bd179c437f85d9c307e0a8d27f5c72
/461.cpp
ba500320ce4f4afbeb1cf22b2a223ebb6121cdaf
[]
no_license
xingoxu/leetcode
5b710a21f3a220655dffa80300bf0515081a93d0
aa109ce7004662e4be7f5771e80a19cbe22bb287
refs/heads/master
2020-05-23T15:10:30.949381
2020-02-27T00:10:01
2020-02-27T00:10:01
186,820,252
1
0
null
null
null
null
UTF-8
C++
false
false
432
cpp
#include <iostream> #include <math.h> using namespace std; class Solution { public: int hammingDistance(int x, int y) { int ret = y < 0 ? 1 : 0; auto exclusiveOr = x ^ y; while (exclusiveOr != 0 && exclusiveOr != -1) { if((exclusiveOr & 1)) ++ret; exclusiveOr = exclusiveOr >> 1; } return ret; } }; int main() { cout << Solution().hammingDistance(3, 7) << endl; return 0; }
[ "xingoxu@gmail.com" ]
xingoxu@gmail.com
40bb1869ea22126816372d236dc6b57a8f311426
b88cf2abe9bf0c771db00b7576f03b9b54a47be5
/smartDogWithSwitch.ino
ae1f6ea866c29114dae271be47171b63eff54ab0
[]
no_license
alice-t/Treat-Dispenser
0e80896bbb82e8951a02e7be396b3372305ed8e8
2907eda7e6b1fa4aad435c329eb0019e42d505f4
refs/heads/master
2020-12-07T05:03:53.616583
2020-01-09T16:28:32
2020-01-09T16:28:32
232,640,168
0
0
null
null
null
null
UTF-8
C++
false
false
13,894
ino
#include <SPI.h> #include <Servo.h> #include "Adafruit_BLE_UART.h" #include <EEPROM.h> // Bluetooth params #define ADAFRUITBLE_REQ 10 #define ADAFRUITBLE_RDY 2 #define ADAFRUITBLE_RST 9 Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST); aci_evt_opcode_t bleStatus; aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED; // Settings for switch const int switchPin = 4; int switchState = 0; int longPressDelay; // Settings for button dictating end of dispensing a treat const int turnPin = 6; const int maxTimeout = 3000; // Settings for buzzer const int buzzerPin = 7; int treatFreq = 500; int noTreatFreq = 160; int errorFreq = 350; // Audio settings boolean notifyTreat = true; boolean notifyLastTreat = false; boolean notifyNoTreat = true; // Treat parameters int remainingTreats; int dispenserCapacity; // 5, 7, 9, 11 // EEPROM Addresses const int dispenserCapacityAddress = 0; const int notifyTreatAddress = 2; const int notifyLastTreatAddress = 4; const int notifyNoTreatAddress = 6; const int longPressDelayAddress = 10; // Servo motor parameters Servo myServo; // create servo object to control a servo int servoPin = 5; // *** IMPORTANT: comment out unless connected to a PC and using serial monitor with the Arduino IDE *** //#define DEBUG // print log messages to serial monitor /**************************************************************************/ /*! Configure the Arduino and start advertising with the radio */ /**************************************************************************/ void setup(void) { #ifdef DEBUG Serial.begin(9600); while(!Serial); // Leonardo/Micro should wait for serial init Serial.println(F("Smart Dog Treat Dispenser")); #endif // Do once - write initial EEPROM values //EEPROMWriteInt(dispenserCapacityAddress, 7); // EEPROMWriteInt(notifyTreatAddress, 1); // EEPROMWriteInt(notifyLastTreatAddress, 1); //EEPROMWriteInt(notifyNoTreatAddress, 1); //EEPROMWriteInt(longPressDelayAddress, 1500); // read values from EEPROM dispenserCapacity = EEPROMReadInt(dispenserCapacityAddress); longPressDelay = EEPROMReadInt(longPressDelayAddress); int eInt = EEPROMReadInt(notifyTreatAddress); if (eInt == 1) notifyTreat = true; else notifyTreat = false; eInt = EEPROMReadInt(notifyLastTreatAddress); if (eInt == 1) notifyLastTreat = true; else notifyLastTreat = false; eInt = EEPROMReadInt(notifyNoTreatAddress); if (eInt == 1) notifyNoTreat = true; else notifyNoTreat = false; #ifdef DEBUG Serial.println(String(dispenserCapacity) + ", " + String(notifyTreat) + ", " + String(notifyLastTreat) + ", " + String(notifyNoTreat) + ", " + String(longPressDelay)); #endif // setup bluetooth BTLEserial.setDeviceName("SDOG-TD"); /* 7 characters max! */ BTLEserial.begin(); // setup switch, reload button and buzzer pinMode(switchPin, INPUT); pinMode(turnPin, INPUT); pinMode(buzzerPin, OUTPUT); } /**************************************************************************/ /*! Constantly checks for new events on the nRF8001 */ /**************************************************************************/ void loop() { // Bluetooth processing BTLEserial.pollACI(); bleStatus = BTLEserial.getState(); // Check current status // If status changed... if (bleStatus != laststatus) { #ifdef DEBUG if (bleStatus == ACI_EVT_DEVICE_STARTED) { Serial.println(F("* Advertising started")); } if (bleStatus == ACI_EVT_CONNECTED) { Serial.println(F("* Connected!")); } if (bleStatus == ACI_EVT_DISCONNECTED) { Serial.println(F("* Disconnected or advertising timed out")); } #endif laststatus = bleStatus; } if (bleStatus == ACI_EVT_CONNECTED) { // if connected, check for data if (BTLEserial.available()) { #ifdef DEBUG Serial.print("* RX "); Serial.print(BTLEserial.available()); Serial.print(" bytes: "); #endif int inputChars = BTLEserial.available(); // While we still have something to read, read a charcter and add to inputString String inputString = ""; while (BTLEserial.available()) { inputString += char(BTLEserial.read()); } #ifdef DEBUG Serial.println(inputString); #endif if (inputString.equals("treat")) { giveTreat(); } else if (inputString.equals("battery")) { sendBatteryVoltage(); } else if (inputString.equals("remaining")) { sendData("Treats=" + String(remainingTreats)); } else if (inputString.equals("reload")) { reload(); } else if (inputString.equals("capacity")) { sendData("Capacity=" + String(dispenserCapacity)); } else if (inputString.equals("longPressDelay")) { sendData("LongPressDelay=" + String(longPressDelay)); } else if (inputString.startsWith("Capacity=")) { String capacityStr = inputString.substring(9); dispenserCapacity = capacityStr.toInt(); if (remainingTreats > dispenserCapacity) { remainingTreats = dispenserCapacity; } EEPROMWriteInt(dispenserCapacityAddress, dispenserCapacity); sendData("Set Capacity"); } else if (inputString.startsWith("LongPressDelay=")) { String delayStr = inputString.substring(15); longPressDelay = delayStr.toInt(); EEPROMWriteInt(longPressDelayAddress, longPressDelay); sendData("Set LongPressDelay"); } else if (inputString.equals("notifyTreat")) { sendData("NotifyTreat=" + String(notifyTreat)); } else if (inputString.equals("notifyLastTreat")) { sendData("NotifyLast=" + String(notifyLastTreat)); } else if (inputString.equals("notifyNoTreat")) { sendData("NotifyNoTreat=" + String(notifyNoTreat)); } else if (inputString.startsWith("NotifyTreat=")) { String notifyTreatStr = inputString.substring(12); if (!notifyTreat && notifyTreatStr.equals("true")) { notifyTreat = true; EEPROMWriteInt(notifyTreatAddress, 1); } else if (notifyTreat && notifyTreatStr.equals("false")) { notifyTreat = false; EEPROMWriteInt(notifyTreatAddress, 0); } sendData("Set NotifyTreat"); } else if (inputString.startsWith("NotifyLast=")) { String notifyLastTreatStr = inputString.substring(11); if (!notifyLastTreat && notifyLastTreatStr.equals("true")) { notifyLastTreat = true; EEPROMWriteInt(notifyLastTreatAddress, 1); } else if (notifyLastTreat && notifyLastTreatStr.equals("false")) { notifyLastTreat = false; EEPROMWriteInt(notifyLastTreatAddress, 0); } sendData("Set NotifyLast"); } else if (inputString.startsWith("NotifyNoTreat=")) { String notifyNoTreatStr = inputString.substring(14); if (!notifyNoTreat && notifyNoTreatStr.equals("true")) { notifyNoTreat = true; EEPROMWriteInt(notifyNoTreatAddress, 1); } else if (notifyNoTreat && notifyNoTreatStr.equals("false")) { notifyNoTreat = false; EEPROMWriteInt(notifyNoTreatAddress, 0); } sendData("Set NotifyNoTreat"); } else { sendData("Unrecognised input"); #ifdef DEBUG Serial.print("Unrecognised input="); Serial.println(inputString); #endif } } } // Check if switch pressed switchState = digitalRead(switchPin); if (switchState == HIGH) { unsigned long longPressTime = millis() + longPressDelay; do { delay(100); switchState = digitalRead(switchPin); if (switchState == LOW) { giveTreat(); #ifdef DEBUG Serial.print("remainingTreats="); Serial.println(String(remainingTreats)); #endif break; } } while (longPressTime > millis()); if (switchState == HIGH) { // long press, so reload #ifdef DEBUG Serial.println("long press - reload"); #endif reload(); } delay(300); // add delay to prevent accidental double press } // Check if reload button pressed /* reloadState = digitalRead(reloadPin); if (reloadState == HIGH) { // stop rotation with myServo.write(90); //reload(); //delay(300); // add delay to prevent accidental double press } */ } void sendData(String outputStr) { uint8_t sendbuf[20]; int strlen = outputStr.length() + 1; // check buffer size not exceeded if (strlen > 20) strlen = 20; outputStr.getBytes(sendbuf, strlen); BTLEserial.write(sendbuf, strlen); #ifdef DEBUG Serial.print("* TX "); Serial.print(strlen); Serial.print(" bytes: "); Serial.println(outputStr); #endif } void giveTreat() { boolean treatDispensed = false; if (remainingTreats > 0) { // Dispense treat myServo.attach(servoPin); myServo.write(105); bool error = true; long timeout = millis() + maxTimeout; while(millis()<timeout){ if(digitalRead(6) == LOW){ break; } } while(millis()<timeout){ if(digitalRead(6) == HIGH){ error = false; break; } } myServo.write(90); myServo.detach(); if(error){ tone(buzzerPin,errorFreq,100); delay(100); tone(buzzerPin,errorFreq-50,100); delay(200); tone(buzzerPin,errorFreq,100); delay(100); tone(buzzerPin,errorFreq-50,100); } else { treatDispensed = true; remainingTreats -= 1; // sound buzzer if (remainingTreats == 0 && notifyLastTreat) { // sound last treat buzzer tones tone(buzzerPin, treatFreq, 250); delay(500); tone(buzzerPin, treatFreq, 250); } else if (notifyTreat) { // sound treat dispensed buzzer tones tone(buzzerPin, treatFreq, 400); } } } else if (notifyNoTreat) { // sound no treat buzzer tones tone(buzzerPin, noTreatFreq, 500); } if (bleStatus == ACI_EVT_CONNECTED) { if (treatDispensed) { sendData("Treat Given"); delay(200); sendData("Treats=" + String(remainingTreats)); } else sendData("No Treats"); delay(200); sendBatteryVoltage(); } } void reload() { remainingTreats = dispenserCapacity; // sound reload buzzer tones tone(buzzerPin, treatFreq, 250); delay(400); tone(buzzerPin, treatFreq, 250); delay(400); tone(buzzerPin, treatFreq, 250); #ifdef DEBUG Serial.print("remainingTreats="); Serial.println(String(remainingTreats)); #endif if (bleStatus == ACI_EVT_CONNECTED) { sendData("Treats=" + String(remainingTreats)); } } void sendBatteryVoltage() { double voltage = double( readVcc() ) / 1000; String outputStr = "Voltage=" + String(voltage) + "v"; sendData(outputStr); } long readVcc() { long result; // Read 1.1V reference against AVcc //ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) ADMUX = _BV(MUX5) | _BV(MUX0); #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) ADMUX = _BV(MUX3) | _BV(MUX2); #else ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #endif #if defined(__AVR_ATmega2560__) ADCSRB &= ~_BV(MUX5); // Without this the function always returns -1 on the ATmega2560 #endif delay(2); // Wait for Vref to settle ADCSRA |= _BV(ADSC); // Convert while (bit_is_set(ADCSRA, ADSC)); result = ADCL; result |= ADCH << 8; result = 1126400L / result; // Back-calculate AVcc in mV return result; } void EEPROMWriteInt(int address, int value) { byte two = (value & 0xFF); byte one = ((value >> 8) & 0xFF); EEPROM.update(address, two); EEPROM.update(address + 1, one); } int EEPROMReadInt(int address) { long two = EEPROM.read(address); long one = EEPROM.read(address + 1); return ((two << 0) & 0xFFFFFF) + ((one << 8) & 0xFFFFFFFF); }
[ "alice.torjussen@gmail.com" ]
alice.torjussen@gmail.com
751f0b085599ba073b19657c64b8d05a976c099c
916ef1b31f0b683de4f043626d9df59f37edbbc4
/atcoder/05_AtCoder-Beginner-Contest/abc167/D/main.cpp
0cc42db0cac32d3b7e0478fc646865378e3aff9e
[]
no_license
solareenlo/cpp
56cc33673d30dd4a4031e4b81cec16b08b3490e0
f78f8a098849938153e6e3a282737e067dbe2c58
refs/heads/master
2021-03-31T04:31:39.420394
2020-11-29T22:22:25
2020-11-29T22:22:25
248,076,420
0
0
null
null
null
null
UTF-8
C++
false
false
878
cpp
#include <iostream> #include <vector> #define REP(i, n) for (int i = 0; i < (n); i++) using namespace std; int main() { int n; long long k; cin >> n >> k; vector<int> a(n); // ワープ手順全部 REP(i, n) cin >> a[i]; vector<int> road; // 必要なワープ手順 (tail と loop の部分) vector<int> count(n + 1, -1); // index の街までのワープする街の個数 int tail = 0; // tail 部分の街の個数 int loop = 1; // loop 部分の街の個数 int v = 1; while (count[v] == -1) { count[v] = road.size(); road.push_back(v); v = a[v - 1]; } tail = count[v]; // v はループ1歩手前の場所 loop = road.size() - tail; if (k < tail) cout << road[k] << '\n'; else { k -= tail; k %= loop; cout << road[tail + k] << '\n'; } return 0; }
[ "solareenlo@gmail.com" ]
solareenlo@gmail.com
fbd777dca1761de9a79bdb979ed667a331292dfe
15e9a40acc6a923ec3d8665e7171b7d55dc2a17e
/2019-2020 Pacific Northwest (Div. 1)/editorial/C. Coloring Contention/accepted/coloringgraphedgesgame_arknave.cpp
1dfcc071cff133af0d541f8a72cd642333de7870
[]
no_license
yuanz4/Codeforces
951ad71469c2419a8bff6287d2989262759cc20b
c9e15f3194c54fe413e3b7cc07d69eb67712e9c7
refs/heads/main
2023-07-17T14:59:51.664501
2021-08-16T16:46:15
2021-08-16T16:46:15
324,513,112
0
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
// #include <bits/stdc++.h> // this is not C++; this is a Linuxism #include <iostream> #include <vector> #include <queue> using namespace std; #define all(x) begin(x), end(x) using ll = long long; using ld = long double; using pii = pair<int, int>; using vi = vector<int>; int main() { int n, m; cin >> n >> m; vector<vi> graph(n); for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; --u; --v; graph[u].push_back(v); graph[v].push_back(u); } vi dist(n, n + 1); dist[0] = 0; queue<int> q; q.push(0); while (!q.empty()) { int u = q.front(); q.pop(); for (int v : graph[u]) { if (dist[v] == n + 1) { dist[v] = dist[u] + 1; q.push(v); } } } cout << dist.back() - 1 << '\n'; return 0; }
[ "yuanz4@illinois.edu" ]
yuanz4@illinois.edu
0e446efb2e4e9f98c38f3fe6f85f669014d8ef8c
bfc88535fa1495c64672f048a5559e8bb6de1ae1
/SPOJ/NDS.cpp
8b87eae74980b8452377844f2d6e1e14b19c6e54
[]
no_license
famus2310/CP
59839ffe23cf74019e2f655f49af224390846776
d8a77572830fb3927de92f1e913ee729d04865e1
refs/heads/master
2021-07-05T00:23:31.113026
2020-08-07T22:28:24
2020-08-07T22:28:24
144,426,214
1
1
null
null
null
null
UTF-8
C++
false
false
1,277
cpp
#include <bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int, int> pii; typedef pair<int, pair<int, int> > piii; #define pb push_back #define debug(x) cout << x << endl #define fastio ios_base::sync_with_stdio(0), cin.tie(0) #define PI acos(-1) #define all(c) c.begin(), c.end() #define SET(x, y) memset((x), y, sizeof(x)) const int MOD = 1e9 + 7; const int INF = 1e9; const LL INF64 = 1e18; const int N = 1e6 + 5; LL BIT[N]; LL arr[N]; LL tail[N]; int main() { int t; scanf("%d", &t); while (t--) { LL zero = 0; SET(BIT, 0); SET(tail, 0); LL n; scanf("%lld", &n); for (int i = 0; i < n; i++) scanf("%lld", arr + i); LL k; scanf("%lld", &k); if (n == 0) { puts("-1"); continue; } LL ans = INF; tail[0] = arr[0]; if (k == 1) ans = min(ans, arr[0]); int len = 1; for (int i = 1; i < n; i++) { if (arr[i] > tail[len - 1]) { tail[len] = arr[i]; if (len + 1 >= k) ans = min(ans, arr[i]); len++; } else { LL ub = lower_bound(tail, tail + len, arr[i]) - tail; // debug(ub); if (tail[ub] == arr[i]) continue; tail[ub] = arr[i]; if (ub + 1 >= k) ans = min(ans, arr[i]); } } if (ans == INF) puts("-1"); else printf("%lld\n", ans); } return 0; }
[ "fadhilmusaad@gmail.com" ]
fadhilmusaad@gmail.com
5a135d27ebacbd81b7a46d8b9a15fd37a02311ca
a6dae8547c72dd40bc1b2ec2bae9b92ba6b96464
/Core/pcre/pcre.cxx
82b604a8011f61dac8a9f6b2570ea59427ca6a9f
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-pcre" ]
permissive
scijones/Soar
543169cad2c93787f930eecfb06e5a4b30be8bee
de3bb9c9daff90499a9ea05aef1360c256628648
refs/heads/master
2023-02-24T22:38:15.956621
2015-07-13T18:07:13
2015-07-13T18:07:13
22,886,200
0
0
NOASSERTION
2023-02-15T23:08:41
2014-08-12T17:32:19
C++
UTF-8
C++
false
false
553
cxx
#include "pcre_chartables.c" #include "pcre_compile.c" #include "pcre_config.c" #include "pcre_dfa_exec.c" #include "pcre_exec.c" #include "pcre_fullinfo.c" #include "pcre_get.c" #include "pcre_globals.c" #include "pcre_info.c" #include "pcre_maketables.c" #include "pcre_newline.c" #include "pcre_ord2utf8.c" #include "pcre_refcount.c" #include "pcre_study.c" #include "pcre_tables.c" #include "pcre_try_flipped.c" #include "pcre_ucp_searchfuncs.c" #include "pcre_valid_utf8.c" #include "pcre_version.c" #include "pcre_xclass.c" #include "pcreposix.c"
[ "mazina@umich.edu" ]
mazina@umich.edu
775d89f13e829471c23bf7cc1412b64a5dba89b0
a6352828dbdfc70485bfe96518d8de6c20d64f65
/Net/Connection/SocketConnection.cpp
8ca36623a3e2888668200a9d0eec0b11899177bc
[]
no_license
lxj362343/framework-nd
cbbed6ccb29e9a5ae130b17947d5b324604a810d
9fe9d770af2bf0a96308fc92811c908b883ed21d
refs/heads/master
2022-01-07T13:07:21.845762
2019-01-11T03:05:50
2019-01-11T03:05:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,067
cpp
#include "BoostProcessor.h" #include "SocketConnection.h" #include "TcpClient.h" #include "Reactor.h" #include "Protocol.h" #include "Log.h" #include <unistd.h> #include <errno.h> #include <string.h> #include <err.h> using namespace Net::Connection; //----------------------------------------------------------------------------- void on_read(int theFd, short theEvt, void *theArg) { SocketConnection* connection = (SocketConnection*)theArg; connection->asynRead(theFd, theEvt); } //----------------------------------------------------------------------------- void on_write(int theFd, short theEvt, void *theArg) { SocketConnection* connection = (SocketConnection*)theArg; connection->asynWrite(theFd, theEvt); } //----------------------------------------------------------------------------- SocketConnection::SocketConnection( IProtocol* theProtocol, Reactor::Reactor* theReactor, Processor::BoostProcessor* theProcessor, evutil_socket_t theFd) : selfM(this) , heartbeatTimerEvtM(NULL) , clientTimerEvtM(NULL) , heartbeatTimeoutCounterM(0) , protocolM(theProtocol) , reactorM(theReactor) , processorM(theProcessor) , fdM(theFd) , inputQueueM(theProtocol->getRBufferSizePower()) , outputQueueM(theProtocol->getWBufferSizePower()) , statusM(ActiveE) , stopReadingM(false) , watcherM(NULL) , clientM(NULL) , isConnectedNotified(true) , uppperDataM(NULL) { readEvtM = reactorM->newEvent(fdM, EV_READ, on_read, this); writeEvtM = reactorM->newEvent(fdM, EV_WRITE, on_write, this); addReadEvent(); protocolM->asynHandleConnected(fdM, selfM); processorM->process(fdM, &SocketConnection::startHeartbeatTimer, this); } //----------------------------------------------------------------------------- SocketConnection::SocketConnection( IProtocol* theProtocol, Reactor::Reactor* theReactor, Processor::BoostProcessor* theProcessor, evutil_socket_t theFd, Client::TcpClient* theClient) : selfM(this) , heartbeatTimerEvtM(NULL) , clientTimerEvtM(NULL) , heartbeatTimeoutCounterM(0) , protocolM(theProtocol) , reactorM(theReactor) , processorM(theProcessor) , fdM(theFd) , inputQueueM(theProtocol->getRBufferSizePower()) , outputQueueM(theProtocol->getWBufferSizePower()) , statusM(ActiveE) , stopReadingM(false) , watcherM(NULL) , clientM(theClient) , isConnectedNotified(false) , uppperDataM(NULL) { readEvtM = reactorM->newEvent(fdM, EV_READ, on_read, this); writeEvtM = reactorM->newEvent(fdM, EV_WRITE, on_write, this); addWriteEvent(); addReadEvent(); } //----------------------------------------------------------------------------- SocketConnection::~SocketConnection() { evutil_closesocket(fdM); if (watcherM) { delete watcherM; watcherM = NULL; } if (uppperDataM != NULL) { LOG_WARN("uppperDataM is not NULL and may leek, please free it and set to NULL in upper handling while connection is closed."); } LOG_DEBUG("close fd:" << fdM); } //----------------------------------------------------------------------------- void SocketConnection::rmClient() { boost::lock_guard<boost::mutex> lock(clientMutexM); clientM = NULL; } //----------------------------------------------------------------------------- void SocketConnection::addReadEvent() { if (CloseE == statusM) return; if (-1 == event_add(readEvtM, NULL)) { processorM->process(fdM, &SocketConnection::addReadEvent, this); } } //----------------------------------------------------------------------------- void SocketConnection::addWriteEvent() { if (CloseE == statusM) return; if (-1 == event_add(writeEvtM, NULL)) { processorM->process(fdM, &SocketConnection::addWriteEvent, this); } } //----------------------------------------------------------------------------- int SocketConnection::asynRead(int theFd, short theEvt) { return processorM->process(fdM, &SocketConnection::onRead, this, theFd, theEvt); } //----------------------------------------------------------------------------- void SocketConnection::onRead(int theFd, short theEvt) { char buffer[1024]= {0}; unsigned readBufferLeft = inputQueueM.unusedSize(); unsigned readLen = (readBufferLeft < sizeof(buffer)) ? readBufferLeft : sizeof(buffer); if (readLen == 0) { if (!stopReadingM) { boost::lock_guard<boost::mutex> lock(stopReadingMutexM); stopReadingM = true; } protocolM->asynHandleInput(fdM, selfM); return; } int len = read(theFd, buffer, readLen); if ((0 == len) ||(len < 0 && errno != EWOULDBLOCK)) { LOG_DEBUG("Client disconnected. fd:" << fdM); _close(); return; } else if (len > SSIZE_MAX) { LOG_WARN("Socket failure, disconnecting client:" << strerror(errno)); _close(); return; } else if (len < 0 && errno == EWOULDBLOCK) { len = 0; } unsigned putLen = inputQueueM.put(buffer, len); assert(putLen == (unsigned)len); while(len > 0 && (Utility::BufferOkE == inputQueueM.getStatus() || Utility::BufferLowE == inputQueueM.getStatus() )) { readBufferLeft = inputQueueM.unusedSize(); readLen = (readBufferLeft < sizeof(buffer)) ? readBufferLeft : sizeof(buffer); len = read(theFd, buffer, readLen); if (len <= 0 || len > SSIZE_MAX) { break; } putLen = inputQueueM.put(buffer, len); assert(putLen == (unsigned)len); } if (Utility::BufferHighE == inputQueueM.getStatus() || Utility::BufferNotEnoughE == inputQueueM.getStatus()) { //TRACE("Flow Control:Socket " << fdM << " stop reading.", fdM); boost::lock_guard<boost::mutex> lock(stopReadingMutexM); stopReadingM = true; } else { addReadEvent(); } protocolM->asynHandleInput(fdM, selfM); } //----------------------------------------------------------------------------- unsigned SocketConnection::getInput(char* const theBuffer, const unsigned theLen) { //if (CloseE == statusM) // return 0; unsigned len = inputQueueM.get(theBuffer, theLen); if (stopReadingM && CloseE != statusM) { Utility::BufferStatus postBufferStatus = inputQueueM.getStatus(); if (postBufferStatus == Utility::BufferLowE) { { boost::lock_guard<boost::mutex> lock(stopReadingMutexM); stopReadingM = false; } asynRead(fdM, 0); //processorM->process(fdM, &SocketConnection::addReadEvent, selfM); } } return len; } //----------------------------------------------------------------------------- unsigned SocketConnection::getnInput(char* const theBuffer, const unsigned theLen) { //if (CloseE == statusM) // return 0; unsigned len = inputQueueM.getn(theBuffer, theLen); if (stopReadingM && CloseE != statusM) { Utility::BufferStatus postBufferStatus = inputQueueM.getStatus(); if (postBufferStatus == Utility::BufferLowE) { { boost::lock_guard<boost::mutex> lock(stopReadingMutexM); stopReadingM = false; } asynRead(fdM, 0); //processorM->process(fdM, &SocketConnection::addReadEvent, selfM); } } return len; } //----------------------------------------------------------------------------- unsigned SocketConnection::peeknInput(char* const theBuffer, const unsigned theLen) { //if (CloseE == statusM) // return 0; return inputQueueM.peekn(theBuffer, theLen); } //----------------------------------------------------------------------------- unsigned SocketConnection::sendn(const char* const theBuffer, const unsigned theLen) { if (CloseE == statusM) return 0; if (0 == theLen || NULL == theBuffer) return 0; unsigned len = 0; { boost::lock_guard<boost::mutex> lock(outputQueueMutexM); len = outputQueueM.putn(theBuffer, theLen); } if (0 == len) { LOG_WARN("outage of the connection's write queue!"); } processorM->process(fdM, &SocketConnection::addWriteEvent, selfM); return len; } //----------------------------------------------------------------------------- int SocketConnection::asynWrite(int theFd, short theEvt) { if (CloseE == statusM) return -1; return processorM->process(fdM, &SocketConnection::onWrite, this, theFd, theEvt); } //----------------------------------------------------------------------------- void SocketConnection::setLowWaterMarkWatcher(Watcher* theWatcher) { //if it is already writable Utility::BufferStatus bufferStatus = outputQueueM.getStatus(); if (bufferStatus == Utility::BufferLowE) { (*theWatcher)(fdM, selfM); return; } //or set theWatcher and add the write event { boost::lock_guard<boost::mutex> lock(watcherMutexM); if (watcherM) { delete watcherM; } watcherM = theWatcher; } if (CloseE != statusM) { addWriteEvent(); } } //----------------------------------------------------------------------------- void SocketConnection::onWrite(int theFd, short theEvt) { if (!isConnectedNotified && clientM) { boost::lock_guard<boost::mutex> lock(clientMutexM); if (clientM) { clientM->onConnected(theFd, selfM); isConnectedNotified = true; startHeartbeatTimer(); } } char buffer[1024]= {0}; unsigned peekLen = outputQueueM.peek(buffer, sizeof(buffer)); int writeLen = 0; while (CloseE != statusM && peekLen > 0) { writeLen = write(theFd, buffer, peekLen); if (writeLen < 0) { if (errno == EINTR || errno == EAGAIN) { break; } else { LOG_DEBUG("Socket write failure."); _close(); return; } } outputQueueM.commitRead(writeLen); peekLen = outputQueueM.peek(buffer, sizeof(buffer)); } Utility::BufferStatus bufferStatus = outputQueueM.getStatus(); if (watcherM && (bufferStatus == Utility::BufferLowE)) { boost::lock_guard<boost::mutex> lock(watcherMutexM); if (watcherM) { (*watcherM)(fdM, selfM); delete watcherM; watcherM = NULL; } } if (CloseE != statusM && !outputQueueM.empty()) { addWriteEvent(); } } //----------------------------------------------------------------------------- void SocketConnection::startHeartbeatTimer() { struct timeval tv; tv.tv_sec = protocolM->getHeartbeatInterval(); if (tv.tv_sec <= 0) tv.tv_sec = 60; tv.tv_usec = 0; heartbeatTimerEvtM = processorM->addLocalTimer(fdM, tv, SocketConnection::onHeartbeat, this); } //----------------------------------------------------------------------------- void SocketConnection::onHeartbeat(int theFd, short theEvt, void *theArg) { SocketConnection* connection = (SocketConnection*) theArg; connection->heartbeatTimerEvtM = NULL; int heartbeatInterval = connection->protocolM->getHeartbeatInterval(); if (heartbeatInterval > 0) { connection->protocolM->asynHandleHeartbeat(connection->fdM, connection->selfM); } connection->startHeartbeatTimer(); } //----------------------------------------------------------------------------- void SocketConnection::addClientTimer(unsigned theSec) { processorM->process(fdM, &SocketConnection::_addClientTimer, this, theSec); } //----------------------------------------------------------------------------- void SocketConnection::_addClientTimer(unsigned theSec) { if (NULL == clientM || 0 == theSec) { return; } if (clientTimerEvtM) { processorM->cancelLocalTimer(fdM, clientTimerEvtM); } struct timeval tv; tv.tv_sec = theSec; tv.tv_usec = 0; clientTimerEvtM = processorM->addLocalTimer(fdM, tv, &SocketConnection::onClientTimeout, this); } //----------------------------------------------------------------------------- void SocketConnection::onClientTimeout(int theFd, short theEvt, void *theArg) { SocketConnection* connection = (SocketConnection*) theArg; boost::lock_guard<boost::mutex> lock(connection->clientMutexM); connection->clientTimerEvtM = NULL; if (connection->clientM) { connection->clientM->onClientTimeout(); } } //----------------------------------------------------------------------------- void SocketConnection::close() { if (CloseE == statusM) return; processorM->process(fdM, &SocketConnection::_close, this); } //----------------------------------------------------------------------------- void SocketConnection::_release() { selfM.reset(); } //----------------------------------------------------------------------------- void SocketConnection::_close() { if (CloseE == statusM) return; statusM = CloseE; if (heartbeatTimerEvtM) { processorM->cancelLocalTimer(fdM, heartbeatTimerEvtM); } if (clientTimerEvtM) { processorM->cancelLocalTimer(fdM, clientTimerEvtM); } protocolM->asynHandleClose(fdM, selfM); if (clientM) { boost::lock_guard<boost::mutex> lock(clientMutexM); if (clientM) { clientM->onError(); clientM = NULL; } } reactorM->delEvent(readEvtM); reactorM->delEvent(writeEvtM); processorM->process(fdM, &SocketConnection::_release, this); } //-----------------------------------------------------------------------------
[ "noodle1983@126.com" ]
noodle1983@126.com
6ea62b428fc3cf83c71333e24d20581b83fca563
d5bd083dbcacce8cf62ebbd73c77c14c8247e057
/external/skia/src/utils/SkTextureCompressor_Blitter.h
73d8ee4ffb362f4fa2937a8dc030ba577b7f74d5
[ "BSD-3-Clause", "SGI-B-2.0" ]
permissive
RetronixTechInc/android-retronix
ab0e10840dab5dc7b0879737953ebf2e1916f2b0
cd7d794dea51c3b287da0d35ddb18c1bdef00372
refs/heads/RTX_NXP_Android601
2021-11-16T03:58:58.169998
2021-11-15T01:51:02
2021-11-15T01:51:02
198,991,737
4
5
null
2020-03-08T23:21:29
2019-07-26T09:49:01
Java
UTF-8
C++
false
false
30,232
h
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkTextureCompressor_Blitter_DEFINED #define SkTextureCompressor_Blitter_DEFINED #include "SkTypes.h" #include "SkBlitter.h" namespace SkTextureCompressor { // Ostensibly, SkBlitter::BlitRect is supposed to set a rect of pixels to full // alpha. This becomes problematic when using compressed texture blitters, since // the rect rarely falls along block boundaries. The proper way to handle this is // to update the compressed encoding of a block by resetting the proper parameters // (and even recompressing the block) where a rect falls inbetween block boundaries. // PEDANTIC_BLIT_RECT attempts to do this by requiring the struct passed to // SkTCompressedAlphaBlitter to implement an UpdateBlock function call. // // However, the way that BlitRect gets used almost exclusively is to bracket inverse // fills for paths. In other words, the top few rows and bottom few rows of a path // that's getting inverse filled are called using blitRect. The rest are called using // the standard blitAntiH. As a result, we can just call blitAntiH with a faux RLE // of full alpha values, and then check in our flush() call that we don't run off the // edge of the buffer. This is why we do not need this flag to be turned on. // // NOTE: This code is unfinished, but is inteded as a starting point if an when // bugs are introduced from the existing code. #define PEDANTIC_BLIT_RECT 0 // This class implements a blitter that blits directly into a buffer that will // be used as an compressed alpha texture. We compute this buffer by // buffering scan lines and then outputting them all at once. The number of // scan lines buffered is controlled by kBlockSize // // The CompressorType is a struct with a bunch of static methods that provides // the specialized compression functionality of the blitter. A complete CompressorType // will implement the following static functions; // // struct CompressorType { // // The function used to compress an A8 block. The layout of the // // block is also expected to be in column-major order. // static void CompressA8Vertical(uint8_t* dst, const uint8_t block[]); // // // The function used to compress an A8 block. The layout of the // // block is also expected to be in row-major order. // static void CompressA8Horizontal(uint8_t* dst, const uint8_t* src, int srcRowBytes); // #if PEDANTIC_BLIT_RECT // // The function used to update an already compressed block. This will // // most likely be implementation dependent. The mask variable will have // // 0xFF in positions where the block should be updated and 0 in positions // // where it shouldn't. src contains an uncompressed buffer of pixels. // static void UpdateBlock(uint8_t* dst, const uint8_t* src, int srcRowBytes, // const uint8_t* mask); #endif // }; template<int BlockDim, int EncodedBlockSize, typename CompressorType> class SkTCompressedAlphaBlitter : public SkBlitter { public: SkTCompressedAlphaBlitter(int width, int height, void *compressedBuffer) // 0x7FFE is one minus the largest positive 16-bit int. We use it for // debugging to make sure that we're properly setting the nextX distance // in flushRuns(). #ifdef SK_DEBUG : fCalledOnceWithNonzeroY(false) , fBlitMaskCalled(false), #else : #endif kLongestRun(0x7FFE), kZeroAlpha(0) , fNextRun(0) , fWidth(width) , fHeight(height) , fBuffer(compressedBuffer) { SkASSERT((width % BlockDim) == 0); SkASSERT((height % BlockDim) == 0); } virtual ~SkTCompressedAlphaBlitter() { this->flushRuns(); } // Blit a horizontal run of one or more pixels. void blitH(int x, int y, int width) override { // This function is intended to be called from any standard RGB // buffer, so we should never encounter it. However, if some code // path does end up here, then this needs to be investigated. SkFAIL("Not implemented!"); } // Blit a horizontal run of antialiased pixels; runs[] is a *sparse* // zero-terminated run-length encoding of spans of constant alpha values. void blitAntiH(int x, int y, const SkAlpha antialias[], const int16_t runs[]) override { SkASSERT(0 == x); // Make sure that the new row to blit is either the first // row that we're blitting, or it's exactly the next scan row // since the last row that we blit. This is to ensure that when // we go to flush the runs, that they are all the same four // runs. if (fNextRun > 0 && ((x != fBufferedRuns[fNextRun-1].fX) || (y-1 != fBufferedRuns[fNextRun-1].fY))) { this->flushRuns(); } // Align the rows to a block boundary. If we receive rows that // are not on a block boundary, then fill in the preceding runs // with zeros. We do this by producing a single RLE that says // that we have 0x7FFE pixels of zero (0x7FFE = 32766). const int row = BlockDim * (y / BlockDim); while ((row + fNextRun) < y) { fBufferedRuns[fNextRun].fAlphas = &kZeroAlpha; fBufferedRuns[fNextRun].fRuns = &kLongestRun; fBufferedRuns[fNextRun].fX = 0; fBufferedRuns[fNextRun].fY = row + fNextRun; ++fNextRun; } // Make sure that our assumptions aren't violated... SkASSERT(fNextRun == (y % BlockDim)); SkASSERT(fNextRun == 0 || fBufferedRuns[fNextRun - 1].fY < y); // Set the values of the next run fBufferedRuns[fNextRun].fAlphas = antialias; fBufferedRuns[fNextRun].fRuns = runs; fBufferedRuns[fNextRun].fX = x; fBufferedRuns[fNextRun].fY = y; // If we've output a block of scanlines in a row that don't violate our // assumptions, then it's time to flush them... if (BlockDim == ++fNextRun) { this->flushRuns(); } } // Blit a vertical run of pixels with a constant alpha value. void blitV(int x, int y, int height, SkAlpha alpha) override { // This function is currently not implemented. It is not explicitly // required by the contract, but if at some time a code path runs into // this function (which is entirely possible), it needs to be implemented. // // TODO (krajcevski): // This function will be most easily implemented in one of two ways: // 1. Buffer each vertical column value and then construct a list // of alpha values and output all of the blocks at once. This only // requires a write to the compressed buffer // 2. Replace the indices of each block with the proper indices based // on the alpha value. This requires a read and write of the compressed // buffer, but much less overhead. SkFAIL("Not implemented!"); } // Blit a solid rectangle one or more pixels wide. It's assumed that blitRect // is called as a way to bracket blitAntiH where above and below the path the // called path just needs a solid rectangle to fill in the mask. #ifdef SK_DEBUG bool fCalledOnceWithNonzeroY; #endif void blitRect(int x, int y, int width, int height) override { // Assumptions: SkASSERT(0 == x); SkASSERT(width <= fWidth); // Make sure that we're only ever bracketing calls to blitAntiH. SkASSERT((0 == y) || (!fCalledOnceWithNonzeroY && (fCalledOnceWithNonzeroY = true))); #if !(PEDANTIC_BLIT_RECT) for (int i = 0; i < height; ++i) { const SkAlpha kFullAlpha = 0xFF; this->blitAntiH(x, y+i, &kFullAlpha, &kLongestRun); } #else const int startBlockX = (x / BlockDim) * BlockDim; const int startBlockY = (y / BlockDim) * BlockDim; const int endBlockX = ((x + width) / BlockDim) * BlockDim; const int endBlockY = ((y + height) / BlockDim) * BlockDim; // If start and end are the same, then we only need to update a single block... if (startBlockY == endBlockY && startBlockX == endBlockX) { uint8_t mask[BlockDim*BlockDim]; memset(mask, 0, sizeof(mask)); const int xoff = x - startBlockX; SkASSERT((xoff + width) <= BlockDim); const int yoff = y - startBlockY; SkASSERT((yoff + height) <= BlockDim); for (int j = 0; j < height; ++j) { memset(mask + (j + yoff)*BlockDim + xoff, 0xFF, width); } uint8_t* dst = this->getBlock(startBlockX, startBlockY); CompressorType::UpdateBlock(dst, mask, BlockDim, mask); // If start and end are the same in the y dimension, then we can freely update an // entire row of blocks... } else if (startBlockY == endBlockY) { this->updateBlockRow(x, y, width, height, startBlockY, startBlockX, endBlockX); // Similarly, if the start and end are in the same column, then we can just update // an entire column of blocks... } else if (startBlockX == endBlockX) { this->updateBlockCol(x, y, width, height, startBlockX, startBlockY, endBlockY); // Otherwise, the rect spans a non-trivial region of blocks, and we have to construct // a kind of 9-patch to update each of the pieces of the rect. The top and bottom // rows are updated using updateBlockRow, and the left and right columns are updated // using updateBlockColumn. Anything in the middle is simply memset to an opaque block // encoding. } else { const int innerStartBlockX = startBlockX + BlockDim; const int innerStartBlockY = startBlockY + BlockDim; // Blit top row const int topRowHeight = innerStartBlockY - y; this->updateBlockRow(x, y, width, topRowHeight, startBlockY, startBlockX, endBlockX); // Advance y y += topRowHeight; height -= topRowHeight; // Blit middle if (endBlockY > innerStartBlockY) { // Update left row this->updateBlockCol(x, y, innerStartBlockX - x, endBlockY, startBlockY, startBlockX, innerStartBlockX); // Update the middle with an opaque encoding... uint8_t mask[BlockDim*BlockDim]; memset(mask, 0xFF, sizeof(mask)); uint8_t opaqueEncoding[EncodedBlockSize]; CompressorType::CompressA8Horizontal(opaqueEncoding, mask, BlockDim); for (int j = innerStartBlockY; j < endBlockY; j += BlockDim) { uint8_t* opaqueDst = this->getBlock(innerStartBlockX, j); for (int i = innerStartBlockX; i < endBlockX; i += BlockDim) { memcpy(opaqueDst, opaqueEncoding, EncodedBlockSize); opaqueDst += EncodedBlockSize; } } // If we need to update the right column, do that too if (x + width > endBlockX) { this->updateBlockCol(endBlockX, y, x + width - endBlockX, endBlockY, endBlockX, innerStartBlockY, endBlockY); } // Advance y height = y + height - endBlockY; y = endBlockY; } // If we need to update the last row, then do that, too. if (height > 0) { this->updateBlockRow(x, y, width, height, endBlockY, startBlockX, endBlockX); } } #endif } // Blit a rectangle with one alpha-blended column on the left, // width (zero or more) opaque pixels, and one alpha-blended column // on the right. The result will always be at least two pixels wide. void blitAntiRect(int x, int y, int width, int height, SkAlpha leftAlpha, SkAlpha rightAlpha) override { // This function is currently not implemented. It is not explicitly // required by the contract, but if at some time a code path runs into // this function (which is entirely possible), it needs to be implemented. // // TODO (krajcevski): // This function will be most easily implemented as follows: // 1. If width/height are smaller than a block, then update the // indices of the affected blocks. // 2. If width/height are larger than a block, then construct a 9-patch // of block encodings that represent the rectangle, and write them // to the compressed buffer as necessary. Whether or not the blocks // are overwritten by zeros or just their indices are updated is up // to debate. SkFAIL("Not implemented!"); } // Blit a pattern of pixels defined by a rectangle-clipped mask; We make an // assumption here that if this function gets called, then it will replace all // of the compressed texture blocks that it touches. Hence, two separate calls // to blitMask that have clips next to one another will cause artifacts. Most // of the time, however, this function gets called because constructing the mask // was faster than constructing the RLE for blitAntiH, and this function will // only be called once. #ifdef SK_DEBUG bool fBlitMaskCalled; #endif void blitMask(const SkMask& mask, const SkIRect& clip) override { // Assumptions: SkASSERT(!fBlitMaskCalled); SkDEBUGCODE(fBlitMaskCalled = true); SkASSERT(SkMask::kA8_Format == mask.fFormat); SkASSERT(mask.fBounds.contains(clip)); // Start from largest block boundary less than the clip boundaries. const int startI = BlockDim * (clip.left() / BlockDim); const int startJ = BlockDim * (clip.top() / BlockDim); for (int j = startJ; j < clip.bottom(); j += BlockDim) { // Get the destination for this block row uint8_t* dst = this->getBlock(startI, j); for (int i = startI; i < clip.right(); i += BlockDim) { // At this point, the block should intersect the clip. SkASSERT(SkIRect::IntersectsNoEmptyCheck( SkIRect::MakeXYWH(i, j, BlockDim, BlockDim), clip)); // Do we need to pad it? if (i < clip.left() || j < clip.top() || i + BlockDim > clip.right() || j + BlockDim > clip.bottom()) { uint8_t block[BlockDim*BlockDim]; memset(block, 0, sizeof(block)); const int startX = SkMax32(i, clip.left()); const int startY = SkMax32(j, clip.top()); const int endX = SkMin32(i + BlockDim, clip.right()); const int endY = SkMin32(j + BlockDim, clip.bottom()); for (int y = startY; y < endY; ++y) { const int col = startX - i; const int row = y - j; const int valsWide = endX - startX; SkASSERT(valsWide <= BlockDim); SkASSERT(0 <= col && col < BlockDim); SkASSERT(0 <= row && row < BlockDim); memcpy(block + row*BlockDim + col, mask.getAddr8(startX, j + row), valsWide); } CompressorType::CompressA8Horizontal(dst, block, BlockDim); } else { // Otherwise, just compress it. uint8_t*const src = mask.getAddr8(i, j); const uint32_t rb = mask.fRowBytes; CompressorType::CompressA8Horizontal(dst, src, rb); } dst += EncodedBlockSize; } } } // If the blitter just sets a single value for each pixel, return the // bitmap it draws into, and assign value. If not, return NULL and ignore // the value parameter. const SkBitmap* justAnOpaqueColor(uint32_t* value) override { return NULL; } /** * Compressed texture blitters only really work correctly if they get * BlockDim rows at a time. That being said, this blitter tries it's best * to preserve semantics if blitAntiH doesn't get called in too many * weird ways... */ int requestRowsPreserved() const override { return BlockDim; } private: static const int kPixelsPerBlock = BlockDim * BlockDim; // The longest possible run of pixels that this blitter will receive. // This is initialized in the constructor to 0x7FFE, which is one less // than the largest positive 16-bit integer. We make sure that it's one // less for debugging purposes. We also don't make this variable static // in order to make sure that we can construct a valid pointer to it. const int16_t kLongestRun; // Usually used in conjunction with kLongestRun. This is initialized to // zero. const SkAlpha kZeroAlpha; // This is the information that we buffer whenever we're asked to blit // a row with this blitter. struct BufferedRun { const SkAlpha* fAlphas; const int16_t* fRuns; int fX, fY; } fBufferedRuns[BlockDim]; // The next row [0, BlockDim) that we need to blit. int fNextRun; // The width and height of the image that we're blitting const int fWidth; const int fHeight; // The compressed buffer that we're blitting into. It is assumed that the buffer // is large enough to store a compressed image of size fWidth*fHeight. void* const fBuffer; // Various utility functions int blocksWide() const { return fWidth / BlockDim; } int blocksTall() const { return fHeight / BlockDim; } int totalBlocks() const { return (fWidth * fHeight) / kPixelsPerBlock; } // Returns the block index for the block containing pixel (x, y). Block // indices start at zero and proceed in raster order. int getBlockOffset(int x, int y) const { SkASSERT(x < fWidth); SkASSERT(y < fHeight); const int blockCol = x / BlockDim; const int blockRow = y / BlockDim; return blockRow * this->blocksWide() + blockCol; } // Returns a pointer to the block containing pixel (x, y) uint8_t *getBlock(int x, int y) const { uint8_t* ptr = reinterpret_cast<uint8_t*>(fBuffer); return ptr + EncodedBlockSize*this->getBlockOffset(x, y); } // Updates the block whose columns are stored in block. curAlphai is expected // to store the alpha values that will be placed within each of the columns in // the range [col, col+colsLeft). typedef uint32_t Column[BlockDim/4]; typedef uint32_t Block[BlockDim][BlockDim/4]; inline void updateBlockColumns(Block block, const int col, const int colsLeft, const Column curAlphai) { SkASSERT(block); SkASSERT(col + colsLeft <= BlockDim); for (int i = col; i < (col + colsLeft); ++i) { memcpy(block[i], curAlphai, sizeof(Column)); } } // The following function writes the buffered runs to compressed blocks. // If fNextRun < BlockDim, then we fill the runs that we haven't buffered with // the constant zero buffer. void flushRuns() { // If we don't have any runs, then just return. if (0 == fNextRun) { return; } #ifndef NDEBUG // Make sure that if we have any runs, they all match for (int i = 1; i < fNextRun; ++i) { SkASSERT(fBufferedRuns[i].fY == fBufferedRuns[i-1].fY + 1); SkASSERT(fBufferedRuns[i].fX == fBufferedRuns[i-1].fX); } #endif // If we don't have as many runs as we have rows, fill in the remaining // runs with constant zeros. for (int i = fNextRun; i < BlockDim; ++i) { fBufferedRuns[i].fY = fBufferedRuns[0].fY + i; fBufferedRuns[i].fX = fBufferedRuns[0].fX; fBufferedRuns[i].fAlphas = &kZeroAlpha; fBufferedRuns[i].fRuns = &kLongestRun; } // Make sure that our assumptions aren't violated. SkASSERT(fNextRun > 0 && fNextRun <= BlockDim); SkASSERT((fBufferedRuns[0].fY % BlockDim) == 0); // The following logic walks BlockDim rows at a time and outputs compressed // blocks to the buffer passed into the constructor. // We do the following: // // c1 c2 c3 c4 // ----------------------------------------------------------------------- // ... | | | | | ----> fBufferedRuns[0] // ----------------------------------------------------------------------- // ... | | | | | ----> fBufferedRuns[1] // ----------------------------------------------------------------------- // ... | | | | | ----> fBufferedRuns[2] // ----------------------------------------------------------------------- // ... | | | | | ----> fBufferedRuns[3] // ----------------------------------------------------------------------- // // curX -- the macro X value that we've gotten to. // c[BlockDim] -- the buffers that represent the columns of the current block // that we're operating on // curAlphaColumn -- buffer containing the column of alpha values from fBufferedRuns. // nextX -- for each run, the next point at which we need to update curAlphaColumn // after the value of curX. // finalX -- the minimum of all the nextX values. // // curX advances to finalX outputting any blocks that it passes along // the way. Since finalX will not change when we reach the end of a // run, the termination criteria will be whenever curX == finalX at the // end of a loop. // Setup: Block block; sk_bzero(block, sizeof(block)); Column curAlphaColumn; sk_bzero(curAlphaColumn, sizeof(curAlphaColumn)); SkAlpha *curAlpha = reinterpret_cast<SkAlpha*>(&curAlphaColumn); int nextX[BlockDim]; for (int i = 0; i < BlockDim; ++i) { nextX[i] = 0x7FFFFF; } uint8_t* outPtr = this->getBlock(fBufferedRuns[0].fX, fBufferedRuns[0].fY); // Populate the first set of runs and figure out how far we need to // advance on the first step int curX = 0; int finalX = 0xFFFFF; for (int i = 0; i < BlockDim; ++i) { nextX[i] = *(fBufferedRuns[i].fRuns); curAlpha[i] = *(fBufferedRuns[i].fAlphas); finalX = SkMin32(nextX[i], finalX); } // Make sure that we have a valid right-bound X value SkASSERT(finalX < 0xFFFFF); // If the finalX is the longest run, then just blit until we have // width... if (kLongestRun == finalX) { finalX = fWidth; } // Run the blitter... while (curX != finalX) { SkASSERT(finalX >= curX); // Do we need to populate the rest of the block? if ((finalX - (BlockDim*(curX / BlockDim))) >= BlockDim) { const int col = curX % BlockDim; const int colsLeft = BlockDim - col; SkASSERT(curX + colsLeft <= finalX); this->updateBlockColumns(block, col, colsLeft, curAlphaColumn); // Write this block CompressorType::CompressA8Vertical(outPtr, reinterpret_cast<uint8_t*>(block)); outPtr += EncodedBlockSize; curX += colsLeft; } // If we can advance even further, then just keep memsetting the block if ((finalX - curX) >= BlockDim) { SkASSERT((curX % BlockDim) == 0); const int col = 0; const int colsLeft = BlockDim; this->updateBlockColumns(block, col, colsLeft, curAlphaColumn); // While we can keep advancing, just keep writing the block. uint8_t lastBlock[EncodedBlockSize]; CompressorType::CompressA8Vertical(lastBlock, reinterpret_cast<uint8_t*>(block)); while((finalX - curX) >= BlockDim) { memcpy(outPtr, lastBlock, EncodedBlockSize); outPtr += EncodedBlockSize; curX += BlockDim; } } // If we haven't advanced within the block then do so. if (curX < finalX) { const int col = curX % BlockDim; const int colsLeft = finalX - curX; this->updateBlockColumns(block, col, colsLeft, curAlphaColumn); curX += colsLeft; } SkASSERT(curX == finalX); // Figure out what the next advancement is... if (finalX < fWidth) { for (int i = 0; i < BlockDim; ++i) { if (nextX[i] == finalX) { const int16_t run = *(fBufferedRuns[i].fRuns); fBufferedRuns[i].fRuns += run; fBufferedRuns[i].fAlphas += run; curAlpha[i] = *(fBufferedRuns[i].fAlphas); nextX[i] += *(fBufferedRuns[i].fRuns); } } finalX = 0xFFFFF; for (int i = 0; i < BlockDim; ++i) { finalX = SkMin32(nextX[i], finalX); } } else { curX = finalX; } } // If we didn't land on a block boundary, output the block... if ((curX % BlockDim) > 0) { #ifdef SK_DEBUG for (int i = 0; i < BlockDim; ++i) { SkASSERT(nextX[i] == kLongestRun || nextX[i] == curX); } #endif const int col = curX % BlockDim; const int colsLeft = BlockDim - col; memset(curAlphaColumn, 0, sizeof(curAlphaColumn)); this->updateBlockColumns(block, col, colsLeft, curAlphaColumn); CompressorType::CompressA8Vertical(outPtr, reinterpret_cast<uint8_t*>(block)); } fNextRun = 0; } #if PEDANTIC_BLIT_RECT void updateBlockRow(int x, int y, int width, int height, int blockRow, int startBlockX, int endBlockX) { if (0 == width || 0 == height || startBlockX == endBlockX) { return; } uint8_t* dst = this->getBlock(startBlockX, BlockDim * (y / BlockDim)); // One horizontal strip to update uint8_t mask[BlockDim*BlockDim]; memset(mask, 0, sizeof(mask)); // Update the left cap int blockX = startBlockX; const int yoff = y - blockRow; for (int j = 0; j < height; ++j) { const int xoff = x - blockX; memset(mask + (j + yoff)*BlockDim + xoff, 0xFF, BlockDim - xoff); } CompressorType::UpdateBlock(dst, mask, BlockDim, mask); dst += EncodedBlockSize; blockX += BlockDim; // Update the middle if (blockX < endBlockX) { for (int j = 0; j < height; ++j) { memset(mask + (j + yoff)*BlockDim, 0xFF, BlockDim); } while (blockX < endBlockX) { CompressorType::UpdateBlock(dst, mask, BlockDim, mask); dst += EncodedBlockSize; blockX += BlockDim; } } SkASSERT(endBlockX == blockX); // Update the right cap (if we need to) if (x + width > endBlockX) { memset(mask, 0, sizeof(mask)); for (int j = 0; j < height; ++j) { const int xoff = (x+width-blockX); memset(mask + (j+yoff)*BlockDim, 0xFF, xoff); } CompressorType::UpdateBlock(dst, mask, BlockDim, mask); } } void updateBlockCol(int x, int y, int width, int height, int blockCol, int startBlockY, int endBlockY) { if (0 == width || 0 == height || startBlockY == endBlockY) { return; } // One vertical strip to update uint8_t mask[BlockDim*BlockDim]; memset(mask, 0, sizeof(mask)); const int maskX0 = x - blockCol; const int maskWidth = maskX0 + width; SkASSERT(maskWidth <= BlockDim); // Update the top cap int blockY = startBlockY; for (int j = (y - blockY); j < BlockDim; ++j) { memset(mask + maskX0 + j*BlockDim, 0xFF, maskWidth); } CompressorType::UpdateBlock(this->getBlock(blockCol, blockY), mask, BlockDim, mask); blockY += BlockDim; // Update middle if (blockY < endBlockY) { for (int j = 0; j < BlockDim; ++j) { memset(mask + maskX0 + j*BlockDim, 0xFF, maskWidth); } while (blockY < endBlockY) { CompressorType::UpdateBlock(this->getBlock(blockCol, blockY), mask, BlockDim, mask); blockY += BlockDim; } } SkASSERT(endBlockY == blockY); // Update bottom if (y + height > endBlockY) { for (int j = y+height; j < endBlockY + BlockDim; ++j) { memset(mask + (j-endBlockY)*BlockDim, 0, BlockDim); } CompressorType::UpdateBlock(this->getBlock(blockCol, blockY), mask, BlockDim, mask); } } #endif // PEDANTIC_BLIT_RECT }; } // namespace SkTextureCompressor #endif // SkTextureCompressor_Blitter_DEFINED
[ "townwang@retronix.com.tw" ]
townwang@retronix.com.tw
284e21121d7202f31145a26d5edd76828e6b391b
52a9241361bd179c437f85d9c307e0a8d27f5c72
/148.cpp
cf395aa8a73010b6fdbac40dbc7e55a883ba40e3
[]
no_license
xingoxu/leetcode
5b710a21f3a220655dffa80300bf0515081a93d0
aa109ce7004662e4be7f5771e80a19cbe22bb287
refs/heads/master
2020-05-23T15:10:30.949381
2020-02-27T00:10:01
2020-02-27T00:10:01
186,820,252
1
0
null
null
null
null
UTF-8
C++
false
false
3,189
cpp
#include <iostream> #include <vector> #include <sstream> #include <stack> #include <unordered_map> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; void trimLeftTrailingSpaces(string &input) { input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { return !isspace(ch); })); } void trimRightTrailingSpaces(string &input) { input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { return !isspace(ch); }) .base(), input.end()); } vector<int> stringToIntegerVector(string input) { vector<int> output; trimLeftTrailingSpaces(input); trimRightTrailingSpaces(input); input = input.substr(1, input.length() - 2); stringstream ss; ss.str(input); string item; char delim = ','; while (getline(ss, item, delim)) { output.push_back(stoi(item)); } return output; } ListNode *stringToListNode(string input) { // Generate list from the input vector<int> list = stringToIntegerVector(input); // Now convert that list into linked list ListNode *dummyRoot = new ListNode(0); ListNode *ptr = dummyRoot; for (int item : list) { ptr->next = new ListNode(item); ptr = ptr->next; } ptr = dummyRoot->next; delete dummyRoot; return ptr; } string listNodeToString(ListNode *node) { if (node == nullptr) { return "[]"; } string result; while (node) { result += to_string(node->val) + ", "; node = node->next; } return "[" + result.substr(0, result.length() - 2) + "]"; } class Solution { ListNode *split(ListNode *head, int num) { int count = 1; while (head && count < num) { ++count; head = head->next; } ListNode *nextHead = NULL; if (head){ nextHead = head->next; head->next = NULL; } return nextHead; } ListNode *merge(ListNode *a, ListNode *b, ListNode *header) { auto cursor = header; while (a && b) { if(a->val < b->val) { cursor->next = a; a = a->next; } else { cursor->next = b; b = b->next; } cursor = cursor->next; cursor->next = NULL; } if (a) { cursor->next = a; } else { cursor->next = b; } while (cursor && cursor->next) { cursor = cursor->next; } // return end return cursor; } public: ListNode *sortList(ListNode *head) { ListNode *cursor = head; int length = 0; // get length while(cursor) { ++length; cursor = cursor->next; } auto tmpNode = ListNode(0); tmpNode.next = head; int i = 1; for (; i < length; i = i << 1) { cursor = tmpNode.next; ListNode *lastEnd = &tmpNode; while(cursor) { auto left = cursor; auto right = split(cursor, i); cursor = split(right, i); lastEnd = merge(left, right, lastEnd); } } return tmpNode.next; } }; int main() { ListNode *head = stringToListNode("[4,2,1,3]"); cout << listNodeToString(Solution().sortList(head)) << endl; return 0; }
[ "xingoxu@gmail.com" ]
xingoxu@gmail.com
f860a1cc4ccc07a367e9519ede0439c0aea78cb3
5fdb36b286e07309e05890e3222a3d8b754c05cc
/GUI Simulation/clix.h
290ee79ee85cd967b863a7dc60a7f9c0dfb6f4ac
[ "MIT" ]
permissive
ADyson/CUDAMultislice
638a659f4d62dfe288272a16cfa471e6b1705b58
27726b57b58213ee71318680ffe5ec764b69dbbb
refs/heads/master
2021-03-13T00:01:50.525599
2014-08-25T11:41:12
2014-08-25T11:41:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,809
h
// ------------------------------------------------------------------------------------------- // // clix.h // // Marshals strings between .NET and C++ using C++/CLI (Visual C++ 2005 and later only). // Faster and cleaner than the System::Interop method because it uses garbage collected memory. // Use at your own leisure. No warranties whatsoever provided. // // Original code by Markus Ewald (http://www.nuclex.org/articles/marshaling-strings-in-cxx-cli) // Updated version including several improvements suggested by Neil Hunt // ------------------------------------------------------------------------------------------- // #pragma once #include <string> #include <vcclr.h> // CLI extensions namespace namespace clix { /// <summary>Encoding types for strings</summary> enum Encoding { /// <summary>ANSI encoding</summary> /// <remarks> /// This is the default encoding you've most likely been using all around in C++. ANSI /// means 8 Bit encoding with character codes depending on the system's selected code page. /// <remarks> E_ANSI, /// <summary>UTF-8 encoding</summary> /// <remarks> /// This is the encoding commonly used for multilingual C++ strings. All ASCII characters /// (0-127) will be represented as single bytes. Be aware that UTF-8 uses more than one /// byte for extended characters, so std::string::length() might not reflect the actual /// length of the string in characters if it contains any non-ASCII characters. /// <remarks> E_UTF8, /// <summary>UTF-16 encoding</summary> /// <remarks> /// This is the suggested to be used for marshaling and the native encoding of .NET /// strings. It is similar to UTF-8 but uses a minimum of two bytes per character, making /// the number of bytes required for a given string better predictable. Be aware, however, /// that UTF-16 can still use more than two bytes for a character, so std::wstring::length() /// might not reflect the actual length of the string. /// </remarks> E_UTF16, E_UNICODE = E_UTF16 }; // Ignore this if you're just scanning the headers for informations :-) /* All this template stuff might seem like overkill, but it is well thought out and enables you to use a readable and convenient call while still keeping the highest possible code efficiency due to compile-time evaluation of the required conversion path. */ namespace detail { // Get C++ string type for specified encoding template<Encoding encoding> struct StringTypeSelecter; template<> struct StringTypeSelecter<E_ANSI> { typedef std::string Type; }; template<> struct StringTypeSelecter<E_UTF8> { typedef std::string Type; }; template<> struct StringTypeSelecter<E_UTF16> { typedef std::wstring Type; }; // Compile-time check whether a given type is a managed System::String template<typename StringType> struct IsManagedString { enum { Result = false }; }; template<> struct IsManagedString<System::String ^> { enum { Result = true }; }; // Compile-time selection of two types depending on a boolean expression template<bool expression> struct Select; template<> struct Select<false> { template<typename TrueType, typename FalseType> struct Type { typedef FalseType Result; }; }; template<> struct Select<true> { template<typename TrueType, typename FalseType> struct Type { typedef TrueType Result; }; }; // Direction of the marshaling process enum MarshalingDirection { CxxFromNet, NetFromCxx }; // The actual marshaling code template<MarshalingDirection direction> struct StringMarshaler; // Marshals to .NET from C++ strings template<> struct StringMarshaler<NetFromCxx> { template<Encoding encoding, typename SourceType> static System::String ^marshal(const SourceType &string) { // Constructs a std::[w]string in case someone gave us a char * to choke on return marshalCxxString<encoding, SourceType>(string); } template<Encoding encoding, typename SourceType> static System::String ^marshalCxxString( const typename StringTypeSelecter<encoding>::Type &cxxString ) { typedef typename StringTypeSelecter<encoding>::Type SourceStringType; size_t byteCount = cxxString.length() * sizeof(SourceStringType::value_type); // Copy the C++ string contents into a managed array of bytes array<unsigned char> ^bytes = gcnew array<unsigned char>(byteCount); { pin_ptr<unsigned char> pinnedBytes = &bytes[0]; memcpy(pinnedBytes, cxxString.c_str(), byteCount); } // Now let one of .NET's encoding classes do the rest return decode<encoding>(bytes); } private: // Converts a byte array based on the selected encoding template<Encoding encoding> static System::String ^decode(array<unsigned char> ^bytes); template<> static System::String ^decode<E_ANSI>(array<unsigned char> ^bytes) { return System::Text::Encoding::Default->GetString(bytes); } template<> static System::String ^decode<E_UTF8>(array<unsigned char> ^bytes) { return System::Text::Encoding::UTF8->GetString(bytes); } template<> static System::String ^decode<E_UTF16>(array<unsigned char> ^bytes) { return System::Text::Encoding::Unicode->GetString(bytes); } }; // Marshals to C++ strings from .NET template<> struct StringMarshaler<CxxFromNet> { template<Encoding encoding, typename SourceType> static typename detail::StringTypeSelecter<encoding>::Type marshal( System::String ^string ) { typedef typename StringTypeSelecter<encoding>::Type StringType; // First, we use .NET's encoding classes to convert the string into a byte array array<unsigned char> ^bytes = encode<encoding>(string); // Then we construct our native string from that byte array pin_ptr<unsigned char> pinnedBytes(&bytes[0]); return StringType( reinterpret_cast<StringType::value_type *>(static_cast<unsigned char *>(pinnedBytes)), bytes->Length / sizeof(StringType::value_type) ); } template<> static std::wstring marshal<E_UTF16, System::String ^>( System::String ^string ) { // We can directly accesss the characters in the managed string pin_ptr<const wchar_t> pinnedChars(::PtrToStringChars(string)); return std::wstring(pinnedChars, string->Length); } private: // Converts a string based on the selected encoding template<Encoding encoding> static array<unsigned char> ^encode(System::String ^string); template<> static array<unsigned char> ^encode<E_ANSI>(System::String ^string) { return System::Text::Encoding::Default->GetBytes(string); } template<> static array<unsigned char> ^encode<E_UTF8>(System::String ^string) { return System::Text::Encoding::UTF8->GetBytes(string); } template<> static array<unsigned char> ^encode<E_UTF16>(System::String ^string) { return System::Text::Encoding::Unicode->GetBytes(string); } }; } // namespace detail // ----------------------------------------------------------------------------------------- // // clix::marshalString() // ----------------------------------------------------------------------------------------- // /// <summary>Marshals strings between .NET managed and C++ native</summary> /// <remarks> /// This all-in-one function marshals native C++ strings to .NET strings and vice versa. /// You have to specify an encoding to use for the conversion, which always applies to the /// native C++ string as .NET always uses UTF-16 for its own strings. /// </remarks> /// <param name="string">String to be marshalled to the other side</param> /// <returns>The marshaled representation of the string</returns> template<Encoding encoding, typename SourceType> typename detail::Select<detail::IsManagedString<SourceType>::Result>::Type< typename detail::StringTypeSelecter<encoding>::Type, System::String ^ >::Result marshalString(SourceType string) { // Pass on the call to our nifty template routines return detail::StringMarshaler< detail::IsManagedString<SourceType>::Result ? detail::CxxFromNet : detail::NetFromCxx >::marshal<encoding, SourceType>(string); } } // namespace clix
[ "dyson.adam@gmail.com" ]
dyson.adam@gmail.com
4f6e8f727aa51c4848aede4e1f94857fc56237e2
54ab0f79f5d68f4732ca7d205f72ecef99862303
/aten/src/ATen/native/quantized/cpu/XnnpackUtils.h
12e4fbbf1e76ccbce83608760da343bfbd7828e8
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
csarofeen/pytorch
a9dd0f8ffa0642d72df2d5e109a8b4d9c2389cbc
e8557ec5e064608577f81e51ccfe7c36c917cb0f
refs/heads/devel
2023-04-30T02:42:13.558738
2023-03-14T00:50:01
2023-03-14T00:50:01
88,071,101
35
10
NOASSERTION
2023-06-21T17:37:30
2017-04-12T16:02:31
C++
UTF-8
C++
false
false
11,876
h
#pragma once #ifdef USE_XNNPACK #include <cstdint> #include <ATen/core/Tensor.h> #include <ATen/native/xnnpack/Common.h> using xnnpack_operator = at::native::xnnpack::Operator; namespace at { namespace native { namespace xnnp_utils { /* * Return shape in the same order as the memory format * e.g. channels_last will return NHWC instead of NCHW */ std::vector<size_t> get_mem_format_aware_shape(const at::Tensor& in); /* * Input is always int8_t, output can be [int8_t, uint8_t]. * input + offset = output * int8_t + 128 = uint8_t * int8_t + 0 = int8_t */ template <typename PT> void q8_copy_int8_weight_and_add_offset(const at::Tensor& in, at::Tensor& out); template <int kSpatialDim> Tensor convert_conv_weights_to_channel_last_tensor( const at::Tensor& src, int groups, bool transpose); /* * Series of create wrapper functions to call xnn_create_[de]conv* functions. */ C10_ALWAYS_INLINE enum xnn_status xnnp_create_convolution2d_nhwc( uint32_t pad_top, uint32_t pad_right, uint32_t pad_bottom, uint32_t pad_left, uint32_t kernel_h, uint32_t kernel_w, uint32_t stride_h, uint32_t stride_w, uint32_t dilation_h, uint32_t dilation_w, uint32_t groups, size_t group_input_channels, size_t group_output_channels, size_t ip_chan_stride, size_t op_chan_stride, int8_t izp, float ip_scale, int8_t kzp, const float* k_scales, const int8_t* kernel, const int32_t* bias, int8_t ozp, float op_scale, int8_t op_min, int8_t op_max, uint32_t flags, xnn_operator_t* op, bool per_channel, bool transpose) { /* Symmetric quantization forces kzp = 0 */ TORCH_CHECK(!kzp, "XNNPACK Q[SC]8 conv kernels expects kernel zero point to be zero." "But got: ", kzp); if (transpose) { TORCH_CHECK(!per_channel, "XNNPACK Q[SC]8 does not have a per channel deconvolution!"); return xnn_create_deconvolution2d_nhwc_qs8( pad_top, /* uint32_t output_padding_top */ pad_right, /* uint32_t output_padding_right */ pad_bottom, /* uint32_t output_padding_bottom */ pad_left, /* uint32_t output_padding_left */ kernel_h, /* uint32_t kernel_height */ kernel_w, /* uint32_t kernel_width */ stride_h, /* uint32_t stride_height */ stride_w, /* uint32_t stride_width */ dilation_h, /* uint32_t dilation_height */ dilation_w, /* uint32_t dilation_width */ groups, /* uint32_t groups */ group_input_channels, /* size_t group_input_channels */ group_output_channels, /* size_t group_output_channels */ ip_chan_stride, /* size_t input_pixel_stride */ op_chan_stride, /* size_t output_pixel_stride */ izp, /* int8_t input_zero_point */ ip_scale, /* float input_scale */ k_scales[0], /* float kernel_scale */ kernel, /* const int8_t* kernel */ bias, /* const int32_t* bias */ ozp, /* int8_t output_zero_point */ op_scale, /* float output_scale */ op_min, /* int8_t output_min */ op_max, /* int8_t output_max */ flags, /* uint32_t flags */ op); /* xnn_operator_t* deconvolution_op_out */ } if (!per_channel) { return xnn_create_convolution2d_nhwc_qs8( pad_top, /* uint32_t input_padding_top */ pad_right, /* uint32_t input_padding_right */ pad_bottom, /* uint32_t input_padding_bottom */ pad_left, /* uint32_t input_padding_left */ kernel_h, /* uint32_t kernel_height */ kernel_w, /* uint32_t kernel_width */ stride_h, /* uint32_t subsampling_height */ stride_w, /* uint32_t subsampling_width */ dilation_h, /* uint32_t dilation_height */ dilation_w, /* uint32_t dilation_width */ groups, /* uint32_t groups */ group_input_channels, /* size_t group_input_channels */ group_output_channels, /* size_t group_output_channels*/ ip_chan_stride, /* size_t input_channel_stride */ op_chan_stride, /* size_t output_channel_stride */ izp, /* int8_t input_zero_point */ ip_scale, /* float input_scale */ k_scales[0], /* float kernel_scale */ kernel, /* const int8_t* kernel */ bias, /* const int32_t* bias */ ozp, /* int8_t output_zero_point */ op_scale, /* float output_scale */ op_min, /* int8_t output_min */ op_max, /* int8_t output_max */ flags, /* uint32_t flags */ op); /* xnn_operator_t* convolution_op_out */ } else { /* per_channel */ return xnn_create_convolution2d_nhwc_qc8( pad_top, /* uint32_t input_padding_top */ pad_right, /* uint32_t input_padding_right */ pad_bottom, /* uint32_t input_padding_bottom */ pad_left, /* uint32_t input_padding_left */ kernel_h, /* uint32_t kernel_height */ kernel_w, /* uint32_t kernel_width */ stride_h, /* uint32_t subsampling_height */ stride_w, /* uint32_t subsampling_width */ dilation_h, /* uint32_t dilation_height */ dilation_w, /* uint32_t dilation_width */ groups, /* uint32_t groups */ group_input_channels, /* size_t group_input_channels */ group_output_channels, /* size_t group_output_channels*/ ip_chan_stride, /* size_t input_channel_stride */ op_chan_stride, /* size_t output_channel_stride */ izp, /* int8_t input_zero_point */ ip_scale, /* float input_scale */ k_scales, /* const float* kernel_scale */ kernel, /* const int8_t* kernel */ bias, /* const int32_t* bias */ ozp, /* int8_t output_zero_point */ op_scale, /* float output_scale */ op_min, /* int8_t output_min */ op_max, /* int8_t output_max */ flags, /* uint32_t flags */ op); /* xnn_operator_t* convolution_op_out */ } } /* * Series of setup wrapper functions to call xnn_setup_[de]conv* functions. */ C10_ALWAYS_INLINE enum xnn_status xnnp_setup_convolution2d_nhwc( xnn_operator_t op, size_t batch, size_t in_h, size_t in_w, const int8_t* inp, int8_t* outp, pthreadpool_t pt_pool, bool per_channel = false, bool transpose = false, uint32_t adj_h = 0, uint32_t adj_w = 0) { if(transpose) { TORCH_CHECK(!per_channel, "XNNPACK Q[SC]8 does not have a per channel deconvolution!"); return xnn_setup_deconvolution2d_nhwc_qs8( op, /* xnn_operator_t deconvolution_op */ batch, /* size_t batch_size */ in_h, /* size_t input_height */ in_w, /* size_t input_width */ adj_h, /* uint32_t adjustment_height */ adj_w, /* uint32_t adjustment_width */ inp, /* const int8_t* input */ outp, /* int8_t* output */ pt_pool); /* pthreadpool_t threadpool */ } if (!per_channel) { return xnn_setup_convolution2d_nhwc_qs8( op, /* xnn_operator_t convolution_op */ batch, /* size_t batch_size */ in_h, /* size_t input_height */ in_w, /* size_t input_width */ inp, /* const int8_t* input */ outp, /* int8_t* output */ pt_pool); /* pthreadpool_t threadpool */ } else { /* per_channel */ return xnn_setup_convolution2d_nhwc_qc8( op, /* xnn_operator_t convolution_op */ batch, /* size_t batch_size */ in_h, /* size_t input_height */ in_w, /* size_t input_width */ inp, /* const int8_t* input */ outp, /* int8_t* output */ pt_pool); /* pthreadpool_t threadpool */ } } /* * Series of wrapper functions to call xnn_create* and xnn_setup* * functions for linear */ C10_ALWAYS_INLINE enum xnn_status xnnp_create_fully_connected_nc( size_t input_channels, size_t output_channels, size_t input_stride, size_t output_stride, int8_t input_zero_point, float input_scale, int8_t kernel_zero_point, float kernel_scale, const int8_t* kernel, const int32_t* bias, int8_t output_zero_point, float output_scale, int8_t output_min, int8_t output_max, uint32_t flags, xnn_operator_t* fully_connected_op_out) { /* Symmetric quantization forces kzp = 0 */ TORCH_CHECK(!kernel_zero_point, "XNNPACK QS8 linear kernel expects kernel zero point to be zero." "But got: ", kernel_zero_point); return xnn_create_fully_connected_nc_qs8( input_channels, /* size_t input_channels */ output_channels, /* size_t output_channels */ input_stride, /* size_t input_stride */ output_stride, /* size_t output_stride */ input_zero_point, /* int8_t input_zero_point */ input_scale, /* float input_scale */ kernel_scale, /* float kernel_scale */ kernel, /* const int8_t* kernel */ bias, /* const int32_t* bias */ output_zero_point, /* int8_t output_zero_point */ output_scale, /* float output_scale */ output_min, /* int8_t output_min */ output_max, /* int8_t output_max */ flags, /* uint32_t flags */ fully_connected_op_out); /* xnn_operator_t* fully_connected_op_out */ } C10_ALWAYS_INLINE enum xnn_status xnnp_setup_fully_connected_nc( xnn_operator_t fully_connected_op, size_t batch_size, const int8_t* input, int8_t* output, pthreadpool_t threadpool) { return xnn_setup_fully_connected_nc_qs8( fully_connected_op, /* xnn_operator_t fully_connected_op */ batch_size, /* size_t batch_size */ input, /* const int8_t* input */ output, /* int8_t* output */ threadpool); /* pthreadpool_t threadpool */ } } // namespace xnnp_utils } // namespace native } // namespace at #endif // USE_XNNPACK
[ "pytorchmergebot@users.noreply.github.com" ]
pytorchmergebot@users.noreply.github.com
f24815e77f5dcbe5fb8e9bac245bae916124661b
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/Editor/BlueprintGraph/Classes/K2Node_PureAssignmentStatement.h
6d01953e9e06c756fc752897512d817c3e710532
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
1,359
h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "K2Node.h" #include "K2Node_PureAssignmentStatement.generated.h" class UEdGraphPin; UCLASS(MinimalAPI) class UK2Node_PureAssignmentStatement : public UK2Node { GENERATED_UCLASS_BODY() // Name of the Variable pin for this node static FString VariablePinName; // Name of the Value pin for this node static FString ValuePinName; // Name of the output pin for this node static FString OutputPinName; //~ Begin UEdGraphNode Interface virtual void AllocateDefaultPins() override; //~ End UEdGraphNode Interface //~ Begin UK2Node Interface virtual bool IsNodePure() const override { return true; } virtual void NotifyPinConnectionListChanged(UEdGraphPin* Pin) override; virtual class FNodeHandlingFunctor* CreateNodeHandler(class FKismetCompilerContext& CompilerContext) const override; virtual int32 GetNodeRefreshPriority() const override { return EBaseNodeRefreshPriority::Low_UsesDependentWildcard; } //~ End UK2Node Interface /** Get the Then output pin */ BLUEPRINTGRAPH_API UEdGraphPin* GetOutputPin() const; /** Get the Variable input pin */ BLUEPRINTGRAPH_API UEdGraphPin* GetVariablePin() const; /** Get the Value input pin */ BLUEPRINTGRAPH_API UEdGraphPin* GetValuePin() const; };
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
d77456196c3c51e1442c83e7c15d5e59b636c5cc
67f988dedfd8ae049d982d1a8213bb83233d90de
/external/chromium/chrome/browser/sync/glue/bridged_invalidator_unittest.cc
110aa635c0d375ea74b276bfefecd5c3002522b8
[ "BSD-3-Clause" ]
permissive
opensourceyouthprogramming/h5vcc
94a668a9384cc3096a365396b5e4d1d3e02aacc4
d55d074539ba4555e69e9b9a41e5deb9b9d26c5b
refs/heads/master
2020-04-20T04:57:47.419922
2019-02-12T00:56:14
2019-02-12T00:56:14
168,643,719
1
1
null
2019-02-12T00:49:49
2019-02-01T04:47:32
C++
UTF-8
C++
false
false
6,250
cc
// 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. #include "chrome/browser/sync/glue/bridged_invalidator.h" #include <string> #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread.h" #include "chrome/browser/sync/glue/chrome_sync_notification_bridge.h" #include "chrome/test/base/profile_mock.h" #include "content/public/test/test_browser_thread.h" #include "google/cacheinvalidation/include/types.h" #include "sync/internal_api/public/base/model_type.h" #include "sync/internal_api/public/base/model_type_test_util.h" #include "sync/notifier/fake_invalidation_handler.h" #include "sync/notifier/fake_invalidator.h" #include "sync/notifier/invalidator_test_template.h" #include "sync/notifier/object_id_invalidation_map_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { class InvalidationStateTracker; } // namespace syncer namespace browser_sync { // BridgedInvalidatorTestDelegate has to be visible from the syncer // namespace (where InvalidatorTest lives). class BridgedInvalidatorTestDelegate { public: BridgedInvalidatorTestDelegate() : ui_thread_(content::BrowserThread::UI, &ui_loop_), bridge_(&mock_profile_, ui_loop_.message_loop_proxy()), fake_delegate_(NULL) { // Pump |ui_loop_| to fully initialize |bridge_|. ui_loop_.RunUntilIdle(); } ~BridgedInvalidatorTestDelegate() { DestroyInvalidator(); } void CreateInvalidator( const std::string& /* initial_state (unused) */, const base::WeakPtr<syncer::InvalidationStateTracker>& /* invalidation_state_tracker (unused) */) { DCHECK(!fake_delegate_); DCHECK(!invalidator_.get()); fake_delegate_ = new syncer::FakeInvalidator(); invalidator_.reset(new BridgedInvalidator( &bridge_, fake_delegate_, syncer::DEFAULT_INVALIDATION_ERROR)); } BridgedInvalidator* GetInvalidator() { return invalidator_.get(); } ChromeSyncNotificationBridge* GetBridge() { return &bridge_; } syncer::FakeInvalidator* GetFakeDelegate() { return fake_delegate_; } void DestroyInvalidator() { invalidator_.reset(); fake_delegate_ = NULL; bridge_.StopForShutdown(); ui_loop_.RunUntilIdle(); } void WaitForInvalidator() { // Do nothing. } void TriggerOnInvalidatorStateChange(syncer::InvalidatorState state) { fake_delegate_->EmitOnInvalidatorStateChange(state); } void TriggerOnIncomingInvalidation( const syncer::ObjectIdInvalidationMap& invalidation_map, syncer::IncomingInvalidationSource source) { fake_delegate_->EmitOnIncomingInvalidation(invalidation_map, source); } static bool InvalidatorHandlesDeprecatedState() { return false; } private: MessageLoop ui_loop_; content::TestBrowserThread ui_thread_; ::testing::NiceMock<ProfileMock> mock_profile_; ChromeSyncNotificationBridge bridge_; // Owned by |invalidator_|. syncer::FakeInvalidator* fake_delegate_; scoped_ptr<BridgedInvalidator> invalidator_; }; namespace { // All tests just verify that each call is passed through to the delegate, with // the exception of RegisterHandler, UnregisterHandler, and // UpdateRegisteredIds, which also verifies the call is forwarded to the // bridge. class BridgedInvalidatorTest : public testing::Test { public: BridgedInvalidatorTest() { delegate_.CreateInvalidator( "fake_state", base::WeakPtr<syncer::InvalidationStateTracker>()); } virtual ~BridgedInvalidatorTest() {} protected: BridgedInvalidatorTestDelegate delegate_; }; TEST_F(BridgedInvalidatorTest, HandlerMethods) { syncer::ObjectIdSet ids; ids.insert(invalidation::ObjectId(1, "id1")); syncer::FakeInvalidationHandler handler; delegate_.GetInvalidator()->RegisterHandler(&handler); EXPECT_TRUE(delegate_.GetFakeDelegate()->IsHandlerRegistered(&handler)); EXPECT_TRUE(delegate_.GetBridge()->IsHandlerRegisteredForTest(&handler)); delegate_.GetInvalidator()->UpdateRegisteredIds(&handler, ids); EXPECT_EQ(ids, delegate_.GetFakeDelegate()->GetRegisteredIds(&handler)); EXPECT_EQ(ids, delegate_.GetBridge()->GetRegisteredIdsForTest(&handler)); delegate_.GetInvalidator()->UnregisterHandler(&handler); EXPECT_FALSE(delegate_.GetFakeDelegate()->IsHandlerRegistered(&handler)); EXPECT_FALSE(delegate_.GetBridge()->IsHandlerRegisteredForTest(&handler)); } TEST_F(BridgedInvalidatorTest, GetInvalidatorState) { EXPECT_EQ(syncer::DEFAULT_INVALIDATION_ERROR, delegate_.GetInvalidator()->GetInvalidatorState()); } TEST_F(BridgedInvalidatorTest, SetUniqueId) { const std::string& unique_id = "unique id"; delegate_.GetInvalidator()->SetUniqueId(unique_id); EXPECT_EQ(unique_id, delegate_.GetFakeDelegate()->GetUniqueId()); } TEST_F(BridgedInvalidatorTest, SetStateDeprecated) { const std::string& state = "state"; delegate_.GetInvalidator()->SetStateDeprecated(state); EXPECT_EQ(state, delegate_.GetFakeDelegate()->GetStateDeprecated()); } TEST_F(BridgedInvalidatorTest, UpdateCredentials) { const std::string& email = "email"; const std::string& token = "token"; delegate_.GetInvalidator()->UpdateCredentials(email, token); EXPECT_EQ(email, delegate_.GetFakeDelegate()->GetCredentialsEmail()); EXPECT_EQ(token, delegate_.GetFakeDelegate()->GetCredentialsToken()); } TEST_F(BridgedInvalidatorTest, SendInvalidation) { syncer::ObjectIdSet ids; ids.insert(invalidation::ObjectId(1, "id1")); ids.insert(invalidation::ObjectId(2, "id2")); const syncer::ObjectIdInvalidationMap& invalidation_map = syncer::ObjectIdSetToInvalidationMap(ids, "payload"); delegate_.GetInvalidator()->SendInvalidation(invalidation_map); EXPECT_THAT(invalidation_map, Eq(delegate_.GetFakeDelegate()->GetLastSentInvalidationMap())); } } // namespace } // namespace browser_sync namespace syncer { namespace { INSTANTIATE_TYPED_TEST_CASE_P( BridgedInvalidatorTest, InvalidatorTest, ::browser_sync::BridgedInvalidatorTestDelegate); } // namespace } // namespace syncer
[ "rjogrady@google.com" ]
rjogrady@google.com
cc06d79739c02464fcf85aeda0aab966cdc9ca5f
9bf8e4bd82ea684dd1f34c42c437faec74616f70
/src/gui/power_gallery.hpp
ae0fb7d4b27d1d34572b1552ab01017275c0f8a0
[]
no_license
tigrangs/ic_modeling
c8a3fcd5612877f53a7e978eca886cdafd25e059
b2e7d3c299bf08f1a755cc11cbda0cc47f944efe
refs/heads/master
2021-05-01T06:26:06.767214
2018-06-20T13:23:21
2018-06-20T13:23:21
121,142,769
0
0
null
null
null
null
UTF-8
C++
false
false
414
hpp
#ifndef POWER_GALLERY_HPP #define POWER_GALLERY_HPP #include <QWidget> namespace core { class ic; } namespace gui { class viewer_3d; class power_gallery : public QWidget { Q_OBJECT public: explicit power_gallery(core::ic*, QWidget *parent = nullptr); private: using layers = QList<viewer_3d*>; private: layers m_layers = {}; }; } #endif // POWER_GALLERY_HPP
[ "programtg@yahoo.com" ]
programtg@yahoo.com
ab3d4bf7a9715372e24fab2ec9e9dadd00e58392
05803cfabffdef2ccdf294fdcbcb6319e31997f4
/src/lib/window_manager_win32.h
b2cc5f43566d2b8930c79800df3099c1a9bd9722
[ "BSD-2-Clause" ]
permissive
abainbridge/trex-warrior
3cedc69d5a69500e5cdde1a393df29e31f005ed9
fac95802ce7efd8dc9c50f915ce8d5891f545640
refs/heads/master
2021-06-02T05:53:21.090486
2015-11-08T19:14:48
2015-11-08T19:14:48
32,854,108
0
0
null
null
null
null
UTF-8
C++
false
false
265
h
#ifndef INCLUDED_WINDOW_MANAGER_WIN32_H #define INCLUDED_WINDOW_MANAGER_WIN32_H class WindowManagerWin32 { public: HWND m_hWnd; HDC m_hDC; HGLRC m_hRC; WindowManagerWin32() : m_hWnd(NULL), m_hDC(NULL), m_hRC(NULL) { } }; #endif
[ "abainbridge2005@gmail.com@ec34d732-e6b3-c456-da3c-2a8e3e90ce8a" ]
abainbridge2005@gmail.com@ec34d732-e6b3-c456-da3c-2a8e3e90ce8a
5e6bd43447446b114a7463c065e38d156efb03a1
a9a84b790be4effadffc755f4f3939245798edd5
/devel/include/franka_control/SetEEFrameResponse.h
ec4fcaee48b42d8a9cd4f5935b16b979a07190ac
[]
no_license
Valkje/panda
bce3e7b2f981e916f06ce0b3d6e5b2cb8506c8ad
6a5177f8d0add40990d17f7027c0573490b52a72
refs/heads/master
2020-03-18T21:18:42.933651
2018-05-29T09:39:21
2018-05-29T09:39:21
135,273,530
1
0
null
null
null
null
UTF-8
C++
false
false
5,721
h
// Generated by gencpp from file franka_control/SetEEFrameResponse.msg // DO NOT EDIT! #ifndef FRANKA_CONTROL_MESSAGE_SETEEFRAMERESPONSE_H #define FRANKA_CONTROL_MESSAGE_SETEEFRAMERESPONSE_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 franka_control { template <class ContainerAllocator> struct SetEEFrameResponse_ { typedef SetEEFrameResponse_<ContainerAllocator> Type; SetEEFrameResponse_() : success(false) , error() { } SetEEFrameResponse_(const ContainerAllocator& _alloc) : success(false) , error(_alloc) { (void)_alloc; } typedef uint8_t _success_type; _success_type success; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _error_type; _error_type error; typedef boost::shared_ptr< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::franka_control::SetEEFrameResponse_<ContainerAllocator> const> ConstPtr; }; // struct SetEEFrameResponse_ typedef ::franka_control::SetEEFrameResponse_<std::allocator<void> > SetEEFrameResponse; typedef boost::shared_ptr< ::franka_control::SetEEFrameResponse > SetEEFrameResponsePtr; typedef boost::shared_ptr< ::franka_control::SetEEFrameResponse const> SetEEFrameResponseConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::franka_control::SetEEFrameResponse_<ContainerAllocator> & v) { ros::message_operations::Printer< ::franka_control::SetEEFrameResponse_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace franka_control namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'franka_control': ['/home/panda1/catkin_ws/devel/share/franka_control/msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/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< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::franka_control::SetEEFrameResponse_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::franka_control::SetEEFrameResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::franka_control::SetEEFrameResponse_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > { static const char* value() { return "45872d25d65c97743cc71afc6d4e884d"; } static const char* value(const ::franka_control::SetEEFrameResponse_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x45872d25d65c9774ULL; static const uint64_t static_value2 = 0x3cc71afc6d4e884dULL; }; template<class ContainerAllocator> struct DataType< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > { static const char* value() { return "franka_control/SetEEFrameResponse"; } static const char* value(const ::franka_control::SetEEFrameResponse_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > { static const char* value() { return "bool success\n\ string error\n\ \n\ \n\ "; } static const char* value(const ::franka_control::SetEEFrameResponse_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.success); stream.next(m.error); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct SetEEFrameResponse_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::franka_control::SetEEFrameResponse_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::franka_control::SetEEFrameResponse_<ContainerAllocator>& v) { s << indent << "success: "; Printer<uint8_t>::stream(s, indent + " ", v.success); s << indent << "error: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.error); } }; } // namespace message_operations } // namespace ros #endif // FRANKA_CONTROL_MESSAGE_SETEEFRAMERESPONSE_H
[ "loran.knol@gmail.com" ]
loran.knol@gmail.com
ce2e65235726fa1c2daedbbd45be10146e823ee1
95b1430f0882b89aa01cf152126e20b83f00aae3
/week7/Inheritance/Car.cpp
f5c77710b254cd514b2e9ad04798b16e7a84e3af
[]
no_license
Vankata/OOP
5bec3ac72c1e3c9e5a38f0c642266589f96d561c
d386638e1ae513e96f1916760423566967b46c58
refs/heads/master
2021-01-10T15:19:31.959667
2016-04-26T11:23:56
2016-04-26T11:23:56
53,796,614
0
0
null
null
null
null
UTF-8
C++
false
false
1,778
cpp
#include "stdafx.h" #include "Car.h" Car::Car() :Vehicle() { this->model = NULL; this->doors = 0; this->HP = 0; } Car::Car(char* color, char* make, int year, int seats, double maxSpeed, char* model, int doors, int HP) : Vehicle(color, make, year, seats, maxSpeed) { this->model = new char[strlen(model) + 1]; strcpy_s(this->model, strlen(model) + 1, model); this->doors = doors; this->HP = HP; } Car::Car(const Car &other) : Vehicle(other) { this->color = new char[strlen(other.color) + 1]; strcpy_s(this->color, strlen(other.color) + 1, other.color); this->make = new char[strlen(other.make) + 1]; strcpy_s(this->make, strlen(other.make) + 1, other.make); this->year = other.year; this->seats = other.seats; this->maxSpeed = other.maxSpeed; this->model = new char[strlen(other.model) + 1]; strcpy_s(this->model, strlen(other.model) + 1, other.model); this->doors = other.doors; this->HP = other.HP; } Car &Car::operator=(const Car &other) { if (this != &other) { delete[]this->color; delete[]this->make; delete[]this->model; this->color = new char[strlen(other.color) + 1]; strcpy_s(this->color, strlen(other.color) + 1, other.color); this->make = new char[strlen(other.make) + 1]; strcpy_s(this->make, strlen(other.make) + 1, other.make); this->year = other.year; this->seats = other.seats; this->maxSpeed = other.maxSpeed; this->model = new char[strlen(other.model) + 1]; strcpy_s(this->model, strlen(other.model) + 1, other.model); this->doors = other.doors; this->HP = other.HP; } return *this; } Car::~Car() { if (this->model != NULL) { delete[]this->model; } } char* Car::getModel()const { return this->model; } int Car::getDoors()const { return this->doors; } int Car::getHP()const { return this->HP; }
[ "vancyki@abv.bg" ]
vancyki@abv.bg
dd25ddd8e95c92aa077ce2bbab5170105ee48bcf
40be95adeb0dbabc0fc4a63799013555c9098135
/sdk/Media/IMediaFilter.cpp
8707ea8e0ba303f207371c1e8e6f99361918865d
[ "MIT" ]
permissive
InfiniteInteractive/LimitlessSDK
af563d5c880c8258d1a67834106b82dbea3e91ba
cb71dde14d8c59cbf8a1ece765989c5787fffefa
refs/heads/master
2020-05-21T19:15:44.208452
2017-07-19T22:27:10
2017-07-19T22:27:10
63,438,341
3
2
null
null
null
null
UTF-8
C++
false
false
29,584
cpp
#include "Media/IMediaFilter.h" #include "Media/MediaPad.h" #include "Media/MediaSampleFactory.h" #include "Media/MediaPluginFactory.h" #include "Media/MediaSourcePad.h" #include "Media/SystemMediaClock.h" #include "Media/MediaSampleFlags.h" #include "Base/JsonSerializer.h" #include "boost/foreach.hpp" #include <boost/tokenizer.hpp> //#include "Base/json.h" //#include <QtCore/QStringList> //#include "rapidjson/document.h" namespace Limitless { IMediaFilter::IMediaFilter(std::string instance, SharedMediaFilter parent): PluginObject(instance), m_parent(parent), m_state(INIT), m_sampleBin(0) { m_baseClasses.push_back("IMediaFilter"); } //IMediaFilter::~IMediaFilter() //{ // MediaPluginFactory::removeFilter(this); //} void IMediaFilter::addSourcePad(SharedMediaPad mediaPad) { m_mediaSourcePads.push_back(mediaPad); } SharedMediaPad IMediaFilter::addSourcePad(std::string name, const char *jsonFormat) { return addSourcePad(name, std::string(jsonFormat)); } SharedMediaPad IMediaFilter::addSourcePad(std::string name, const std::string &jsonFormat) { JsonUnserializer unserializer; unserializer.parse(jsonFormat); if(unserializer.type() == Type::ARRAY) { SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); unserializer.openArray(); while(unserializer.openObject()) { mediaPad->addMediaFormat(&unserializer); unserializer.closeObject(); } m_mediaSourcePads.push_back(mediaPad); unserializer.closeArray(); return mediaPad; } else if(unserializer.type()==Type::OBJECT) { unserializer.openObject(); if(unserializer.key("formats")) { if(unserializer.type() == Type::ARRAY) { unserializer.openArray(); SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); while(unserializer.openObject()) { mediaPad->addMediaFormat(&unserializer); unserializer.closeObject(); } m_mediaSourcePads.push_back(mediaPad); unserializer.closeArray(); } } else { SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); mediaPad->addMediaFormat(&unserializer); m_mediaSourcePads.push_back(mediaPad); } unserializer.closeObject(); } // rapidjson::Document document; // // document.Parse(jsonFormat); // // if(document.IsArray()) // { // SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); // // for(rapidjson::Value::ConstMemberIterator iter=document.MemberBegin(); iter!=document.MemberEnd(); ++iter) // mediaPad->addMediaFormat(iter->value.GetString()); // m_mediaSourcePads.push_back(mediaPad); // // return mediaPad; // } // else if(document.IsObject()) // { // if(document.HasMember("formats")) // { // rapidjson::Value &value=document["formats"]; // // if(value.IsArray()) // { // SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); // // for(rapidjson::Value::ConstMemberIterator iter=value.MemberBegin(); iter!=value.MemberEnd(); ++iter) // mediaPad->addMediaFormat(iter->value.GetString()); // m_mediaSourcePads.push_back(mediaPad); // } // } // else // { // SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); // // mediaPad->addMediaFormat(jsonFormat); // m_mediaSourcePads.push_back(mediaPad); // } // } return SharedMediaPad(); } //SharedMediaPad IMediaFilter::addSourcePad(std::string name, const std::string &jsonFormat) //{ // QVariant jsonVariant=QtJson::parse(QString::fromStdString(jsonFormat)); // // if(jsonVariant.type() == QVariant::List) // { // SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); // QVariantList formats=jsonVariant.toList(); // // for(int i=0; i<formats.size(); ++i) // { // mediaPad->addMediaFormat(&formats[i]); // } // m_mediaSourcePads.push_back(mediaPad); // // return mediaPad; // } // else if(jsonVariant.type() == QVariant::Map) // { // QVariantMap variantMap=jsonVariant.toMap(); // QStringList keys=variantMap.keys(); // // if(keys.size() > 0) // { // if(keys[0] == "formats") // { // SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); // QVariant &formatsVariant=variantMap["formats"]; // // if(formatsVariant.type() == QVariant::List) // { // QVariantList formats=formatsVariant.toList(); // // for(int i=0; i<formats.size(); ++i) // { // mediaPad->addMediaFormat(&formats[i]); // } // m_mediaSourcePads.push_back(mediaPad); // } // return mediaPad; // } // else // { // SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); // // mediaPad->addMediaFormat(&jsonVariant); // m_mediaSourcePads.push_back(mediaPad); // return mediaPad; // } // } // } // // return SharedMediaPad(); //// mediaPad->addMediaFormat(jsonFormat); //// m_mediaSourcePads.push_back(mediaPad); //} SharedMediaPad IMediaFilter::addSourcePad(std::string name, SharedMediaFormat format) { SharedMediaPad mediaPad(new MediaSourcePad(name, shared_from_this())); mediaPad->addMediaFormat(format); m_mediaSourcePads.push_back(mediaPad); return mediaPad; } void IMediaFilter::removeSourcePad(SharedMediaPad mediaPad) { SharedMediaPads::iterator iter=std::find(m_mediaSourcePads.begin(), m_mediaSourcePads.end(), mediaPad); if(iter != m_mediaSourcePads.end()) m_mediaSourcePads.erase(iter); } SharedMediaPads IMediaFilter::getSourcePads() { return m_mediaSourcePads; } size_t IMediaFilter::sourcePads() { return m_mediaSourcePads.size(); } void IMediaFilter::addSinkPad(SharedMediaPad mediaPad) { m_mediaSinkPads.push_back(mediaPad); } SharedMediaPad IMediaFilter::addSinkPad(std::string name, const char *jsonFormat) { return addSinkPad(name, std::string(jsonFormat)); } SharedMediaPad IMediaFilter::addSinkPad(std::string name, const std::string &jsonFormat) { JsonUnserializer unserializer; unserializer.parse(jsonFormat); Type type=unserializer.type(); if(unserializer.type() == Type::ARRAY) { unserializer.openArray(); SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); while(unserializer.openObject()) { mediaPad->addMediaFormat(&unserializer); unserializer.closeObject(); } unserializer.closeArray(); m_mediaSinkPads.push_back(mediaPad); return mediaPad; } else if(unserializer.type()==Type::OBJECT) { unserializer.openObject(); if(unserializer.key("formats")) { if(unserializer.type()==Type::ARRAY) { unserializer.openArray(); SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); while(unserializer.openObject()) { mediaPad->addMediaFormat(&unserializer); unserializer.closeObject(); } unserializer.closeArray(); m_mediaSinkPads.push_back(mediaPad); } } else { SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); mediaPad->addMediaFormat(&unserializer); m_mediaSinkPads.push_back(mediaPad); } unserializer.closeObject(); } // rapidjson::Document document; // // rapidjson::ParseResult result=document.Parse(jsonFormat); // // if(!result) // return SharedMediaPad(); // // if(document.IsArray()) // { // SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); // // for(rapidjson::Value::ConstValueIterator iter=document.Begin(); iter!=document.End(); ++iter) // mediaPad->addMediaFormat(iter->GetString()); // m_mediaSourcePads.push_back(mediaPad); // // return mediaPad; // } // else if(document.IsObject()) // { // if(document.HasMember("formats")) // { // rapidjson::Value &value=document["formats"]; // // if(value.IsArray()) // { // SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); // // for(rapidjson::Value::ConstMemberIterator iter=value.MemberBegin(); iter!=value.MemberEnd(); ++iter) // mediaPad->addMediaFormat(iter->value.GetString()); // m_mediaSourcePads.push_back(mediaPad); // } // } // else // { // SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); // // mediaPad->addMediaFormat(jsonFormat); // m_mediaSourcePads.push_back(mediaPad); // } // } return SharedMediaPad(); } //SharedMediaPad IMediaFilter::addSinkPad(std::string name, const std::string &jsonFormat) //{ //// SharedMediaPad mediaPad(new MediaSinkPad(shared_from_this())); //// //// mediaPad->addMediaFormat(jsonFormat); //// m_mediaSinkPads.push_back(mediaPad); // QVariant jsonVariant=QtJson::parse(QString::fromStdString(jsonFormat)); // // if(jsonVariant.type() == QVariant::List) // { // SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); // QVariantList formats=jsonVariant.toList(); // // for(int i=0; i<formats.size(); ++i) // { // mediaPad->addMediaFormat(&formats[i]); // } // m_mediaSinkPads.push_back(mediaPad); // return mediaPad; // } // else if(jsonVariant.type() == QVariant::Map) // { // QVariantMap variantMap=jsonVariant.toMap(); // QStringList keys=variantMap.keys(); // // if(keys.size() > 0) // { // if(keys[0] == "formats") // { // SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); // QVariant &formatsVariant=variantMap["formats"]; // // if(formatsVariant.type() == QVariant::List) // { // QVariantList formats=formatsVariant.toList(); // // for(int i=0; i<formats.size(); ++i) // { // mediaPad->addMediaFormat(&formats[i]); // } // m_mediaSinkPads.push_back(mediaPad); // return mediaPad; // } // } // else // { // SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); // // mediaPad->addMediaFormat(&jsonVariant); // m_mediaSinkPads.push_back(mediaPad); // return mediaPad; // } // } // } // return SharedMediaPad(); //} SharedMediaPad IMediaFilter::addSinkPad(std::string name, SharedMediaFormat format) { SharedMediaPad mediaPad(new MediaSinkPad(name, shared_from_this())); mediaPad->addMediaFormat(format); m_mediaSinkPads.push_back(mediaPad); return mediaPad; } void IMediaFilter::removeSinkPad(SharedMediaPad mediaPad) { SharedMediaPads::iterator iter=std::find(m_mediaSinkPads.begin(), m_mediaSinkPads.end(), mediaPad); if(iter != m_mediaSinkPads.end()) m_mediaSinkPads.erase(iter); } SharedMediaPads IMediaFilter::getSinkPads() { return m_mediaSinkPads; } size_t IMediaFilter::sinkPads() { return m_mediaSinkPads.size(); } SharedMediaPad IMediaFilter::sourcePad(std::string name) { BOOST_FOREACH(SharedMediaPad pad, m_mediaSourcePads) { if(pad->name() == name) return pad; } return SharedMediaPad(); } SharedMediaPad IMediaFilter::sinkPad(std::string name) { BOOST_FOREACH(SharedMediaPad pad, m_mediaSinkPads) { if(pad->name() == name) return pad; } return SharedMediaPad(); } size_t IMediaFilter::sourcePadIndex(SharedMediaPad mediaPad) { for(size_t i=0; i<m_mediaSourcePads.size(); ++i) { if(m_mediaSourcePads[i] == mediaPad) return i; } return InvalidPin; } size_t IMediaFilter::sinkPadIndex(SharedMediaPad mediaPad) { for(size_t i=0; i<m_mediaSinkPads.size(); ++i) { if(m_mediaSinkPads[i] == mediaPad) return i; } return InvalidPin; } size_t IMediaFilter::sourcePadIndex(std::string name) { for(size_t i=0; i<m_mediaSourcePads.size(); ++i) { MediaPad *pad=m_mediaSourcePads[i].get(); if(pad->name() == name) return i; } return InvalidPin; } size_t IMediaFilter::sinkPadIndex(std::string name) { for(size_t i=0; i<m_mediaSinkPads.size(); ++i) { MediaPad *pad=m_mediaSinkPads[i].get(); if(pad->name() == name) return i; } return InvalidPin; } //bool IMediaFilter::accept(SharedMediaPad mediaPad, SharedMediaFormat mediaFormat) //{ // if(mediaPad->type() == MediaPad::SOURCE) // { // SharedMediaPads sourcePads=getSourcePads(); // // BOOST_FOREACH(SharedMediaPad &sourcePad, sourcePads) // { // if(sourcePad->accept(mediaFormat)) // return true; // } // } // else // { // SharedMediaPads sinkPads=getSinkPads(); // // BOOST_FOREACH(SharedMediaPad &sinkPad, sinkPads) // { // if(sinkPad->accept(mediaFormat)) // return true; // } // } // return true; //} //bool IMediaFilter::accept(SharedMediaFilter sink, SharedMediaFormat format) //{ // SharedMediaPads sourcePads=getSourcePads(); // // if(format != SharedMediaFormat()) // { // BOOST_FOREACH(SharedMediaPad mediaPad, sourcePads) // { // SharedMediaSourcePad sourcePad=boost::dynamic_pointer_cast<MediaSourcePad>(mediaPad); // // if(sourcePad->accept(format)) // { // SharedMediaPads sinkPads=sink->getSinkPads(); // // BOOST_FOREACH(SharedMediaPad sinkPad, sinkPads) // { // if(sinkPad->accept(format)) // return true; // } // } // } // } // else // { // BOOST_FOREACH(SharedMediaPad mediaPad, sourcePads) // { // SharedMediaSourcePad sourcePad=boost::dynamic_pointer_cast<MediaSourcePad>(mediaPad); // SharedMediaFormats sourceMediaFormats=sourcePad->queryMediaFormats(); // // BOOST_FOREACH(SharedMediaFormat sourceMediaFormat, sourceMediaFormats) // { // SharedMediaPads sinkPads=sink->getSinkPads(); // // BOOST_FOREACH(SharedMediaPad sinkPad, sinkPads) // { // if(sinkPad->accept(sourceMediaFormat)) // return true; // } // } // } // } // return false; //} bool IMediaFilter::link(boost::shared_ptr<IMediaFilter> sinkFilter) { SharedMediaPads sourcePads=getSourcePads(); SharedMediaPads sinkPads=sinkFilter->getSinkPads(); BOOST_FOREACH(SharedMediaPad &sourcePad, sourcePads) { if(!sourcePad->linked()) { if(sourcePad->link(sinkFilter)) return true; // SharedMediaFormats sourceMediaFormats=sourcePad->queryMediaFormats(); // // BOOST_FOREACH(SharedMediaFormat &sourceMediaFormat, sourceMediaFormats) // { // DEBUG_MEDIA_FORMAT(sourceMediaFormat); // BOOST_FOREACH(SharedMediaPad sinkPad, sinkPads) // { // if(!sinkPad->linked()) // { // if(sinkPad->accept(sourceMediaFormat)) // { // return sourcePad->link(sinkPad, sourceMediaFormat); // } // } // } // } } } return false; } bool IMediaFilter::link(SharedMediaPad sinkPad) { SharedMediaPads sourcePads=getSourcePads(); BOOST_FOREACH(SharedMediaPad &sourcePad, sourcePads) { if(!sourcePad->linked()) { if(sourcePad->link(sinkPad)) return true; } } return false; } //SharedMediaFormat IMediaFilter::connect(boost::shared_ptr<IMediaFilter> sink, SharedMediaFormat format) //{ // SharedMediaFormat acceptedFormat=accept(sink); // SharedMediaPads sourcePads=getSourcePads(); // // if(acceptedFormat != SharedMediaFormat()) // { // BOOST_FOREACH(SharedMediaPad sourcePad, sourcePads) // { // if(!sourcePad->accept(acceptedFormat)) // continue; // // SharedMediaPads sinkPads=sink->getSinkPads(); // // BOOST_FOREACH(SharedMediaPad sinkPad, sinkPads) // { // if(!sinkPad->accept(acceptedFormat)) // continue; // // acceptedFormat=sourcePad->connect(sinkPad, acceptedFormat); // return acceptedFormat; // } // } // } // return SharedMediaFormat(); //} //bool IMediaFilter::connectLinkedPads() //{ // bool connected=false; // // BOOST_FOREACH(SharedMediaPad &sourceMediaPad, m_mediaSourcePads) // { // if(!sourceMediaPad->connect()) // return false; // else // connected=true; // } // return connected; //} bool IMediaFilter::reLinkPads() { bool linked=true; BOOST_FOREACH(SharedMediaPad &sourceMediaPad, m_mediaSourcePads) { if(sourceMediaPad->linked()) linked=true; else if(sourceMediaPad->linkChanged()) { linked=sourceMediaPad->relink(); if(!linked) return false; } } return linked; } bool IMediaFilter::onAcceptMediaFormat(SharedMediaPad pad, SharedMediaFormat format) { if(pad->type() == MediaPad::SOURCE) { SharedMediaPads::iterator iter=std::find(m_mediaSourcePads.begin(), m_mediaSourcePads.end(), pad); if(iter != m_mediaSourcePads.end()) { return pad->onAccept(format); } } else { SharedMediaPads::iterator iter=std::find(m_mediaSinkPads.begin(), m_mediaSinkPads.end(), pad); if(iter != m_mediaSinkPads.end()) { return pad->onAccept(format); } } return false; } //bool IMediaFilter::linkSourcePad(SharedMediaPad sourcePad, SharedMediaPad sinkPad, SharedMediaFormat format) //{ // return sourcePad->onLink(sinkPad, format); //} // //bool IMediaFilter::linkSinkPad(SharedMediaPad sourcePad, SharedMediaPad sinkPad, SharedMediaFormat format) //{ // return sourcePad->onLink(sinkPad, format); //} // //SharedMediaFormat IMediaFilter::connectSourcePad(SharedMediaPad sourcePad, SharedMediaPad sinkPad, SharedMediaFormat format) //{ // return sourcePad->onConnect(sinkPad, format); //} // //SharedMediaFormat IMediaFilter::connectSinkPad(SharedMediaPad sourcePad, SharedMediaPad sinkPad, SharedMediaFormat format) //{ // return sourcePad->onConnect(sinkPad, format); //} void IMediaFilter::disconnect(boost::shared_ptr<IMediaFilter> sink) { SharedMediaPads sourcePads=getSourcePads(); BOOST_FOREACH(SharedMediaPad sourcePad, sourcePads) { if(sourcePad->linked()) { SharedMediaPad linkedPad=sourcePad->linkedPad(); if(linkedPad != SharedMediaPad()) { if(linkedPad->parent() == sink) sourcePad->disconnect(); } } } } void IMediaFilter::disconnect(SharedMediaPad localPad) { SharedMediaPads sourcePads=getSourcePads(); SharedMediaPads::iterator iter=std::find(sourcePads.begin(), sourcePads.end(), localPad); if(iter != sourcePads.end()) { SharedMediaPad sourcePad=(*iter); if(sourcePad->linked()) sourcePad->disconnect(); } } bool IMediaFilter::inStream(boost::shared_ptr<IMediaFilter> filter) { if(upStream(filter)) return true; if(downStream(filter)) return true; return false; } bool IMediaFilter::upStream(boost::shared_ptr<IMediaFilter> filter) { BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSinkPads) { if(mediaPad->linked()) { if(mediaPad->parent() == filter) return true; if(mediaPad->parent()->upStream(filter)) return true; } } return false; } bool IMediaFilter::downStream(SharedMediaFilter filter) { BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSourcePads) { if(mediaPad->linked()) { if(mediaPad->parent() == filter) return true; if(mediaPad->parent()->downStream(filter)) return true; } } return false; } SharedMediaFilters IMediaFilter::findUpStream(std::string typeName) { SharedMediaFilters filters; BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSinkPads) { SharedMediaFilters childFilters=mediaPad->findUpStream(typeName); if(!childFilters.empty()) filters.insert(filters.end(), childFilters.begin(), childFilters.end()); } return filters; } SharedMediaFilters IMediaFilter::findUpStream(FilterType filterType) { SharedMediaFilters filters; BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSinkPads) { SharedMediaFilters childFilters=mediaPad->findUpStream(filterType); if(!childFilters.empty()) filters.insert(filters.end(), childFilters.begin(), childFilters.end()); } return filters; } SharedMediaFilter IMediaFilter::findFirstUpStream(std::string typeName, FilterSearch search) { if(search == FilterSearch::Depth) { BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSinkPads) { if(mediaPad->linked()) { SharedMediaFilter parentFilter=mediaPad->linkedPad()->parent(); if(parentFilter == SharedMediaFilter()) return SharedMediaFilter(); if(parentFilter->typeName() == typeName) return mediaPad->parent(); SharedMediaFilter filter=parentFilter->findFirstUpStream(typeName); if(filter != SharedMediaFilter()) return filter; } } } else assert(false); return SharedMediaFilter(); } SharedMediaFilters IMediaFilter::findDownStream(std::string typeName) { SharedMediaFilters filters; BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSourcePads) { SharedMediaFilters childFilters=mediaPad->findDownStream(typeName); if(!childFilters.empty()) filters.insert(filters.end(), childFilters.begin(), childFilters.end()); } return filters; } SharedMediaFilters IMediaFilter::findDownStream(FilterType filterType) { SharedMediaFilters filters; BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSinkPads) { SharedMediaFilters childFilters=mediaPad->findDownStream(filterType); if(!childFilters.empty()) filters.insert(filters.end(), childFilters.begin(), childFilters.end()); } return filters; } SharedMediaFilter IMediaFilter::findFirstDownStream(std::string typeName, FilterSearch search) { if(search == FilterSearch::Depth) { BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSourcePads) { if(mediaPad->linked()) { SharedMediaFilter parentFilter=mediaPad->linkedPad()->parent(); if(parentFilter == SharedMediaFilter()) return SharedMediaFilter(); if(parentFilter->typeName() == typeName) return parentFilter; SharedMediaFilter filter=parentFilter->findFirstDownStream(typeName); if(filter != SharedMediaFilter()) return filter; } } } else assert(false); return SharedMediaFilter(); } SharedMediaFilters IMediaFilter::upStreamFilters() { SharedMediaFilters upStreamFilters; BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSinkPads) { if(mediaPad->linked()) upStreamFilters.push_back(mediaPad->parent()); } return upStreamFilters; } SharedMediaFilters IMediaFilter::downStreamFilters() { SharedMediaFilters downStreamFilters; BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSourcePads) { if(mediaPad->linked()) downStreamFilters.push_back(mediaPad->parent()); } return downStreamFilters; } size_t IMediaFilter::getSampleBin() { if(m_sampleBin == 0) m_sampleBin=allocSampleBin(); return m_sampleBin; } size_t IMediaFilter::allocSampleBin() { return allocSampleBin(this); } size_t IMediaFilter::allocSampleBin(IMediaFilter *filter) { if(m_parent != SharedMediaFilter()) return m_parent->allocSampleBin(); return 0; } void IMediaFilter::releaseSampleBin(size_t bin) { releaseSampleBin(bin, this); } void IMediaFilter::releaseSampleBin(size_t bin, IMediaFilter *filter) { if(m_parent != SharedMediaFilter()) return m_parent->releaseSampleBin(bin, this); } SharedMediaSample IMediaFilter::newSample(unsigned int type) { return newSample(type, getSampleBin()); } SharedMediaSample IMediaFilter::newSample(unsigned int type, size_t sampleBin) { if(m_parent != SharedMediaFilter()) return m_parent->newSample(type, sampleBin); SharedMediaSample sample=MediaSampleFactory::createType(type); return sample; } void IMediaFilter::deleteSample(SharedMediaSample sample) { // if(m_parent != SharedMediaFilter()) // return m_parent->deleteSample(sample); sample.reset(); } MediaTime IMediaFilter::getTime() { if(m_mediaClock != SharedMediaClock()) return m_mediaClock->time(); else { if(m_parent != SharedMediaFilter()) return m_parent->getTime(); else { m_mediaClock.reset(new SystemMediaClock()); return m_mediaClock->time(); } } } MediaTime IMediaFilter::getStreamTime() { // return getTime(); if(m_parent!=SharedMediaFilter()) return m_parent->getStreamTime(); else return getTime(); } IMediaFilter::FilterState IMediaFilter::getState() const { return m_state; } IMediaFilter::StateChange IMediaFilter::setState(IMediaFilter::FilterState state) { StateChange stateChange=SUCCESS; if(state == READY) stateChange=ready(); else if(state == PAUSED) stateChange=pause(); else if(state == PLAYING) stateChange=play(); return stateChange; } IMediaFilter::StateChange IMediaFilter::ready() { StateChange stateChange; if(m_state == READY) return SUCCESS; if(m_state == PLAYING) { stateChange=onPaused(); if(stateChange != SUCCESS) return stateChange; m_state=PAUSED; } if((m_state == INIT) || (m_state == PAUSED)) { // if(m_state == INIT) // { // if(!connectLinkedPads()) // return FAILED; // } stateChange=onReady(); if(stateChange != SUCCESS) return stateChange; if(!reLinkPads()) return FAILED; m_state=READY; return stateChange; // m_state=READY; // return stateChange; } return FAILED; } IMediaFilter::StateChange IMediaFilter::pause() { StateChange stateChange; if(m_state == PAUSED) return SUCCESS; if(m_state == INIT) { stateChange=onReady(); if(stateChange != SUCCESS) return stateChange; m_state=READY; } if((m_state == READY) || (m_state == PLAYING)) { stateChange=onPaused(); if(stateChange != SUCCESS) return stateChange; m_state=PAUSED; return stateChange; } return FAILED; } IMediaFilter::StateChange IMediaFilter::play() { StateChange stateChange; if(m_state == PLAYING) return SUCCESS; if(m_state == INIT) { stateChange=onReady(); if(stateChange != SUCCESS) return stateChange; m_state=READY; } if(m_state == READY) { stateChange=onPaused(); if(stateChange != SUCCESS) return stateChange; m_state=PAUSED; } if(m_state == PAUSED) { stateChange=onPlaying(); if(stateChange != SUCCESS) return stateChange; m_state=PLAYING; return stateChange; } return FAILED; } void IMediaFilter::onLinkFormatChanged(SharedMediaPad mediaPad, SharedMediaFormat format) { } void IMediaFilter::pushSample(SharedMediaPad mediaPad, SharedMediaSample sample) { if(mediaPad->linked()) mediaPad->linkedPad()->processSample(sample); } void IMediaFilter::pushSample(SharedMediaSample sample) { SharedMediaPads sourcePads=getSourcePads(); bool pushed=false; BOOST_FOREACH(SharedMediaPad &sourcePad, sourcePads) { if(sourcePad->linked()) { // sourcePad->processSample(sample); sourcePad->linkedPad()->processSample(sample); pushed=true; } } if(!pushed) //sample was not pushed please delete deleteSample(sample); } void IMediaFilter::sendMessage(Attribute *attribute) { sendMessage(this, attribute); } void IMediaFilter::sendMessage(IMediaFilter *sender, Attribute *attribute) { sendMessageUpStream(sender, attribute); sendMessageDownStream(sender, attribute); } void IMediaFilter::sendMessageUpStream(Attribute *attribute) { sendMessageUpStream(this, attribute); } void IMediaFilter::sendMessageUpStream(IMediaFilter *sender, Attribute *attribute) { BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSinkPads) { if(mediaPad->linked()) { SharedMediaFilter linkedFilter; if(mediaPad->linkedPad() != SharedMediaPad()) linkedFilter=mediaPad->linkedPad()->parent(); if(linkedFilter != SharedMediaFilter()) { linkedFilter->onMessage(mediaPad.get(), sender, attribute); linkedFilter->sendMessageUpStream(sender, attribute); } } } } void IMediaFilter::sendMessageDownStream(Attribute *attribute) { sendMessageDownStream(this, attribute); } void IMediaFilter::sendMessageDownStream(IMediaFilter *sender, Attribute *attribute) { BOOST_FOREACH(SharedMediaPad mediaPad, m_mediaSourcePads) { if(mediaPad->linked()) { SharedMediaFilter linkedFilter; if(mediaPad->linkedPad() != SharedMediaPad()) linkedFilter=mediaPad->linkedPad()->parent(); if(linkedFilter != SharedMediaFilter()) { linkedFilter->onMessage(mediaPad.get(), sender, attribute); linkedFilter->sendMessageDownStream(sender, attribute); } } } } void IMediaFilter::serialize(Serializer *serializer) { serializer->startObject(); serializer->addKey("type"); serializer->addString(typeName()); serializer->addKey("instance"); serializer->addString(instance()); SharedMediaPads sourcePads=getSourcePads(); if(!sourcePads.empty()) { serializer->addKey("links"); serializer->startArray(); for(SharedMediaPad sourcePad:sourcePads) { if(sourcePad->linked()) { serializer->startObject(); SharedMediaPad linkedPad=sourcePad->linkedPad(); serializer->addKey("padName"); serializer->addString(sourcePad->name()); serializer->addKey("linkedFilter"); serializer->addString(linkedPad->parent()->instance()); serializer->addKey("linkedPad"); serializer->addString(linkedPad->name()); serializer->endObject(); } } serializer->endArray(); } AttributeContainer::serialize(serializer); serializer->endObject(); } void IMediaFilter::unserialize(Unserializer *unserializer) { if(unserializer->key("attributes")) AttributeContainer::unserialize(unserializer); } SharedMediaFilter Limitless::findByInstance(SharedMediaFilters mediaFilters, std::string instance) { for(SharedMediaFilters::iterator iter=mediaFilters.begin(); iter!=mediaFilters.end(); ++iter) { if((*iter)->instance() == instance) return *iter; } return SharedMediaFilter(); } std::string Limitless::stateName(IMediaFilter::FilterState state) { std::string stateString="Unknown"; switch(state) { case IMediaFilter::INIT: stateString="Init"; break; case IMediaFilter::READY: stateString="Ready"; break; case IMediaFilter::PAUSED: stateString="Paused"; break; case IMediaFilter::PLAYING: stateString="Playing"; break; }; return stateString; } Limitless::MimeDetail Limitless::parseMimeDetail(std::string mime) { MimeDetail detail; boost::char_separator<char> separator("/"); boost::tokenizer<boost::char_separator<char> > mimeTokens(mime, separator); std::string mimeType; std::string mimeFormat; int index=0; for(const auto &token:mimeTokens) { if(index == 0) detail.type=token; else if(index == 1) detail.codec=token; else if(index == 2) detail.format=token; index++; } return detail; } }//namespace Limitless
[ "caseymcc@krazer.net" ]
caseymcc@krazer.net
0534cf6a3b0bf2ac6067fc7db747b4ee447d6a1b
14e30c5f520f0ed28117914101d9bdf2f3d5dac7
/project/source/game/states/game_state_manager.cpp
9e0a68dabd2468f26e23d20bc4c50a1a06f31a59
[]
no_license
danielePiracci/arlight
f356eb5a162d0cd62a759720cbc6da41a820642f
15a68c4c80c97f2fe7458e7ddf03f3e1063e25a4
refs/heads/master
2016-08-11T13:45:35.252916
2011-01-24T20:22:50
2011-01-24T20:22:50
44,962,821
0
0
null
null
null
null
UTF-8
C++
false
false
3,110
cpp
/// \file game/states/game_state_manager.cpp /// \author Juan Carlos De Abreu (jcabreur@gmail.com) /// \date 2010/02/06 /// \version 1.0 /// /// \brief This file implements the DissertationProject::States::GameStateManager /// class, declared at game/states/game_manager.h. #include "game/states/game_state_manager.h" BEGIN_PROJECT_NAMESPACE(); BEGIN_NAMESPACE(States); GameStateManager::GameStateManager() { // Load all the default game states. Initialize(); } GameStateManager::~GameStateManager() { // Release all the game states resources. Release(); } void GameStateManager::Initialize() { // Register all the default game states. } void GameStateManager::Release() { // Release all the states stacked. while (!states_.empty()) states_.pop(); // Iterate over all the registered states and release it's resources. std::map<GameState::StateId, GameState*>::iterator it = game_states_.begin(); std::map<GameState::StateId, GameState*>::iterator end = game_states_.end(); for (; it != end; ++it) UnregisterState(it->first); game_states_.clear(); } void GameStateManager::RegisterState(GameState* game_state, GameState::StateId state) { // Add the state to game state manager map. game_states_[state] = game_state; game_state->Initialize(); } void GameStateManager::UnregisterState(GameState::StateId state) { // Remove the state from the game state manager map. if (game_states_[state]) delete game_states_[state]; game_states_[state] = NULL; } void GameStateManager::ChangeState(GameState::StateId state) { // Check if a current game state exist and if so removed. if (!states_.empty()) { game_states_[states_.top()]->Exit(); states_.pop(); } // Add the new game state. states_.push(state); game_states_[state]->Enter(); } void GameStateManager::PushState(GameState::StateId state) { // Check if a current game state exist and if so pause it's execution. if (!states_.empty()) game_states_[states_.top()]->Pause(); // Add the new game state. states_.push(state); game_states_[state]->Enter(); } void GameStateManager::PopState() { // Check if a current game state exist and if so finish it's execution. if (!states_.empty()) { game_states_[states_.top()]->Exit(); states_.pop(); } // Restore the previous game state execution. if (!states_.empty()) game_states_[states_.top()]->Resume(); } void GameStateManager::Update(Game& game) { // Check if a current game state exist and if so update it. if (!states_.empty()) game_states_[states_.top()]->Update(game); } void GameStateManager::Render(Game& game) { // Check fi a current game state exist and if so render it. if (!states_.empty()) game_states_[states_.top()]->Render(game); } void GameStateManager::HandleEvents(Game& game) { // Check if a current game state exist and if so handle the event. if (!states_.empty()) game_states_[states_.top()]->HandleEvents(game); } END_NAMESPACE(States); END_PROJECT_NAMESPACE();
[ "jcabreur@db05138c-34b8-7cfb-67b9-2db12d2e1ab0" ]
jcabreur@db05138c-34b8-7cfb-67b9-2db12d2e1ab0
2873dcd149218c3402df3ab5832cfe179e21033a
e08bde972d5856a256857e238055bc94876fae9c
/Path planning/Scurve/Scurve/PTP.cpp
fd21a83c394b5c0c796004c6df183c17b6cda038
[]
no_license
YuCH-Hank/MyRobot
5038cd2ebc4788804ae1bf0037c5df22cab916e3
b65354d40150bb30397e0f6d40a42f53e8ab005d
refs/heads/master
2023-03-09T21:06:18.153447
2021-02-27T08:06:29
2021-02-27T08:06:29
null
0
0
null
null
null
null
BIG5
C++
false
false
5,693
cpp
#include "PTP.h" //================ 點對點命令 ================ double Time = 0.0; vector<double> jerk = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; vector<double> Displacement; double DisplacementFunction; double max_time = 0.0; double Ta, Tb, Tc, Ts, t1, t2, t3, t4, t5, t6, t7; double ta, tb, tc, ts; int NumberMax; void PTP_Scurve_Joint(vector<double> InitialPos, vector<double> FinalPos, vector<double>(&PosCmd), vector<double>(&VelCmd), vector<double>(&AccCmd), int(&EndFlag)) { vector<double> Vmax = { 2.4933, 2.4933, 2.4933, 2.4933, 3.4700, 5.8667 }; // Velocity Limitation (rad/s) vector<double> Amax = { 3.4907, 3.4907, 3.4907, 3.4907, 3.4907, 3.4907 }; // Acceleration Limitation (rad/s^2) vector<double> Aavg = V_MultiplyScalar(Amax, 0.75); // Average Accleration (0.75 * Max Acceleration) if (Time == 0) { Displacement = V_SubVector(FinalPos, InitialPos); for (size_t i = 0; i < AXIS; i++) { ta = Vmax[i] / Aavg[i]; tb = 2 * Vmax[i] / Amax[i] - ta; tc = (ta - tb) / 2; ts = (Displacement[i] - Vmax[i] * ta) / Vmax[i]; if (ts < 0) { ts = 0; Vmax[i] = sqrt(abs(Displacement[i] * Aavg[i])); } if ((ts + 2 * ta) > max_time) { Tc = tc; Ta = ta; Ts = ts; Tb = tb; max_time = ts + 2 * ta; } if (Displacement[i] < 0) { Amax[i] = -Amax[i]; Vmax[i] = -Vmax[i]; Aavg[i] = -Aavg[i]; } } t1 = Tc; t2 = Tc + Tb; t3 = Ta; t4 = Ta + Ts; t5 = Ta + Ts + Tc; t6 = Ta + Ts + Tc + Tb; t7 = Ta + Ts + Ta; //================ DisplacementFunction ================ DisplacementFunction = pow(t1, 3) / 6 + pow(t2, 3) / 6 + pow(t3, 3) / 3 + pow(t4, 3) / 6 - pow(t5, 3) / 6 - pow(t6, 3) / 6 + pow(t7, 3) / 6 - t1 * pow(t3, 2) / 2 - pow(t1, 2)*t7 / 2 + t1*t3*t7 - t2 * pow(t3, 2) / 2 - pow(t2, 2)*t7 / 2 + t2*t3*t7 - pow(t3, 2)*t7 / 2 - pow(t4, 2) * t7 / 2 + t4*pow(t7, 2) / 2 + pow(t5, 2)*t7 / 2 - t5 * pow(t7, 2) / 2 + pow(t6, 2)*t7 / 2 - t6 * pow(t7, 2) / 2; //================ Calculate Jerk ================ jerk = V_MultiplyScalar(Displacement, 1 / DisplacementFunction); } if (Time <= t7) { for (int j = 0; j < 1; j++) { if (t1 >= Time) { AccCmd = V_MultiplyScalar(jerk , Time); VelCmd = V_MultiplyScalar(jerk, (pow(Time, 2) / 2)); PosCmd = V_AddVector(InitialPos , V_MultiplyScalar(jerk, (pow(Time, 3) / 6))); } else if (t2 >= Time && Time > t1) { AccCmd = V_MultiplyScalar(jerk , t1); VelCmd = V_MultiplyScalar(jerk , (-pow(t1, 2) / 2 + t1*Time)); PosCmd = V_AddVector(InitialPos , V_MultiplyScalar(jerk, (pow(t1, 3) / 6 ) - Time * pow(t1, 2) / 2 + t1 * pow(Time, 2) / 2)); } else if (t3 >= Time && Time > t2) { AccCmd = V_MultiplyScalar(jerk, (t1 + t2 - Time)); VelCmd = V_MultiplyScalar(jerk, (-pow(t1, 2) / 2 - pow(t2, 2) / 2 + Time * (t2 + t1) - pow(Time, 2) / 2)); PosCmd = V_AddVector(InitialPos, V_MultiplyScalar(jerk, (pow(t1, 3) / 6 + pow(t2, 3) / 6 - Time * (pow(t1, 2) / 2 + pow(t2, 2) / 2) + pow(Time, 2) * (t2 + t1) / 2 - pow(Time, 3) / 6))); } else if (t4 >= Time && Time > t3) { AccCmd = V_MultiplyScalar(jerk, 0); VelCmd = V_MultiplyScalar(jerk, (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 + t1 * t3 + t2*t3)); PosCmd = V_AddVector(InitialPos, V_MultiplyScalar(jerk, (pow(t1, 3) / 6 + pow(t2, 3) / 6 + pow(t3, 3) / 3 - t1 * pow(t3, 2) / 2 - t2 * pow(t3, 2) / 2 + Time * (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 + t1 * t3 + t2 * t3)))); } else if (t5 >= Time && Time > t4) { AccCmd = V_MultiplyScalar(jerk, (t4 - Time)); VelCmd = V_MultiplyScalar(jerk, (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 - pow(t4, 2) / 2 + t1 * t3 + t2 * t3 + Time * t4 - pow(Time, 2) / 2)); PosCmd = V_AddVector(InitialPos, V_MultiplyScalar(jerk, (pow(t1, 3) / 6 + pow(t2, 3) / 6 + pow(t3, 3) / 3 + pow(t4, 3) / 6 - t1 * pow(t3, 2) / 2 - t2 * pow(t3, 2) / 2 + Time * (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 - pow(t4, 2) / 2 + t1 * t3 + t2 * t3) + t4 * pow(Time, 2) / 2 - pow(Time, 3) / 6))); } else if (t6 >= Time && Time > t5) { AccCmd = V_MultiplyScalar(jerk, (t4 - t5)); VelCmd = V_MultiplyScalar(jerk, (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 - pow(t4, 2) / 2 + pow(t5, 2) / 2 + t1 * t3 + t2 * t3 - Time * (t5 - t4))); PosCmd = V_AddVector(InitialPos, V_MultiplyScalar(jerk, (pow(t1, 3) / 6 + pow(t2, 3) / 6 + pow(t3, 3) / 3 + pow(t4, 3) / 6 - pow(t5, 3) / 6 - t1 * pow(t3, 2) / 2 - t2 * pow(t3, 2) / 2 + Time * (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 - pow(t4, 2) / 2 + pow(t5, 2) / 2 + t1 * t3 + t2 * t3) - pow(Time, 2) * (t5 - t4) / 2))); } else if (t7 >= Time && Time > t6) { AccCmd = V_MultiplyScalar(jerk, (Time - t6 - t5 + t4)); VelCmd = V_MultiplyScalar(jerk, (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 - pow(t4, 2) / 2 + pow(t5, 2) / 2 + pow(t6, 2) / 2 + t1 * t3 + t2 * t3 + Time * (-t6 - t5 + t4) + pow(Time, 2) / 2)); PosCmd = V_AddVector(InitialPos, V_MultiplyScalar(jerk, (pow(t1, 3) / 6 + pow(t2, 3) / 6 + pow(t3, 3) / 3 + pow(t4, 3) / 6 - pow(t5, 3) / 6 - t1 * pow(t3, 2) / 2 - t2 * pow(t3, 2) / 2 - pow(t6, 3) / 6 + Time * (-pow(t1, 2) / 2 - pow(t2, 2) / 2 - pow(t3, 2) / 2 - pow(t4, 2) / 2 + pow(t5, 2) / 2 + pow(t6, 2) / 2 + t1 * t3 + t2 * t3) - pow(Time, 2) * (t5 - t4 + t6) / 2 + pow(Time, 3) / 6))); } } Time = Time + SamplingTime; EndFlag = 0; // 判別PTP命令是否結束(未結束) } else { Time = 0; max_time = 0; PosCmd = FinalPos; VelCmd = V_MultiplyScalar(jerk, 0); AccCmd = V_MultiplyScalar(jerk, 0); EndFlag = 1; // 判別PTP命令是否結束(結束) } }
[ "70463744+YuCH-Hank@users.noreply.github.com" ]
70463744+YuCH-Hank@users.noreply.github.com
80e9cc36900ca8e24063f72ce740fc4f783eeb67
39040af0ff84935d083209731dd7343f93fa2874
/inc/uprogressbar.h
7f1c83ba565f38ec938dbdf22cfb92e0fc487e2f
[ "Apache-2.0" ]
permissive
alanzw/ulib-win
02f8b7bcd8220b6a057fd3b33e733500294f9b56
b67f644ed11c849e3c93b909f90d443df7be4e4c
refs/heads/master
2020-04-06T05:26:54.849486
2011-07-23T05:47:17
2011-07-23T05:47:17
34,505,292
5
3
null
null
null
null
UTF-8
C++
false
false
1,184
h
#ifndef U_PROGRESSBAR_H #define U_PROGRESSBAR_H #include "ucontrol.h" #include "colors.h" class ULIB_API UProgressBar : public UControl { public: UProgressBar(HWND hParent, UINT nResource, HINSTANCE hInst); ~UProgressBar(); // virtual BOOL create(); // virtual BOOL setRange(int min, int max); virtual int getLowLimit(); virtual int getHighLimit(); // virtual BOOL setStep(int nStepSize); virtual BOOL stepIt(); virtual int getStep(); // virtual BOOL setPBPos(int nNewPos); virtual BOOL deltaPBPos(int nIncrement); virtual UINT getPBPos(); #if (_WIN32_WINNT >= 0x0501) virtual BOOL setMarquee(BOOL bMarqueeModeOn, UINT nUpdateTimeInMs); #endif // _WIN32_WINNT >= 0x0501 virtual BOOL setState(int iState); virtual int getState(); virtual BOOL setBKColor(huys::Color clr); virtual BOOL setBarColor(huys::Color clr); virtual huys::Color getBKColor(); virtual huys::Color getBarColor(); protected: private: }; #if (_WIN32_WINNT >= 0x0501) #define PBS_MARQUEE 0x08 #define PBM_SETMARQUEE (WM_USER+10) #endif // _WIN32_WINNT >= 0x0501 #endif // U_PROGRESSBAR_H
[ "fox000002@48c0247c-a797-11de-8c46-7bd654735883" ]
fox000002@48c0247c-a797-11de-8c46-7bd654735883
6f5acd5bd1de8ce8dc9d437c350189994a4077b6
b18e47f011236926956de8894e1de2a4d5bde1f5
/2.Bai tap YT/Bai tap so 4/nhap.cpp
a9627c215204b24a1752977ad1fc0d18fd947212
[]
no_license
DuyetVu2001/Study-C-languge
0209030efea57626ba88240ad67620ebedb0a403
0e16ad166a3e5b376b866a7f3aa9b45ca923293e
refs/heads/master
2022-12-06T01:22:18.449125
2020-08-24T18:49:52
2020-08-24T18:49:52
290,013,393
1
0
null
null
null
null
UTF-8
C++
false
false
104
cpp
#include<stdio.h> #include<math.h> int main(){ int n; n = ceil(7/2); printf("%d", n); return 0; }
[ "vungocduyet24@gmail.com" ]
vungocduyet24@gmail.com
99c873e2ee088889b1f483b3f06552fe1d53432f
4209e97658f8fdb6997c661d6e16b96aa0698977
/A_star/MainFrm.cpp
8c75ab70f224c08f5688498f814502872ce062b3
[]
no_license
Feoggou/astar
fcf09a762bad2b9d0916fc93df24d2f0927668b7
8afd6c9581ad4dffd6a0cc7cfafd5732aa52a9d2
refs/heads/master
2016-09-01T23:26:49.057080
2013-04-02T21:00:43
2013-04-02T21:00:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,241
cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "A_star.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif extern BOOL StoredOnce; // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() ON_WM_CLOSE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame construction/destruction CMainFrame::CMainFrame() { // TODO: add member initialization code here } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; // if (!m_wndToolBar.Create(this) || // m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_FLYBY | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create tool bar\n"); return -1; } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs cs.style |= WS_MAXIMIZE; return TRUE; } // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame message handlers void CMainFrame::OnClose() { // TODO: Add your message handler code here and/or call default /* if (StoredOnce) { int value = MessageBox(L"Do you want to save changes of this file?", 0, MB_YESNOCANCEL); if (value==IDCANCEL) return; else if (value==IDYES) SendMessage(WM_COMMAND, (WPARAM)ID_FILE_SAVE); }*/ CFrameWnd::OnClose(); }
[ "samuel.ghinet@moredevs.ro" ]
samuel.ghinet@moredevs.ro
9af42367f7e7fa28c2a68dbd2b908477f63c20b9
e52ce84e5ef50594d870ab31bb45e462557a926e
/Account.cpp
e47300f4e221c5574adf5163f741c8fb7cb5cebf
[]
no_license
minilooth/Kursovaya_3sem
86fbd2b6487087a302019c106d44c8090788012c
46cc19f24cec1786926a70f21bdcb05d3bc40f35
refs/heads/master
2023-01-22T11:55:30.963213
2019-12-28T15:42:22
2019-12-28T15:42:22
219,169,182
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,475
cpp
#include "AccountHandler.h" using namespace account; Account::Account() { username_ = ""; password_ = ""; adminAccess_ = false; banStatus_ = false; } Account::Account(const string& username, const string& password, bool adminAccess, bool banStatus) { username_ = username; password_ = password; adminAccess_ = adminAccess; banStatus_ = banStatus; } void Account::setUsername(const string& username) { username_ = username; }; void Account::setPassword(const string& password) { password_ = password; } void Account::setBanStatus(bool banStatus) { banStatus_ = banStatus; } string Account::getUsername() const { return username_; } string Account::getPassword() const { return password_; } bool Account::getAdminAccess() const { return adminAccess_; } bool Account::getBanStatus() const { return banStatus_; } ostream& account::operator<<(ostream& out, const Account& account) { out << "| " << setw(AccountPrinter::getUsernameLabelLength()) << left << account.username_ << " | " << setw(AccountPrinter::getPasswordLabelLength()) << left << (AccountHandler::getShowPasswordStatus() ? account.password_ : makeMaskedString(account.password_)) << " | " << setw(AccountPrinter::getAdminAccessLabelLength()) << left << (account.adminAccess_ ? "Да" : "Нет") << " | " << setw(AccountPrinter::getBanStatusLabelLength()) << left << (account.banStatus_ ? "Да" : "Нет") << " |"; return out; } Account::~Account() = default;
[ "minilooth@gmail.com" ]
minilooth@gmail.com
9acb75049f0880cda0c3a60bf6186126dcb7e100
d7d5790c315b3f321873bf0c0853c2c7346bc23e
/tests/toolchain/abigen-pass/aliased_type_variant_template_arg.cpp
ab144ec55ac39d47841397307ddc6488520676c0
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
DarthVader1977/eosio.cdt
ee4a45bf7a745c6ffb46a316f4e26228cd048d81
1853c2523ba248fc5dd2232471804543804d2fc4
refs/heads/master
2021-07-16T07:26:10.381721
2020-10-07T09:39:16
2020-10-07T09:39:16
220,968,301
0
0
MIT
2020-10-16T14:46:08
2019-11-11T11:39:44
C++
UTF-8
C++
false
false
529
cpp
/* * Regression test for https://github.com/EOSIO/eosio.cdt/issues/602. * * Verifies that an aliased type can be used as a variant template arg. */ #include <eosio/eosio.hpp> using namespace eosio; using str = std::string; class [[eosio::contract]] aliased_type_variant_template_arg : public contract { public: using contract::contract; [[eosio::action]] void hi(std::variant<uint64_t,str> v) { if (std::holds_alternative<uint64_t>(v)) { } else if (std::holds_alternative<str>(v)) { } } };
[ "jeffreyssmith2nd@gmail.com" ]
jeffreyssmith2nd@gmail.com
ff4a0ed55cb490929099944065c2922c0da293d8
b0568af5234e6ff8bb23d93725b00c895fb44f91
/Assignment1/Assignment1/Order.cpp
bb7a337a34b086a51a8ba5ec52b5b8767ae7d40f
[]
no_license
JaiiParmar/C-Projects
96a9ad390ed04208bdea749670c2463a708842ad
4ec92c65752b365b9b35d07431d3857d9bddd3c9
refs/heads/master
2020-08-28T12:53:59.445140
2020-02-29T12:49:10
2020-02-29T12:49:10
217,704,390
1
0
null
null
null
null
UTF-8
C++
false
false
459
cpp
#include "Order.h" #include <vector> #include <fstream> void Order::createOrder(std::string path) const { std::ifstream fin(path); while (!fin.eof()) { // read line by line and store it in the vector or order. // increment total accordingly } fin.close(); } std::vector<Order> Order::getOrders() const { std::vector<Order> arr(orders.begin(), orders.end()); return arr; } unsigned int Order::totalQuantity() const { return this->total; }
[ "jaiparmar207@gmail.com" ]
jaiparmar207@gmail.com
e8ba7357a7dcf55a802f5f6bb86c6ef87354130b
c5cbf21e9867eb1f4c9b42c5fc9ca3a22c3bc6e0
/src/init.cpp
572e4f97c560f35f7f00bc1f842dddd5c0505622
[ "MIT" ]
permissive
fancywarlock/bitcoinR
3af69835110f3ece8d629919b210bc71aeb9f3fe
12b4dee6342556c0890218b843f29cadfab06214
refs/heads/master
2022-07-17T09:48:39.681406
2020-05-19T22:30:55
2020-05-19T22:30:55
265,382,334
2
3
null
null
null
null
UTF-8
C++
false
false
91,688
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2020 The bitcoinR Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoinr-config.h> #endif #include <init.h> #include <addrman.h> #include <amount.h> #include <chain.h> #include <chainparams.h> #include <checkpoints.h> #include <compat/sanity.h> #include <consensus/validation.h> #include <fs.h> #include <httpserver.h> #include <httprpc.h> #include <index/txindex.h> #include <key.h> #include <validation.h> #include <miner.h> #include <netbase.h> #include <net.h> #include <net_processing.h> #include <policy/feerate.h> #include <policy/fees.h> #include <policy/policy.h> #include <rpc/server.h> #include <rpc/register.h> #include <rpc/blockchain.h> #include <script/standard.h> #include <script/sigcache.h> #include <scheduler.h> #include <shutdown.h> #include <timedata.h> #include <txdb.h> #include <txmempool.h> #include <torcontrol.h> #include <ui_interface.h> #include <util.h> #include <utilmoneystr.h> #include <validationinterface.h> #include <warnings.h> #include <walletinitinterface.h> #include <stdint.h> #include <stdio.h> #ifndef WIN32 #include <signal.h> #endif #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/bind.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #if ENABLE_ZMQ #include <zmq/zmqnotificationinterface.h> #include <zmq/zmqrpc.h> #endif bool fFeeEstimatesInitialized = false; static const bool DEFAULT_PROXYRANDOMIZE = true; static const bool DEFAULT_REST_ENABLE = false; static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false; std::unique_ptr<CConnman> g_connman; std::unique_ptr<PeerLogicValidation> peerLogic; #if !(ENABLE_WALLET) class DummyWalletInit : public WalletInitInterface { public: void AddWalletOptions() const override; bool ParameterInteraction() const override {return true;} void RegisterRPC(CRPCTable &) const override {} bool Verify() const override {return true;} bool Open() const override {LogPrintf("No wallet support compiled in!\n"); return true;} void Start(CScheduler& scheduler) const override {} void Flush() const override {} void Stop() const override {} void Close() const override {} }; void DummyWalletInit::AddWalletOptions() const { std::vector<std::string> opts = {"-addresstype", "-changetype", "-disablewallet", "-discardfee=<amt>", "-fallbackfee=<amt>", "-keypool=<n>", "-mintxfee=<amt>", "-paytxfee=<amt>", "-rescan", "-salvagewallet", "-spendzeroconfchange", "-txconfirmtarget=<n>", "-upgradewallet", "-wallet=<path>", "-walletbroadcast", "-walletdir=<dir>", "-walletnotify=<cmd>", "-walletrbf", "-zapwallettxes=<mode>", "-dblogsize=<n>", "-flushwallet", "-privdb", "-walletrejectlongchains"}; gArgs.AddHiddenArgs(opts); } const WalletInitInterface& g_wallet_init_interface = DummyWalletInit(); #endif #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files don't count towards the fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat"; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets ShutdownRequested(), which makes main thread's // WaitForShutdown() interrupts the thread group. // And then, WaitForShutdown() makes all other on-going threads // in the thread group join the main thread. // Shutdown() is then called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Shutdown for Qt is very similar, only it uses a QTimer to detect // ShutdownRequested() getting set, and then does the normal Qt // shutdown thing. // /** * This is a minimally invasive approach to shutdown on LevelDB read errors from the * chainstate, while keeping user interface out of the common library, which is shared * between bitcoinrd, and bitcoinr-qt and non-server tools. */ class CCoinsViewErrorCatcher final : public CCoinsViewBacked { public: explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} bool GetCoin(const COutPoint &outpoint, Coin &coin) const override { try { return CCoinsViewBacked::GetCoin(outpoint, coin); } catch(const std::runtime_error& e) { uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); LogPrintf("Error reading from database: %s\n", e.what()); // Starting the shutdown sequence and returning false to the caller would be // interpreted as 'entry not found' (as opposed to unable to read data), and // could lead to invalid interpretation. Just exit immediately, as we can't // continue anyway, and all writes should be atomic. abort(); } } // Writes do not need similar protection, as failure to write is handled by the caller. }; static std::unique_ptr<CCoinsViewErrorCatcher> pcoinscatcher; static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle; static boost::thread_group threadGroup; static CScheduler scheduler; void Interrupt() { InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); InterruptREST(); InterruptTorControl(); InterruptMapPort(); if (g_connman) g_connman->Interrupt(); if (g_txindex) { g_txindex->Interrupt(); } } void Shutdown() { LogPrintf("%s: In progress...\n", __func__); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. RenameThread("bitcoinr-shutoff"); mempool.AddTransactionsUpdated(1); StopHTTPRPC(); StopREST(); StopRPC(); StopHTTPServer(); g_wallet_init_interface.Flush(); StopMapPort(); // Because these depend on each-other, we make sure that neither can be // using the other before destroying them. if (peerLogic) UnregisterValidationInterface(peerLogic.get()); if (g_connman) g_connman->Stop(); if (g_txindex) g_txindex->Stop(); StopTorControl(); // After everything has been shut down, but before things get flushed, stop the // CScheduler/checkqueue threadGroup threadGroup.interrupt_all(); threadGroup.join_all(); // After the threads that potentially access these pointers have been stopped, // destruct and reset all to nullptr. peerLogic.reset(); g_connman.reset(); g_txindex.reset(); if (g_is_mempool_loaded && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { DumpMempool(); } if (fFeeEstimatesInitialized) { ::feeEstimator.FlushUnconfirmed(); fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION); if (!est_fileout.IsNull()) ::feeEstimator.Write(est_fileout); else LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string()); fFeeEstimatesInitialized = false; } // FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing if (pcoinsTip != nullptr) { FlushStateToDisk(); } // After there are no more peers/RPC left to give us new data which may generate // CValidationInterface callbacks, flush them... GetMainSignals().FlushBackgroundCallbacks(); // Any future callbacks will be dropped. This should absolutely be safe - if // missing a callback results in an unrecoverable situation, unclean shutdown // would too. The only reason to do the above flushes is to let the wallet catch // up with our current chain to avoid any strange pruning edge cases and make // next startup faster by avoiding rescan. { LOCK(cs_main); if (pcoinsTip != nullptr) { FlushStateToDisk(); } pcoinsTip.reset(); pcoinscatcher.reset(); pcoinsdbview.reset(); pblocktree.reset(); } g_wallet_init_interface.Stop(); #if ENABLE_ZMQ if (g_zmq_notification_interface) { UnregisterValidationInterface(g_zmq_notification_interface); delete g_zmq_notification_interface; g_zmq_notification_interface = nullptr; } #endif #ifndef WIN32 try { fs::remove(GetPidFile()); } catch (const fs::filesystem_error& e) { LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what()); } #endif UnregisterAllValidationInterfaces(); GetMainSignals().UnregisterBackgroundSignalScheduler(); GetMainSignals().UnregisterWithMempoolSignals(mempool); g_wallet_init_interface.Close(); globalVerifyHandle.reset(); ECC_Stop(); LogPrintf("%s: done\n", __func__); } /** * Signal handlers are very limited in what they are allowed to do. * The execution context the handler is invoked in is not guaranteed, * so we restrict handler operations to just touching variables: */ #ifndef WIN32 static void HandleSIGTERM(int) { StartShutdown(); } static void HandleSIGHUP(int) { g_logger->m_reopen_file = true; } #else static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType) { StartShutdown(); Sleep(INFINITE); return true; } #endif #ifndef WIN32 static void registerSignalHandler(int signal, void(*handler)(int)) { struct sigaction sa; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(signal, &sa, nullptr); } #endif static void OnRPCStarted() { uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange); } static void OnRPCStopped() { uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange); RPCNotifyBlockChange(false, nullptr); g_best_block_cv.notify_all(); LogPrint(BCLog::RPC, "RPC stopped.\n"); } void SetupServerArgs() { const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN); const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET); const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN); const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET); // Hidden Options std::vector<std::string> hidden_args = {"-rpcssl", "-benchmark", "-h", "-help", "-socks", "-tor", "-debugnet", "-whitelistalwaysrelay", "-prematurewitness", "-walletprematurewitness", "-promiscuousmempoolflags", "-blockminsize", "-dbcrashratio", "-forcecompactdb", "-usehd", // GUI args. These will be overwritten by SetupUIArgs for the GUI "-allowselfsignedrootcertificates", "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-rootcertificates=<file>", "-splash", "-uiplatform"}; // Set all of the args and their help // When adding new options to the categories, please keep and ensure alphabetical ordering. gArgs.AddArg("-?", "Print this help message and exit", false, OptionsCategory::OPTIONS); gArgs.AddArg("-version", "Print version and exit", false, OptionsCategory::OPTIONS); gArgs.AddArg("-alertnotify=<cmd>", "Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)", false, OptionsCategory::OPTIONS); gArgs.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()), false, OptionsCategory::OPTIONS); gArgs.AddArg("-blocksdir=<dir>", "Specify blocks directory (default: <datadir>/blocks)", false, OptionsCategory::OPTIONS); gArgs.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", false, OptionsCategory::OPTIONS); gArgs.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), false, OptionsCategory::OPTIONS); gArgs.AddArg("-blocksonly", strprintf("Whether to operate in a blocks only mode (default: %u)", DEFAULT_BLOCKSONLY), true, OptionsCategory::OPTIONS); gArgs.AddArg("-conf=<file>", strprintf("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOINR_CONF_FILENAME), false, OptionsCategory::OPTIONS); gArgs.AddArg("-datadir=<dir>", "Specify data directory", false, OptionsCategory::OPTIONS); gArgs.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), true, OptionsCategory::OPTIONS); gArgs.AddArg("-dbcache=<n>", strprintf("Set database cache size in megabytes (%d to %d, default: %d)", nMinDbCache, nMaxDbCache, nDefaultDbCache), false, OptionsCategory::OPTIONS); gArgs.AddArg("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), false, OptionsCategory::OPTIONS); gArgs.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), true, OptionsCategory::OPTIONS); gArgs.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", false, OptionsCategory::OPTIONS); gArgs.AddArg("-loadblock=<file>", "Imports blocks from external blk000??.dat file on startup", false, OptionsCategory::OPTIONS); gArgs.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), false, OptionsCategory::OPTIONS); gArgs.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), false, OptionsCategory::OPTIONS); gArgs.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), false, OptionsCategory::OPTIONS); gArgs.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()), true, OptionsCategory::OPTIONS); gArgs.AddArg("-par=<n>", strprintf("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)", -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), false, OptionsCategory::OPTIONS); gArgs.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), false, OptionsCategory::OPTIONS); #ifndef WIN32 gArgs.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOINR_PID_FILENAME), false, OptionsCategory::OPTIONS); #else hidden_args.emplace_back("-pid"); #endif gArgs.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. " "Warning: Reverting this setting requires re-downloading the entire blockchain. " "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), false, OptionsCategory::OPTIONS); gArgs.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", false, OptionsCategory::OPTIONS); gArgs.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks", false, OptionsCategory::OPTIONS); #ifndef WIN32 gArgs.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", false, OptionsCategory::OPTIONS); #else hidden_args.emplace_back("-sysperms"); #endif gArgs.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), false, OptionsCategory::OPTIONS); gArgs.AddArg("-addnode=<ip>", "Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.", false, OptionsCategory::CONNECTION); gArgs.AddArg("-banscore=<n>", strprintf("Threshold for disconnecting misbehaving peers (default: %u)", DEFAULT_BANSCORE_THRESHOLD), false, OptionsCategory::CONNECTION); gArgs.AddArg("-bantime=<n>", strprintf("Number of seconds to keep misbehaving peers from reconnecting (default: %u)", DEFAULT_MISBEHAVING_BANTIME), false, OptionsCategory::CONNECTION); gArgs.AddArg("-bind=<addr>", "Bind to given address and always listen on it. Use [host]:port notation for IPv6", false, OptionsCategory::CONNECTION); gArgs.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", false, OptionsCategory::CONNECTION); gArgs.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", false, OptionsCategory::CONNECTION); gArgs.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), false, OptionsCategory::CONNECTION); gArgs.AddArg("-dnsseed", "Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)", false, OptionsCategory::CONNECTION); gArgs.AddArg("-enablebip61", strprintf("Send reject messages per BIP61 (default: %u)", DEFAULT_ENABLE_BIP61), false, OptionsCategory::CONNECTION); gArgs.AddArg("-externalip=<ip>", "Specify your own public address", false, OptionsCategory::CONNECTION); gArgs.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), false, OptionsCategory::CONNECTION); gArgs.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", false, OptionsCategory::CONNECTION); gArgs.AddArg("-listenonion", strprintf("Automatically create Tor hidden service (default: %d)", DEFAULT_LISTEN_ONION), false, OptionsCategory::CONNECTION); gArgs.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u)", DEFAULT_MAX_PEER_CONNECTIONS), false, OptionsCategory::CONNECTION); gArgs.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), false, OptionsCategory::CONNECTION); gArgs.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), false, OptionsCategory::CONNECTION); gArgs.AddArg("-maxtimeadjustment", strprintf("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)", DEFAULT_MAX_TIME_ADJUSTMENT), false, OptionsCategory::CONNECTION); gArgs.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)", DEFAULT_MAX_UPLOAD_TARGET), false, OptionsCategory::CONNECTION); gArgs.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor hidden services, set -noonion to disable (default: -proxy)", false, OptionsCategory::CONNECTION); gArgs.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks.", false, OptionsCategory::CONNECTION); gArgs.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), false, OptionsCategory::CONNECTION); gArgs.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), false, OptionsCategory::CONNECTION); gArgs.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u or testnet: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort()), false, OptionsCategory::CONNECTION); gArgs.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", false, OptionsCategory::CONNECTION); gArgs.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), false, OptionsCategory::CONNECTION); gArgs.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", false, OptionsCategory::CONNECTION); gArgs.AddArg("-timeout=<n>", strprintf("Specify connection timeout in milliseconds (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), false, OptionsCategory::CONNECTION); gArgs.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), false, OptionsCategory::CONNECTION); gArgs.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", false, OptionsCategory::CONNECTION); #ifdef USE_UPNP #if USE_UPNP gArgs.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", false, OptionsCategory::CONNECTION); #else gArgs.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), false, OptionsCategory::CONNECTION); #endif #else hidden_args.emplace_back("-upnp"); #endif gArgs.AddArg("-whitebind=<addr>", "Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6", false, OptionsCategory::CONNECTION); gArgs.AddArg("-whitelist=<IP address or network>", "Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times." " Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway", false, OptionsCategory::CONNECTION); g_wallet_init_interface.AddWalletOptions(); #if ENABLE_ZMQ gArgs.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", false, OptionsCategory::ZMQ); gArgs.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", false, OptionsCategory::ZMQ); gArgs.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", false, OptionsCategory::ZMQ); gArgs.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", false, OptionsCategory::ZMQ); #else hidden_args.emplace_back("-zmqpubhashblock=<address>"); hidden_args.emplace_back("-zmqpubhashtx=<address>"); hidden_args.emplace_back("-zmqpubrawblock=<address>"); hidden_args.emplace_back("-zmqpubrawtx=<address>"); #endif gArgs.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is (0-4, default: %u)", DEFAULT_CHECKLEVEL), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. (default: %u)", defaultChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", defaultChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages", true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-vbparams=deployment:start:end", "Use given start/end times for specified version bits deployment (regtest-only)", true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-addrmantest", "Allows to test address relay on localhost", true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). " "If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + ListLogCategories() + ".", false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-debugexclude=<category>", strprintf("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories."), false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-help-debug", "Show all debugging options (usage: --help -help-debug)", false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)", true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-maxtxfee=<amt>", strprintf("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)), false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", false, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", false, OptionsCategory::DEBUG_TEST); SetupChainParamsBaseOptions(); gArgs.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), true, OptionsCategory::NODE_RELAY); gArgs.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), true, OptionsCategory::NODE_RELAY); gArgs.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), true, OptionsCategory::NODE_RELAY); gArgs.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), false, OptionsCategory::NODE_RELAY); gArgs.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), false, OptionsCategory::NODE_RELAY); gArgs.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), false, OptionsCategory::NODE_RELAY); gArgs.AddArg("-mempoolreplacement", strprintf("Enable transaction replacement in the memory pool (default: %u)", DEFAULT_ENABLE_REPLACEMENT), false, OptionsCategory::NODE_RELAY); gArgs.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), false, OptionsCategory::NODE_RELAY); gArgs.AddArg("-whitelistforcerelay", strprintf("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)", DEFAULT_WHITELISTFORCERELAY), false, OptionsCategory::NODE_RELAY); gArgs.AddArg("-whitelistrelay", strprintf("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), false, OptionsCategory::NODE_RELAY); gArgs.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), false, OptionsCategory::BLOCK_CREATION); gArgs.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), false, OptionsCategory::BLOCK_CREATION); gArgs.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", true, OptionsCategory::BLOCK_CREATION); gArgs.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), false, OptionsCategory::RPC); gArgs.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times", false, OptionsCategory::RPC); gArgs.AddArg("-rpcauth=<userpw>", "Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", false, OptionsCategory::RPC); gArgs.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)", false, OptionsCategory::RPC); gArgs.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", false, OptionsCategory::RPC); gArgs.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", false, OptionsCategory::RPC); gArgs.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()), false, OptionsCategory::RPC); gArgs.AddArg("-rpcserialversion", strprintf("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION), false, OptionsCategory::RPC); gArgs.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), true, OptionsCategory::RPC); gArgs.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), false, OptionsCategory::RPC); gArgs.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", false, OptionsCategory::RPC); gArgs.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), true, OptionsCategory::RPC); gArgs.AddArg("-server", "Accept command line and JSON-RPC commands", false, OptionsCategory::RPC); #if HAVE_DECL_DAEMON gArgs.AddArg("-daemon", "Run in the background as a daemon and accept commands", false, OptionsCategory::OPTIONS); #else hidden_args.emplace_back("-daemon"); #endif // Add the hidden options gArgs.AddHiddenArgs(hidden_args); } std::string LicenseInfo() { const std::string URL_SOURCE_CODE = "<https://www.gitgub.com/fancywarlock/bitcoinr>"; const std::string URL_WEBSITE = "<https://www.bitcoinr.org>"; return CopyrightHolders(strprintf(_("Copyright (C) %i"), COPYRIGHT_YEAR) + " ") + "\n" + "\n" + strprintf(_("Please contribute if you find %s useful. " "Visit %s for further information about the software."), PACKAGE_NAME, URL_WEBSITE) + "\n" + strprintf(_("The source code is available from %s."), URL_SOURCE_CODE) + "\n" + "\n" + _("This is experimental software.") + "\n" + strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" + "\n" + strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."), "<https://www.openssl.org>") + "\n"; } static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex) { if (initialSync || !pBlockIndex) return; std::string strCmd = gArgs.GetArg("-blocknotify", ""); if (!strCmd.empty()) { boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex()); std::thread t(runCommand, strCmd); t.detach(); // thread runs free } } static bool fHaveGenesis = false; static CWaitableCriticalSection cs_GenesisWait; static CConditionVariable condvar_GenesisWait; static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex) { if (pBlockIndex != nullptr) { { WaitableLock lock_GenesisWait(cs_GenesisWait); fHaveGenesis = true; } condvar_GenesisWait.notify_all(); } } struct CImportingNow { CImportingNow() { assert(fImporting == false); fImporting = true; } ~CImportingNow() { assert(fImporting == true); fImporting = false; } }; // If we're using -prune with -reindex, then delete block files that will be ignored by the // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile // is missing, do the same here to delete any later block files after a gap. Also delete all // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile // is in sync with what's actually on disk by the time we start downloading, so that pruning // works correctly. static void CleanupBlockRevFiles() { std::map<std::string, fs::path> mapBlockFiles; // Glob all blk?????.dat and rev?????.dat files from the blocks directory. // Remove the rev files immediately and insert the blk file paths into an // ordered map keyed by block file index. LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n"); fs::path blocksdir = GetBlocksDir(); for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) { if (fs::is_regular_file(*it) && it->path().filename().string().length() == 12 && it->path().filename().string().substr(8,4) == ".dat") { if (it->path().filename().string().substr(0,3) == "blk") mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path(); else if (it->path().filename().string().substr(0,3) == "rev") remove(it->path()); } } // Remove all block files that aren't part of a contiguous set starting at // zero by walking the ordered map (keys are block file indices) by // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist) // start removing block files. int nContigCounter = 0; for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) { if (atoi(item.first) == nContigCounter) { nContigCounter++; continue; } remove(item.second); } } static void ThreadImport(std::vector<fs::path> vImportFiles) { const CChainParams& chainparams = Params(); RenameThread("bitcoinr-loadblk"); ScheduleBatchPriority(); { CImportingNow imp; // -reindex if (fReindex) { int nFile = 0; while (true) { CDiskBlockPos pos(nFile, 0); if (!fs::exists(GetBlockPosFilename(pos, "blk"))) break; // No block files left to reindex FILE *file = OpenBlockFile(pos, true); if (!file) break; // This error is logged in OpenBlockFile LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); LoadExternalBlockFile(chainparams, file, &pos); nFile++; } pblocktree->WriteReindexing(false); fReindex = false; LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): LoadGenesisBlock(chainparams); } // hardcoded $DATADIR/bootstrap.dat fs::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (fs::exists(pathBootstrap)) { FILE *file = fsbridge::fopen(pathBootstrap, "rb"); if (file) { fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LogPrintf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(chainparams, file); RenameOver(pathBootstrap, pathBootstrapOld); } else { LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string()); } } // -loadblock= for (const fs::path& path : vImportFiles) { FILE *file = fsbridge::fopen(path, "rb"); if (file) { LogPrintf("Importing blocks file %s...\n", path.string()); LoadExternalBlockFile(chainparams, file); } else { LogPrintf("Warning: Could not open blocks file %s\n", path.string()); } } // scan for better chains in the block chain database, that are not yet connected in the active best chain CValidationState state; if (!ActivateBestChain(state, chainparams)) { LogPrintf("Failed to connect best block (%s)\n", FormatStateMessage(state)); StartShutdown(); return; } if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) { LogPrintf("Stopping after block import\n"); StartShutdown(); return; } } // End scope of CImportingNow if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) { LoadMempool(); } g_is_mempool_loaded = !ShutdownRequested(); } /** Sanity checks * Ensure that bitcoinR is running in a usable environment with all * necessary library support. */ static bool InitSanityCheck(void) { if(!ECC_InitSanityCheck()) { InitError("Elliptic curve cryptography sanity check failure. Aborting."); return false; } if (!glibc_sanity_test() || !glibcxx_sanity_test()) return false; if (!Random_SanityCheck()) { InitError("OS cryptographic RNG sanity check failure. Aborting."); return false; } return true; } static bool AppInitServers() { RPCServer::OnStarted(&OnRPCStarted); RPCServer::OnStopped(&OnRPCStopped); if (!InitHTTPServer()) return false; StartRPC(); if (!StartHTTPRPC()) return false; if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST()) return false; StartHTTPServer(); return true; } // Parameter interaction based on rules void InitParameterInteraction() { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (gArgs.IsArgSet("-bind")) { if (gArgs.SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__); } if (gArgs.IsArgSet("-whitebind")) { if (gArgs.SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); } if (gArgs.IsArgSet("-connect")) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (gArgs.SoftSetBoolArg("-dnsseed", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__); if (gArgs.SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__); } if (gArgs.IsArgSet("-proxy")) { // to protect privacy, do not listen by default if a default proxy server is specified if (gArgs.SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1 // to listen locally, so don't rely on this happening through -listen below. if (gArgs.SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); // to protect privacy, do not discover addresses by default if (gArgs.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__); } if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (gArgs.SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__); if (gArgs.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__); if (gArgs.SoftSetBoolArg("-listenonion", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__); } if (gArgs.IsArgSet("-externalip")) { // if an explicit public IP is specified, do not try to find others if (gArgs.SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); } // disable whitelistrelay in blocksonly mode if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) { if (gArgs.SoftSetBoolArg("-whitelistrelay", false)) LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__); } // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place. if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) { if (gArgs.SoftSetBoolArg("-whitelistrelay", true)) LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__); } // Warn if network-specific options (-addnode, -connect, etc) are // specified in default section of config file, but not overridden // on the command line or in this network's section of the config file. gArgs.WarnForSectionOnlyArgs(); } static std::string ResolveErrMsg(const char * const optname, const std::string& strBind) { return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind); } /** * Initialize global loggers. * * Note that this is called very early in the process lifetime, so you should be * careful about what global state you rely on here. */ void InitLogging() { g_logger->m_print_to_file = !gArgs.IsArgNegated("-debuglogfile"); g_logger->m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE)); // Add newlines to the logfile to distinguish this execution from the last // one; called before console logging is set up, so this is only sent to // debug.log. LogPrintf("\n\n\n\n\n"); g_logger->m_print_to_console = gArgs.GetBoolArg("-printtoconsole", !gArgs.GetBoolArg("-daemon", false)); g_logger->m_log_timestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS); g_logger->m_log_time_micros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS); fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS); std::string version_string = FormatFullVersion(); #ifdef DEBUG version_string += " (debug build)"; #else version_string += " (release build)"; #endif LogPrintf(PACKAGE_NAME " version %s\n", version_string); } namespace { // Variables internal to initialization process only int nMaxConnections; int nUserMaxConnections; int nFD; ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK | NODE_NETWORK_LIMITED); } // namespace [[noreturn]] static void new_handler_terminate() { // Rather than throwing std::bad-alloc if allocation fails, terminate // immediately to (try to) avoid chain corruption. // Since LogPrintf may itself allocate memory, set the handler directly // to terminate first. std::set_new_handler(std::terminate); LogPrintf("Error: Out of memory. Terminating.\n"); // The log was successful, terminate now. std::terminate(); }; bool AppInitBasicSetup() { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0)); // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != nullptr) setProcDEPPol(PROCESS_DEP_ENABLE); #endif if (!SetupNetworking()) return InitError("Initializing networking failed"); #ifndef WIN32 if (!gArgs.GetBoolArg("-sysperms", false)) { umask(077); } // Clean shutdown on SIGTERM registerSignalHandler(SIGTERM, HandleSIGTERM); registerSignalHandler(SIGINT, HandleSIGTERM); // Reopen debug.log on SIGHUP registerSignalHandler(SIGHUP, HandleSIGHUP); // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly signal(SIGPIPE, SIG_IGN); #else SetConsoleCtrlHandler(consoleCtrlHandler, true); #endif std::set_new_handler(new_handler_terminate); return true; } bool AppInitParameterInteraction() { const CChainParams& chainparams = Params(); // ********************************************************* Step 2: parameter interactions // also see: InitParameterInteraction() if (!fs::is_directory(GetBlocksDir(false))) { return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist."), gArgs.GetArg("-blocksdir", "").c_str())); } // if using block pruning, then disallow txindex if (gArgs.GetArg("-prune", 0)) { if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) return InitError(_("Prune mode is incompatible with -txindex.")); } // -bind and -whitebind can't be set when not listening size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size(); if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) { return InitError("Cannot set -bind or -whitebind together with -listen=0"); } // Make sure enough file descriptors are available int nBind = std::max(nUserBind, size_t(1)); nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); nMaxConnections = std::max(nUserMaxConnections, 0); // Trim requested connection counts, to fit into system limitations // <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695 nMaxConnections = std::max(std::min<int>(nMaxConnections, FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0); nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections); if (nMaxConnections < nUserMaxConnections) InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections)); // ********************************************************* Step 3: parameter-to-internal-flags if (gArgs.IsArgSet("-debug")) { // Special-case: if -debug=0/-nodebug is set, turn off debugging messages const std::vector<std::string> categories = gArgs.GetArgs("-debug"); if (std::none_of(categories.begin(), categories.end(), [](std::string cat){return cat == "0" || cat == "none";})) { for (const auto& cat : categories) { if (!g_logger->EnableCategory(cat)) { InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat)); } } } } // Now remove the logging categories which were explicitly excluded for (const std::string& cat : gArgs.GetArgs("-debugexclude")) { if (!g_logger->DisableCategory(cat)) { InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat)); } } // Check for -debugnet if (gArgs.GetBoolArg("-debugnet", false)) InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net.")); // Check for -socks - as this is a privacy risk to continue, exit here if (gArgs.IsArgSet("-socks")) return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); // Check for -tor - as this is a privacy risk to continue, exit here if (gArgs.GetBoolArg("-tor", false)) return InitError(_("Unsupported argument -tor found, use -onion.")); if (gArgs.GetBoolArg("-benchmark", false)) InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench.")); if (gArgs.GetBoolArg("-whitelistalwaysrelay", false)) InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.")); if (gArgs.IsArgSet("-blockminsize")) InitWarning("Unsupported argument -blockminsize ignored."); // Checkmempool and checkblockindex default to true in regtest mode int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000); if (ratio != 0) { mempool.setSanityCheck(1.0 / ratio); } fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks()); fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED); hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex())); if (!hashAssumeValid.IsNull()) LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex()); else LogPrintf("Validating signatures for all blocks.\n"); if (gArgs.IsArgSet("-minimumchainwork")) { const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", ""); if (!IsHexNumber(minChainWorkStr)) { return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr)); } nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr)); } else { nMinimumChainWork = UintToArith256(chainparams.GetConsensus().nMinimumChainWork); } LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex()); if (nMinimumChainWork < UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) { LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex()); } // mempool limits int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40; if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin) return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0))); // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting. if (gArgs.IsArgSet("-incrementalrelayfee")) { CAmount n = 0; if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n)) return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", ""))); incrementalRelayFee = CFeeRate(n); } // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); if (nScriptCheckThreads <= 0) nScriptCheckThreads += GetNumCores(); if (nScriptCheckThreads <= 1) nScriptCheckThreads = 0; else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; // block pruning; get the amount of disk space (in MiB) to allot for block & undo files int64_t nPruneArg = gArgs.GetArg("-prune", 0); if (nPruneArg < 0) { return InitError(_("Prune cannot be configured with a negative value.")); } nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024; if (nPruneArg == 1) { // manual pruning: -prune=1 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n"); nPruneTarget = std::numeric_limits<uint64_t>::max(); fPruneMode = true; } else if (nPruneTarget) { if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) { return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); } LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024); fPruneMode = true; } nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT); if (nConnectTimeout <= 0) nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; if (gArgs.IsArgSet("-minrelaytxfee")) { CAmount n = 0; if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) { return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", ""))); } // High fee check is done afterward in WalletParameterInteraction() ::minRelayTxFee = CFeeRate(n); } else if (incrementalRelayFee > ::minRelayTxFee) { // Allow only setting incrementalRelayFee to control both ::minRelayTxFee = incrementalRelayFee; LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString()); } // Sanity check argument for min fee for including tx in block // TODO: Harmonize which arguments need sanity checking and where that happens if (gArgs.IsArgSet("-blockmintxfee")) { CAmount n = 0; if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n)) return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", ""))); } // Feerate used to define dust. Shouldn't be changed lightly as old // implementations may inadvertently create non-standard transactions if (gArgs.IsArgSet("-dustrelayfee")) { CAmount n = 0; if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n)) return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", ""))); dustRelayFee = CFeeRate(n); } fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard()); if (chainparams.RequireStandard() && !fRequireStandard) return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString())); nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp); if (!g_wallet_init_interface.ParameterInteraction()) return false; fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG); fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER); nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes); // Option to startup with mocktime set (used for regression testing): SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM); if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0) return InitError("rpcserialversion must be non-negative."); if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1) return InitError("unknown rpcserialversion requested."); nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE); fEnableReplacement = gArgs.GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT); if ((!fEnableReplacement) && gArgs.IsArgSet("-mempoolreplacement")) { // Minimal effort at forwards compatibility std::string strReplacementModeList = gArgs.GetArg("-mempoolreplacement", ""); // default is impossible std::vector<std::string> vstrReplacementModes; boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(",")); fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end()); } if (gArgs.IsArgSet("-vbparams")) { // Allow overriding version bits parameters for testing if (!chainparams.MineBlocksOnDemand()) { return InitError("Version bits parameters may only be overridden on regtest."); } for (const std::string& strDeployment : gArgs.GetArgs("-vbparams")) { std::vector<std::string> vDeploymentParams; boost::split(vDeploymentParams, strDeployment, boost::is_any_of(":")); if (vDeploymentParams.size() != 3) { return InitError("Version bits parameters malformed, expecting deployment:start:end"); } int64_t nStartTime, nTimeout; if (!ParseInt64(vDeploymentParams[1], &nStartTime)) { return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1])); } if (!ParseInt64(vDeploymentParams[2], &nTimeout)) { return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2])); } bool found = false; for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) { if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) { UpdateVersionBitsParameters(Consensus::DeploymentPos(j), nStartTime, nTimeout); found = true; LogPrintf("Setting version bits activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout); break; } } if (!found) { return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0])); } } } return true; } static bool LockDataDirectory(bool probeOnly) { // Make sure only a single bitcoinR process is using the data directory. fs::path datadir = GetDataDir(); if (!DirIsWritable(datadir)) { return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions."), datadir.string())); } if (!LockDirectory(datadir, ".lock", probeOnly)) { return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), datadir.string(), _(PACKAGE_NAME))); } return true; } bool AppInitSanityChecks() { // ********************************************************* Step 4: sanity checks // Initialize elliptic curve code std::string sha256_algo = SHA256AutoDetect(); LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo); RandomInit(); ECC_Start(); globalVerifyHandle.reset(new ECCVerifyHandle()); // Sanity check if (!InitSanityCheck()) return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME))); // Probe the data directory lock to give an early error message, if possible // We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened, // and a fork will cause weird behavior to it. return LockDataDirectory(true); } bool AppInitLockDataDirectory() { // After daemonization get the data directory lock again and hold on to it until exit // This creates a slight window for a race condition to happen, however this condition is harmless: it // will at most make us exit without printing a message to console. if (!LockDataDirectory(false)) { // Detailed error printed inside LockDataDirectory return false; } return true; } bool AppInitMain() { const CChainParams& chainparams = Params(); // ********************************************************* Step 4a: application initialization #ifndef WIN32 CreatePidFile(GetPidFile(), getpid()); #endif if (g_logger->m_print_to_file) { if (gArgs.GetBoolArg("-shrinkdebugfile", g_logger->DefaultShrinkDebugFile())) { // Do this first since it both loads a bunch of debug.log into memory, // and because this needs to happen before any other debug.log printing g_logger->ShrinkDebugFile(); } if (!g_logger->OpenDebugLog()) { return InitError(strprintf("Could not open debug log file %s", g_logger->m_file_path.string())); } } if (!g_logger->m_log_timestamps) LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime())); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); LogPrintf("Using data directory %s\n", GetDataDir().string()); LogPrintf("Using config file %s\n", GetConfigFile(gArgs.GetArg("-conf", BITCOINR_CONF_FILENAME)).string()); LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD); // Warn about relative -datadir path. if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) { LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */ "current working directory '%s'. This is fragile, because if bitcoinr is started in the future " "from a different location, it will be unable to locate the current data files. There could " "also be data loss if bitcoinr is started while in a temporary directory.\n", gArgs.GetArg("-datadir", ""), fs::current_path().string()); } InitSignatureCache(); InitScriptExecutionCache(); LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads); if (nScriptCheckThreads) { for (int i=0; i<nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } // Start the lightweight task scheduler thread CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler); threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop)); GetMainSignals().RegisterBackgroundSignalScheduler(scheduler); GetMainSignals().RegisterWithMempoolSignals(mempool); /* Register RPC commands regardless of -server setting so they will be * available in the GUI RPC console even if external calls are disabled. */ RegisterAllCoreRPCCommands(tableRPC); g_wallet_init_interface.RegisterRPC(tableRPC); #if ENABLE_ZMQ RegisterZMQRPCCommands(tableRPC); #endif /* Start the RPC server already. It will be started in "warmup" mode * and not really process calls already (but it will signify connections * that the server is there and will be ready later). Warmup mode will * be disabled when initialisation is finished. */ if (gArgs.GetBoolArg("-server", false)) { uiInterface.InitMessage.connect(SetRPCWarmupStatus); if (!AppInitServers()) return InitError(_("Unable to start HTTP server. See debug log for details.")); } // ********************************************************* Step 5: verify wallet database integrity if (!g_wallet_init_interface.Verify()) return false; // ********************************************************* Step 6: network initialization // Note that we absolutely cannot open any actual connections // until the very end ("start node") as the UTXO/block state // is not yet setup and may end up being set up twice if we // need to reindex later. assert(!g_connman); g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()))); CConnman& connman = *g_connman; peerLogic.reset(new PeerLogicValidation(&connman, scheduler, gArgs.GetBoolArg("-enablebip61", DEFAULT_ENABLE_BIP61))); RegisterValidationInterface(peerLogic.get()); // sanitize comments per BIP-0014, format user agent and check total size std::vector<std::string> uacomments; for (const std::string& cmt : gArgs.GetArgs("-uacomment")) { if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); uacomments.push_back(cmt); } strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments); if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."), strSubVersion.size(), MAX_SUBVERSION_LENGTH)); } if (gArgs.IsArgSet("-onlynet")) { std::set<enum Network> nets; for (const std::string& snet : gArgs.GetArgs("-onlynet")) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } // Check for host lookup allowed before parsing any network related parameters fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP); bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE); // -proxy sets a proxy for all outgoing network traffic // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default std::string proxyArg = gArgs.GetArg("-proxy", ""); SetLimited(NET_ONION); if (proxyArg != "" && proxyArg != "0") { CService proxyAddr; if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) { return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); } proxyType addrProxy = proxyType(proxyAddr, proxyRandomize); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); SetProxy(NET_IPV4, addrProxy); SetProxy(NET_IPV6, addrProxy); SetProxy(NET_ONION, addrProxy); SetNameProxy(addrProxy); SetLimited(NET_ONION, false); // by default, -proxy sets onion as reachable, unless -noonion later } // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses // -noonion (or -onion=0) disables connecting to .onion entirely // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none) std::string onionArg = gArgs.GetArg("-onion", ""); if (onionArg != "") { if (onionArg == "0") { // Handle -noonion/-onion=0 SetLimited(NET_ONION); // set onions as unreachable } else { CService onionProxy; if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) { return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg)); } proxyType addrOnion = proxyType(onionProxy, proxyRandomize); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg)); SetProxy(NET_ONION, addrOnion); SetLimited(NET_ONION, false); } } // see Step 2: parameter interactions for more information about these fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN); fDiscover = gArgs.GetBoolArg("-discover", true); fRelayTxes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY); for (const std::string& strAddr : gArgs.GetArgs("-externalip")) { CService addrLocal; if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid()) AddLocal(addrLocal, LOCAL_MANUAL); else return InitError(ResolveErrMsg("externalip", strAddr)); } #if ENABLE_ZMQ g_zmq_notification_interface = CZMQNotificationInterface::Create(); if (g_zmq_notification_interface) { RegisterValidationInterface(g_zmq_notification_interface); } #endif uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME; if (gArgs.IsArgSet("-maxuploadtarget")) { nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024; } // ********************************************************* Step 7: load block chain fReindex = gArgs.GetBoolArg("-reindex", false); bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false); // cache size calculations int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20); nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20); nTotalCache -= nBlockTreeDBCache; int64_t nTxIndexCache = std::min(nTotalCache / 8, gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0); nTotalCache -= nTxIndexCache; int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache nTotalCache -= nCoinDBCache; nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; LogPrintf("Cache configuration:\n"); LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024)); if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { LogPrintf("* Using %.1fMiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024)); } LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024)); LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024)); bool fLoaded = false; while (!fLoaded && !ShutdownRequested()) { bool fReset = fReindex; std::string strLoadError; uiInterface.InitMessage(_("Loading block index...")); LOCK(cs_main); do { const int64_t load_block_index_start_time = GetTimeMillis(); try { UnloadBlockIndex(); pcoinsTip.reset(); pcoinsdbview.reset(); pcoinscatcher.reset(); // new CBlockTreeDB tries to delete the existing file, which // fails if it's still open from the previous loop. Close it first: pblocktree.reset(); pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset)); if (fReset) { pblocktree->WriteReindexing(true); //If we're reindexing in prune mode, wipe away unusable block files and all undo data files if (fPruneMode) CleanupBlockRevFiles(); } if (ShutdownRequested()) break; // LoadBlockIndex will load fHavePruned if we've ever removed a // block file from disk. // Note that it also sets fReindex based on the disk flag! // From here on out fReindex and fReset mean something different! if (!LoadBlockIndex(chainparams)) { strLoadError = _("Error loading block database"); break; } // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). if (!mapBlockIndex.empty() && !LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) { return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); } // Check for changed -prune state. What we are concerned about is a user who has pruned blocks // in the past, but is now trying to run unpruned. if (fHavePruned && !fPruneMode) { strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain"); break; } // At this point blocktree args are consistent with what's on disk. // If we're not mid-reindex (based on disk + args), add a genesis block on disk // (otherwise we use the one already on disk). // This is called again in ThreadImport after the reindex completes. if (!fReindex && !LoadGenesisBlock(chainparams)) { strLoadError = _("Error initializing block database"); break; } // At this point we're either in reindex or we've loaded a useful // block tree into mapBlockIndex! pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState)); pcoinscatcher.reset(new CCoinsViewErrorCatcher(pcoinsdbview.get())); // If necessary, upgrade from older database format. // This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate if (!pcoinsdbview->Upgrade()) { strLoadError = _("Error upgrading chainstate database"); break; } // ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate if (!ReplayBlocks(chainparams, pcoinsdbview.get())) { strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate."); break; } // The on-disk coinsdb is now in a good state, create the cache pcoinsTip.reset(new CCoinsViewCache(pcoinscatcher.get())); bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull(); if (!is_coinsview_empty) { // LoadChainTip sets chainActive based on pcoinsTip's best block if (!LoadChainTip(chainparams)) { strLoadError = _("Error initializing block database"); break; } assert(chainActive.Tip() != nullptr); } if (!fReset) { // Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate. // It both disconnects blocks based on chainActive, and drops block data in // mapBlockIndex based on lack of available witness data. uiInterface.InitMessage(_("Rewinding blocks...")); if (!RewindBlockIndex(chainparams)) { strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain"); break; } } if (!is_coinsview_empty) { uiInterface.InitMessage(_("Verifying blocks...")); if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) { LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n", MIN_BLOCKS_TO_KEEP); } CBlockIndex* tip = chainActive.Tip(); RPCNotifyBlockChange(true, tip); if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) { strLoadError = _("The block database contains a block which appears to be from the future. " "This may be due to your computer's date and time being set incorrectly. " "Only rebuild the block database if you are sure that your computer's date and time are correct"); break; } if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview.get(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL), gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) { strLoadError = _("Corrupted block database detected"); break; } } } catch (const std::exception& e) { LogPrintf("%s\n", e.what()); strLoadError = _("Error opening block database"); break; } fLoaded = true; LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time); } while(false); if (!fLoaded && !ShutdownRequested()) { // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeQuestion( strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.", "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; AbortShutdown(); } else { LogPrintf("Aborted block database rebuild. Exiting.\n"); return false; } } else { return InitError(strLoadError); } } } // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (ShutdownRequested()) { LogPrintf("Shutdown requested. Exiting.\n"); return false; } fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION); // Allowed to fail as this file IS missing on first startup. if (!est_filein.IsNull()) ::feeEstimator.Read(est_filein); fFeeEstimatesInitialized = true; // ********************************************************* Step 8: start indexers if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) { g_txindex = MakeUnique<TxIndex>(nTxIndexCache, false, fReindex); g_txindex->Start(); } // ********************************************************* Step 9: load wallet if (!g_wallet_init_interface.Open()) return false; // ********************************************************* Step 10: data directory maintenance // if pruning, unset the service bit and perform the initial blockstore prune // after any wallet rescanning has taken place. if (fPruneMode) { LogPrintf("Unsetting NODE_NETWORK on prune mode\n"); nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK); if (!fReindex) { uiInterface.InitMessage(_("Pruning blockstore...")); PruneAndFlush(); } } if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) { // Only advertise witness capabilities if they have a reasonable start time. // This allows us to have the code merged without a defined softfork, by setting its // end time to 0. // Note that setting NODE_WITNESS is never required: the only downside from not // doing so is that after activation, no upgraded nodes will fetch from you. nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS); } // ********************************************************* Step 11: import blocks if (!CheckDiskSpace() && !CheckDiskSpace(0, true)) return false; // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly. // No locking, as this happens before any background thread is started. if (chainActive.Tip() == nullptr) { uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait); } else { fHaveGenesis = true; } if (gArgs.IsArgSet("-blocknotify")) uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); std::vector<fs::path> vImportFiles; for (const std::string& strFile : gArgs.GetArgs("-loadblock")) { vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); // Wait for genesis block to be processed { WaitableLock lock(cs_GenesisWait); // We previously could hang here if StartShutdown() is called prior to // ThreadImport getting started, so instead we just wait on a timer to // check ShutdownRequested() regularly. while (!fHaveGenesis && !ShutdownRequested()) { condvar_GenesisWait.wait_for(lock, std::chrono::milliseconds(500)); } uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait); } if (ShutdownRequested()) { return false; } // ********************************************************* Step 12: start node int chain_active_height; //// debug print { LOCK(cs_main); LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); chain_active_height = chainActive.Height(); } LogPrintf("nBestHeight = %d\n", chain_active_height); if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) StartTorControl(); Discover(); // Map ports with UPnP if (gArgs.GetBoolArg("-upnp", DEFAULT_UPNP)) { StartMapPort(); } CConnman::Options connOptions; connOptions.nLocalServices = nLocalServices; connOptions.nMaxConnections = nMaxConnections; connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections); connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS; connOptions.nMaxFeeler = 1; connOptions.nBestHeight = chain_active_height; connOptions.uiInterface = &uiInterface; connOptions.m_msgproc = peerLogic.get(); connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); connOptions.m_added_nodes = gArgs.GetArgs("-addnode"); connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe; connOptions.nMaxOutboundLimit = nMaxOutboundLimit; for (const std::string& strBind : gArgs.GetArgs("-bind")) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) { return InitError(ResolveErrMsg("bind", strBind)); } connOptions.vBinds.push_back(addrBind); } for (const std::string& strBind : gArgs.GetArgs("-whitebind")) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, 0, false)) { return InitError(ResolveErrMsg("whitebind", strBind)); } if (addrBind.GetPort() == 0) { return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind)); } connOptions.vWhiteBinds.push_back(addrBind); } for (const auto& net : gArgs.GetArgs("-whitelist")) { CSubNet subnet; LookupSubNet(net.c_str(), subnet); if (!subnet.IsValid()) return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net)); connOptions.vWhitelistedRange.push_back(subnet); } connOptions.vSeedNodes = gArgs.GetArgs("-seednode"); // Initiate outbound connections unless connect=0 connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect"); if (!connOptions.m_use_addrman_outgoing) { const auto connect = gArgs.GetArgs("-connect"); if (connect.size() != 1 || connect[0] != "0") { connOptions.m_specified_outgoing = connect; } } if (!connman.Start(scheduler, connOptions)) { return false; } // ********************************************************* Step 13: finished SetRPCWarmupFinished(); uiInterface.InitMessage(_("Done loading")); g_wallet_init_interface.Start(scheduler); return true; }
[ "62725809+fancywarlock@users.noreply.github.com" ]
62725809+fancywarlock@users.noreply.github.com
0d710b81edb1c3286f405ccbb7ac98daa4d02680
50165286c35e6e27b7c3734795cc0e64b7f643fd
/include/Base_writer.h
eebb6a00c88155bbda608dad2f0e7e3a564a893c
[ "Zlib" ]
permissive
suppositio/Mandelbrot_fractal_explorer
90741ecd1c35d513af193f8bc6f8c939b6cd9ec5
3c723558490813ea1f26f22922f6ca8e3f9d0920
refs/heads/master
2023-06-19T19:47:01.115852
2021-07-15T15:54:26
2021-07-15T15:54:26
373,987,407
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
#pragma once #include "Buffer.h" namespace suppositio { template <typename Pix_t> class Base_writer { public: Base_writer(const std::shared_ptr<Buffer<Pix_t>>& buffer) : buffer_{ buffer }, width_{ buffer->get_width() }, height_{ buffer->get_height() } {} virtual void write(const std::string& file_name) = 0; virtual ~Base_writer() = default; protected: std::shared_ptr<Buffer<Pix_t>> buffer_; int width_; int height_; }; } // suppositio
[ "rostyslav.paranko@gmail.com" ]
rostyslav.paranko@gmail.com
35bc6649d5d131ae13bb7ca6d26ccb862df2557d
0f835bc34c99d9a776b6ecf308d4acb723539870
/worldsettings.cpp
cfd720d5d0f8bca0ff8906a3a9d65ee40f64c74f
[]
no_license
jacobmoroni/SnowGlobe
526380a8684543cd056ec114bd0a3593228fc555
4c7c9144af2fb36d24810ec7637864e92657a769
refs/heads/master
2023-07-30T16:41:56.444181
2021-09-17T18:30:37
2021-09-17T18:30:37
407,608,664
0
0
null
null
null
null
UTF-8
C++
false
false
1,358
cpp
#include "worldsettings.h" #include "ui_worldsettings.h" #include "vector.h" WorldSettings::WorldSettings(QWidget *parent) : QDialog(parent), ui(new Ui::WorldSettings) { ui->setupUi(this); ui->gravity_x->setDisabled(true); ui->gravity_y->setDisabled(true); ui->gravity_z->setDisabled(true); } WorldSettings::~WorldSettings() { delete ui; } phys::Vector WorldSettings::getGravity() { double grav_x = ui->gravity_x->value(); double grav_y = ui->gravity_y->value(); double grav_z = ui->gravity_z->value(); phys::Vector gravity{grav_x,grav_y,grav_z}; return gravity; } double WorldSettings::getDensity() { double density = ui->density->value(); return density; } bool WorldSettings::getAutogravity() { return m_autogravity; } void WorldSettings::on_buttonBox_accepted() { QDialog::accept(); } void WorldSettings::on_buttonBox_rejected() { QDialog::reject(); } void WorldSettings::on_checkBox_clicked(bool checked) { if (checked == true) { m_autogravity = true; ui->gravity_x->setDisabled(true); ui->gravity_y->setDisabled(true); ui->gravity_z->setDisabled(true); } else { m_autogravity = false; ui->gravity_x->setEnabled(true); ui->gravity_y->setEnabled(true); ui->gravity_z->setEnabled(true); } }
[ "jacobmoroniolson@gmail.com" ]
jacobmoroniolson@gmail.com
53c42b8d64870a90aa66630fa0b9d5aeed719c2b
0f9f42ed3e125dbffd5a4fc021a91ce021c45a64
/Bai Tap/clearing-input-buffer.cpp
f123fc6d07f5ea2bfb6c2b9f573d7cbc31d6fad4
[]
no_license
luanquanghuy/LapTrinhNangCao
94aa4a7e0f9fa0fd57fe159a96280ebd084789fe
08678860a61ea2c1ef95b1146a454a61ff240b6c
refs/heads/master
2021-05-05T23:24:17.854844
2018-05-07T15:13:02
2018-05-07T15:13:02
116,674,822
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include <iostream> //#include <ios> #include <limits> using namespace std; int main() { int a; char s[100]; cin >> a; cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin.getline(s, 100); cout << numeric_limits<streamsize>::max() << endl; }
[ "luanquanghuy@gmail.com" ]
luanquanghuy@gmail.com
754d2e26b0f801df8fabaae149932192bb09997d
621ff38e8b62885c592b3f992e73ca12d06f8cdb
/Driver.cpp
44831d91bc20a93f44ffd5131eca5ea86bbcf6dc
[]
no_license
etsc9287/Starting-Computing
8b2673beba2800ba6133f6c93c23c0c9ef9c3820
b418ad0d4531cd208486fa1aafaf4bf8c02c78a1
refs/heads/master
2020-12-10T18:43:55.837210
2020-01-13T19:28:45
2020-01-13T19:28:45
233,675,711
0
0
null
null
null
null
UTF-8
C++
false
false
1,374
cpp
#include "Hero.h" #include "Emperor.h" #include "StormTrooper.h" #include "Shuffler.h" #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <vector> #include <string> using namespace std; void game(){ //1. Welcome user to the Death Star, they encounter first group of stormtroopers //2. While stormtroopers or hero haven't run out of health, alternate between attacking and defending menus // *Attacking/Defending menus contain all complex functions in Hero class //3. If hero runs out of health, end the game and give option to restart //4. If stormtroopers run out of health, reset hero health and move on to next clan //5. Repeat 2-4 for all three stormtrooper clans //6. When all clans are defeated, move on to emperor //7. While emperor or hero haven't run out of health, alternate between attacking and defending menus //8. If hero runs out of health, end the game and give option to restart //9. If emperor runs out of health, alert the user that they can now try to destroy the death star //10. Move on to shuffler function if the user chooses "yes". If "no", hero escapes and game ends //11. The user has 5 tries to shuffle the matching code. If they fail, they get killed by backup. If they succeed, they win. } int main() { // start the game! game(); return 0; }
[ "etsc9287@colorado.edu" ]
etsc9287@colorado.edu
72101bb823e76aefaef140a114d1c1c5d3e7f42c
3a936048e29b527d04fd1ebee1efdefed87bfb52
/201812/p1207.cpp
3a030e4c4dae1372bf59e366a3462751d5e0dc98
[]
no_license
j921724/201802-practice-j921724
79ecd30eb44026b1a34b3d8af876b6c2e66c27c3
d8ad57c993ce1cf232f0db740588db69299be72d
refs/heads/master
2020-05-05T13:48:42.902402
2018-12-09T09:32:00
2018-12-09T09:32:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
cpp
#include <iostream> class student { public: int value; static int count; static int* m_pArray; public: student() { count++; if(m_pArray == nullptr) m_pArray = new int[100]; } ~student() { count--; if(count == 0) { delete [] m_pArray; std::cout << "deleted" << std::endl; } } }; int student::count = 0; int* student::m_pArray = nullptr; int main() { /* student s1; student s2; s1.value = 10; s2.value = 20; std::cout << &s1.value << std::endl; std::cout << &s2.value << std::endl; std::cout << &s1.count << std::endl; std::cout << &s2.count << std::endl; */ /* student array[10]; for(int i = 0; i < 10; i++) { std::cout << array + i << std::endl; } */ { student s1; { student s2; std::cout << "Inside of the local scope:" << student::count << std::endl; } std::cout << student::count << std::endl; } std::cout << student::count << std::endl; return 0; }
[ "21600156@handong.edu" ]
21600156@handong.edu
efd02f7ba95d8c20c6215531d7f6743c04141dda
3922ea0006690e982d37b879cb259f72ed0d77ff
/14_01_资源管理类的copying行为/stdafx.cpp
e7a1612ec901fa431fb6da2e308032ca4e067ecd
[]
no_license
c437yuyang/EffectiveCPlusPlus
f746d6e4391db6792e8772bdee58349f610852be
45abc4e18e3245722d2be6491d7abfdae24dc37b
refs/heads/master
2021-01-23T06:25:35.199922
2018-02-03T13:33:56
2018-02-03T13:33:56
93,022,219
0
2
null
null
null
null
GB18030
C++
false
false
288
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // 14_01_资源管理类的copying行为.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中引用任何所需的附加头文件, //而不是在此文件中引用
[ "954222619@qq.com" ]
954222619@qq.com
67c20c576f501acd44501a5c6fe10e3ff2fd1f7a
7648c7c574c972baf73ae74f5112acfc49a4c456
/project2/bagback/Led.cpp
06e0790f8846dc9fbc2992b95f9dd793f8e12fec
[]
no_license
hoenic07/sensors-networks-projects
a986da287f6497f5e3e72268b5912836a7cec138
93a8879ddd080e07b8a7a7b84d4e59235def84b0
refs/heads/master
2021-01-21T04:47:53.627712
2016-06-15T08:40:45
2016-06-15T08:40:45
55,857,574
0
0
null
null
null
null
UTF-8
C++
false
false
236
cpp
#include "Led.h" Led::Led(int lid) { ledId = lid; } void Led::init() { pinMode(ledId, OUTPUT); } void Led::setActive(bool isActive) { if(isActive) { digitalWrite(ledId, HIGH); }else{ digitalWrite(ledId, LOW); } }
[ "magda.radinger@gmail.com" ]
magda.radinger@gmail.com
6d625d9e5c3e8d5d896e27c8b5111f5f8f6cab78
82c147779dfb0ddd4e539159c902d25487f8790f
/ABC/ABC121-130/ABC123/D/D.cpp
253058f50cc2e7ff7063d901728eecad31bb47ec
[]
no_license
nayuta1019/AtCoder
4350e17ef21baf6015cbcf5a6d6ece8c5bbe767b
a1d8d85885e75dc103f185adfabd5354d0a69a6c
refs/heads/master
2023-03-09T02:15:42.219174
2021-02-16T07:18:57
2021-02-16T07:18:57
339,315,134
0
0
null
null
null
null
UTF-8
C++
false
false
1,542
cpp
/** ABC123 2019/04/06/ 解説AC **/ #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i = (a); i < (b); ++i) #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define all(x) (x).begin(),(x).end() inline int toInt(string s) {int v; istringstream sin(s);sin>>v; return v;} typedef long long ll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector< vector<int> > Mat; typedef tuple<int, int, int, int> T; const int MOD = (int)1e9+7; const int INF = (int)1e9; const int dx[] = {0, 1, 0, -1}; const int dy[] = {1, 0, -1, 0}; const int ddx[] = {0, 1, 1, 1, 0, -1, -1, -1}; const int ddy[] = {1, 1, 0, -1, -1, -1, 0, 1}; int main(){ ios::sync_with_stdio(false); cin.tie(0); ll X, Y, Z, K; cin >> X >> Y >> Z >> K; vector<ll> A(X), B(Y), C(Z), p; rep(i, X) cin >> A[i]; rep(i, Y) cin >> B[i]; rep(i, Z) cin >> C[i]; sort(A.begin(), A.end(), greater<ll>()); sort(B.begin(), B.end(), greater<ll>()); sort(C.begin(), C.end(), greater<ll>()); rep(i, X){ rep(j, Y){ p.push_back(A[i] + B[j]); } } sort(p.begin(), p.end(), greater<ll>()); vector<ll> tmp; int pp = min((ll)p.size(), K); rep(i, pp) tmp.push_back(p[i]); vector<ll> ans; rep(i, pp){ rep(j, Z) ans.push_back(tmp[i]+C[j]); } sort(ans.begin(), ans.end(), greater<ll>()); rep(i, K){ cout << ans[i] << endl; } return 0; }
[ "nayuta.04510@gmail.com" ]
nayuta.04510@gmail.com
307e6812238468cf5bc77ffa1f4fe12b72831d91
18c2ae623a0a35aa0de2d4c0d80baf2db17586ef
/options.h
543fdd74268033ad9b1abcd3d38ff4dd015b734c
[]
no_license
gritukan/gas-simulator
8d8243c2e00b8ebba64c73975086c2d4d71b2261
d47ebcaa2b38e5a34ef36ccee0bba8b4ed896963
refs/heads/master
2022-04-17T06:12:25.463617
2020-04-14T20:45:59
2020-04-14T20:45:59
255,721,726
0
0
null
null
null
null
UTF-8
C++
false
false
645
h
#ifndef TOPTIONS_H #define TOPTIONS_H #include "common.h" #include <vector> struct TPetrol { //! Price per liter (without markup). double Price = 1; //! Markup of petrol cost (in percent) double Markup = 0; double GetPrice() const { return Price * (1 + Markup / 100); } }; struct TOptions { //! Number of queues processing requests. int QueueCount = 1; //! Maximum size of queue. int MaxQueueSize = 10; //! Period of one step of simulation (in minutes). TTime SimulationPeriod = 10; //! Petrol types descriptions. std::vector<TPetrol> Petrols; }; #endif // TOPTIONS_H
[ "gritukan@yandex-team.ru" ]
gritukan@yandex-team.ru
ac34e3d640ac89ef8490d7e4a9c813fc8127fa6e
b050304dc5a3799116a6c811962835e88a6619dc
/external/pure_pursuit_old/external/catch/catch.hh
aee81ea1b1452e8033d1b3df7b8e498d6f511b27
[]
no_license
iscumd/path_tracking
a420eafa4130b038bbe46644be113dd5d7667a34
8ff32488349defe60363c9677aabf304744c5c91
refs/heads/master
2020-05-04T19:17:04.821479
2019-04-04T00:50:09
2019-04-04T00:50:09
179,385,609
0
1
null
2019-04-04T00:50:10
2019-04-03T23:27:45
C++
UTF-8
C++
false
false
469,740
hh
/* * Catch v2.2.2 * Generated: 2018-04-06 12:05:03.186665 * ---------------------------------------------------------- * This file has been merged from multiple headers. Please don't edit it directly * Copyright (c) 2018 Two Blue Cubes Ltd. All rights reserved. * * 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 TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED // start catch.hpp #define CATCH_VERSION_MAJOR 2 #define CATCH_VERSION_MINOR 2 #define CATCH_VERSION_PATCH 2 #ifdef __clang__ #pragma clang system_header #elif defined __GNUC__ #pragma GCC system_header #endif // start catch_suppress_warnings.h #ifdef __clang__ #ifdef __ICC // icpc defines the __clang__ macro #pragma warning( push ) #pragma warning( disable : 161 1682 ) #else // __ICC #pragma clang diagnostic ignored "-Wunused-variable" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wswitch-enum" #pragma clang diagnostic ignored "-Wcovered-switch-default" #endif #elif defined __GNUC__ #pragma GCC diagnostic ignored "-Wparentheses" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wpadded" #endif // end catch_suppress_warnings.h #if defined( CATCH_CONFIG_MAIN ) || defined( CATCH_CONFIG_RUNNER ) #define CATCH_IMPL #define CATCH_CONFIG_ALL_PARTS #endif // In the impl file, we want to have access to all parts of the headers // Can also be used to sanely support PCHs #if defined( CATCH_CONFIG_ALL_PARTS ) #define CATCH_CONFIG_EXTERNAL_INTERFACES #if defined( CATCH_CONFIG_DISABLE_MATCHERS ) #undef CATCH_CONFIG_DISABLE_MATCHERS #endif #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER #endif #if !defined( CATCH_CONFIG_IMPL_ONLY ) // start catch_platform.h #ifdef __APPLE__ #include <TargetConditionals.h> #if TARGET_OS_OSX == 1 #define CATCH_PLATFORM_MAC #elif TARGET_OS_IPHONE == 1 #define CATCH_PLATFORM_IPHONE #endif #elif defined( linux ) || defined( __linux ) || defined( __linux__ ) #define CATCH_PLATFORM_LINUX #elif defined( WIN32 ) || defined( __WIN32__ ) || defined( _WIN32 ) \ || defined( _MSC_VER ) #define CATCH_PLATFORM_WINDOWS #endif // end catch_platform.h #ifdef CATCH_IMPL #ifndef CLARA_CONFIG_MAIN #define CLARA_CONFIG_MAIN_NOT_DEFINED #define CLARA_CONFIG_MAIN #endif #endif // start catch_user_interfaces.h namespace Catch { unsigned int rngSeed(); } // end catch_user_interfaces.h // start catch_tag_alias_autoregistrar.h // start catch_common.h // start catch_compiler_capabilities.h // Detect a number of compiler features - by compiler // The following features are defined: // // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too // **************** // In general each macro has a _NO_<feature name> form // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. #ifdef __cplusplus #if __cplusplus >= 201402L #define CATCH_CPP14_OR_GREATER #endif #if __cplusplus >= 201703L #define CATCH_CPP17_OR_GREATER #endif #endif #if defined( CATCH_CPP17_OR_GREATER ) #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif #ifdef __clang__ #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ _Pragma( "clang diagnostic push" ) \ _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"" ) #define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS _Pragma( "clang diagnostic pop" ) #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ _Pragma( "clang diagnostic push" ) \ _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) #define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS _Pragma( "clang diagnostic pop" ) #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // Assume that non-Windows platforms support posix signals by default #if !defined( CATCH_PLATFORM_WINDOWS ) #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS #endif //////////////////////////////////////////////////////////////////////////////// // We know some environments not to support full POSIX signals #if defined( __CYGWIN__ ) || defined( __QNX__ ) || defined( __EMSCRIPTEN__ ) \ || defined( __DJGPP__ ) #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS #endif #ifdef __OS400__ #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS #define CATCH_CONFIG_COLOUR_NONE #endif //////////////////////////////////////////////////////////////////////////////// // Cygwin #ifdef __CYGWIN__ // Required for some versions of Cygwin to declare gettimeofday // see: // http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin #define _BSD_SOURCE #endif // __CYGWIN__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #ifdef _MSC_VER #if _MSC_VER >= 1900 // Visual Studio 2015 or newer #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif // Universal Windows platform does not support SEH // Or console colours (or console at all...) #if defined( WINAPI_FAMILY ) && ( WINAPI_FAMILY == WINAPI_FAMILY_APP ) #define CATCH_CONFIG_COLOUR_NONE #else #define CATCH_INTERNAL_CONFIG_WINDOWS_SEH #endif #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // DJGPP #ifdef __DJGPP__ #define CATCH_INTERNAL_CONFIG_NO_WCHAR #endif // __DJGPP__ //////////////////////////////////////////////////////////////////////////////// // Use of __COUNTER__ is suppressed during code analysis in // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly // handled by it. // Otherwise all supported compilers support COUNTER macro, // but user still might want to turn it off #if ( !defined( __JETBRAINS_IDE__ ) || __JETBRAINS_IDE__ >= 20170300L ) #define CATCH_INTERNAL_CONFIG_COUNTER #endif #if defined( CATCH_INTERNAL_CONFIG_COUNTER ) && !defined( CATCH_CONFIG_NO_COUNTER ) \ && !defined( CATCH_CONFIG_COUNTER ) #define CATCH_CONFIG_COUNTER #endif #if defined( CATCH_INTERNAL_CONFIG_WINDOWS_SEH ) \ && !defined( CATCH_CONFIG_NO_WINDOWS_SEH ) && !defined( CATCH_CONFIG_WINDOWS_SEH ) #define CATCH_CONFIG_WINDOWS_SEH #endif // This is set by default, because we assume that unix compilers are // posix-signal-compatible by default. #if defined( CATCH_INTERNAL_CONFIG_POSIX_SIGNALS ) \ && !defined( CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS ) \ && !defined( CATCH_CONFIG_NO_POSIX_SIGNALS ) \ && !defined( CATCH_CONFIG_POSIX_SIGNALS ) #define CATCH_CONFIG_POSIX_SIGNALS #endif // This is set by default, because we assume that compilers with no wchar_t support are // just rare exceptions. #if !defined( CATCH_INTERNAL_CONFIG_NO_WCHAR ) && !defined( CATCH_CONFIG_NO_WCHAR ) \ && !defined( CATCH_CONFIG_WCHAR ) #define CATCH_CONFIG_WCHAR #endif #if defined( CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS ) \ && !defined( CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS ) \ && !defined( CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS ) #define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS #endif #if !defined( CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS ) #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS #define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS #endif #if !defined( CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS ) #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS #define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS #endif // end catch_compiler_capabilities.h #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) \ INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) #ifdef CATCH_CONFIG_COUNTER #define INTERNAL_CATCH_UNIQUE_NAME( name ) \ INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) #else #define INTERNAL_CATCH_UNIQUE_NAME( name ) \ INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) #endif #include <cstdint> #include <iosfwd> #include <string> namespace Catch { struct CaseSensitive { enum Choice { Yes, No }; }; class NonCopyable { NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable&& ) = delete; NonCopyable& operator=( NonCopyable const& ) = delete; NonCopyable& operator=( NonCopyable&& ) = delete; protected: NonCopyable(); virtual ~NonCopyable(); }; struct SourceLineInfo { SourceLineInfo() = delete; SourceLineInfo( char const* _file, std::size_t _line ) noexcept : file( _file ) , line( _line ) { } SourceLineInfo( SourceLineInfo const& other ) = default; SourceLineInfo( SourceLineInfo&& ) = default; SourceLineInfo& operator=( SourceLineInfo const& ) = default; SourceLineInfo& operator=( SourceLineInfo&& ) = default; bool empty() const noexcept; bool operator==( SourceLineInfo const& other ) const noexcept; bool operator<( SourceLineInfo const& other ) const noexcept; char const* file; std::size_t line; }; std::ostream& operator<<( std::ostream& os, SourceLineInfo const& info ); // Use this in variadic streaming macros to allow // >> +StreamEndStop // as well as // >> stuff +StreamEndStop struct StreamEndStop { std::string operator+() const; }; template <typename T> T const& operator+( T const& value, StreamEndStop ) { return value; } } #define CATCH_INTERNAL_LINEINFO \ ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) ) // end catch_common.h namespace Catch { struct RegistrarForTagAliases { RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); }; } // end namespace Catch #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace \ { \ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( \ AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); \ } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS // end catch_tag_alias_autoregistrar.h // start catch_test_registry.h // start catch_interfaces_testcase.h #include <memory> #include <vector> namespace Catch { class TestSpec; struct ITestInvoker { virtual void invoke() const = 0; virtual ~ITestInvoker(); }; using ITestCasePtr = std::shared_ptr<ITestInvoker>; class TestCase; struct IConfig; struct ITestCaseRegistry { virtual ~ITestCaseRegistry(); virtual std::vector<TestCase> const& getAllTests() const = 0; virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0; }; bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); } // end catch_interfaces_testcase.h // start catch_stringref.h #include <cstddef> #include <iosfwd> #include <string> namespace Catch { class StringData; /// A non-owning string class (similar to the forthcoming std::string_view) /// Note that, because a StringRef may be a substring of another string, /// it may not be null terminated. c_str() must return a null terminated /// string, however, and so the StringRef will internally take ownership /// (taking a copy), if necessary. In theory this ownership is not externally /// visible - but it does mean (substring) StringRefs should not be shared between /// threads. class StringRef { public: using size_type = std::size_t; private: friend struct StringRefTestAccess; char const* m_start; size_type m_size; char* m_data = nullptr; void takeOwnership(); static constexpr char const* const s_empty = ""; public: // construction/ assignment StringRef() noexcept : StringRef( s_empty, 0 ) { } StringRef( StringRef const& other ) noexcept : m_start( other.m_start ) , m_size( other.m_size ) { } StringRef( StringRef&& other ) noexcept : m_start( other.m_start ) , m_size( other.m_size ) , m_data( other.m_data ) { other.m_data = nullptr; } StringRef( char const* rawChars ) noexcept; StringRef( char const* rawChars, size_type size ) noexcept : m_start( rawChars ) , m_size( size ) { } StringRef( std::string const& stdString ) noexcept : m_start( stdString.c_str() ) , m_size( stdString.size() ) { } ~StringRef() noexcept { delete[] m_data; } auto operator=( StringRef const& other ) noexcept -> StringRef& { delete[] m_data; m_data = nullptr; m_start = other.m_start; m_size = other.m_size; return *this; } operator std::string() const; void swap( StringRef& other ) noexcept; public: // operators auto operator==( StringRef const& other ) const noexcept -> bool; auto operator!=( StringRef const& other ) const noexcept -> bool; auto operator[]( size_type index ) const noexcept -> char; public: // named queries auto empty() const noexcept -> bool { return m_size == 0; } auto size() const noexcept -> size_type { return m_size; } auto numberOfCharacters() const noexcept -> size_type; auto c_str() const -> char const*; public: // substrings and searches auto substr( size_type start, size_type size ) const noexcept -> StringRef; // Returns the current start pointer. // Note that the pointer can change when if the StringRef is a substring auto currentData() const noexcept -> char const*; private: // ownership queries - may not be consistent between calls auto isOwned() const noexcept -> bool; auto isSubstring() const noexcept -> bool; }; auto operator+( StringRef const& lhs, StringRef const& rhs ) -> std::string; auto operator+( StringRef const& lhs, char const* rhs ) -> std::string; auto operator+( char const* lhs, StringRef const& rhs ) -> std::string; auto operator+=( std::string& lhs, StringRef const& sr ) -> std::string&; auto operator<<( std::ostream& os, StringRef const& sr ) -> std::ostream&; inline auto operator"" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { return StringRef( rawChars, size ); } } // namespace Catch // end catch_stringref.h namespace Catch { template <typename C> class TestInvokerAsMethod : public ITestInvoker { void ( C::*m_testAsMethod )(); public: TestInvokerAsMethod( void ( C::*testAsMethod )() ) noexcept : m_testAsMethod( testAsMethod ) { } void invoke() const override { C obj; ( obj.*m_testAsMethod )(); } }; auto makeTestInvoker( void ( *testAsFunction )() ) noexcept -> ITestInvoker*; template <typename C> auto makeTestInvoker( void ( C::*testAsMethod )() ) noexcept -> ITestInvoker* { return new ( std::nothrow ) TestInvokerAsMethod<C>( testAsMethod ); } struct NameAndTags { NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept; StringRef name; StringRef tags; }; struct AutoReg : NonCopyable { AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept; ~AutoReg(); }; } // end namespace Catch #if defined( CATCH_CONFIG_DISABLE ) #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) static void TestName() #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ namespace \ { \ struct TestName : ClassName \ { \ void test(); \ }; \ } \ void TestName::test() #endif /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ static void TestName(); \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace \ { \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( \ Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", \ Catch::NameAndTags{ __VA_ARGS__ } ); \ } /* NOLINT */ \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ static void TestName() #define INTERNAL_CATCH_TESTCASE( ... ) \ INTERNAL_CATCH_TESTCASE2( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace \ { \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( \ Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, \ "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); \ } /* NOLINT */ \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace \ { \ struct TestName : ClassName \ { \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( \ Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, \ #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ void TestName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD2( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, \ __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( \ Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", \ Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS // end catch_test_registry.h // start catch_capture.hpp // start catch_assertionhandler.h // start catch_assertioninfo.h // start catch_result_type.h namespace Catch { // ResultWas::OfType enum struct ResultWas { enum OfType { Unknown = -1, Ok = 0, Info = 1, Warning = 2, FailureBit = 0x10, ExpressionFailed = FailureBit | 1, ExplicitFailure = FailureBit | 2, Exception = 0x100 | FailureBit, ThrewException = Exception | 1, DidntThrowException = Exception | 2, FatalErrorCondition = 0x200 | FailureBit }; }; bool isOk( ResultWas::OfType resultType ); bool isJustInfo( int flags ); // ResultDisposition::Flags enum struct ResultDisposition { enum Flags { Normal = 0x01, ContinueOnFailure = 0x02, // Failures fail test, but execution continues FalseTest = 0x04, // Prefix expression with ! SuppressFail = 0x08 // Failures are reported but do not fail the test }; }; ResultDisposition::Flags operator|( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ); bool shouldContinueOnFailure( int flags ); inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } bool shouldSuppressFailure( int flags ); } // end namespace Catch // end catch_result_type.h namespace Catch { struct AssertionInfo { StringRef macroName; SourceLineInfo lineInfo; StringRef capturedExpression; ResultDisposition::Flags resultDisposition; // We want to delete this constructor but a compiler bug in 4.8 means // the struct is then treated as non-aggregate // AssertionInfo() = delete; }; } // end namespace Catch // end catch_assertioninfo.h // start catch_decomposer.h // start catch_tostring.h #include <cstddef> #include <string> #include <type_traits> #include <vector> // start catch_stream.h #include <cstddef> #include <iosfwd> #include <ostream> namespace Catch { std::ostream& cout(); std::ostream& cerr(); std::ostream& clog(); class StringRef; struct IStream { virtual ~IStream(); virtual std::ostream& stream() const = 0; }; auto makeStream( StringRef const& filename ) -> IStream const*; class ReusableStringStream { std::size_t m_index; std::ostream* m_oss; public: ReusableStringStream(); ~ReusableStringStream(); auto str() const -> std::string; template <typename T> auto operator<<( T const& value ) -> ReusableStringStream& { *m_oss << value; return *this; } auto get() -> std::ostream& { return *m_oss; } static void cleanup(); }; } // end catch_stream.h #ifdef __OBJC__ // start catch_objc_arc.hpp #import <Foundation/Foundation.h> #ifdef __has_feature #define CATCH_ARC_ENABLED __has_feature( objc_arc ) #else #define CATCH_ARC_ENABLED 0 #endif void arcSafeRelease( NSObject* obj ); id performOptionalSelector( id obj, SEL sel ); #if !CATCH_ARC_ENABLED inline void arcSafeRelease( NSObject* obj ) { [obj release]; } inline id performOptionalSelector( id obj, SEL sel ) { if ( [obj respondsToSelector:sel] ) return [obj performSelector:sel]; return nil; } #define CATCH_UNSAFE_UNRETAINED #define CATCH_ARC_STRONG #else inline void arcSafeRelease( NSObject* ) {} inline id performOptionalSelector( id obj, SEL sel ) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" #endif if ( [obj respondsToSelector:sel] ) return [obj performSelector:sel]; #ifdef __clang__ #pragma clang diagnostic pop #endif return nil; } #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained #define CATCH_ARC_STRONG __strong #endif // end catch_objc_arc.hpp #endif #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4180 ) // We attempt to stream a function (address) by // const&, which MSVC // complains about but is harmless #endif // We need a dummy global operator<< so we can bring it into Catch namespace later struct Catch_global_namespace_dummy { }; std::ostream& operator<<( std::ostream&, Catch_global_namespace_dummy ); namespace Catch { // Bring in operator<< from global namespace into Catch namespace using ::operator<<; namespace Detail { extern const std::string unprintableString; std::string rawMemoryToString( const void* object, std::size_t size ); template <typename T> std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof( object ) ); } template <typename T> class IsStreamInsertable { template <typename SS, typename TT> static auto test( int ) -> decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() ); template <typename, typename> static auto test( ... ) -> std::false_type; public: static const bool value = decltype( test<std::ostream, const T&>( 0 ) )::value; }; template <typename E> std::string convertUnknownEnumToString( E e ); template <typename T> typename std::enable_if<!std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) { #if !defined( CATCH_CONFIG_FALLBACK_STRINGIFIER ) (void)value; return Detail::unprintableString; #else return CATCH_CONFIG_FALLBACK_STRINGIFIER( value ); #endif } template <typename T> typename std::enable_if<std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) { return convertUnknownEnumToString( value ); } #if defined( _MANAGED ) //! Convert a CLR string to a utf8 std::string template <typename T> std::string clrReferenceToString( T ^ ref ) { if ( ref == nullptr ) return std::string( "null" ); auto bytes = System::Text::Encoding::UTF8->GetBytes( ref->ToString() ); cli::pin_ptr<System::Byte> p = &bytes[0]; return std::string( reinterpret_cast<char const*>( p ), bytes->Length ); } #endif } // namespace Detail // If we decide for C++14, change these to enable_if_ts template <typename T, typename = void> struct StringMaker { template <typename Fake = T> static typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type convert( const Fake& value ) { ReusableStringStream rss; rss << value; return rss.str(); } template <typename Fake = T> static typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type convert( const Fake& value ) { return Detail::convertUnstreamable( value ); } }; namespace Detail { // This function dispatches all stringification requests inside of Catch. // Should be preferably called fully qualified, like ::Catch::Detail::stringify template <typename T> std::string stringify( const T& e ) { return ::Catch::StringMaker<typename std::remove_cv< typename std::remove_reference<T>::type>::type>::convert( e ); } template <typename E> std::string convertUnknownEnumToString( E e ) { return ::Catch::Detail::stringify( static_cast<typename std::underlying_type<E>::type>( e ) ); } #if defined( _MANAGED ) template <typename T> std::string stringify( T ^ e ) { return ::Catch::StringMaker<T ^>::convert( e ); } #endif } // namespace Detail // Some predefined specializations template <> struct StringMaker<std::string> { static std::string convert( const std::string& str ); }; #ifdef CATCH_CONFIG_WCHAR template <> struct StringMaker<std::wstring> { static std::string convert( const std::wstring& wstr ); }; #endif template <> struct StringMaker<char const*> { static std::string convert( char const* str ); }; template <> struct StringMaker<char*> { static std::string convert( char* str ); }; #ifdef CATCH_CONFIG_WCHAR template <> struct StringMaker<wchar_t const*> { static std::string convert( wchar_t const* str ); }; template <> struct StringMaker<wchar_t*> { static std::string convert( wchar_t* str ); }; #endif // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer, // while keeping string semantics? template <int SZ> struct StringMaker<char[SZ]> { static std::string convert( char const* str ) { return ::Catch::Detail::stringify( std::string{ str } ); } }; template <int SZ> struct StringMaker<signed char[SZ]> { static std::string convert( signed char const* str ) { return ::Catch::Detail::stringify( std::string{ reinterpret_cast<char const*>( str ) } ); } }; template <int SZ> struct StringMaker<unsigned char[SZ]> { static std::string convert( unsigned char const* str ) { return ::Catch::Detail::stringify( std::string{ reinterpret_cast<char const*>( str ) } ); } }; template <> struct StringMaker<int> { static std::string convert( int value ); }; template <> struct StringMaker<long> { static std::string convert( long value ); }; template <> struct StringMaker<long long> { static std::string convert( long long value ); }; template <> struct StringMaker<unsigned int> { static std::string convert( unsigned int value ); }; template <> struct StringMaker<unsigned long> { static std::string convert( unsigned long value ); }; template <> struct StringMaker<unsigned long long> { static std::string convert( unsigned long long value ); }; template <> struct StringMaker<bool> { static std::string convert( bool b ); }; template <> struct StringMaker<char> { static std::string convert( char c ); }; template <> struct StringMaker<signed char> { static std::string convert( signed char c ); }; template <> struct StringMaker<unsigned char> { static std::string convert( unsigned char c ); }; template <> struct StringMaker<std::nullptr_t> { static std::string convert( std::nullptr_t ); }; template <> struct StringMaker<float> { static std::string convert( float value ); }; template <> struct StringMaker<double> { static std::string convert( double value ); }; template <typename T> struct StringMaker<T*> { template <typename U> static std::string convert( U* p ) { if ( p ) { return ::Catch::Detail::rawMemoryToString( p ); } else { return "nullptr"; } } }; template <typename R, typename C> struct StringMaker<R C::*> { static std::string convert( R C::*p ) { if ( p ) { return ::Catch::Detail::rawMemoryToString( p ); } else { return "nullptr"; } } }; #if defined( _MANAGED ) template <typename T> struct StringMaker<T ^> { static std::string convert( T ^ ref ) { return ::Catch::Detail::clrReferenceToString( ref ); } }; #endif namespace Detail { template <typename InputIterator> std::string rangeToString( InputIterator first, InputIterator last ) { ReusableStringStream rss; rss << "{ "; if ( first != last ) { rss << ::Catch::Detail::stringify( *first ); for ( ++first; first != last; ++first ) rss << ", " << ::Catch::Detail::stringify( *first ); } rss << " }"; return rss.str(); } } #ifdef __OBJC__ template <> struct StringMaker<NSString*> { static std::string convert( NSString* nsstring ) { if ( !nsstring ) return "nil"; return std::string( "@" ) + [nsstring UTF8String]; } }; template <> struct StringMaker<NSObject*> { static std::string convert( NSObject* nsObject ) { return ::Catch::Detail::stringify( [nsObject description] ); } }; namespace Detail { inline std::string stringify( NSString* nsstring ) { return StringMaker<NSString*>::convert( nsstring ); } } // namespace Detail #endif // __OBJC__ } // namespace Catch ////////////////////////////////////////////////////// // Separate std-lib types stringification, so it can be selectively enabled // This means that we do not bring in #if defined( CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS ) #define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER #define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER #endif // Separate std::pair specialization #if defined( CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER ) #include <utility> namespace Catch { template <typename T1, typename T2> struct StringMaker<std::pair<T1, T2>> { static std::string convert( const std::pair<T1, T2>& pair ) { ReusableStringStream rss; rss << "{ " << ::Catch::Detail::stringify( pair.first ) << ", " << ::Catch::Detail::stringify( pair.second ) << " }"; return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER // Separate std::tuple specialization #if defined( CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER ) #include <tuple> namespace Catch { namespace Detail { template <typename Tuple, std::size_t N = 0, bool = ( N < std::tuple_size<Tuple>::value )> struct TupleElementPrinter { static void print( const Tuple& tuple, std::ostream& os ) { os << ( N ? ", " : " " ) << ::Catch::Detail::stringify( std::get<N>( tuple ) ); TupleElementPrinter<Tuple, N + 1>::print( tuple, os ); } }; template <typename Tuple, std::size_t N> struct TupleElementPrinter<Tuple, N, false> { static void print( const Tuple&, std::ostream& ) {} }; } template <typename... Types> struct StringMaker<std::tuple<Types...>> { static std::string convert( const std::tuple<Types...>& tuple ) { ReusableStringStream rss; rss << '{'; Detail::TupleElementPrinter<std::tuple<Types...>>::print( tuple, rss.get() ); rss << " }"; return rss.str(); } }; } #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER namespace Catch { struct not_this_one { }; // Tag type for detecting which begin/ end are being selected // Import begin/ end from std here so they are considered alongside the fallback (...) // overloads in this namespace using std::begin; using std::end; not_this_one begin( ... ); not_this_one end( ... ); template <typename T> struct is_range { static const bool value = !std::is_same<decltype( begin( std::declval<T>() ) ), not_this_one>::value && !std::is_same<decltype( end( std::declval<T>() ) ), not_this_one>::value; }; #if defined( _MANAGED ) // Managed types are never ranges template <typename T> struct is_range<T ^> { static const bool value = false; }; #endif template <typename Range> std::string rangeToString( Range const& range ) { return ::Catch::Detail::rangeToString( begin( range ), end( range ) ); } // Handle vector<bool> specially template <typename Allocator> std::string rangeToString( std::vector<bool, Allocator> const& v ) { ReusableStringStream rss; rss << "{ "; bool first = true; for ( bool b : v ) { if ( first ) first = false; else rss << ", "; rss << ::Catch::Detail::stringify( b ); } rss << " }"; return rss.str(); } template <typename R> struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail:: IsStreamInsertable<R>::value>::type> { static std::string convert( R const& range ) { return rangeToString( range ); } }; template <typename T, int SZ> struct StringMaker<T[SZ]> { static std::string convert( T const ( &arr )[SZ] ) { return rangeToString( arr ); } }; } // namespace Catch // Separate std::chrono::duration specialization #if defined( CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER ) #include <chrono> #include <ctime> #include <ratio> namespace Catch { template <class Ratio> struct ratio_string { static std::string symbol(); }; template <class Ratio> std::string ratio_string<Ratio>::symbol() { Catch::ReusableStringStream rss; rss << '[' << Ratio::num << '/' << Ratio::den << ']'; return rss.str(); } template <> struct ratio_string<std::atto> { static std::string symbol(); }; template <> struct ratio_string<std::femto> { static std::string symbol(); }; template <> struct ratio_string<std::pico> { static std::string symbol(); }; template <> struct ratio_string<std::nano> { static std::string symbol(); }; template <> struct ratio_string<std::micro> { static std::string symbol(); }; template <> struct ratio_string<std::milli> { static std::string symbol(); }; //////////// // std::chrono::duration specializations template <typename Value, typename Ratio> struct StringMaker<std::chrono::duration<Value, Ratio>> { static std::string convert( std::chrono::duration<Value, Ratio> const& duration ) { ReusableStringStream rss; rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's'; return rss.str(); } }; template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> { static std::string convert( std::chrono::duration<Value, std::ratio<1>> const& duration ) { ReusableStringStream rss; rss << duration.count() << " s"; return rss.str(); } }; template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> { static std::string convert( std::chrono::duration<Value, std::ratio<60>> const& duration ) { ReusableStringStream rss; rss << duration.count() << " m"; return rss.str(); } }; template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> { static std::string convert( std::chrono::duration<Value, std::ratio<3600>> const& duration ) { ReusableStringStream rss; rss << duration.count() << " h"; return rss.str(); } }; //////////// // std::chrono::time_point specialization // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock> template <typename Clock, typename Duration> struct StringMaker<std::chrono::time_point<Clock, Duration>> { static std::string convert( std::chrono::time_point<Clock, Duration> const& time_point ) { return ::Catch::Detail::stringify( time_point.time_since_epoch() ) + " since epoch"; } }; // std::chrono::time_point<system_clock> specialization template <typename Duration> struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> { static std::string convert( std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point ) { auto converted = std::chrono::system_clock::to_time_t( time_point ); #ifdef _MSC_VER std::tm timeInfo = {}; gmtime_s( &timeInfo, &converted ); #else std::tm* timeInfo = std::gmtime( &converted ); #endif auto const timeStampSize = sizeof( "2017-01-16T17:06:45Z" ); char timeStamp[timeStampSize]; const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; #ifdef _MSC_VER std::strftime( timeStamp, timeStampSize, fmt, &timeInfo ); #else std::strftime( timeStamp, timeStampSize, fmt, timeInfo ); #endif return std::string( timeStamp ); } }; } #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER #ifdef _MSC_VER #pragma warning( pop ) #endif // end catch_tostring.h #include <iosfwd> #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4389 ) // '==' : signed/unsigned mismatch #pragma warning( disable : 4018 ) // more "signed/unsigned mismatch" #pragma warning( disable : 4312 ) // Converting int to T* using reinterpret_cast (issue // on x64 platform) #pragma warning( disable : 4180 ) // qualifier applied to function type has no meaning #endif namespace Catch { struct ITransientExpression { auto isBinaryExpression() const -> bool { return m_isBinaryExpression; } auto getResult() const -> bool { return m_result; } virtual void streamReconstructedExpression( std::ostream& os ) const = 0; ITransientExpression( bool isBinaryExpression, bool result ) : m_isBinaryExpression( isBinaryExpression ) , m_result( result ) { } // We don't actually need a virtual destructor, but many static analysers // complain if it's not here :-( virtual ~ITransientExpression(); bool m_isBinaryExpression; bool m_result; }; void formatReconstructedExpression( std::ostream& os, std::string const& lhs, StringRef op, std::string const& rhs ); template <typename LhsT, typename RhsT> class BinaryExpr : public ITransientExpression { LhsT m_lhs; StringRef m_op; RhsT m_rhs; void streamReconstructedExpression( std::ostream& os ) const override { formatReconstructedExpression( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) ); } public: BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs ) : ITransientExpression{ true, comparisonResult } , m_lhs( lhs ) , m_op( op ) , m_rhs( rhs ) { } }; template <typename LhsT> class UnaryExpr : public ITransientExpression { LhsT m_lhs; void streamReconstructedExpression( std::ostream& os ) const override { os << Catch::Detail::stringify( m_lhs ); } public: explicit UnaryExpr( LhsT lhs ) : ITransientExpression{ false, lhs ? true : false } , m_lhs( lhs ) { } }; // Specialised comparison functions to handle equality comparisons between ints and // pointers (NULL deduces as an int) template <typename LhsT, typename RhsT> auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>( lhs == rhs ); } template <typename T> auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } template <typename T> auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); } template <typename T> auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } template <typename T> auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; } template <typename LhsT, typename RhsT> auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>( lhs != rhs ); } template <typename T> auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } template <typename T> auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); } template <typename T> auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } template <typename T> auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; } template <typename LhsT> class ExprLhs { LhsT m_lhs; public: explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) { } template <typename RhsT> auto operator==( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs }; } auto operator==( bool rhs ) -> BinaryExpr<LhsT, bool> const { return { m_lhs == rhs, m_lhs, "==", rhs }; } template <typename RhsT> auto operator!=( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs }; } auto operator!=( bool rhs ) -> BinaryExpr<LhsT, bool> const { return { m_lhs != rhs, m_lhs, "!=", rhs }; } template <typename RhsT> auto operator>( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>( m_lhs > rhs ), m_lhs, ">", rhs }; } template <typename RhsT> auto operator<( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>( m_lhs < rhs ), m_lhs, "<", rhs }; } template <typename RhsT> auto operator>=( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>( m_lhs >= rhs ), m_lhs, ">=", rhs }; } template <typename RhsT> auto operator<=( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const { return { static_cast<bool>( m_lhs <= rhs ), m_lhs, "<=", rhs }; } auto makeUnaryExpr() const -> UnaryExpr<LhsT> { return UnaryExpr<LhsT>{ m_lhs }; } }; void handleExpression( ITransientExpression const& expr ); template <typename T> void handleExpression( ExprLhs<T> const& expr ) { handleExpression( expr.makeUnaryExpr() ); } struct Decomposer { template <typename T> auto operator<=( T const& lhs ) -> ExprLhs<T const&> { return ExprLhs<T const&>{ lhs }; } auto operator<=( bool value ) -> ExprLhs<bool> { return ExprLhs<bool>{ value }; } }; } // end namespace Catch #ifdef _MSC_VER #pragma warning( pop ) #endif // end catch_decomposer.h // start catch_interfaces_capture.h #include <string> namespace Catch { class AssertionResult; struct AssertionInfo; struct SectionInfo; struct SectionEndInfo; struct MessageInfo; struct Counts; struct BenchmarkInfo; struct BenchmarkStats; struct AssertionReaction; struct ITransientExpression; struct IResultCapture { virtual ~IResultCapture(); virtual bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) = 0; virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0; virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0; virtual void pushScopedMessage( MessageInfo const& message ) = 0; virtual void popScopedMessage( MessageInfo const& message ) = 0; virtual void handleFatalErrorCondition( StringRef message ) = 0; virtual void handleExpr( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) = 0; virtual void handleMessage( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedExceptionNotThrown( AssertionInfo const& info, AssertionReaction& reaction ) = 0; virtual void handleUnexpectedInflightException( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) = 0; virtual void handleIncomplete( AssertionInfo const& info ) = 0; virtual void handleNonExpr( AssertionInfo const& info, ResultWas::OfType resultType, AssertionReaction& reaction ) = 0; virtual bool lastAssertionPassed() = 0; virtual void assertionPassed() = 0; // Deprecated, do not use: virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; virtual void exceptionEarlyReported() = 0; }; IResultCapture& getResultCapture(); } // end catch_interfaces_capture.h namespace Catch { struct TestFailureException { }; struct AssertionResultData; struct IResultCapture; class RunContext; class LazyExpression { friend class AssertionHandler; friend struct AssertionStats; friend class RunContext; ITransientExpression const* m_transientExpression = nullptr; bool m_isNegated; public: LazyExpression( bool isNegated ); LazyExpression( LazyExpression const& other ); LazyExpression& operator=( LazyExpression const& ) = delete; explicit operator bool() const; friend auto operator<<( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&; }; struct AssertionReaction { bool shouldDebugBreak = false; bool shouldThrow = false; }; class AssertionHandler { AssertionInfo m_assertionInfo; AssertionReaction m_reaction; bool m_completed = false; IResultCapture& m_resultCapture; public: AssertionHandler( StringRef macroName, SourceLineInfo const& lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition ); ~AssertionHandler() { if ( !m_completed ) { m_resultCapture.handleIncomplete( m_assertionInfo ); } } template <typename T> void handleExpr( ExprLhs<T> const& expr ) { handleExpr( expr.makeUnaryExpr() ); } void handleExpr( ITransientExpression const& expr ); void handleMessage( ResultWas::OfType resultType, StringRef const& message ); void handleExceptionThrownAsExpected(); void handleUnexpectedExceptionNotThrown(); void handleExceptionNotThrownAsExpected(); void handleThrowingCallSkipped(); void handleUnexpectedInflightException(); void complete(); void setCompleted(); // query auto allowThrows() const -> bool; }; void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ); } // namespace Catch // end catch_assertionhandler.h // start catch_message.h #include <string> namespace Catch { struct MessageInfo { MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ); std::string macroName; std::string message; SourceLineInfo lineInfo; ResultWas::OfType type; unsigned int sequence; bool operator==( MessageInfo const& other ) const; bool operator<( MessageInfo const& other ) const; private: static unsigned int globalCount; }; struct MessageStream { template <typename T> MessageStream& operator<<( T const& value ) { m_stream << value; return *this; } ReusableStringStream m_stream; }; struct MessageBuilder : MessageStream { MessageBuilder( std::string const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ); template <typename T> MessageBuilder& operator<<( T const& value ) { m_stream << value; return *this; } MessageInfo m_info; }; class ScopedMessage { public: explicit ScopedMessage( MessageBuilder const& builder ); ~ScopedMessage(); MessageInfo m_info; }; } // end namespace Catch // end catch_message.h #if !defined( CATCH_CONFIG_DISABLE ) #if !defined( CATCH_CONFIG_DISABLE_STRINGIFICATION ) #define CATCH_INTERNAL_STRINGIFY( ... ) #__VA_ARGS__ #else #define CATCH_INTERNAL_STRINGIFY( ... ) \ "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" #endif #if defined( CATCH_CONFIG_FAST_COMPILE ) /////////////////////////////////////////////////////////////////////////////// // Another way to speed-up compilation is to omit local try-catch for REQUIRE* // macros. #define INTERNAL_CATCH_TRY #define INTERNAL_CATCH_CATCH( capturer ) #else // CATCH_CONFIG_FAST_COMPILE #define INTERNAL_CATCH_TRY try #define INTERNAL_CATCH_CATCH( handler ) \ catch ( ... ) { handler.handleUnexpectedInflightException(); } #endif #define INTERNAL_CATCH_REACT( handler ) handler.complete(); /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, \ CATCH_INTERNAL_STRINGIFY( __VA_ARGS__ ), resultDisposition ); \ INTERNAL_CATCH_TRY \ { \ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ } \ INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( (void)0, \ false && static_cast<bool>( !!( __VA_ARGS__ ) ) ) // the expression here // is never evaluated at // runtime but it forces // the compiler to give // it a look // The double negation silences MSVC's C4800 warning, the static_cast forces // short-circuit evaluation if the type has overloaded &&. /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ if ( Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ if ( !Catch::getResultCapture().lastAssertionPassed() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, \ CATCH_INTERNAL_STRINGIFY( __VA_ARGS__ ), resultDisposition ); \ try \ { \ static_cast<void>( __VA_ARGS__ ); \ catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ } \ catch ( ... ) \ { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, \ CATCH_INTERNAL_STRINGIFY( __VA_ARGS__ ), resultDisposition ); \ if ( catchAssertionHandler.allowThrows() ) \ try \ { \ static_cast<void>( __VA_ARGS__ ); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch ( ... ) \ { \ catchAssertionHandler.handleExceptionThrownAsExpected(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, \ CATCH_INTERNAL_STRINGIFY( expr ) ", " CATCH_INTERNAL_STRINGIFY( \ exceptionType ), \ resultDisposition ); \ if ( catchAssertionHandler.allowThrows() ) \ try \ { \ static_cast<void>( expr ); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch ( exceptionType const& ) \ { \ catchAssertionHandler.handleExceptionThrownAsExpected(); \ } \ catch ( ... ) \ { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ catchAssertionHandler.handleMessage( \ messageType, \ ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ) \ .m_stream.str() ); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_INFO( macroName, log ) \ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( \ Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, \ Catch::ResultWas::Info ) \ << log ); /////////////////////////////////////////////////////////////////////////////// // Although this is matcher-based, it can be used with just a string #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, \ CATCH_INTERNAL_STRINGIFY( __VA_ARGS__ ) ", " CATCH_INTERNAL_STRINGIFY( \ matcher ), \ resultDisposition ); \ if ( catchAssertionHandler.allowThrows() ) \ try \ { \ static_cast<void>( __VA_ARGS__ ); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch ( ... ) \ { \ Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, \ #matcher ); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( false ) #endif // CATCH_CONFIG_DISABLE // end catch_capture.hpp // start catch_section.h // start catch_section_info.h // start catch_totals.h #include <cstddef> namespace Catch { struct Counts { Counts operator-( Counts const& other ) const; Counts& operator+=( Counts const& other ); std::size_t total() const; bool allPassed() const; bool allOk() const; std::size_t passed = 0; std::size_t failed = 0; std::size_t failedButOk = 0; }; struct Totals { Totals operator-( Totals const& other ) const; Totals& operator+=( Totals const& other ); Totals delta( Totals const& prevTotals ) const; int error = 0; Counts assertions; Counts testCases; }; } // end catch_totals.h #include <string> namespace Catch { struct SectionInfo { SectionInfo( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description = std::string() ); std::string name; std::string description; SourceLineInfo lineInfo; }; struct SectionEndInfo { SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds ); SectionInfo sectionInfo; Counts prevAssertions; double durationInSeconds; }; } // end namespace Catch // end catch_section_info.h // start catch_timer.h #include <cstdint> namespace Catch { auto getCurrentNanosecondsSinceEpoch() -> uint64_t; auto getEstimatedClockResolution() -> uint64_t; class Timer { uint64_t m_nanoseconds = 0; public: void start(); auto getElapsedNanoseconds() const -> uint64_t; auto getElapsedMicroseconds() const -> uint64_t; auto getElapsedMilliseconds() const -> unsigned int; auto getElapsedSeconds() const -> double; }; } // namespace Catch // end catch_timer.h #include <string> namespace Catch { class Section : NonCopyable { public: Section( SectionInfo const& info ); ~Section(); // This indicates whether the section should be executed or not explicit operator bool() const; private: SectionInfo m_info; std::string m_name; Counts m_assertions; bool m_sectionIncluded; Timer m_timer; }; } // end namespace Catch #define INTERNAL_CATCH_SECTION( ... ) \ if ( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) \ = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) // end catch_section.h // start catch_benchmark.h #include <cstdint> #include <string> namespace Catch { class BenchmarkLooper { std::string m_name; std::size_t m_count = 0; std::size_t m_iterationsToRun = 1; uint64_t m_resolution; Timer m_timer; static auto getResolution() -> uint64_t; public: // Keep most of this inline as it's on the code path that is being timed BenchmarkLooper( StringRef name ) : m_name( name ) , m_resolution( getResolution() ) { reportStart(); m_timer.start(); } explicit operator bool() { if ( m_count < m_iterationsToRun ) return true; return needsMoreIterations(); } void increment() { ++m_count; } void reportStart(); auto needsMoreIterations() -> bool; }; } // end namespace Catch #define BENCHMARK( name ) \ for ( Catch::BenchmarkLooper looper( name ); looper; looper.increment() ) // end catch_benchmark.h // start catch_interfaces_exception.h // start catch_interfaces_registry_hub.h #include <memory> #include <string> namespace Catch { class TestCase; struct ITestCaseRegistry; struct IExceptionTranslatorRegistry; struct IExceptionTranslator; struct IReporterRegistry; struct IReporterFactory; struct ITagAliasRegistry; class StartupExceptionRegistry; using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>; struct IRegistryHub { virtual ~IRegistryHub(); virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0; }; struct IMutableRegistryHub { virtual ~IMutableRegistryHub(); virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0; virtual void registerListener( IReporterFactoryPtr const& factory ) = 0; virtual void registerTest( TestCase const& testInfo ) = 0; virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; virtual void registerStartupException() noexcept = 0; }; IRegistryHub& getRegistryHub(); IMutableRegistryHub& getMutableRegistryHub(); void cleanUp(); std::string translateActiveException(); } // end catch_interfaces_registry_hub.h #if defined( CATCH_CONFIG_DISABLE ) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature ) \ static std::string translatorName( signature ) #endif #include <exception> #include <string> #include <vector> namespace Catch { using exceptionTranslateFunction = std::string ( * )(); struct IExceptionTranslator; using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>; struct IExceptionTranslator { virtual ~IExceptionTranslator(); virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; }; struct IExceptionTranslatorRegistry { virtual ~IExceptionTranslatorRegistry(); virtual std::string translateActiveException() const = 0; }; class ExceptionTranslatorRegistrar { template <typename T> class ExceptionTranslator : public IExceptionTranslator { public: ExceptionTranslator( std::string ( *translateFunction )( T& ) ) : m_translateFunction( translateFunction ) { } std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override { try { if ( it == itEnd ) std::rethrow_exception( std::current_exception() ); else return ( *it )->translate( it + 1, itEnd ); } catch ( T& ex ) { return m_translateFunction( ex ); } } protected: std::string ( *m_translateFunction )( T& ); }; public: template <typename T> ExceptionTranslatorRegistrar( std::string ( *translateFunction )( T& ) ) { getMutableRegistryHub().registerTranslator( new ExceptionTranslator<T>( translateFunction ) ); } }; } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ static std::string translatorName( signature ); \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace \ { \ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( \ catch_internal_ExceptionRegistrar )( &translatorName ); \ } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ static std::string translatorName( signature ) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) \ INTERNAL_CATCH_TRANSLATE_EXCEPTION2( \ INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) // end catch_interfaces_exception.h // start catch_approx.h #include <stdexcept> #include <type_traits> namespace Catch { namespace Detail { class Approx { private: bool equalityComparisonImpl( double other ) const; public: explicit Approx( double value ); static Approx custom(); template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx operator()( T const& value ) { Approx approx( static_cast<double>( value ) ); approx.epsilon( m_epsilon ); approx.margin( m_margin ); approx.scale( m_scale ); return approx; } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> explicit Approx( T const& value ) : Approx( static_cast<double>( value ) ) { } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator==( const T& lhs, Approx const& rhs ) { auto lhs_v = static_cast<double>( lhs ); return rhs.equalityComparisonImpl( lhs_v ); } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator==( Approx const& lhs, const T& rhs ) { return operator==( rhs, lhs ); } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator!=( T const& lhs, Approx const& rhs ) { return !operator==( lhs, rhs ); } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator!=( Approx const& lhs, T const& rhs ) { return !operator==( rhs, lhs ); } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator<=( T const& lhs, Approx const& rhs ) { return static_cast<double>( lhs ) < rhs.m_value || lhs == rhs; } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator<=( Approx const& lhs, T const& rhs ) { return lhs.m_value < static_cast<double>( rhs ) || lhs == rhs; } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator>=( T const& lhs, Approx const& rhs ) { return static_cast<double>( lhs ) > rhs.m_value || lhs == rhs; } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> friend bool operator>=( Approx const& lhs, T const& rhs ) { return lhs.m_value > static_cast<double>( rhs ) || lhs == rhs; } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx& epsilon( T const& newEpsilon ) { double epsilonAsDouble = static_cast<double>( newEpsilon ); if ( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) { throw std::domain_error( "Invalid Approx::epsilon: " + Catch::Detail::stringify( epsilonAsDouble ) + ", Approx::epsilon has to be between 0 and 1" ); } m_epsilon = epsilonAsDouble; return *this; } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx& margin( T const& newMargin ) { double marginAsDouble = static_cast<double>( newMargin ); if ( marginAsDouble < 0 ) { throw std::domain_error( "Invalid Approx::margin: " + Catch::Detail::stringify( marginAsDouble ) + ", Approx::Margin has to be non-negative." ); } m_margin = marginAsDouble; return *this; } template < typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> Approx& scale( T const& newScale ) { m_scale = static_cast<double>( newScale ); return *this; } std::string toString() const; private: double m_epsilon; double m_margin; double m_scale; double m_value; }; } template <> struct StringMaker<Catch::Detail::Approx> { static std::string convert( Catch::Detail::Approx const& value ); }; } // end namespace Catch // end catch_approx.h // start catch_string_manip.h #include <iosfwd> #include <string> namespace Catch { bool startsWith( std::string const& s, std::string const& prefix ); bool startsWith( std::string const& s, char prefix ); bool endsWith( std::string const& s, std::string const& suffix ); bool endsWith( std::string const& s, char suffix ); bool contains( std::string const& s, std::string const& infix ); void toLowerInPlace( std::string& s ); std::string toLower( std::string const& s ); std::string trim( std::string const& str ); bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); struct pluralise { pluralise( std::size_t count, std::string const& label ); friend std::ostream& operator<<( std::ostream& os, pluralise const& pluraliser ); std::size_t m_count; std::string m_label; }; } // end catch_string_manip.h #ifndef CATCH_CONFIG_DISABLE_MATCHERS // start catch_capture_matchers.h // start catch_matchers.h #include <string> #include <vector> namespace Catch { namespace Matchers { namespace Impl { template <typename ArgT> struct MatchAllOf; template <typename ArgT> struct MatchAnyOf; template <typename ArgT> struct MatchNotOf; class MatcherUntypedBase { public: MatcherUntypedBase() = default; MatcherUntypedBase( MatcherUntypedBase const& ) = default; MatcherUntypedBase& operator=( MatcherUntypedBase const& ) = delete; std::string toString() const; protected: virtual ~MatcherUntypedBase(); virtual std::string describe() const = 0; mutable std::string m_cachedToString; }; template <typename ObjectT> struct MatcherMethod { virtual bool match( ObjectT const& arg ) const = 0; }; template <typename PtrT> struct MatcherMethod<PtrT*> { virtual bool match( PtrT* arg ) const = 0; }; template <typename T> struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> { MatchAllOf<T> operator&&( MatcherBase const& other ) const; MatchAnyOf<T> operator||( MatcherBase const& other ) const; MatchNotOf<T> operator!() const; }; template <typename ArgT> struct MatchAllOf : MatcherBase<ArgT> { bool match( ArgT const& arg ) const override { for ( auto matcher : m_matchers ) { if ( !matcher->match( arg ) ) return false; } return true; } std::string describe() const override { std::string description; description.reserve( 4 + m_matchers.size() * 32 ); description += "( "; bool first = true; for ( auto matcher : m_matchers ) { if ( first ) first = false; else description += " and "; description += matcher->toString(); } description += " )"; return description; } MatchAllOf<ArgT>& operator&&( MatcherBase<ArgT> const& other ) { m_matchers.push_back( &other ); return *this; } std::vector<MatcherBase<ArgT> const*> m_matchers; }; template <typename ArgT> struct MatchAnyOf : MatcherBase<ArgT> { bool match( ArgT const& arg ) const override { for ( auto matcher : m_matchers ) { if ( matcher->match( arg ) ) return true; } return false; } std::string describe() const override { std::string description; description.reserve( 4 + m_matchers.size() * 32 ); description += "( "; bool first = true; for ( auto matcher : m_matchers ) { if ( first ) first = false; else description += " or "; description += matcher->toString(); } description += " )"; return description; } MatchAnyOf<ArgT>& operator||( MatcherBase<ArgT> const& other ) { m_matchers.push_back( &other ); return *this; } std::vector<MatcherBase<ArgT> const*> m_matchers; }; template <typename ArgT> struct MatchNotOf : MatcherBase<ArgT> { MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) { } bool match( ArgT const& arg ) const override { return !m_underlyingMatcher.match( arg ); } std::string describe() const override { return "not " + m_underlyingMatcher.toString(); } MatcherBase<ArgT> const& m_underlyingMatcher; }; template <typename T> MatchAllOf<T> MatcherBase<T>::operator&&( MatcherBase const& other ) const { return MatchAllOf<T>() && *this && other; } template <typename T> MatchAnyOf<T> MatcherBase<T>::operator||( MatcherBase const& other ) const { return MatchAnyOf<T>() || *this || other; } template <typename T> MatchNotOf<T> MatcherBase<T>::operator!() const { return MatchNotOf<T>( *this ); } } // namespace Impl } // namespace Matchers using namespace Matchers; using Matchers::Impl::MatcherBase; } // namespace Catch // end catch_matchers.h // start catch_matchers_floating.h #include <cmath> #include <type_traits> namespace Catch { namespace Matchers { namespace Floating { enum class FloatingPointKind : uint8_t; struct WithinAbsMatcher : MatcherBase<double> { WithinAbsMatcher( double target, double margin ); bool match( double const& matchee ) const override; std::string describe() const override; private: double m_target; double m_margin; }; struct WithinUlpsMatcher : MatcherBase<double> { WithinUlpsMatcher( double target, int ulps, FloatingPointKind baseType ); bool match( double const& matchee ) const override; std::string describe() const override; private: double m_target; int m_ulps; FloatingPointKind m_type; }; } // namespace Floating // The following functions create the actual matcher objects. // This allows the types to be inferred Floating::WithinUlpsMatcher WithinULP( double target, int maxUlpDiff ); Floating::WithinUlpsMatcher WithinULP( float target, int maxUlpDiff ); Floating::WithinAbsMatcher WithinAbs( double target, double margin ); } // namespace Matchers } // namespace Catch // end catch_matchers_floating.h // start catch_matchers_generic.hpp #include <functional> #include <string> namespace Catch { namespace Matchers { namespace Generic { namespace Detail { std::string finalizeDescription( const std::string& desc ); } template <typename T> class PredicateMatcher : public MatcherBase<T> { std::function<bool( T const& )> m_predicate; std::string m_description; public: PredicateMatcher( std::function<bool( T const& )> const& elem, std::string const& descr ) : m_predicate( std::move( elem ) ) , m_description( Detail::finalizeDescription( descr ) ) { } bool match( T const& item ) const override { return m_predicate( item ); } std::string describe() const override { return m_description; } }; } // namespace Generic // The following functions create the actual matcher objects. // The user has to explicitly specify type to the function, because // infering std::function<bool(T const&)> is hard (but possible) and // requires a lot of TMP. template <typename T> Generic::PredicateMatcher<T> Predicate( std::function<bool( T const& )> const& predicate, std::string const& description = "" ) { return Generic::PredicateMatcher<T>( predicate, description ); } } // namespace Matchers } // namespace Catch // end catch_matchers_generic.hpp // start catch_matchers_string.h #include <string> namespace Catch { namespace Matchers { namespace StdString { struct CasedString { CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ); std::string adjustString( std::string const& str ) const; std::string caseSensitivitySuffix() const; CaseSensitive::Choice m_caseSensitivity; std::string m_str; }; struct StringMatcherBase : MatcherBase<std::string> { StringMatcherBase( std::string const& operation, CasedString const& comparator ); std::string describe() const override; CasedString m_comparator; std::string m_operation; }; struct EqualsMatcher : StringMatcherBase { EqualsMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct ContainsMatcher : StringMatcherBase { ContainsMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct StartsWithMatcher : StringMatcherBase { StartsWithMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct EndsWithMatcher : StringMatcherBase { EndsWithMatcher( CasedString const& comparator ); bool match( std::string const& source ) const override; }; struct RegexMatcher : MatcherBase<std::string> { RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity ); bool match( std::string const& matchee ) const override; std::string describe() const override; private: std::string m_regex; CaseSensitive::Choice m_caseSensitivity; }; } // namespace StdString // The following functions create the actual matcher objects. // This allows the types to be inferred StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); } // namespace Matchers } // namespace Catch // end catch_matchers_string.h // start catch_matchers_vector.h #include <algorithm> namespace Catch { namespace Matchers { namespace Vector { namespace Detail { template <typename InputIterator, typename T> size_t count( InputIterator first, InputIterator last, T const& item ) { size_t cnt = 0; for ( ; first != last; ++first ) { if ( *first == item ) { ++cnt; } } return cnt; } template <typename InputIterator, typename T> bool contains( InputIterator first, InputIterator last, T const& item ) { for ( ; first != last; ++first ) { if ( *first == item ) { return true; } } return false; } } template <typename T> struct ContainsElementMatcher : MatcherBase<std::vector<T>> { ContainsElementMatcher( T const& comparator ) : m_comparator( comparator ) { } bool match( std::vector<T> const& v ) const override { for ( auto const& el : v ) { if ( el == m_comparator ) { return true; } } return false; } std::string describe() const override { return "Contains: " + ::Catch::Detail::stringify( m_comparator ); } T const& m_comparator; }; template <typename T> struct ContainsMatcher : MatcherBase<std::vector<T>> { ContainsMatcher( std::vector<T> const& comparator ) : m_comparator( comparator ) { } bool match( std::vector<T> const& v ) const override { // !TBD: see note in EqualsMatcher if ( m_comparator.size() > v.size() ) return false; for ( auto const& comparator : m_comparator ) { auto present = false; for ( const auto& el : v ) { if ( el == comparator ) { present = true; break; } } if ( !present ) { return false; } } return true; } std::string describe() const override { return "Contains: " + ::Catch::Detail::stringify( m_comparator ); } std::vector<T> const& m_comparator; }; template <typename T> struct EqualsMatcher : MatcherBase<std::vector<T>> { EqualsMatcher( std::vector<T> const& comparator ) : m_comparator( comparator ) { } bool match( std::vector<T> const& v ) const override { // !TBD: This currently works if all elements can be compared using != // - a more general approach would be via a compare template that // defaults // to using !=. but could be specialised for, e.g. std::vector<T> etc // - then just call that directly if ( m_comparator.size() != v.size() ) return false; for ( std::size_t i = 0; i < v.size(); ++i ) if ( m_comparator[i] != v[i] ) return false; return true; } std::string describe() const override { return "Equals: " + ::Catch::Detail::stringify( m_comparator ); } std::vector<T> const& m_comparator; }; template <typename T> struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> { UnorderedEqualsMatcher( std::vector<T> const& target ) : m_target( target ) { } bool match( std::vector<T> const& vec ) const override { // Note: This is a reimplementation of std::is_permutation, // because I don't want to include <algorithm> inside the common // path if ( m_target.size() != vec.size() ) { return false; } auto lfirst = m_target.begin(), llast = m_target.end(); auto rfirst = vec.begin(), rlast = vec.end(); // Cut common prefix to optimize checking of permuted parts while ( lfirst != llast && *lfirst != *rfirst ) { ++lfirst; ++rfirst; } if ( lfirst == llast ) { return true; } for ( auto mid = lfirst; mid != llast; ++mid ) { // Skip already counted items if ( Detail::contains( lfirst, mid, *mid ) ) { continue; } size_t num_vec = Detail::count( rfirst, rlast, *mid ); if ( num_vec == 0 || Detail::count( lfirst, llast, *mid ) != num_vec ) { return false; } } return true; } std::string describe() const override { return "UnorderedEquals: " + ::Catch::Detail::stringify( m_target ); } private: std::vector<T> const& m_target; }; } // namespace Vector // The following functions create the actual matcher objects. // This allows the types to be inferred template <typename T> Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) { return Vector::ContainsMatcher<T>( comparator ); } template <typename T> Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) { return Vector::ContainsElementMatcher<T>( comparator ); } template <typename T> Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) { return Vector::EqualsMatcher<T>( comparator ); } template <typename T> Vector::UnorderedEqualsMatcher<T> UnorderedEquals( std::vector<T> const& target ) { return Vector::UnorderedEqualsMatcher<T>( target ); } } // namespace Matchers } // namespace Catch // end catch_matchers_vector.h namespace Catch { template <typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression { ArgT const& m_arg; MatcherT m_matcher; StringRef m_matcherString; public: MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) : ITransientExpression{ true, matcher.match( arg ) } , m_arg( arg ) , m_matcher( matcher ) , m_matcherString( matcherString ) { } void streamReconstructedExpression( std::ostream& os ) const override { auto matcherAsString = m_matcher.toString(); os << Catch::Detail::stringify( m_arg ) << ' '; if ( matcherAsString == Detail::unprintableString ) os << m_matcherString; else os << matcherAsString; } }; using StringMatcher = Matchers::Impl::MatcherBase<std::string>; void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ); template <typename ArgT, typename MatcherT> auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> { return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString ); } } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, \ CATCH_INTERNAL_STRINGIFY( arg ) ", " CATCH_INTERNAL_STRINGIFY( matcher ), \ resultDisposition ); \ INTERNAL_CATCH_TRY \ { \ catchAssertionHandler.handleExpr( \ Catch::makeMatchExpr( arg, matcher, #matcher ) ); \ } \ INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( false ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, \ matcher, ... ) \ do \ { \ Catch::AssertionHandler catchAssertionHandler( \ macroName, CATCH_INTERNAL_LINEINFO, \ CATCH_INTERNAL_STRINGIFY( __VA_ARGS__ ) ", " CATCH_INTERNAL_STRINGIFY( \ exceptionType ) ", " CATCH_INTERNAL_STRINGIFY( matcher ), \ resultDisposition ); \ if ( catchAssertionHandler.allowThrows() ) \ try \ { \ static_cast<void>( __VA_ARGS__ ); \ catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ } \ catch ( exceptionType const& ex ) \ { \ catchAssertionHandler.handleExpr( \ Catch::makeMatchExpr( ex, matcher, #matcher ) ); \ } \ catch ( ... ) \ { \ catchAssertionHandler.handleUnexpectedInflightException(); \ } \ else \ catchAssertionHandler.handleThrowingCallSkipped(); \ INTERNAL_CATCH_REACT( catchAssertionHandler ) \ } while ( false ) // end catch_capture_matchers.h #endif // These files are included here so the single_include script doesn't put them // in the conditionally compiled sections // start catch_test_case_info.h #include <memory> #include <string> #include <vector> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif namespace Catch { struct ITestInvoker; struct TestCaseInfo { enum SpecialProperties { None = 0, IsHidden = 1 << 1, ShouldFail = 1 << 2, MayFail = 1 << 3, Throws = 1 << 4, NonPortable = 1 << 5, Benchmark = 1 << 6 }; TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::vector<std::string> const& _tags, SourceLineInfo const& _lineInfo ); friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ); bool isHidden() const; bool throws() const; bool okToFail() const; bool expectedToFail() const; std::string tagsAsString() const; std::string name; std::string className; std::string description; std::vector<std::string> tags; std::vector<std::string> lcaseTags; SourceLineInfo lineInfo; SpecialProperties properties; }; class TestCase : public TestCaseInfo { public: TestCase( ITestInvoker* testCase, TestCaseInfo&& info ); TestCase withName( std::string const& _newName ) const; void invoke() const; TestCaseInfo const& getTestCaseInfo() const; bool operator==( TestCase const& other ) const; bool operator<( TestCase const& other ) const; private: std::shared_ptr<ITestInvoker> test; }; TestCase makeTestCase( ITestInvoker* testCase, std::string const& className, NameAndTags const& nameAndTags, SourceLineInfo const& lineInfo ); } #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_test_case_info.h // start catch_interfaces_runner.h namespace Catch { struct IRunner { virtual ~IRunner(); virtual bool aborting() const = 0; }; } // end catch_interfaces_runner.h #ifdef __OBJC__ // start catch_objc.hpp #import <objc/runtime.h> #include <string> // NB. Any general catch headers included here must be included // in catch.hpp first to make sure they are included by the single // header for non obj-usage /////////////////////////////////////////////////////////////////////////////// // This protocol is really only here for (self) documenting purposes, since // all its methods are optional. @protocol OcFixture @optional - (void)setUp; - (void)tearDown; @end namespace Catch { class OcMethod : public ITestInvoker { public: OcMethod( Class cls, SEL sel ) : m_cls( cls ) , m_sel( sel ) { } virtual void invoke() const { id obj = [[m_cls alloc] init]; performOptionalSelector( obj, @selector( setUp ) ); performOptionalSelector( obj, m_sel ); performOptionalSelector( obj, @selector( tearDown ) ); arcSafeRelease( obj ); } private: virtual ~OcMethod() {} Class m_cls; SEL m_sel; }; namespace Detail { inline std::string getAnnotation( Class cls, std::string const& annotationName, std::string const& testCaseName ) { NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; SEL sel = NSSelectorFromString( selStr ); arcSafeRelease( selStr ); id value = performOptionalSelector( cls, sel ); if ( value ) return [(NSString*)value UTF8String]; return ""; } } inline std::size_t registerTestMethods() { std::size_t noTestMethods = 0; int noClasses = objc_getClassList( nullptr, 0 ); Class* classes = (CATCH_UNSAFE_UNRETAINED Class*)malloc( sizeof( Class ) * noClasses ); objc_getClassList( classes, noClasses ); for ( int c = 0; c < noClasses; c++ ) { Class cls = classes[c]; { u_int count; Method* methods = class_copyMethodList( cls, &count ); for ( u_int m = 0; m < count; m++ ) { SEL selector = method_getName( methods[m] ); std::string methodName = sel_getName( selector ); if ( startsWith( methodName, "Catch_TestCase_" ) ) { std::string testCaseName = methodName.substr( 15 ); std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); const char* className = class_getName( cls ); getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo( "", 0 ) ) ); noTestMethods++; } } free( methods ); } } return noTestMethods; } #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) namespace Matchers { namespace Impl { namespace NSStringMatchers { struct StringHolder : MatcherBase<NSString*> { StringHolder( NSString* substr ) : m_substr( [substr copy] ) { } StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ) { } StringHolder() { arcSafeRelease( m_substr ); } bool match( NSString* arg ) const override { return false; } NSString* CATCH_ARC_STRONG m_substr; }; struct Equals : StringHolder { Equals( NSString* substr ) : StringHolder( substr ) { } bool match( NSString* str ) const override { return ( str != nil || m_substr == nil ) && [str isEqualToString:m_substr]; } std::string describe() const override { return "equals string: " + Catch::Detail::stringify( m_substr ); } }; struct Contains : StringHolder { Contains( NSString* substr ) : StringHolder( substr ) { } bool match( NSString* str ) const { return ( str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location != NSNotFound; } std::string describe() const override { return "contains string: " + Catch::Detail::stringify( m_substr ); } }; struct StartsWith : StringHolder { StartsWith( NSString* substr ) : StringHolder( substr ) { } bool match( NSString* str ) const override { return ( str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == 0; } std::string describe() const override { return "starts with: " + Catch::Detail::stringify( m_substr ); } }; struct EndsWith : StringHolder { EndsWith( NSString* substr ) : StringHolder( substr ) { } bool match( NSString* str ) const override { return ( str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == [str length] - [m_substr length]; } std::string describe() const override { return "ends with: " + Catch::Detail::stringify( m_substr ); } }; } // namespace NSStringMatchers } // namespace Impl inline Impl::NSStringMatchers::Equals Equals( NSString* substr ) { return Impl::NSStringMatchers::Equals( substr ); } inline Impl::NSStringMatchers::Contains Contains( NSString* substr ) { return Impl::NSStringMatchers::Contains( substr ); } inline Impl::NSStringMatchers::StartsWith StartsWith( NSString* substr ) { return Impl::NSStringMatchers::StartsWith( substr ); } inline Impl::NSStringMatchers::EndsWith EndsWith( NSString* substr ) { return Impl::NSStringMatchers::EndsWith( substr ); } } // namespace Matchers using namespace Matchers; #endif // CATCH_CONFIG_DISABLE_MATCHERS } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ +(NSString*)OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) { return @name; } \ +(NSString*)OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ { \ return @desc; \ } \ -(void)OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) // end catch_objc.hpp #endif #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES // start catch_external_interfaces.h // start catch_reporter_bases.hpp // start catch_interfaces_reporter.h // start catch_config.hpp // start catch_test_spec_parser.h #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // start catch_test_spec.h #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif // start catch_wildcard_pattern.h namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, WildcardAtStart = 1, WildcardAtEnd = 2, WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd }; public: WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ); virtual ~WildcardPattern() = default; virtual bool matches( std::string const& str ) const; private: std::string adjustCase( std::string const& str ) const; CaseSensitive::Choice m_caseSensitivity; WildcardPosition m_wildcard = NoWildcard; std::string m_pattern; }; } // end catch_wildcard_pattern.h #include <memory> #include <string> #include <vector> namespace Catch { class TestSpec { struct Pattern { virtual ~Pattern(); virtual bool matches( TestCaseInfo const& testCase ) const = 0; }; using PatternPtr = std::shared_ptr<Pattern>; class NamePattern : public Pattern { public: NamePattern( std::string const& name ); virtual ~NamePattern(); virtual bool matches( TestCaseInfo const& testCase ) const override; private: WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: TagPattern( std::string const& tag ); virtual ~TagPattern(); virtual bool matches( TestCaseInfo const& testCase ) const override; private: std::string m_tag; }; class ExcludedPattern : public Pattern { public: ExcludedPattern( PatternPtr const& underlyingPattern ); virtual ~ExcludedPattern(); virtual bool matches( TestCaseInfo const& testCase ) const override; private: PatternPtr m_underlyingPattern; }; struct Filter { std::vector<PatternPtr> m_patterns; bool matches( TestCaseInfo const& testCase ) const; }; public: bool hasFilters() const; bool matches( TestCaseInfo const& testCase ) const; private: std::vector<Filter> m_filters; friend class TestSpecParser; }; } #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_test_spec.h // start catch_interfaces_tag_alias_registry.h #include <string> namespace Catch { struct TagAlias; struct ITagAliasRegistry { virtual ~ITagAliasRegistry(); // Nullptr if not present virtual TagAlias const* find( std::string const& alias ) const = 0; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; static ITagAliasRegistry const& get(); }; } // end namespace Catch // end catch_interfaces_tag_alias_registry.h namespace Catch { class TestSpecParser { enum Mode { None, Name, QuotedName, Tag, EscapedName }; Mode m_mode = None; bool m_exclusion = false; std::size_t m_start = std::string::npos, m_pos = 0; std::string m_arg; std::vector<std::size_t> m_escapeChars; TestSpec::Filter m_currentFilter; TestSpec m_testSpec; ITagAliasRegistry const* m_tagAliases = nullptr; public: TestSpecParser( ITagAliasRegistry const& tagAliases ); TestSpecParser& parse( std::string const& arg ); TestSpec testSpec(); private: void visitChar( char c ); void startNewMode( Mode mode, std::size_t start ); void escape(); std::string subString() const; template <typename T> void addPattern() { std::string token = subString(); for ( std::size_t i = 0; i < m_escapeChars.size(); ++i ) token = token.substr( 0, m_escapeChars[i] - m_start - i ) + token.substr( m_escapeChars[i] - m_start - i + 1 ); m_escapeChars.clear(); if ( startsWith( token, "exclude:" ) ) { m_exclusion = true; token = token.substr( 8 ); } if ( !token.empty() ) { TestSpec::PatternPtr pattern = std::make_shared<T>( token ); if ( m_exclusion ) pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern ); m_currentFilter.m_patterns.push_back( pattern ); } m_exclusion = false; m_mode = None; } void addFilter(); }; TestSpec parseTestSpec( std::string const& arg ); } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_test_spec_parser.h // start catch_interfaces_config.h #include <iosfwd> #include <memory> #include <string> #include <vector> namespace Catch { enum class Verbosity { Quiet = 0, Normal, High }; struct WarnAbout { enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 }; }; struct ShowDurations { enum OrNot { DefaultForReporter, Always, Never }; }; struct RunTests { enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder }; }; struct UseColour { enum YesOrNo { Auto, Yes, No }; }; struct WaitForKeypress { enum When { Never, BeforeStart = 1, BeforeExit = 2, BeforeStartAndExit = BeforeStart | BeforeExit }; }; class TestSpec; struct IConfig : NonCopyable { virtual ~IConfig(); virtual bool allowThrows() const = 0; virtual std::ostream& stream() const = 0; virtual std::string name() const = 0; virtual bool includeSuccessfulResults() const = 0; virtual bool shouldDebugBreak() const = 0; virtual bool warnAboutMissingAssertions() const = 0; virtual bool warnAboutNoTests() const = 0; virtual int abortAfter() const = 0; virtual bool showInvisibles() const = 0; virtual ShowDurations::OrNot showDurations() const = 0; virtual TestSpec const& testSpec() const = 0; virtual bool hasTestFilters() const = 0; virtual RunTests::InWhatOrder runOrder() const = 0; virtual unsigned int rngSeed() const = 0; virtual int benchmarkResolutionMultiple() const = 0; virtual UseColour::YesOrNo useColour() const = 0; virtual std::vector<std::string> const& getSectionsToRun() const = 0; virtual Verbosity verbosity() const = 0; }; using IConfigPtr = std::shared_ptr<IConfig const>; } // end catch_interfaces_config.h // Libstdc++ doesn't like incomplete classes for unique_ptr #include <memory> #include <string> #include <vector> #ifndef CATCH_CONFIG_CONSOLE_WIDTH #define CATCH_CONFIG_CONSOLE_WIDTH 80 #endif namespace Catch { struct IStream; struct ConfigData { bool listTests = false; bool listTags = false; bool listReporters = false; bool listTestNamesOnly = false; bool showSuccessfulTests = false; bool shouldDebugBreak = false; bool noThrow = false; bool showHelp = false; bool showInvisibles = false; bool filenamesAsTags = false; bool libIdentify = false; int abortAfter = -1; unsigned int rngSeed = 0; int benchmarkResolutionMultiple = 100; Verbosity verbosity = Verbosity::Normal; WarnAbout::What warnings = WarnAbout::Nothing; ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter; RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder; UseColour::YesOrNo useColour = UseColour::Auto; WaitForKeypress::When waitForKeypress = WaitForKeypress::Never; std::string outputFilename; std::string name; std::string processName; std::vector<std::string> reporterNames; std::vector<std::string> testsOrTags; std::vector<std::string> sectionsToRun; }; class Config : public IConfig { public: Config() = default; Config( ConfigData const& data ); virtual ~Config() = default; std::string const& getFilename() const; bool listTests() const; bool listTestNamesOnly() const; bool listTags() const; bool listReporters() const; std::string getProcessName() const; std::vector<std::string> const& getReporterNames() const; std::vector<std::string> const& getTestsOrTags() const; std::vector<std::string> const& getSectionsToRun() const override; virtual TestSpec const& testSpec() const override; bool hasTestFilters() const override; bool showHelp() const; // IConfig interface bool allowThrows() const override; std::ostream& stream() const override; std::string name() const override; bool includeSuccessfulResults() const override; bool warnAboutMissingAssertions() const override; bool warnAboutNoTests() const override; ShowDurations::OrNot showDurations() const override; RunTests::InWhatOrder runOrder() const override; unsigned int rngSeed() const override; int benchmarkResolutionMultiple() const override; UseColour::YesOrNo useColour() const override; bool shouldDebugBreak() const override; int abortAfter() const override; bool showInvisibles() const override; Verbosity verbosity() const override; private: IStream const* openStream(); ConfigData m_data; std::unique_ptr<IStream const> m_stream; TestSpec m_testSpec; bool m_hasTestFilters = false; }; } // end namespace Catch // end catch_config.hpp // start catch_assertionresult.h #include <string> namespace Catch { struct AssertionResultData { AssertionResultData() = delete; AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression ); std::string message; mutable std::string reconstructedExpression; LazyExpression lazyExpression; ResultWas::OfType resultType; std::string reconstructExpression() const; }; class AssertionResult { public: AssertionResult() = delete; AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); bool isOk() const; bool succeeded() const; ResultWas::OfType getResultType() const; bool hasExpression() const; bool hasMessage() const; std::string getExpression() const; std::string getExpressionInMacro() const; bool hasExpandedExpression() const; std::string getExpandedExpression() const; std::string getMessage() const; SourceLineInfo getSourceInfo() const; StringRef getTestMacroName() const; // protected: AssertionInfo m_info; AssertionResultData m_resultData; }; } // end namespace Catch // end catch_assertionresult.h // start catch_option.hpp namespace Catch { // An optional type template <typename T> class Option { public: Option() : nullableValue( nullptr ) { } Option( T const& _value ) : nullableValue( new ( storage ) T( _value ) ) { } Option( Option const& _other ) : nullableValue( _other ? new ( storage ) T( *_other ) : nullptr ) { } ~Option() { reset(); } Option& operator=( Option const& _other ) { if ( &_other != this ) { reset(); if ( _other ) nullableValue = new ( storage ) T( *_other ); } return *this; } Option& operator=( T const& _value ) { reset(); nullableValue = new ( storage ) T( _value ); return *this; } void reset() { if ( nullableValue ) nullableValue->~T(); nullableValue = nullptr; } T& operator*() { return *nullableValue; } T const& operator*() const { return *nullableValue; } T* operator->() { return nullableValue; } const T* operator->() const { return nullableValue; } T valueOr( T const& defaultValue ) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != nullptr; } bool none() const { return nullableValue == nullptr; } bool operator!() const { return nullableValue == nullptr; } explicit operator bool() const { return some(); } private: T* nullableValue; alignas( alignof( T ) ) char storage[sizeof( T )]; }; } // end namespace Catch // end catch_option.hpp #include <iosfwd> #include <map> #include <memory> #include <set> #include <string> namespace Catch { struct ReporterConfig { explicit ReporterConfig( IConfigPtr const& _fullConfig ); ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ); std::ostream& stream() const; IConfigPtr fullConfig() const; private: std::ostream* m_stream; IConfigPtr m_fullConfig; }; struct ReporterPreferences { bool shouldRedirectStdOut = false; }; template <typename T> struct LazyStat : Option<T> { LazyStat& operator=( T const& _value ) { Option<T>::operator=( _value ); used = false; return *this; } void reset() { Option<T>::reset(); used = false; } bool used = false; }; struct TestRunInfo { TestRunInfo( std::string const& _name ); std::string name; }; struct GroupInfo { GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ); std::string name; std::size_t groupIndex; std::size_t groupsCounts; }; struct AssertionStats { AssertionStats( AssertionResult const& _assertionResult, std::vector<MessageInfo> const& _infoMessages, Totals const& _totals ); AssertionStats( AssertionStats const& ) = default; AssertionStats( AssertionStats&& ) = default; AssertionStats& operator=( AssertionStats const& ) = default; AssertionStats& operator=( AssertionStats&& ) = default; virtual ~AssertionStats(); AssertionResult assertionResult; std::vector<MessageInfo> infoMessages; Totals totals; }; struct SectionStats { SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ); SectionStats( SectionStats const& ) = default; SectionStats( SectionStats&& ) = default; SectionStats& operator=( SectionStats const& ) = default; SectionStats& operator=( SectionStats&& ) = default; virtual ~SectionStats(); SectionInfo sectionInfo; Counts assertions; double durationInSeconds; bool missingAssertions; }; struct TestCaseStats { TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ); TestCaseStats( TestCaseStats const& ) = default; TestCaseStats( TestCaseStats&& ) = default; TestCaseStats& operator=( TestCaseStats const& ) = default; TestCaseStats& operator=( TestCaseStats&& ) = default; virtual ~TestCaseStats(); TestCaseInfo testInfo; Totals totals; std::string stdOut; std::string stdErr; bool aborting; }; struct TestGroupStats { TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ); TestGroupStats( GroupInfo const& _groupInfo ); TestGroupStats( TestGroupStats const& ) = default; TestGroupStats( TestGroupStats&& ) = default; TestGroupStats& operator=( TestGroupStats const& ) = default; TestGroupStats& operator=( TestGroupStats&& ) = default; virtual ~TestGroupStats(); GroupInfo groupInfo; Totals totals; bool aborting; }; struct TestRunStats { TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ); TestRunStats( TestRunStats const& ) = default; TestRunStats( TestRunStats&& ) = default; TestRunStats& operator=( TestRunStats const& ) = default; TestRunStats& operator=( TestRunStats&& ) = default; virtual ~TestRunStats(); TestRunInfo runInfo; Totals totals; bool aborting; }; struct BenchmarkInfo { std::string name; }; struct BenchmarkStats { BenchmarkInfo info; std::size_t iterations; uint64_t elapsedTimeInNanoseconds; }; struct IStreamingReporter { virtual ~IStreamingReporter() = default; // Implementing class must also provide the following static methods: // static std::string getDescription(); // static std::set<Verbosity> getSupportedVerbosities() virtual ReporterPreferences getPreferences() const = 0; virtual void noMatchingTestCases( std::string const& spec ) = 0; virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; // *** experimental *** virtual void benchmarkStarting( BenchmarkInfo const& ) {} virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; // *** experimental *** virtual void benchmarkEnded( BenchmarkStats const& ) {} virtual void sectionEnded( SectionStats const& sectionStats ) = 0; virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; virtual void skipTest( TestCaseInfo const& testInfo ) = 0; // Default empty implementation provided virtual void fatalErrorEncountered( StringRef name ); virtual bool isMulti() const; }; using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>; struct IReporterFactory { virtual ~IReporterFactory(); virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0; virtual std::string getDescription() const = 0; }; using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>; struct IReporterRegistry { using FactoryMap = std::map<std::string, IReporterFactoryPtr>; using Listeners = std::vector<IReporterFactoryPtr>; virtual ~IReporterRegistry(); virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0; virtual FactoryMap const& getFactories() const = 0; virtual Listeners const& getListeners() const = 0; }; void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ); } // end namespace Catch // end catch_interfaces_reporter.h #include <assert.h> #include <algorithm> #include <cfloat> #include <cstdio> #include <cstring> #include <memory> #include <ostream> namespace Catch { void prepareExpandedExpression( AssertionResult& result ); // Returns double formatted as %.3f (format expected on output) std::string getFormattedDuration( double duration ); template <typename DerivedT> struct StreamingReporterBase : IStreamingReporter { StreamingReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ) , stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; if ( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) throw std::domain_error( "Verbosity level not supported by this reporter" ); } ReporterPreferences getPreferences() const override { return m_reporterPrefs; } static std::set<Verbosity> getSupportedVerbosities() { return { Verbosity::Normal }; } ~StreamingReporterBase() override = default; void noMatchingTestCases( std::string const& ) override {} void testRunStarting( TestRunInfo const& _testRunInfo ) override { currentTestRunInfo = _testRunInfo; } void testGroupStarting( GroupInfo const& _groupInfo ) override { currentGroupInfo = _groupInfo; } void testCaseStarting( TestCaseInfo const& _testInfo ) override { currentTestCaseInfo = _testInfo; } void sectionStarting( SectionInfo const& _sectionInfo ) override { m_sectionStack.push_back( _sectionInfo ); } void sectionEnded( SectionStats const& /* _sectionStats */ ) override { m_sectionStack.pop_back(); } void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) override { currentTestCaseInfo.reset(); } void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) override { currentGroupInfo.reset(); } void testRunEnded( TestRunStats const& /* _testRunStats */ ) override { currentTestCaseInfo.reset(); currentGroupInfo.reset(); currentTestRunInfo.reset(); } void skipTest( TestCaseInfo const& ) override { // Don't do anything with this by default. // It can optionally be overridden in the derived class. } IConfigPtr m_config; std::ostream& stream; LazyStat<TestRunInfo> currentTestRunInfo; LazyStat<GroupInfo> currentGroupInfo; LazyStat<TestCaseInfo> currentTestCaseInfo; std::vector<SectionInfo> m_sectionStack; ReporterPreferences m_reporterPrefs; }; template <typename DerivedT> struct CumulativeReporterBase : IStreamingReporter { template <typename T, typename ChildNodeT> struct Node { explicit Node( T const& _value ) : value( _value ) { } virtual ~Node() {} using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>; T value; ChildNodes children; }; struct SectionNode { explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) { } virtual ~SectionNode() = default; bool operator==( SectionNode const& other ) const { return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; } bool operator==( std::shared_ptr<SectionNode> const& other ) const { return operator==( *other ); } SectionStats stats; using ChildSections = std::vector<std::shared_ptr<SectionNode>>; using Assertions = std::vector<AssertionStats>; ChildSections childSections; Assertions assertions; std::string stdOut; std::string stdErr; }; struct BySectionInfo { BySectionInfo( SectionInfo const& other ) : m_other( other ) { } BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) { } bool operator()( std::shared_ptr<SectionNode> const& node ) const { return ( ( node->stats.sectionInfo.name == m_other.name ) && ( node->stats.sectionInfo.lineInfo == m_other.lineInfo ) ); } void operator=( BySectionInfo const& ) = delete; private: SectionInfo const& m_other; }; using TestCaseNode = Node<TestCaseStats, SectionNode>; using TestGroupNode = Node<TestGroupStats, TestCaseNode>; using TestRunNode = Node<TestRunStats, TestGroupNode>; CumulativeReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ) , stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; if ( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) throw std::domain_error( "Verbosity level not supported by this reporter" ); } ~CumulativeReporterBase() override = default; ReporterPreferences getPreferences() const override { return m_reporterPrefs; } static std::set<Verbosity> getSupportedVerbosities() { return { Verbosity::Normal }; } void testRunStarting( TestRunInfo const& ) override {} void testGroupStarting( GroupInfo const& ) override {} void testCaseStarting( TestCaseInfo const& ) override {} void sectionStarting( SectionInfo const& sectionInfo ) override { SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); std::shared_ptr<SectionNode> node; if ( m_sectionStack.empty() ) { if ( !m_rootSection ) m_rootSection = std::make_shared<SectionNode>( incompleteStats ); node = m_rootSection; } else { SectionNode& parentNode = *m_sectionStack.back(); auto it = std::find_if( parentNode.childSections.begin(), parentNode.childSections.end(), BySectionInfo( sectionInfo ) ); if ( it == parentNode.childSections.end() ) { node = std::make_shared<SectionNode>( incompleteStats ); parentNode.childSections.push_back( node ); } else node = *it; } m_sectionStack.push_back( node ); m_deepestSection = std::move( node ); } void assertionStarting( AssertionInfo const& ) override {} bool assertionEnded( AssertionStats const& assertionStats ) override { assert( !m_sectionStack.empty() ); // AssertionResult holds a pointer to a temporary DecomposedExpression, // which getExpandedExpression() calls to build the expression string. // Our section stack copy of the assertionResult will likely outlive the // temporary, so it must be expanded or discarded now to avoid calling // a destroyed object later. prepareExpandedExpression( const_cast<AssertionResult&>( assertionStats.assertionResult ) ); SectionNode& sectionNode = *m_sectionStack.back(); sectionNode.assertions.push_back( assertionStats ); return true; } void sectionEnded( SectionStats const& sectionStats ) override { assert( !m_sectionStack.empty() ); SectionNode& node = *m_sectionStack.back(); node.stats = sectionStats; m_sectionStack.pop_back(); } void testCaseEnded( TestCaseStats const& testCaseStats ) override { auto node = std::make_shared<TestCaseNode>( testCaseStats ); assert( m_sectionStack.size() == 0 ); node->children.push_back( m_rootSection ); m_testCases.push_back( node ); m_rootSection.reset(); assert( m_deepestSection ); m_deepestSection->stdOut = testCaseStats.stdOut; m_deepestSection->stdErr = testCaseStats.stdErr; } void testGroupEnded( TestGroupStats const& testGroupStats ) override { auto node = std::make_shared<TestGroupNode>( testGroupStats ); node->children.swap( m_testCases ); m_testGroups.push_back( node ); } void testRunEnded( TestRunStats const& testRunStats ) override { auto node = std::make_shared<TestRunNode>( testRunStats ); node->children.swap( m_testGroups ); m_testRuns.push_back( node ); testRunEndedCumulative(); } virtual void testRunEndedCumulative() = 0; void skipTest( TestCaseInfo const& ) override {} IConfigPtr m_config; std::ostream& stream; std::vector<AssertionStats> m_assertions; std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections; std::vector<std::shared_ptr<TestCaseNode>> m_testCases; std::vector<std::shared_ptr<TestGroupNode>> m_testGroups; std::vector<std::shared_ptr<TestRunNode>> m_testRuns; std::shared_ptr<SectionNode> m_rootSection; std::shared_ptr<SectionNode> m_deepestSection; std::vector<std::shared_ptr<SectionNode>> m_sectionStack; ReporterPreferences m_reporterPrefs; }; template <char C> char const* getLineOfChars() { static char line[CATCH_CONFIG_CONSOLE_WIDTH] = { 0 }; if ( !*line ) { std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1 ); line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0; } return line; } struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> { TestEventListenerBase( ReporterConfig const& _config ); void assertionStarting( AssertionInfo const& ) override; bool assertionEnded( AssertionStats const& ) override; }; } // end namespace Catch // end catch_reporter_bases.hpp // start catch_console_colour.h namespace Catch { struct Colour { enum Code { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White, BrightYellow = Bright | Yellow, // By intention FileName = LightGrey, Warning = BrightYellow, ResultError = BrightRed, ResultSuccess = BrightGreen, ResultExpectedFailure = Warning, Error = BrightRed, Success = Green, OriginalExpression = Cyan, ReconstructedExpression = BrightYellow, SecondaryText = LightGrey, Headers = White }; // Use constructed object for RAII guard Colour( Code _colourCode ); Colour( Colour&& other ) noexcept; Colour& operator=( Colour&& other ) noexcept; ~Colour(); // Use static method for one-shot changes static void use( Code _colourCode ); private: bool m_moved = false; }; std::ostream& operator<<( std::ostream& os, Colour const& ); } // end namespace Catch // end catch_console_colour.h // start catch_reporter_registrars.hpp namespace Catch { template <typename T> class ReporterRegistrar { class ReporterFactory : public IReporterFactory { virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override { return std::unique_ptr<T>( new T( config ) ); } virtual std::string getDescription() const override { return T::getDescription(); } }; public: explicit ReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() ); } }; template <typename T> class ListenerRegistrar { class ListenerFactory : public IReporterFactory { virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override { return std::unique_ptr<T>( new T( config ) ); } virtual std::string getDescription() const override { return std::string(); } }; public: ListenerRegistrar() { getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() ); } }; } #if !defined( CATCH_CONFIG_DISABLE ) #define CATCH_REGISTER_REPORTER( name, reporterType ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace \ { \ Catch::ReporterRegistrar<reporterType> \ catch_internal_RegistrarFor##reporterType( name ); \ } \ CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS #define CATCH_REGISTER_LISTENER( listenerType ) \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ namespace \ { \ Catch::ListenerRegistrar<listenerType> \ catch_internal_RegistrarFor##listenerType; \ } \ CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS #else // CATCH_CONFIG_DISABLE #define CATCH_REGISTER_REPORTER( name, reporterType ) #define CATCH_REGISTER_LISTENER( listenerType ) #endif // CATCH_CONFIG_DISABLE // end catch_reporter_registrars.hpp // Allow users to base their work off existing reporters // start catch_reporter_compact.h namespace Catch { struct CompactReporter : StreamingReporterBase<CompactReporter> { using StreamingReporterBase::StreamingReporterBase; ~CompactReporter() override; static std::string getDescription(); ReporterPreferences getPreferences() const override; void noMatchingTestCases( std::string const& spec ) override; void assertionStarting( AssertionInfo const& ) override; bool assertionEnded( AssertionStats const& _assertionStats ) override; void sectionEnded( SectionStats const& _sectionStats ) override; void testRunEnded( TestRunStats const& _testRunStats ) override; }; } // end namespace Catch // end catch_reporter_compact.h // start catch_reporter_console.h #if defined( _MSC_VER ) #pragma warning( push ) #pragma warning( disable : 4061 ) // Not all labels are EXPLICITLY handled in switch // Note that 4062 (not all labels are handled // and default is missing) is enabled #endif namespace Catch { // Fwd decls struct SummaryColumn; class TablePrinter; struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> { std::unique_ptr<TablePrinter> m_tablePrinter; ConsoleReporter( ReporterConfig const& config ); ~ConsoleReporter() override; static std::string getDescription(); void noMatchingTestCases( std::string const& spec ) override; void assertionStarting( AssertionInfo const& ) override; bool assertionEnded( AssertionStats const& _assertionStats ) override; void sectionStarting( SectionInfo const& _sectionInfo ) override; void sectionEnded( SectionStats const& _sectionStats ) override; void benchmarkStarting( BenchmarkInfo const& info ) override; void benchmarkEnded( BenchmarkStats const& stats ) override; void testCaseEnded( TestCaseStats const& _testCaseStats ) override; void testGroupEnded( TestGroupStats const& _testGroupStats ) override; void testRunEnded( TestRunStats const& _testRunStats ) override; private: void lazyPrint(); void lazyPrintWithoutClosingBenchmarkTable(); void lazyPrintRunInfo(); void lazyPrintGroupInfo(); void printTestCaseAndSectionHeader(); void printClosedHeader( std::string const& _name ); void printOpenHeader( std::string const& _name ); // if string has a : in first line will set indent to follow it on // subsequent lines void printHeaderString( std::string const& _string, std::size_t indent = 0 ); void printTotals( Totals const& totals ); void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ); void printTotalsDivider( Totals const& totals ); void printSummaryDivider(); private: bool m_headerPrinted = false; }; } // end namespace Catch #if defined( _MSC_VER ) #pragma warning( pop ) #endif // end catch_reporter_console.h // start catch_reporter_junit.h // start catch_xmlwriter.h #include <vector> namespace Catch { class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); void encodeTo( std::ostream& os ) const; friend std::ostream& operator<<( std::ostream& os, XmlEncode const& xmlEncode ); private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer ); ScopedElement( ScopedElement&& other ) noexcept; ScopedElement& operator=( ScopedElement&& other ) noexcept; ~ScopedElement(); ScopedElement& writeText( std::string const& text, bool indent = true ); template <typename T> ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer = nullptr; }; XmlWriter( std::ostream& os = Catch::cout() ); ~XmlWriter(); XmlWriter( XmlWriter const& ) = delete; XmlWriter& operator=( XmlWriter const& ) = delete; XmlWriter& startElement( std::string const& name ); ScopedElement scopedElement( std::string const& name ); XmlWriter& endElement(); XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); XmlWriter& writeAttribute( std::string const& name, bool attribute ); template <typename T> XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { ReusableStringStream rss; rss << attribute; return writeAttribute( name, rss.str() ); } XmlWriter& writeText( std::string const& text, bool indent = true ); XmlWriter& writeComment( std::string const& text ); void writeStylesheetRef( std::string const& url ); XmlWriter& writeBlankLine(); void ensureTagClosed(); private: void writeDeclaration(); void newlineIfNecessary(); bool m_tagIsOpen = false; bool m_needsNewline = false; std::vector<std::string> m_tags; std::string m_indent; std::ostream& m_os; }; } // end catch_xmlwriter.h namespace Catch { class JunitReporter : public CumulativeReporterBase<JunitReporter> { public: JunitReporter( ReporterConfig const& _config ); ~JunitReporter() override; static std::string getDescription(); void noMatchingTestCases( std::string const& /*spec*/ ) override; void testRunStarting( TestRunInfo const& runInfo ) override; void testGroupStarting( GroupInfo const& groupInfo ) override; void testCaseStarting( TestCaseInfo const& testCaseInfo ) override; bool assertionEnded( AssertionStats const& assertionStats ) override; void testCaseEnded( TestCaseStats const& testCaseStats ) override; void testGroupEnded( TestGroupStats const& testGroupStats ) override; void testRunEndedCumulative() override; void writeGroup( TestGroupNode const& groupNode, double suiteTime ); void writeTestCase( TestCaseNode const& testCaseNode ); void writeSection( std::string const& className, std::string const& rootName, SectionNode const& sectionNode ); void writeAssertions( SectionNode const& sectionNode ); void writeAssertion( AssertionStats const& stats ); XmlWriter xml; Timer suiteTimer; std::string stdOutForSuite; std::string stdErrForSuite; unsigned int unexpectedExceptions = 0; bool m_okToFail = false; }; } // end namespace Catch // end catch_reporter_junit.h // start catch_reporter_xml.h namespace Catch { class XmlReporter : public StreamingReporterBase<XmlReporter> { public: XmlReporter( ReporterConfig const& _config ); ~XmlReporter() override; static std::string getDescription(); virtual std::string getStylesheetRef() const; void writeSourceInfo( SourceLineInfo const& sourceInfo ); public: // StreamingReporterBase void noMatchingTestCases( std::string const& s ) override; void testRunStarting( TestRunInfo const& testInfo ) override; void testGroupStarting( GroupInfo const& groupInfo ) override; void testCaseStarting( TestCaseInfo const& testInfo ) override; void sectionStarting( SectionInfo const& sectionInfo ) override; void assertionStarting( AssertionInfo const& ) override; bool assertionEnded( AssertionStats const& assertionStats ) override; void sectionEnded( SectionStats const& sectionStats ) override; void testCaseEnded( TestCaseStats const& testCaseStats ) override; void testGroupEnded( TestGroupStats const& testGroupStats ) override; void testRunEnded( TestRunStats const& testRunStats ) override; private: Timer m_testCaseTimer; XmlWriter m_xml; int m_sectionDepth = 0; }; } // end namespace Catch // end catch_reporter_xml.h // end catch_external_interfaces.h #endif #endif // ! CATCH_CONFIG_IMPL_ONLY #ifdef CATCH_IMPL // start catch_impl.hpp #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-vtables" #endif // Keep these here for external reporters // start catch_test_case_tracker.h #include <memory> #include <string> #include <vector> namespace Catch { namespace TestCaseTracking { struct NameAndLocation { std::string name; SourceLineInfo location; NameAndLocation( std::string const& _name, SourceLineInfo const& _location ); }; struct ITracker; using ITrackerPtr = std::shared_ptr<ITracker>; struct ITracker { virtual ~ITracker(); // static queries virtual NameAndLocation const& nameAndLocation() const = 0; // dynamic queries virtual bool isComplete() const = 0; // Successfully completed or failed virtual bool isSuccessfullyCompleted() const = 0; virtual bool isOpen() const = 0; // Started but not complete virtual bool hasChildren() const = 0; virtual ITracker& parent() = 0; // actions virtual void close() = 0; // Successfully complete virtual void fail() = 0; virtual void markAsNeedingAnotherRun() = 0; virtual void addChild( ITrackerPtr const& child ) = 0; virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0; virtual void openChild() = 0; // Debug/ checking virtual bool isSectionTracker() const = 0; virtual bool isIndexTracker() const = 0; }; class TrackerContext { enum RunState { NotStarted, Executing, CompletedCycle }; ITrackerPtr m_rootTracker; ITracker* m_currentTracker = nullptr; RunState m_runState = NotStarted; public: static TrackerContext& instance(); ITracker& startRun(); void endRun(); void startCycle(); void completeCycle(); bool completedCycle() const; ITracker& currentTracker(); void setCurrentTracker( ITracker* tracker ); }; class TrackerBase : public ITracker { protected: enum CycleState { NotStarted, Executing, ExecutingChildren, NeedsAnotherRun, CompletedSuccessfully, Failed }; class TrackerHasName { NameAndLocation m_nameAndLocation; public: TrackerHasName( NameAndLocation const& nameAndLocation ); bool operator()( ITrackerPtr const& tracker ) const; }; using Children = std::vector<ITrackerPtr>; NameAndLocation m_nameAndLocation; TrackerContext& m_ctx; ITracker* m_parent; Children m_children; CycleState m_runState = NotStarted; public: TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); NameAndLocation const& nameAndLocation() const override; bool isComplete() const override; bool isSuccessfullyCompleted() const override; bool isOpen() const override; bool hasChildren() const override; void addChild( ITrackerPtr const& child ) override; ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override; ITracker& parent() override; void openChild() override; bool isSectionTracker() const override; bool isIndexTracker() const override; void open(); void close() override; void fail() override; void markAsNeedingAnotherRun() override; private: void moveToParent(); void moveToThis(); }; class SectionTracker : public TrackerBase { std::vector<std::string> m_filters; public: SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); bool isSectionTracker() const override; static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ); void tryOpen(); void addInitialFilters( std::vector<std::string> const& filters ); void addNextFilters( std::vector<std::string> const& filters ); }; class IndexTracker : public TrackerBase { int m_size; int m_index = -1; public: IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size ); bool isIndexTracker() const override; void close() override; static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ); int index() const; void moveNext(); }; } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; using TestCaseTracking::IndexTracker; } // namespace Catch // end catch_test_case_tracker.h // start catch_leak_detector.h namespace Catch { struct LeakDetector { LeakDetector(); }; } // end catch_leak_detector.h // Cpp files will be included in the single-header file here // start catch_approx.cpp #include <cmath> #include <limits> namespace { // Performs equivalent check of std::fabs(lhs - rhs) <= margin // But without the subtraction to allow for INFINITY in comparison bool marginComparison( double lhs, double rhs, double margin ) { return ( lhs + margin >= rhs ) && ( rhs + margin >= lhs ); } } namespace Catch { namespace Detail { Approx::Approx( double value ) : m_epsilon( std::numeric_limits<float>::epsilon() * 100 ) , m_margin( 0.0 ) , m_scale( 0.0 ) , m_value( value ) { } Approx Approx::custom() { return Approx( 0 ); } std::string Approx::toString() const { ReusableStringStream rss; rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )"; return rss.str(); } bool Approx::equalityComparisonImpl( const double other ) const { // First try with fixed margin, then compute margin based on epsilon, scale and // Approx's value // Thanks to Richard Harris for his help refining the scaled margin value return marginComparison( m_value, other, m_margin ) || marginComparison( m_value, other, m_epsilon * ( m_scale + std::fabs( m_value ) ) ); } } // end namespace Detail std::string StringMaker<Catch::Detail::Approx>::convert( Catch::Detail::Approx const& value ) { return value.toString(); } } // end namespace Catch // end catch_approx.cpp // start catch_assertionhandler.cpp // start catch_context.h #include <memory> namespace Catch { struct IResultCapture; struct IRunner; struct IConfig; struct IMutableContext; using IConfigPtr = std::shared_ptr<IConfig const>; struct IContext { virtual ~IContext(); virtual IResultCapture* getResultCapture() = 0; virtual IRunner* getRunner() = 0; virtual IConfigPtr const& getConfig() const = 0; }; struct IMutableContext : IContext { virtual ~IMutableContext(); virtual void setResultCapture( IResultCapture* resultCapture ) = 0; virtual void setRunner( IRunner* runner ) = 0; virtual void setConfig( IConfigPtr const& config ) = 0; private: static IMutableContext* currentContext; friend IMutableContext& getCurrentMutableContext(); friend void cleanUpContext(); static void createContext(); }; inline IMutableContext& getCurrentMutableContext() { if ( !IMutableContext::currentContext ) IMutableContext::createContext(); return *IMutableContext::currentContext; } inline IContext& getCurrentContext() { return getCurrentMutableContext(); } void cleanUpContext(); } // end catch_context.h // start catch_debugger.h namespace Catch { bool isDebuggerActive(); } #ifdef CATCH_PLATFORM_MAC #define CATCH_TRAP() __asm__( "int $3\n" : : ) /* NOLINT */ #elif defined( CATCH_PLATFORM_LINUX ) // If we can use inline assembler, do it because this allows us to break // directly at the location of the failing check instead of breaking inside // raise() called from it, i.e. one stack frame below. #if defined( __GNUC__ ) && ( defined( __i386 ) || defined( __x86_64 ) ) #define CATCH_TRAP() asm volatile( "int $3" ) /* NOLINT */ #else // Fall back to the generic way. #include <signal.h> #define CATCH_TRAP() raise( SIGTRAP ) #endif #elif defined( _MSC_VER ) #define CATCH_TRAP() __debugbreak() #elif defined( __MINGW32__ ) extern "C" __declspec( dllimport ) void __stdcall DebugBreak(); #define CATCH_TRAP() DebugBreak() #endif #ifdef CATCH_TRAP #define CATCH_BREAK_INTO_DEBUGGER() \ if ( Catch::isDebuggerActive() ) \ { \ CATCH_TRAP(); \ } #else namespace Catch { inline void doNothing() {} } #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing() #endif // end catch_debugger.h // start catch_run_context.h // start catch_fatal_condition.h // start catch_windows_h_proxy.h #if defined( CATCH_PLATFORM_WINDOWS ) #if !defined( NOMINMAX ) && !defined( CATCH_CONFIG_NO_NOMINMAX ) #define CATCH_DEFINED_NOMINMAX #define NOMINMAX #endif #if !defined( WIN32_LEAN_AND_MEAN ) && !defined( CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN ) #define CATCH_DEFINED_WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifdef __AFXDLL #include <AfxWin.h> #else #include <windows.h> #endif #ifdef CATCH_DEFINED_NOMINMAX #undef NOMINMAX #endif #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #endif #endif // defined(CATCH_PLATFORM_WINDOWS) // end catch_windows_h_proxy.h #if defined( CATCH_CONFIG_WINDOWS_SEH ) namespace Catch { struct FatalConditionHandler { static LONG CALLBACK handleVectoredException( PEXCEPTION_POINTERS ExceptionInfo ); FatalConditionHandler(); static void reset(); ~FatalConditionHandler(); private: static bool isSet; static ULONG guaranteeSize; static PVOID exceptionHandlerHandle; }; } // namespace Catch #elif defined( CATCH_CONFIG_POSIX_SIGNALS ) #include <signal.h> namespace Catch { struct FatalConditionHandler { static bool isSet; static struct sigaction oldSigActions[]; static stack_t oldSigStack; static char altStackMem[]; static void handleSignal( int sig ); FatalConditionHandler(); ~FatalConditionHandler(); static void reset(); }; } // namespace Catch #else namespace Catch { struct FatalConditionHandler { void reset(); }; } #endif // end catch_fatal_condition.h #include <string> namespace Catch { struct IMutableContext; /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { public: RunContext( RunContext const& ) = delete; RunContext& operator=( RunContext const& ) = delete; explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter ); ~RunContext() override; void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ); void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ); Totals runTest( TestCase const& testCase ); IConfigPtr config() const; IStreamingReporter& reporter() const; public: // IResultCapture // Assertion handlers void handleExpr( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) override; void handleMessage( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) override; void handleUnexpectedExceptionNotThrown( AssertionInfo const& info, AssertionReaction& reaction ) override; void handleUnexpectedInflightException( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) override; void handleIncomplete( AssertionInfo const& info ) override; void handleNonExpr( AssertionInfo const& info, ResultWas::OfType resultType, AssertionReaction& reaction ) override; bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override; void sectionEnded( SectionEndInfo const& endInfo ) override; void sectionEndedEarly( SectionEndInfo const& endInfo ) override; void benchmarkStarting( BenchmarkInfo const& info ) override; void benchmarkEnded( BenchmarkStats const& stats ) override; void pushScopedMessage( MessageInfo const& message ) override; void popScopedMessage( MessageInfo const& message ) override; std::string getCurrentTestName() const override; const AssertionResult* getLastResult() const override; void exceptionEarlyReported() override; void handleFatalErrorCondition( StringRef message ) override; bool lastAssertionPassed() override; void assertionPassed() override; public: // !TBD We need to do this another way! bool aborting() const final; private: void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ); void invokeActiveTestCase(); void resetAssertionInfo(); bool testForMissingAssertions( Counts& assertions ); void assertionEnded( AssertionResult const& result ); void reportExpr( AssertionInfo const& info, ResultWas::OfType resultType, ITransientExpression const* expr, bool negated ); void populateReaction( AssertionReaction& reaction ); private: void handleUnfinishedSections(); TestRunInfo m_runInfo; IMutableContext& m_context; TestCase const* m_activeTestCase = nullptr; ITracker* m_testCaseTracker; Option<AssertionResult> m_lastResult; IConfigPtr m_config; Totals m_totals; IStreamingReporterPtr m_reporter; std::vector<MessageInfo> m_messages; AssertionInfo m_lastAssertionInfo; std::vector<SectionEndInfo> m_unfinishedSections; std::vector<ITracker*> m_activeSections; TrackerContext m_trackerContext; bool m_lastAssertionPassed = false; bool m_shouldReportUnexpected = true; bool m_includeSuccessfulResults; }; } // end namespace Catch // end catch_run_context.h namespace Catch { auto operator<<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& { expr.streamReconstructedExpression( os ); return os; } LazyExpression::LazyExpression( bool isNegated ) : m_isNegated( isNegated ) { } LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) { } LazyExpression::operator bool() const { return m_transientExpression != nullptr; } auto operator<<( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& { if ( lazyExpr.m_isNegated ) os << "!"; if ( lazyExpr ) { if ( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() ) os << "(" << *lazyExpr.m_transientExpression << ")"; else os << *lazyExpr.m_transientExpression; } else { os << "{** error - unchecked empty expression requested **}"; } return os; } AssertionHandler::AssertionHandler( StringRef macroName, SourceLineInfo const& lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition ) : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition } , m_resultCapture( getResultCapture() ) { } void AssertionHandler::handleExpr( ITransientExpression const& expr ) { m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction ); } void AssertionHandler::handleMessage( ResultWas::OfType resultType, StringRef const& message ) { m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction ); } auto AssertionHandler::allowThrows() const -> bool { return getCurrentContext().getConfig()->allowThrows(); } void AssertionHandler::complete() { setCompleted(); if ( m_reaction.shouldDebugBreak ) { // If you find your debugger stopping you here then go one level up on the // call-stack for the code that caused it (typically a failed assertion) // (To go back to the test and change execution, jump over the throw, next) CATCH_BREAK_INTO_DEBUGGER(); } if ( m_reaction.shouldThrow ) throw Catch::TestFailureException(); } void AssertionHandler::setCompleted() { m_completed = true; } void AssertionHandler::handleUnexpectedInflightException() { m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction ); } void AssertionHandler::handleExceptionThrownAsExpected() { m_resultCapture.handleNonExpr( m_assertionInfo, ResultWas::Ok, m_reaction ); } void AssertionHandler::handleExceptionNotThrownAsExpected() { m_resultCapture.handleNonExpr( m_assertionInfo, ResultWas::Ok, m_reaction ); } void AssertionHandler::handleUnexpectedExceptionNotThrown() { m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction ); } void AssertionHandler::handleThrowingCallSkipped() { m_resultCapture.handleNonExpr( m_assertionInfo, ResultWas::Ok, m_reaction ); } // This is the overload that takes a string and infers the Equals matcher from it // The more general overload, that takes any string matcher, is in // catch_capture_matchers.cpp void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) { handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString ); } } // namespace Catch // end catch_assertionhandler.cpp // start catch_assertionresult.cpp namespace Catch { AssertionResultData::AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression ) : lazyExpression( _lazyExpression ) , resultType( _resultType ) { } std::string AssertionResultData::reconstructExpression() const { if ( reconstructedExpression.empty() ) { if ( lazyExpression ) { ReusableStringStream rss; rss << lazyExpression; reconstructedExpression = rss.str(); } } return reconstructedExpression; } AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) : m_info( info ) , m_resultData( data ) { } // Result was a success bool AssertionResult::succeeded() const { return Catch::isOk( m_resultData.resultType ); } // Result was a success, or failure is suppressed bool AssertionResult::isOk() const { return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); } ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; } bool AssertionResult::hasExpression() const { return m_info.capturedExpression[0] != 0; } bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); } std::string AssertionResult::getExpression() const { if ( isFalseTest( m_info.resultDisposition ) ) return "!(" + m_info.capturedExpression + ")"; else return m_info.capturedExpression; } std::string AssertionResult::getExpressionInMacro() const { std::string expr; if ( m_info.macroName[0] == 0 ) expr = m_info.capturedExpression; else { expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 ); expr += m_info.macroName; expr += "( "; expr += m_info.capturedExpression; expr += " )"; } return expr; } bool AssertionResult::hasExpandedExpression() const { return hasExpression() && getExpandedExpression() != getExpression(); } std::string AssertionResult::getExpandedExpression() const { std::string expr = m_resultData.reconstructExpression(); return expr.empty() ? getExpression() : expr; } std::string AssertionResult::getMessage() const { return m_resultData.message; } SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; } StringRef AssertionResult::getTestMacroName() const { return m_info.macroName; } } // end namespace Catch // end catch_assertionresult.cpp // start catch_benchmark.cpp namespace Catch { auto BenchmarkLooper::getResolution() -> uint64_t { return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple(); } void BenchmarkLooper::reportStart() { getResultCapture().benchmarkStarting( { m_name } ); } auto BenchmarkLooper::needsMoreIterations() -> bool { auto elapsed = m_timer.getElapsedNanoseconds(); // Exponentially increasing iterations until we're confident in our timer resolution if ( elapsed < m_resolution ) { m_iterationsToRun *= 10; return true; } getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } ); return false; } } // end namespace Catch // end catch_benchmark.cpp // start catch_capture_matchers.cpp namespace Catch { using StringMatcher = Matchers::Impl::MatcherBase<std::string>; // This is the general overload that takes a any string matcher // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string // and infers // the Equals matcher (so the header does not mention matchers) void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) { std::string exceptionMessage = Catch::translateActiveException(); MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString ); handler.handleExpr( expr ); } } // namespace Catch // end catch_capture_matchers.cpp // start catch_commandline.cpp // start catch_commandline.h // start catch_clara.h // Use Catch's value for console width (store Clara's off to the side, if present) #ifdef CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #endif #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - 1 #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wweak-vtables" #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wshadow" #endif // start clara.hpp // Copyright 2017 Two Blue Cubes Ltd. All rights reserved. // // 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) // // See https://github.com/philsquared/Clara for more details // Clara v1.1.4 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 #endif #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH #endif #ifndef CLARA_CONFIG_OPTIONAL_TYPE #ifdef __has_include #if __has_include( <optional> ) && __cplusplus >= 201703L #include <optional> #define CLARA_CONFIG_OPTIONAL_TYPE std::optional #endif #endif #endif // ----------- #included from clara_textflow.hpp ----------- // TextFlowCpp // // A single-header library for wrapping and laying out basic text, by Phil Nash // // This work is licensed under the BSD 2-Clause license. // See the accompanying LICENSE file, or the one at // https://opensource.org/licenses/BSD-2-Clause // // This project is hosted at https://github.com/philsquared/textflowcpp #include <cassert> #include <ostream> #include <sstream> #include <vector> #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 #endif namespace Catch { namespace clara { namespace TextFlow { inline auto isWhitespace( char c ) -> bool { static std::string chars = " \t\n\r"; return chars.find( c ) != std::string::npos; } inline auto isBreakableBefore( char c ) -> bool { static std::string chars = "[({<|"; return chars.find( c ) != std::string::npos; } inline auto isBreakableAfter( char c ) -> bool { static std::string chars = "])}>.,:;*+-=&/\\"; return chars.find( c ) != std::string::npos; } class Columns; class Column { std::vector<std::string> m_strings; size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; size_t m_indent = 0; size_t m_initialIndent = std::string::npos; public: class iterator { friend Column; Column const& m_column; size_t m_stringIndex = 0; size_t m_pos = 0; size_t m_len = 0; size_t m_end = 0; bool m_suffix = false; iterator( Column const& column, size_t stringIndex ) : m_column( column ) , m_stringIndex( stringIndex ) { } auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; } auto isBoundary( size_t at ) const -> bool { assert( at > 0 ); assert( at <= line().size() ); return at == line().size() || ( isWhitespace( line()[at] ) && !isWhitespace( line()[at - 1] ) ) || isBreakableBefore( line()[at] ) || isBreakableAfter( line()[at - 1] ); } void calcLength() { assert( m_stringIndex < m_column.m_strings.size() ); m_suffix = false; auto width = m_column.m_width - indent(); m_end = m_pos; while ( m_end < line().size() && line()[m_end] != '\n' ) ++m_end; if ( m_end < m_pos + width ) { m_len = m_end - m_pos; } else { size_t len = width; while ( len > 0 && !isBoundary( m_pos + len ) ) --len; while ( len > 0 && isWhitespace( line()[m_pos + len - 1] ) ) --len; if ( len > 0 ) { m_len = len; } else { m_suffix = true; m_len = width - 1; } } } auto indent() const -> size_t { auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos; return initial == std::string::npos ? m_column.m_indent : initial; } auto addIndentAndSuffix( std::string const& plain ) const -> std::string { return std::string( indent(), ' ' ) + ( m_suffix ? plain + "-" : plain ); } public: explicit iterator( Column const& column ) : m_column( column ) { assert( m_column.m_width > m_column.m_indent ); assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent ); calcLength(); if ( m_len == 0 ) m_stringIndex++; // Empty string } auto operator*() const -> std::string { assert( m_stringIndex < m_column.m_strings.size() ); assert( m_pos <= m_end ); if ( m_pos + m_column.m_width < m_end ) return addIndentAndSuffix( line().substr( m_pos, m_len ) ); else return addIndentAndSuffix( line().substr( m_pos, m_end - m_pos ) ); } auto operator++() -> iterator& { m_pos += m_len; if ( m_pos < line().size() && line()[m_pos] == '\n' ) m_pos += 1; else while ( m_pos < line().size() && isWhitespace( line()[m_pos] ) ) ++m_pos; if ( m_pos == line().size() ) { m_pos = 0; ++m_stringIndex; } if ( m_stringIndex < m_column.m_strings.size() ) calcLength(); return *this; } auto operator++(int) -> iterator { iterator prev( *this ); operator++(); return prev; } auto operator==( iterator const& other ) const -> bool { return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex && &m_column == &other.m_column; } auto operator!=( iterator const& other ) const -> bool { return !operator==( other ); } }; using const_iterator = iterator; explicit Column( std::string const& text ) { m_strings.push_back( text ); } auto width( size_t newWidth ) -> Column& { assert( newWidth > 0 ); m_width = newWidth; return *this; } auto indent( size_t newIndent ) -> Column& { m_indent = newIndent; return *this; } auto initialIndent( size_t newIndent ) -> Column& { m_initialIndent = newIndent; return *this; } auto width() const -> size_t { return m_width; } auto begin() const -> iterator { return iterator( *this ); } auto end() const -> iterator { return { *this, m_strings.size() }; } inline friend std::ostream& operator<<( std::ostream& os, Column const& col ) { bool first = true; for ( auto line : col ) { if ( first ) first = false; else os << "\n"; os << line; } return os; } auto operator+( Column const& other ) -> Columns; auto toString() const -> std::string { std::ostringstream oss; oss << *this; return oss.str(); } }; class Spacer : public Column { public: explicit Spacer( size_t spaceWidth ) : Column( "" ) { width( spaceWidth ); } }; class Columns { std::vector<Column> m_columns; public: class iterator { friend Columns; struct EndTag { }; std::vector<Column> const& m_columns; std::vector<Column::iterator> m_iterators; size_t m_activeIterators; iterator( Columns const& columns, EndTag ) : m_columns( columns.m_columns ) , m_activeIterators( 0 ) { m_iterators.reserve( m_columns.size() ); for ( auto const& col : m_columns ) m_iterators.push_back( col.end() ); } public: explicit iterator( Columns const& columns ) : m_columns( columns.m_columns ) , m_activeIterators( m_columns.size() ) { m_iterators.reserve( m_columns.size() ); for ( auto const& col : m_columns ) m_iterators.push_back( col.begin() ); } auto operator==( iterator const& other ) const -> bool { return m_iterators == other.m_iterators; } auto operator!=( iterator const& other ) const -> bool { return m_iterators != other.m_iterators; } auto operator*() const -> std::string { std::string row, padding; for ( size_t i = 0; i < m_columns.size(); ++i ) { auto width = m_columns[i].width(); if ( m_iterators[i] != m_columns[i].end() ) { std::string col = *m_iterators[i]; row += padding + col; if ( col.size() < width ) padding = std::string( width - col.size(), ' ' ); else padding = ""; } else { padding += std::string( width, ' ' ); } } return row; } auto operator++() -> iterator& { for ( size_t i = 0; i < m_columns.size(); ++i ) { if ( m_iterators[i] != m_columns[i].end() ) ++m_iterators[i]; } return *this; } auto operator++(int) -> iterator { iterator prev( *this ); operator++(); return prev; } }; using const_iterator = iterator; auto begin() const -> iterator { return iterator( *this ); } auto end() const -> iterator { return { *this, iterator::EndTag() }; } auto operator+=( Column const& col ) -> Columns& { m_columns.push_back( col ); return *this; } auto operator+( Column const& col ) -> Columns { Columns combined = *this; combined += col; return combined; } inline friend std::ostream& operator<<( std::ostream& os, Columns const& cols ) { bool first = true; for ( auto line : cols ) { if ( first ) first = false; else os << "\n"; os << line; } return os; } auto toString() const -> std::string { std::ostringstream oss; oss << *this; return oss.str(); } }; inline auto Column::operator+( Column const& other ) -> Columns { Columns cols; cols += *this; cols += other; return cols; } } } } // namespace Catch::clara::TextFlow // ----------- end of #include from clara_textflow.hpp ----------- // ........... back in clara.hpp #include <algorithm> #include <memory> #include <set> #if !defined( CATCH_PLATFORM_WINDOWS ) \ && ( defined( WIN32 ) || defined( __WIN32__ ) || defined( _WIN32 ) \ || defined( _MSC_VER ) ) #define CATCH_PLATFORM_WINDOWS #endif namespace Catch { namespace clara { namespace detail { // Traits for extracting arg and return type of lambdas (for single argument // lambdas) template <typename L> struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> { }; template <typename ClassT, typename ReturnT, typename... Args> struct UnaryLambdaTraits<ReturnT ( ClassT::* )( Args... ) const> { static const bool isValid = false; }; template <typename ClassT, typename ReturnT, typename ArgT> struct UnaryLambdaTraits<ReturnT ( ClassT::* )( ArgT ) const> { static const bool isValid = true; using ArgType = typename std::remove_const< typename std::remove_reference<ArgT>::type>::type; using ReturnType = ReturnT; }; class TokenStream; // Transport for raw args (copied from main args, or supplied via init list for // testing) class Args { friend TokenStream; std::string m_exeName; std::vector<std::string> m_args; public: Args( int argc, char const* const* argv ) : m_exeName( argv[0] ) , m_args( argv + 1, argv + argc ) { } Args( std::initializer_list<std::string> args ) : m_exeName( *args.begin() ) , m_args( args.begin() + 1, args.end() ) { } auto exeName() const -> std::string { return m_exeName; } }; // Wraps a token coming from a token stream. These may not directly correspond to // strings as a single string // may encode an option + its argument if the : or = form is used enum class TokenType { Option, Argument }; struct Token { TokenType type; std::string token; }; inline auto isOptPrefix( char c ) -> bool { return c == '-' #ifdef CATCH_PLATFORM_WINDOWS || c == '/' #endif ; } // Abstracts iterators into args as a stream of tokens, with option arguments // uniformly handled class TokenStream { using Iterator = std::vector<std::string>::const_iterator; Iterator it; Iterator itEnd; std::vector<Token> m_tokenBuffer; void loadBuffer() { m_tokenBuffer.resize( 0 ); // Skip any empty strings while ( it != itEnd && it->empty() ) ++it; if ( it != itEnd ) { auto const& next = *it; if ( isOptPrefix( next[0] ) ) { auto delimiterPos = next.find_first_of( " :=" ); if ( delimiterPos != std::string::npos ) { m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } ); m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } ); } else { if ( next[1] != '-' && next.size() > 2 ) { std::string opt = "- "; for ( size_t i = 1; i < next.size(); ++i ) { opt[1] = next[i]; m_tokenBuffer.push_back( { TokenType::Option, opt } ); } } else { m_tokenBuffer.push_back( { TokenType::Option, next } ); } } } else { m_tokenBuffer.push_back( { TokenType::Argument, next } ); } } } public: explicit TokenStream( Args const& args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) { } TokenStream( Iterator it, Iterator itEnd ) : it( it ) , itEnd( itEnd ) { loadBuffer(); } explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; } auto count() const -> size_t { return m_tokenBuffer.size() + ( itEnd - it ); } auto operator*() const -> Token { assert( !m_tokenBuffer.empty() ); return m_tokenBuffer.front(); } auto operator-> () const -> Token const* { assert( !m_tokenBuffer.empty() ); return &m_tokenBuffer.front(); } auto operator++() -> TokenStream& { if ( m_tokenBuffer.size() >= 2 ) { m_tokenBuffer.erase( m_tokenBuffer.begin() ); } else { if ( it != itEnd ) ++it; loadBuffer(); } return *this; } }; class ResultBase { public: enum Type { Ok, LogicError, RuntimeError }; protected: ResultBase( Type type ) : m_type( type ) { } virtual ~ResultBase() = default; virtual void enforceOk() const = 0; Type m_type; }; template <typename T> class ResultValueBase : public ResultBase { public: auto value() const -> T const& { enforceOk(); return m_value; } protected: ResultValueBase( Type type ) : ResultBase( type ) { } ResultValueBase( ResultValueBase const& other ) : ResultBase( other ) { if ( m_type == ResultBase::Ok ) new ( &m_value ) T( other.m_value ); } ResultValueBase( Type, T const& value ) : ResultBase( Ok ) { new ( &m_value ) T( value ); } auto operator=( ResultValueBase const& other ) -> ResultValueBase& { if ( m_type == ResultBase::Ok ) m_value.~T(); ResultBase::operator=( other ); if ( m_type == ResultBase::Ok ) new ( &m_value ) T( other.m_value ); return *this; } ~ResultValueBase() override { if ( m_type == Ok ) m_value.~T(); } union { T m_value; }; }; template <> class ResultValueBase<void> : public ResultBase { protected: using ResultBase::ResultBase; }; template <typename T = void> class BasicResult : public ResultValueBase<T> { public: template <typename U> explicit BasicResult( BasicResult<U> const& other ) : ResultValueBase<T>( other.type() ) , m_errorMessage( other.errorMessage() ) { assert( type() != ResultBase::Ok ); } template <typename U> static auto ok( U const& value ) -> BasicResult { return { ResultBase::Ok, value }; } static auto ok() -> BasicResult { return { ResultBase::Ok }; } static auto logicError( std::string const& message ) -> BasicResult { return { ResultBase::LogicError, message }; } static auto runtimeError( std::string const& message ) -> BasicResult { return { ResultBase::RuntimeError, message }; } explicit operator bool() const { return m_type == ResultBase::Ok; } auto type() const -> ResultBase::Type { return m_type; } auto errorMessage() const -> std::string { return m_errorMessage; } protected: void enforceOk() const override { // Errors shouldn't reach this point, but if they do // the actual error message will be in m_errorMessage assert( m_type != ResultBase::LogicError ); assert( m_type != ResultBase::RuntimeError ); if ( m_type != ResultBase::Ok ) std::abort(); } std::string m_errorMessage; // Only populated if resultType is an error BasicResult( ResultBase::Type type, std::string const& message ) : ResultValueBase<T>( type ) , m_errorMessage( message ) { assert( m_type != ResultBase::Ok ); } using ResultValueBase<T>::ResultValueBase; using ResultBase::m_type; }; enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame }; class ParseState { public: ParseState( ParseResultType type, TokenStream const& remainingTokens ) : m_type( type ) , m_remainingTokens( remainingTokens ) { } auto type() const -> ParseResultType { return m_type; } auto remainingTokens() const -> TokenStream { return m_remainingTokens; } private: ParseResultType m_type; TokenStream m_remainingTokens; }; using Result = BasicResult<void>; using ParserResult = BasicResult<ParseResultType>; using InternalParseResult = BasicResult<ParseState>; struct HelpColumns { std::string left; std::string right; }; template <typename T> inline auto convertInto( std::string const& source, T& target ) -> ParserResult { std::stringstream ss; ss << source; ss >> target; if ( ss.fail() ) return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" ); else return ParserResult::ok( ParseResultType::Matched ); } inline auto convertInto( std::string const& source, std::string& target ) -> ParserResult { target = source; return ParserResult::ok( ParseResultType::Matched ); } inline auto convertInto( std::string const& source, bool& target ) -> ParserResult { std::string srcLC = source; std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>(::tolower( c ) ); } ); if ( srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on" ) target = true; else if ( srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off" ) target = false; else return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" ); return ParserResult::ok( ParseResultType::Matched ); } #ifdef CLARA_CONFIG_OPTIONAL_TYPE template <typename T> inline auto convertInto( std::string const& source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult { T temp; auto result = convertInto( source, temp ); if ( result ) target = std::move( temp ); return result; } #endif // CLARA_CONFIG_OPTIONAL_TYPE struct NonCopyable { NonCopyable() = default; NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable&& ) = delete; NonCopyable& operator=( NonCopyable const& ) = delete; NonCopyable& operator=( NonCopyable&& ) = delete; }; struct BoundRef : NonCopyable { virtual ~BoundRef() = default; virtual auto isContainer() const -> bool { return false; } virtual auto isFlag() const -> bool { return false; } }; struct BoundValueRefBase : BoundRef { virtual auto setValue( std::string const& arg ) -> ParserResult = 0; }; struct BoundFlagRefBase : BoundRef { virtual auto setFlag( bool flag ) -> ParserResult = 0; virtual auto isFlag() const -> bool { return true; } }; template <typename T> struct BoundValueRef : BoundValueRefBase { T& m_ref; explicit BoundValueRef( T& ref ) : m_ref( ref ) { } auto setValue( std::string const& arg ) -> ParserResult override { return convertInto( arg, m_ref ); } }; template <typename T> struct BoundValueRef<std::vector<T>> : BoundValueRefBase { std::vector<T>& m_ref; explicit BoundValueRef( std::vector<T>& ref ) : m_ref( ref ) { } auto isContainer() const -> bool override { return true; } auto setValue( std::string const& arg ) -> ParserResult override { T temp; auto result = convertInto( arg, temp ); if ( result ) m_ref.push_back( temp ); return result; } }; struct BoundFlagRef : BoundFlagRefBase { bool& m_ref; explicit BoundFlagRef( bool& ref ) : m_ref( ref ) { } auto setFlag( bool flag ) -> ParserResult override { m_ref = flag; return ParserResult::ok( ParseResultType::Matched ); } }; template <typename ReturnType> struct LambdaInvoker { static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" ); template <typename L, typename ArgType> static auto invoke( L const& lambda, ArgType const& arg ) -> ParserResult { return lambda( arg ); } }; template <> struct LambdaInvoker<void> { template <typename L, typename ArgType> static auto invoke( L const& lambda, ArgType const& arg ) -> ParserResult { lambda( arg ); return ParserResult::ok( ParseResultType::Matched ); } }; template <typename ArgType, typename L> inline auto invokeLambda( L const& lambda, std::string const& arg ) -> ParserResult { ArgType temp{}; auto result = convertInto( arg, temp ); return !result ? result : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp ); } template <typename L> struct BoundLambda : BoundValueRefBase { L m_lambda; static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); explicit BoundLambda( L const& lambda ) : m_lambda( lambda ) { } auto setValue( std::string const& arg ) -> ParserResult override { return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg ); } }; template <typename L> struct BoundFlagLambda : BoundFlagRefBase { L m_lambda; static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" ); static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" ); explicit BoundFlagLambda( L const& lambda ) : m_lambda( lambda ) { } auto setFlag( bool flag ) -> ParserResult override { return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag ); } }; enum class Optionality { Optional, Required }; struct Parser; class ParserBase { public: virtual ~ParserBase() = default; virtual auto validate() const -> Result { return Result::ok(); } virtual auto parse( std::string const& exeName, TokenStream const& tokens ) const -> InternalParseResult = 0; virtual auto cardinality() const -> size_t { return 1; } auto parse( Args const& args ) const -> InternalParseResult { return parse( args.exeName(), TokenStream( args ) ); } }; template <typename DerivedT> class ComposableParserImpl : public ParserBase { public: template <typename T> auto operator|( T const& other ) const -> Parser; template <typename T> auto operator+( T const& other ) const -> Parser; }; // Common code and state for Args and Opts template <typename DerivedT> class ParserRefImpl : public ComposableParserImpl<DerivedT> { protected: Optionality m_optionality = Optionality::Optional; std::shared_ptr<BoundRef> m_ref; std::string m_hint; std::string m_description; explicit ParserRefImpl( std::shared_ptr<BoundRef> const& ref ) : m_ref( ref ) { } public: template <typename T> ParserRefImpl( T& ref, std::string const& hint ) : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ) , m_hint( hint ) { } template <typename LambdaT> ParserRefImpl( LambdaT const& ref, std::string const& hint ) : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ) , m_hint( hint ) { } auto operator()( std::string const& description ) -> DerivedT& { m_description = description; return static_cast<DerivedT&>( *this ); } auto optional() -> DerivedT& { m_optionality = Optionality::Optional; return static_cast<DerivedT&>( *this ); }; auto required() -> DerivedT& { m_optionality = Optionality::Required; return static_cast<DerivedT&>( *this ); }; auto isOptional() const -> bool { return m_optionality == Optionality::Optional; } auto cardinality() const -> size_t override { if ( m_ref->isContainer() ) return 0; else return 1; } auto hint() const -> std::string { return m_hint; } }; class ExeName : public ComposableParserImpl<ExeName> { std::shared_ptr<std::string> m_name; std::shared_ptr<BoundValueRefBase> m_ref; template <typename LambdaT> static auto makeRef( LambdaT const& lambda ) -> std::shared_ptr<BoundValueRefBase> { return std::make_shared<BoundLambda<LambdaT>>( lambda ); } public: ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) { } explicit ExeName( std::string& ref ) : ExeName() { m_ref = std::make_shared<BoundValueRef<std::string>>( ref ); } template <typename LambdaT> explicit ExeName( LambdaT const& lambda ) : ExeName() { m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda ); } // The exe name is not parsed out of the normal tokens, but is handled // specially auto parse( std::string const&, TokenStream const& tokens ) const -> InternalParseResult override { return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); } auto name() const -> std::string { return *m_name; } auto set( std::string const& newName ) -> ParserResult { auto lastSlash = newName.find_last_of( "\\/" ); auto filename = ( lastSlash == std::string::npos ) ? newName : newName.substr( lastSlash + 1 ); *m_name = filename; if ( m_ref ) return m_ref->setValue( filename ); else return ParserResult::ok( ParseResultType::Matched ); } }; class Arg : public ParserRefImpl<Arg> { public: using ParserRefImpl::ParserRefImpl; auto parse( std::string const&, TokenStream const& tokens ) const -> InternalParseResult override { auto validationResult = validate(); if ( !validationResult ) return InternalParseResult( validationResult ); auto remainingTokens = tokens; auto const& token = *remainingTokens; if ( token.type != TokenType::Argument ) return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); assert( !m_ref->isFlag() ); auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() ); auto result = valueRef->setValue( remainingTokens->token ); if ( !result ) return InternalParseResult( result ); else return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); } }; inline auto normaliseOpt( std::string const& optName ) -> std::string { #ifdef CATCH_PLATFORM_WINDOWS if ( optName[0] == '/' ) return "-" + optName.substr( 1 ); else #endif return optName; } class Opt : public ParserRefImpl<Opt> { protected: std::vector<std::string> m_optNames; public: template <typename LambdaT> explicit Opt( LambdaT const& ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) { } explicit Opt( bool& ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) { } template <typename LambdaT> Opt( LambdaT const& ref, std::string const& hint ) : ParserRefImpl( ref, hint ) { } template <typename T> Opt( T& ref, std::string const& hint ) : ParserRefImpl( ref, hint ) { } auto operator[]( std::string const& optName ) -> Opt& { m_optNames.push_back( optName ); return *this; } auto getHelpColumns() const -> std::vector<HelpColumns> { std::ostringstream oss; bool first = true; for ( auto const& opt : m_optNames ) { if ( first ) first = false; else oss << ", "; oss << opt; } if ( !m_hint.empty() ) oss << " <" << m_hint << ">"; return { { oss.str(), m_description } }; } auto isMatch( std::string const& optToken ) const -> bool { auto normalisedToken = normaliseOpt( optToken ); for ( auto const& name : m_optNames ) { if ( normaliseOpt( name ) == normalisedToken ) return true; } return false; } using ParserBase::parse; auto parse( std::string const&, TokenStream const& tokens ) const -> InternalParseResult override { auto validationResult = validate(); if ( !validationResult ) return InternalParseResult( validationResult ); auto remainingTokens = tokens; if ( remainingTokens && remainingTokens->type == TokenType::Option ) { auto const& token = *remainingTokens; if ( isMatch( token.token ) ) { if ( m_ref->isFlag() ) { auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() ); auto result = flagRef->setFlag( true ); if ( !result ) return InternalParseResult( result ); if ( result.value() == ParseResultType::ShortCircuitAll ) return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); } else { auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() ); ++remainingTokens; if ( !remainingTokens ) return InternalParseResult::runtimeError( "Expected argument following " + token.token ); auto const& argToken = *remainingTokens; if ( argToken.type != TokenType::Argument ) return InternalParseResult::runtimeError( "Expected argument following " + token.token ); auto result = valueRef->setValue( argToken.token ); if ( !result ) return InternalParseResult( result ); if ( result.value() == ParseResultType::ShortCircuitAll ) return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); } return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); } } return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); } auto validate() const -> Result override { if ( m_optNames.empty() ) return Result::logicError( "No options supplied to Opt" ); for ( auto const& name : m_optNames ) { if ( name.empty() ) return Result::logicError( "Option name cannot be empty" ); #ifdef CATCH_PLATFORM_WINDOWS if ( name[0] != '-' && name[0] != '/' ) return Result::logicError( "Option name must begin with '-' or '/'" ); #else if ( name[0] != '-' ) return Result::logicError( "Option name must begin with '-'" ); #endif } return ParserRefImpl::validate(); } }; struct Help : Opt { Help( bool& showHelpFlag ) : Opt( [&]( bool flag ) { showHelpFlag = flag; return ParserResult::ok( ParseResultType::ShortCircuitAll ); } ) { static_cast<Opt&> ( *this )( "display usage information" )["-?"]["-h"]["--help"] .optional(); } }; struct Parser : ParserBase { mutable ExeName m_exeName; std::vector<Opt> m_options; std::vector<Arg> m_args; auto operator|=( ExeName const& exeName ) -> Parser& { m_exeName = exeName; return *this; } auto operator|=( Arg const& arg ) -> Parser& { m_args.push_back( arg ); return *this; } auto operator|=( Opt const& opt ) -> Parser& { m_options.push_back( opt ); return *this; } auto operator|=( Parser const& other ) -> Parser& { m_options.insert( m_options.end(), other.m_options.begin(), other.m_options.end() ); m_args.insert( m_args.end(), other.m_args.begin(), other.m_args.end() ); return *this; } template <typename T> auto operator|( T const& other ) const -> Parser { return Parser( *this ) |= other; } // Forward deprecated interface with '+' instead of '|' template <typename T> auto operator+=( T const& other ) -> Parser& { return operator|=( other ); } template <typename T> auto operator+( T const& other ) const -> Parser { return operator|( other ); } auto getHelpColumns() const -> std::vector<HelpColumns> { std::vector<HelpColumns> cols; for ( auto const& o : m_options ) { auto childCols = o.getHelpColumns(); cols.insert( cols.end(), childCols.begin(), childCols.end() ); } return cols; } void writeToStream( std::ostream& os ) const { if ( !m_exeName.name().empty() ) { os << "usage:\n" << " " << m_exeName.name() << " "; bool required = true, first = true; for ( auto const& arg : m_args ) { if ( first ) first = false; else os << " "; if ( arg.isOptional() && required ) { os << "["; required = false; } os << "<" << arg.hint() << ">"; if ( arg.cardinality() == 0 ) os << " ... "; } if ( !required ) os << "]"; if ( !m_options.empty() ) os << " options"; os << "\n\nwhere options are:" << std::endl; } auto rows = getHelpColumns(); size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH; size_t optWidth = 0; for ( auto const& cols : rows ) optWidth = ( std::max )( optWidth, cols.left.size() + 2 ); optWidth = ( std::min )( optWidth, consoleWidth / 2 ); for ( auto const& cols : rows ) { auto row = TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) + TextFlow::Spacer( 4 ) + TextFlow::Column( cols.right ) .width( consoleWidth - 7 - optWidth ); os << row << std::endl; } } friend auto operator<<( std::ostream& os, Parser const& parser ) -> std::ostream& { parser.writeToStream( os ); return os; } auto validate() const -> Result override { for ( auto const& opt : m_options ) { auto result = opt.validate(); if ( !result ) return result; } for ( auto const& arg : m_args ) { auto result = arg.validate(); if ( !result ) return result; } return Result::ok(); } using ParserBase::parse; auto parse( std::string const& exeName, TokenStream const& tokens ) const -> InternalParseResult override { struct ParserInfo { ParserBase const* parser = nullptr; size_t count = 0; }; const size_t totalParsers = m_options.size() + m_args.size(); assert( totalParsers < 512 ); // ParserInfo parseInfos[totalParsers]; // <-- this is what we really // want to do ParserInfo parseInfos[512]; { size_t i = 0; for ( auto const& opt : m_options ) parseInfos[i++].parser = &opt; for ( auto const& arg : m_args ) parseInfos[i++].parser = &arg; } m_exeName.set( exeName ); auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); while ( result.value().remainingTokens() ) { bool tokenParsed = false; for ( size_t i = 0; i < totalParsers; ++i ) { auto& parseInfo = parseInfos[i]; if ( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) { result = parseInfo.parser->parse( exeName, result.value().remainingTokens() ); if ( !result ) return result; if ( result.value().type() != ParseResultType::NoMatch ) { tokenParsed = true; ++parseInfo.count; break; } } } if ( result.value().type() == ParseResultType::ShortCircuitAll ) return result; if ( !tokenParsed ) return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token ); } // !TBD Check missing required options return result; } }; template <typename DerivedT> template <typename T> auto ComposableParserImpl<DerivedT>::operator|( T const& other ) const -> Parser { return Parser() | static_cast<DerivedT const&>( *this ) | other; } } // namespace detail // A Combined parser using detail::Parser; // A parser for options using detail::Opt; // A parser for arguments using detail::Arg; // Wrapper for argc, argv from main() using detail::Args; // Specifies the name of the executable using detail::ExeName; // Convenience wrapper for option parser that specifies the help option using detail::Help; // enum of result types from a parse using detail::ParseResultType; // Result type for parser operation using detail::ParserResult; } } // namespace Catch::clara // end clara.hpp #ifdef __clang__ #pragma clang diagnostic pop #endif // Restore Clara's value for console width, if present #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #endif // end catch_clara.h namespace Catch { clara::Parser makeCommandLineParser( ConfigData& config ); } // end namespace Catch // end catch_commandline.h #include <ctime> #include <fstream> namespace Catch { clara::Parser makeCommandLineParser( ConfigData& config ) { using namespace clara; auto const setWarning = [&]( std::string const& warning ) { auto warningSet = [&]() { if ( warning == "NoAssertions" ) return WarnAbout::NoAssertions; if ( warning == "NoTests" ) return WarnAbout::NoTests; return WarnAbout::Nothing; }(); if ( warningSet == WarnAbout::Nothing ) return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" ); config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet ); return ParserResult::ok( ParseResultType::Matched ); }; auto const loadTestNamesFromFile = [&]( std::string const& filename ) { std::ifstream f( filename.c_str() ); if ( !f.is_open() ) return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" ); std::string line; while ( std::getline( f, line ) ) { line = trim( line ); if ( !line.empty() && !startsWith( line, '#' ) ) { if ( !startsWith( line, '"' ) ) line = '"' + line + '"'; config.testsOrTags.push_back( line + ',' ); } } return ParserResult::ok( ParseResultType::Matched ); }; auto const setTestOrder = [&]( std::string const& order ) { if ( startsWith( "declared", order ) ) config.runOrder = RunTests::InDeclarationOrder; else if ( startsWith( "lexical", order ) ) config.runOrder = RunTests::InLexicographicalOrder; else if ( startsWith( "random", order ) ) config.runOrder = RunTests::InRandomOrder; else return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setRngSeed = [&]( std::string const& seed ) { if ( seed != "time" ) return clara::detail::convertInto( seed, config.rngSeed ); config.rngSeed = static_cast<unsigned int>( std::time( nullptr ) ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setColourUsage = [&]( std::string const& useColour ) { auto mode = toLower( useColour ); if ( mode == "yes" ) config.useColour = UseColour::Yes; else if ( mode == "no" ) config.useColour = UseColour::No; else if ( mode == "auto" ) config.useColour = UseColour::Auto; else return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setWaitForKeypress = [&]( std::string const& keypress ) { auto keypressLc = toLower( keypress ); if ( keypressLc == "start" ) config.waitForKeypress = WaitForKeypress::BeforeStart; else if ( keypressLc == "exit" ) config.waitForKeypress = WaitForKeypress::BeforeExit; else if ( keypressLc == "both" ) config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; else return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" ); return ParserResult::ok( ParseResultType::Matched ); }; auto const setVerbosity = [&]( std::string const& verbosity ) { auto lcVerbosity = toLower( verbosity ); if ( lcVerbosity == "quiet" ) config.verbosity = Verbosity::Quiet; else if ( lcVerbosity == "normal" ) config.verbosity = Verbosity::Normal; else if ( lcVerbosity == "high" ) config.verbosity = Verbosity::High; else return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" ); return ParserResult::ok( ParseResultType::Matched ); }; auto cli = ExeName( config.processName ) | Help( config.showHelp ) | Opt( config.listTests )["-l"]["--list-tests"]( "list all/matching test cases" ) | Opt( config.listTags )["-t"]["--list-tags"]( "list all/matching tags" ) | Opt( config.showSuccessfulTests )["-s"]["--success"]( "include successful tests in output" ) | Opt( config.shouldDebugBreak )["-b"]["--break"]( "break into debugger on failure" ) | Opt( config.noThrow )["-e"]["--nothrow"]( "skip exception tests" ) | Opt( config.showInvisibles )["-i"]["--invisibles"]( "show invisibles (tabs, newlines)" ) | Opt( config.outputFilename, "filename" )["-o"]["--out"]( "output filename" ) | Opt( config.reporterNames, "name" )["-r"]["--reporter"]( "reporter to use (defaults to console)" ) | Opt( config.name, "name" )["-n"]["--name"]( "suite name" ) | Opt( [&]( bool ) { config.abortAfter = 1; } )["-a"]["--abort"]( "abort at first failure" ) | Opt( [&]( int x ) { config.abortAfter = x; }, "no. failures" )["-x"]["--abortx"]( "abort after x failures" ) | Opt( setWarning, "warning name" )["-w"]["--warn"]( "enable warnings" ) | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )["-d"]["--durations"]( "show test durations" ) | Opt( loadTestNamesFromFile, "filename" )["-f"]["--input-file"]( "load test names to run from a file" ) | Opt( config.filenamesAsTags )["-#"]["--filenames-as-tags"]( "adds a tag for the filename" ) | Opt( config.sectionsToRun, "section name" )["-c"]["--section"]( "specify section to run" ) | Opt( setVerbosity, "quiet|normal|high" )["-v"]["--verbosity"]( "set output verbosity" ) | Opt( config.listTestNamesOnly )["--list-test-names-only"]( "list all/matching test cases names only" ) | Opt( config.listReporters )["--list-reporters"]( "list all reporters" ) | Opt( setTestOrder, "decl|lex|rand" )["--order"]( "test case order (defaults to decl)" ) | Opt( setRngSeed, "'time'|number" )["--rng-seed"]( "set a specific seed for random numbers" ) | Opt( setColourUsage, "yes|no" )["--use-colour"]( "should output be colourised" ) | Opt( config.libIdentify )["--libidentify"]( "report name and version according to libidentify standard" ) | Opt( setWaitForKeypress, "start|exit|both" )["--wait-for-keypress"]( "waits for a keypress before exiting" ) | Opt( config.benchmarkResolutionMultiple, "multiplier" )["--benchmark-resolution-multiple"]( "multiple of clock resolution to run benchmarks" ) | Arg( config.testsOrTags, "test name|pattern|tags" )( "which test or tests to use" ); return cli; } } // end namespace Catch // end catch_commandline.cpp // start catch_common.cpp #include <cstring> #include <ostream> namespace Catch { bool SourceLineInfo::empty() const noexcept { return file[0] == '\0'; } bool SourceLineInfo::operator==( SourceLineInfo const& other ) const noexcept { return line == other.line && ( file == other.file || std::strcmp( file, other.file ) == 0 ); } bool SourceLineInfo::operator<( SourceLineInfo const& other ) const noexcept { return line < other.line || ( line == other.line && ( std::strcmp( file, other.file ) < 0 ) ); } std::ostream& operator<<( std::ostream& os, SourceLineInfo const& info ) { #ifndef __GNUG__ os << info.file << '(' << info.line << ')'; #else os << info.file << ':' << info.line; #endif return os; } std::string StreamEndStop::operator+() const { return std::string(); } NonCopyable::NonCopyable() = default; NonCopyable::~NonCopyable() = default; } // end catch_common.cpp // start catch_config.cpp // start catch_enforce.h #include <stdexcept> #define CATCH_PREPARE_EXCEPTION( type, msg ) \ type( ( Catch::ReusableStringStream() << msg ).str() ) #define CATCH_INTERNAL_ERROR( msg ) \ throw CATCH_PREPARE_EXCEPTION( std::logic_error, \ CATCH_INTERNAL_LINEINFO \ << ": Internal Catch error: " << msg ); #define CATCH_ERROR( msg ) throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg ) #define CATCH_ENFORCE( condition, msg ) \ do \ { \ if ( !( condition ) ) \ CATCH_ERROR( msg ); \ } while ( false ) // end catch_enforce.h namespace Catch { Config::Config( ConfigData const& data ) : m_data( data ) , m_stream( openStream() ) { TestSpecParser parser( ITagAliasRegistry::get() ); if ( data.testsOrTags.empty() ) { parser.parse( "~[.]" ); // All not hidden tests } else { m_hasTestFilters = true; for ( auto const& testOrTags : data.testsOrTags ) parser.parse( testOrTags ); } m_testSpec = parser.testSpec(); } std::string const& Config::getFilename() const { return m_data.outputFilename; } bool Config::listTests() const { return m_data.listTests; } bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; } bool Config::listTags() const { return m_data.listTags; } bool Config::listReporters() const { return m_data.listReporters; } std::string Config::getProcessName() const { return m_data.processName; } std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; } std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; } std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; } TestSpec const& Config::testSpec() const { return m_testSpec; } bool Config::hasTestFilters() const { return m_hasTestFilters; } bool Config::showHelp() const { return m_data.showHelp; } // IConfig interface bool Config::allowThrows() const { return !m_data.noThrow; } std::ostream& Config::stream() const { return m_stream->stream(); } std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; } bool Config::warnAboutMissingAssertions() const { return !!( m_data.warnings & WarnAbout::NoAssertions ); } bool Config::warnAboutNoTests() const { return !!( m_data.warnings & WarnAbout::NoTests ); } ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; } RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; } unsigned int Config::rngSeed() const { return m_data.rngSeed; } int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; } UseColour::YesOrNo Config::useColour() const { return m_data.useColour; } bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; } int Config::abortAfter() const { return m_data.abortAfter; } bool Config::showInvisibles() const { return m_data.showInvisibles; } Verbosity Config::verbosity() const { return m_data.verbosity; } IStream const* Config::openStream() { return Catch::makeStream( m_data.outputFilename ); } } // end namespace Catch // end catch_config.cpp // start catch_console_colour.cpp #if defined( __clang__ ) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" #endif // start catch_errno_guard.h namespace Catch { class ErrnoGuard { public: ErrnoGuard(); ~ErrnoGuard(); private: int m_oldErrno; }; } // end catch_errno_guard.h #include <sstream> namespace Catch { namespace { struct IColourImpl { virtual ~IColourImpl() = default; virtual void use( Colour::Code _colourCode ) = 0; }; struct NoColourImpl : IColourImpl { void use( Colour::Code ) {} static IColourImpl* instance() { static NoColourImpl s_instance; return &s_instance; } }; } // anon namespace } // namespace Catch #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) \ && !defined( CATCH_CONFIG_COLOUR_ANSI ) #ifdef CATCH_PLATFORM_WINDOWS #define CATCH_CONFIG_COLOUR_WINDOWS #else #define CATCH_CONFIG_COLOUR_ANSI #endif #endif #if defined( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// namespace Catch { namespace { class Win32ColourImpl : public IColourImpl { public: Win32ColourImpl() : stdoutHandle( GetStdHandle( STD_OUTPUT_HANDLE ) ) { CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); } virtual void use( Colour::Code _colourCode ) override { switch ( _colourCode ) { case Colour::None: return setTextAttribute( originalForegroundAttributes ); case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Red: return setTextAttribute( FOREGROUND_RED ); case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); case Colour::Grey: return setTextAttribute( 0 ); case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN ); case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); default: CATCH_ERROR( "Unknown colour requested" ); } } private: void setTextAttribute( WORD _textAttribute ) { SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); } HANDLE stdoutHandle; WORD originalForegroundAttributes; WORD originalBackgroundAttributes; }; IColourImpl* platformColourInstance() { static Win32ColourImpl s_instance; IConfigPtr config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if ( colourMode == UseColour::Auto ) colourMode = UseColour::Yes; return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// #include <unistd.h> namespace Catch { namespace { // use POSIX/ ANSI console terminal codes // Thanks to Adam Strzelecki for original contribution // (http://github.com/nanoant) // https://github.com/philsquared/Catch/pull/131 class PosixColourImpl : public IColourImpl { public: virtual void use( Colour::Code _colourCode ) override { switch ( _colourCode ) { case Colour::None: case Colour::White: return setColour( "[0m" ); case Colour::Red: return setColour( "[0;31m" ); case Colour::Green: return setColour( "[0;32m" ); case Colour::Blue: return setColour( "[0;34m" ); case Colour::Cyan: return setColour( "[0;36m" ); case Colour::Yellow: return setColour( "[0;33m" ); case Colour::Grey: return setColour( "[1;30m" ); case Colour::LightGrey: return setColour( "[0;37m" ); case Colour::BrightRed: return setColour( "[1;31m" ); case Colour::BrightGreen: return setColour( "[1;32m" ); case Colour::BrightWhite: return setColour( "[1;37m" ); case Colour::BrightYellow: return setColour( "[1;33m" ); case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); default: CATCH_INTERNAL_ERROR( "Unknown colour requested" ); } } static IColourImpl* instance() { static PosixColourImpl s_instance; return &s_instance; } private: void setColour( const char* _escapeCode ) { Catch::cout() << '\033' << _escapeCode; } }; bool useColourOnPlatform() { return #ifdef CATCH_PLATFORM_MAC !isDebuggerActive() && #endif #if !( defined( __DJGPP__ ) && defined( __STRICT_ANSI__ ) ) isatty( STDOUT_FILENO ) #else false #endif ; } IColourImpl* platformColourInstance() { ErrnoGuard guard; IConfigPtr config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if ( colourMode == UseColour::Auto ) colourMode = useColourOnPlatform() ? UseColour::Yes : UseColour::No; return colourMode == UseColour::Yes ? PosixColourImpl::instance() : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #else // not Windows or ANSI /////////////////////////////////////////////// namespace Catch { static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } } // end namespace Catch #endif // Windows/ ANSI/ None namespace Catch { Colour::Colour( Code _colourCode ) { use( _colourCode ); } Colour::Colour( Colour&& rhs ) noexcept { m_moved = rhs.m_moved; rhs.m_moved = true; } Colour& Colour::operator=( Colour&& rhs ) noexcept { m_moved = rhs.m_moved; rhs.m_moved = true; return *this; } Colour::~Colour() { if ( !m_moved ) use( None ); } void Colour::use( Code _colourCode ) { static IColourImpl* impl = platformColourInstance(); impl->use( _colourCode ); } std::ostream& operator<<( std::ostream& os, Colour const& ) { return os; } } // end namespace Catch #if defined( __clang__ ) #pragma clang diagnostic pop #endif // end catch_console_colour.cpp // start catch_context.cpp namespace Catch { class Context : public IMutableContext, NonCopyable { public: // IContext virtual IResultCapture* getResultCapture() override { return m_resultCapture; } virtual IRunner* getRunner() override { return m_runner; } virtual IConfigPtr const& getConfig() const override { return m_config; } virtual ~Context() override; public: // IMutableContext virtual void setResultCapture( IResultCapture* resultCapture ) override { m_resultCapture = resultCapture; } virtual void setRunner( IRunner* runner ) override { m_runner = runner; } virtual void setConfig( IConfigPtr const& config ) override { m_config = config; } friend IMutableContext& getCurrentMutableContext(); private: IConfigPtr m_config; IRunner* m_runner = nullptr; IResultCapture* m_resultCapture = nullptr; }; IMutableContext* IMutableContext::currentContext = nullptr; void IMutableContext::createContext() { currentContext = new Context(); } void cleanUpContext() { delete IMutableContext::currentContext; IMutableContext::currentContext = nullptr; } IContext::~IContext() = default; IMutableContext::~IMutableContext() = default; Context::~Context() = default; } // end catch_context.cpp // start catch_debug_console.cpp // start catch_debug_console.h #include <string> namespace Catch { void writeToDebugConsole( std::string const& text ); } // end catch_debug_console.h #ifdef CATCH_PLATFORM_WINDOWS namespace Catch { void writeToDebugConsole( std::string const& text ) { ::OutputDebugStringA( text.c_str() ); } } #else namespace Catch { void writeToDebugConsole( std::string const& text ) { // !TBD: Need a version for Mac/ XCode and other IDEs Catch::cout() << text; } } #endif // Platform // end catch_debug_console.cpp // start catch_debugger.cpp #ifdef CATCH_PLATFORM_MAC #include <assert.h> #include <stdbool.h> #include <sys/types.h> #include <unistd.h> #include <cstddef> #include <ostream> #include <sys/sysctl.h> namespace Catch { // The following function is taken directly from the following technical note: // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). bool isDebuggerActive() { int mib[4]; struct kinfo_proc info; std::size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof( info ); if ( sysctl( mib, sizeof( mib ) / sizeof( *mib ), &info, &size, nullptr, 0 ) != 0 ) { Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger " "is active **\n" << std::endl; return false; } // We're being debugged if the P_TRACED flag is set. return ( ( info.kp_proc.p_flag & P_TRACED ) != 0 ); } } // namespace Catch #elif defined( CATCH_PLATFORM_LINUX ) #include <fstream> #include <string> namespace Catch { // The standard POSIX way of detecting a debugger is to attempt to // ptrace() the process, but this needs to be done from a child and not // this process itself to still allow attaching to this process later // if wanted, so is rather heavy. Under Linux we have the PID of the // "debugger" (which doesn't need to be gdb, of course, it could also // be strace, for example) in /proc/$PID/status, so just get it from // there instead. bool isDebuggerActive() { // Libstdc++ has a bug, where std::ifstream sets errno to 0 // This way our users can properly assert over errno values ErrnoGuard guard; std::ifstream in( "/proc/self/status" ); for ( std::string line; std::getline( in, line ); ) { static const int PREFIX_LEN = 11; if ( line.compare( 0, PREFIX_LEN, "TracerPid:\t" ) == 0 ) { // We're traced if the PID is not 0 and no other PID starts // with 0 digit, so it's enough to check for just a single // character. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; } } return false; } } // namespace Catch #elif defined( _MSC_VER ) extern "C" __declspec( dllimport ) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #elif defined( __MINGW32__ ) extern "C" __declspec( dllimport ) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #else namespace Catch { bool isDebuggerActive() { return false; } } #endif // Platform // end catch_debugger.cpp // start catch_decomposer.cpp namespace Catch { ITransientExpression::~ITransientExpression() = default; void formatReconstructedExpression( std::ostream& os, std::string const& lhs, StringRef op, std::string const& rhs ) { if ( lhs.size() + rhs.size() < 40 && lhs.find( '\n' ) == std::string::npos && rhs.find( '\n' ) == std::string::npos ) os << lhs << " " << op << " " << rhs; else os << lhs << "\n" << op << "\n" << rhs; } } // end catch_decomposer.cpp // start catch_errno_guard.cpp #include <cerrno> namespace Catch { ErrnoGuard::ErrnoGuard() : m_oldErrno( errno ) { } ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; } } // end catch_errno_guard.cpp // start catch_exception_translator_registry.cpp // start catch_exception_translator_registry.h #include <memory> #include <string> #include <vector> namespace Catch { class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry(); virtual void registerTranslator( const IExceptionTranslator* translator ); virtual std::string translateActiveException() const override; std::string tryTranslators() const; private: std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators; }; } // end catch_exception_translator_registry.h #ifdef __OBJC__ #import "Foundation/Foundation.h" #endif namespace Catch { ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {} void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) { m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) ); } std::string ExceptionTranslatorRegistry::translateActiveException() const { try { #ifdef __OBJC__ // In Objective-C try objective-c exceptions first @try { return tryTranslators(); } @catch ( NSException* exception ) { return Catch::Detail::stringify( [exception description] ); } #else // Compiling a mixed mode project with MSVC means that CLR // exceptions will be caught in (...) as well. However, these // do not fill-in std::current_exception and thus lead to crash // when attempting rethrow. // /EHa switch also causes structured exceptions to be caught // here, but they fill-in current_exception properly, so // at worst the output should be a little weird, instead of // causing a crash. if ( std::current_exception() == nullptr ) { return "Non C++ exception. Possibly a CLR exception."; } return tryTranslators(); #endif } catch ( TestFailureException& ) { std::rethrow_exception( std::current_exception() ); } catch ( std::exception& ex ) { return ex.what(); } catch ( std::string& msg ) { return msg; } catch ( const char* msg ) { return msg; } catch ( ... ) { return "Unknown exception"; } } std::string ExceptionTranslatorRegistry::tryTranslators() const { if ( m_translators.empty() ) std::rethrow_exception( std::current_exception() ); else return m_translators[0]->translate( m_translators.begin() + 1, m_translators.end() ); } } // end catch_exception_translator_registry.cpp // start catch_fatal_condition.cpp #if defined( __GNUC__ ) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) namespace { // Report the error condition void reportFatal( char const* const message ) { Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message ); } } #endif // signals/SEH handling #if defined( CATCH_CONFIG_WINDOWS_SEH ) namespace Catch { struct SignalDefs { DWORD id; const char* name; }; // There is no 1-1 mapping between signals and windows exceptions. // Windows can easily distinguish between SO and SigSegV, // but SigInt, SigTerm, etc are handled differently. static SignalDefs signalDefs[] = { { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" }, { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" }, { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" }, { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" }, }; LONG CALLBACK FatalConditionHandler::handleVectoredException( PEXCEPTION_POINTERS ExceptionInfo ) { for ( auto const& def : signalDefs ) { if ( ExceptionInfo->ExceptionRecord->ExceptionCode == def.id ) { reportFatal( def.name ); } } // If its not an exception we care about, pass it along. // This stops us from eating debugger breaks etc. return EXCEPTION_CONTINUE_SEARCH; } FatalConditionHandler::FatalConditionHandler() { isSet = true; // 32k seems enough for Catch to handle stack overflow, // but the value was found experimentally, so there is no strong guarantee guaranteeSize = 32 * 1024; exceptionHandlerHandle = nullptr; // Register as first handler in current chain exceptionHandlerHandle = AddVectoredExceptionHandler( 1, handleVectoredException ); // Pass in guarantee size to be filled SetThreadStackGuarantee( &guaranteeSize ); } void FatalConditionHandler::reset() { if ( isSet ) { RemoveVectoredExceptionHandler( exceptionHandlerHandle ); SetThreadStackGuarantee( &guaranteeSize ); exceptionHandlerHandle = nullptr; isSet = false; } } FatalConditionHandler::~FatalConditionHandler() { reset(); } bool FatalConditionHandler::isSet = false; ULONG FatalConditionHandler::guaranteeSize = 0; PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr; } // namespace Catch #elif defined( CATCH_CONFIG_POSIX_SIGNALS ) namespace Catch { struct SignalDefs { int id; const char* name; }; static SignalDefs signalDefs[] = { { SIGINT, "SIGINT - Terminal interrupt signal" }, { SIGILL, "SIGILL - Illegal instruction signal" }, { SIGFPE, "SIGFPE - Floating point error signal" }, { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, { SIGTERM, "SIGTERM - Termination request signal" }, { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } }; void FatalConditionHandler::handleSignal( int sig ) { char const* name = "<unknown signal>"; for ( auto const& def : signalDefs ) { if ( sig == def.id ) { name = def.name; break; } } reset(); reportFatal( name ); raise( sig ); } FatalConditionHandler::FatalConditionHandler() { isSet = true; stack_t sigStack; sigStack.ss_sp = altStackMem; sigStack.ss_size = SIGSTKSZ; sigStack.ss_flags = 0; sigaltstack( &sigStack, &oldSigStack ); struct sigaction sa = {}; sa.sa_handler = handleSignal; sa.sa_flags = SA_ONSTACK; for ( std::size_t i = 0; i < sizeof( signalDefs ) / sizeof( SignalDefs ); ++i ) { sigaction( signalDefs[i].id, &sa, &oldSigActions[i] ); } } FatalConditionHandler::~FatalConditionHandler() { reset(); } void FatalConditionHandler::reset() { if ( isSet ) { // Set signals back to previous values -- hopefully nobody overwrote them in the // meantime for ( std::size_t i = 0; i < sizeof( signalDefs ) / sizeof( SignalDefs ); ++i ) { sigaction( signalDefs[i].id, &oldSigActions[i], nullptr ); } // Return the old stack sigaltstack( &oldSigStack, nullptr ); isSet = false; } } bool FatalConditionHandler::isSet = false; struct sigaction FatalConditionHandler::oldSigActions[sizeof( signalDefs ) / sizeof( SignalDefs )] = {}; stack_t FatalConditionHandler::oldSigStack = {}; char FatalConditionHandler::altStackMem[SIGSTKSZ] = {}; } // namespace Catch #else namespace Catch { void FatalConditionHandler::reset() {} } #endif // signals/SEH handling #if defined( __GNUC__ ) #pragma GCC diagnostic pop #endif // end catch_fatal_condition.cpp // start catch_interfaces_capture.cpp namespace Catch { IResultCapture::~IResultCapture() = default; } // end catch_interfaces_capture.cpp // start catch_interfaces_config.cpp namespace Catch { IConfig::~IConfig() = default; } // end catch_interfaces_config.cpp // start catch_interfaces_exception.cpp namespace Catch { IExceptionTranslator::~IExceptionTranslator() = default; IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default; } // end catch_interfaces_exception.cpp // start catch_interfaces_registry_hub.cpp namespace Catch { IRegistryHub::~IRegistryHub() = default; IMutableRegistryHub::~IMutableRegistryHub() = default; } // end catch_interfaces_registry_hub.cpp // start catch_interfaces_reporter.cpp // start catch_reporter_multi.h namespace Catch { class MultipleReporters : public IStreamingReporter { using Reporters = std::vector<IStreamingReporterPtr>; Reporters m_reporters; public: void add( IStreamingReporterPtr&& reporter ); public: // IStreamingReporter ReporterPreferences getPreferences() const override; void noMatchingTestCases( std::string const& spec ) override; static std::set<Verbosity> getSupportedVerbosities(); void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override; void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override; void testRunStarting( TestRunInfo const& testRunInfo ) override; void testGroupStarting( GroupInfo const& groupInfo ) override; void testCaseStarting( TestCaseInfo const& testInfo ) override; void sectionStarting( SectionInfo const& sectionInfo ) override; void assertionStarting( AssertionInfo const& assertionInfo ) override; // The return value indicates if the messages buffer should be cleared: bool assertionEnded( AssertionStats const& assertionStats ) override; void sectionEnded( SectionStats const& sectionStats ) override; void testCaseEnded( TestCaseStats const& testCaseStats ) override; void testGroupEnded( TestGroupStats const& testGroupStats ) override; void testRunEnded( TestRunStats const& testRunStats ) override; void skipTest( TestCaseInfo const& testInfo ) override; bool isMulti() const override; }; } // end namespace Catch // end catch_reporter_multi.h namespace Catch { ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig ) : m_stream( &_fullConfig->stream() ) , m_fullConfig( _fullConfig ) { } ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ) : m_stream( &_stream ) , m_fullConfig( _fullConfig ) { } std::ostream& ReporterConfig::stream() const { return *m_stream; } IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; } TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) { } GroupInfo::GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ) : name( _name ) , groupIndex( _groupIndex ) , groupsCounts( _groupsCount ) { } AssertionStats::AssertionStats( AssertionResult const& _assertionResult, std::vector<MessageInfo> const& _infoMessages, Totals const& _totals ) : assertionResult( _assertionResult ) , infoMessages( _infoMessages ) , totals( _totals ) { assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression; if ( assertionResult.hasMessage() ) { // Copy message into messages list. // !TBD This should have been done earlier, somewhere MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); builder << assertionResult.getMessage(); builder.m_info.message = builder.m_stream.str(); infoMessages.push_back( builder.m_info ); } } AssertionStats::~AssertionStats() = default; SectionStats::SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ) : sectionInfo( _sectionInfo ) , assertions( _assertions ) , durationInSeconds( _durationInSeconds ) , missingAssertions( _missingAssertions ) { } SectionStats::~SectionStats() = default; TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ) : testInfo( _testInfo ) , totals( _totals ) , stdOut( _stdOut ) , stdErr( _stdErr ) , aborting( _aborting ) { } TestCaseStats::~TestCaseStats() = default; TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ) : groupInfo( _groupInfo ) , totals( _totals ) , aborting( _aborting ) { } TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo ) : groupInfo( _groupInfo ) , aborting( false ) { } TestGroupStats::~TestGroupStats() = default; TestRunStats::TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ) : runInfo( _runInfo ) , totals( _totals ) , aborting( _aborting ) { } TestRunStats::~TestRunStats() = default; void IStreamingReporter::fatalErrorEncountered( StringRef ) {} bool IStreamingReporter::isMulti() const { return false; } IReporterFactory::~IReporterFactory() = default; IReporterRegistry::~IReporterRegistry() = default; void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) { if ( !existingReporter ) { existingReporter = std::move( additionalReporter ); return; } MultipleReporters* multi = nullptr; if ( existingReporter->isMulti() ) { multi = static_cast<MultipleReporters*>( existingReporter.get() ); } else { auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters ); newMulti->add( std::move( existingReporter ) ); multi = newMulti.get(); existingReporter = std::move( newMulti ); } multi->add( std::move( additionalReporter ) ); } } // end namespace Catch // end catch_interfaces_reporter.cpp // start catch_interfaces_runner.cpp namespace Catch { IRunner::~IRunner() = default; } // end catch_interfaces_runner.cpp // start catch_interfaces_testcase.cpp namespace Catch { ITestInvoker::~ITestInvoker() = default; ITestCaseRegistry::~ITestCaseRegistry() = default; } // end catch_interfaces_testcase.cpp // start catch_leak_detector.cpp #ifdef CATCH_CONFIG_WINDOWS_CRTDBG #include <crtdbg.h> namespace Catch { LeakDetector::LeakDetector() { int flag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); flag |= _CRTDBG_LEAK_CHECK_DF; flag |= _CRTDBG_ALLOC_MEM_DF; _CrtSetDbgFlag( flag ); _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ); // Change this to leaking allocation's number to break there _CrtSetBreakAlloc( -1 ); } } #else Catch::LeakDetector::LeakDetector() {} #endif // end catch_leak_detector.cpp // start catch_list.cpp // start catch_list.h #include <set> namespace Catch { std::size_t listTests( Config const& config ); std::size_t listTestsNamesOnly( Config const& config ); struct TagInfo { void add( std::string const& spelling ); std::string all() const; std::set<std::string> spellings; std::size_t count = 0; }; std::size_t listTags( Config const& config ); std::size_t listReporters( Config const& /*config*/ ); Option<std::size_t> list( Config const& config ); } // end namespace Catch // end catch_list.h // start catch_text.h namespace Catch { using namespace clara::TextFlow; } // end catch_text.h #include <algorithm> #include <iomanip> #include <limits> namespace Catch { std::size_t listTests( Config const& config ) { TestSpec testSpec = config.testSpec(); if ( config.hasTestFilters() ) Catch::cout() << "Matching test cases:\n"; else { Catch::cout() << "All available test cases:\n"; } auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for ( auto const& testCaseInfo : matchedTestCases ) { Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None; Colour colourGuard( colour ); Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n"; if ( config.verbosity() >= Verbosity::High ) { Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ) .indent( 4 ) << std::endl; std::string description = testCaseInfo.description; if ( description.empty() ) description = "(NO DESCRIPTION)"; Catch::cout() << Column( description ).indent( 4 ) << std::endl; } if ( !testCaseInfo.tags.empty() ) Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n"; } if ( !config.hasTestFilters() ) Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl; else Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl; return matchedTestCases.size(); } std::size_t listTestsNamesOnly( Config const& config ) { TestSpec testSpec = config.testSpec(); std::size_t matchedTests = 0; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for ( auto const& testCaseInfo : matchedTestCases ) { matchedTests++; if ( startsWith( testCaseInfo.name, '#' ) ) Catch::cout() << '"' << testCaseInfo.name << '"'; else Catch::cout() << testCaseInfo.name; if ( config.verbosity() >= Verbosity::High ) Catch::cout() << "\t@" << testCaseInfo.lineInfo; Catch::cout() << std::endl; } return matchedTests; } void TagInfo::add( std::string const& spelling ) { ++count; spellings.insert( spelling ); } std::string TagInfo::all() const { std::string out; for ( auto const& spelling : spellings ) out += "[" + spelling + "]"; return out; } std::size_t listTags( Config const& config ) { TestSpec testSpec = config.testSpec(); if ( config.hasTestFilters() ) Catch::cout() << "Tags for matching test cases:\n"; else { Catch::cout() << "All available tags:\n"; } std::map<std::string, TagInfo> tagCounts; std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for ( auto const& testCase : matchedTestCases ) { for ( auto const& tagName : testCase.getTestCaseInfo().tags ) { std::string lcaseTagName = toLower( tagName ); auto countIt = tagCounts.find( lcaseTagName ); if ( countIt == tagCounts.end() ) countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ) .first; countIt->second.add( tagName ); } } for ( auto const& tagCount : tagCounts ) { ReusableStringStream rss; rss << " " << std::setw( 2 ) << tagCount.second.count << " "; auto str = rss.str(); auto wrapper = Column( tagCount.second.all() ) .initialIndent( 0 ) .indent( str.size() ) .width( CATCH_CONFIG_CONSOLE_WIDTH - 10 ); Catch::cout() << str << wrapper << '\n'; } Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl; return tagCounts.size(); } std::size_t listReporters( Config const& /*config*/ ) { Catch::cout() << "Available reporters:\n"; IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); std::size_t maxNameLen = 0; for ( auto const& factoryKvp : factories ) maxNameLen = ( std::max )( maxNameLen, factoryKvp.first.size() ); for ( auto const& factoryKvp : factories ) { Catch::cout() << Column( factoryKvp.first + ":" ).indent( 2 ).width( 5 + maxNameLen ) + Column( factoryKvp.second->getDescription() ) .initialIndent( 0 ) .indent( 2 ) .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8 ) << "\n"; } Catch::cout() << std::endl; return factories.size(); } Option<std::size_t> list( Config const& config ) { Option<std::size_t> listedCount; if ( config.listTests() ) listedCount = listedCount.valueOr( 0 ) + listTests( config ); if ( config.listTestNamesOnly() ) listedCount = listedCount.valueOr( 0 ) + listTestsNamesOnly( config ); if ( config.listTags() ) listedCount = listedCount.valueOr( 0 ) + listTags( config ); if ( config.listReporters() ) listedCount = listedCount.valueOr( 0 ) + listReporters( config ); return listedCount; } } // end namespace Catch // end catch_list.cpp // start catch_matchers.cpp namespace Catch { namespace Matchers { namespace Impl { std::string MatcherUntypedBase::toString() const { if ( m_cachedToString.empty() ) m_cachedToString = describe(); return m_cachedToString; } MatcherUntypedBase::~MatcherUntypedBase() = default; } // namespace Impl } // namespace Matchers using namespace Matchers; using Matchers::Impl::MatcherBase; } // namespace Catch // end catch_matchers.cpp // start catch_matchers_floating.cpp #include <cstdint> #include <cstdlib> #include <cstring> #include <stdexcept> namespace Catch { namespace Matchers { namespace Floating { enum class FloatingPointKind : uint8_t { Float, Double }; } } } namespace { template <typename T> struct Converter; template <> struct Converter<float> { static_assert( sizeof( float ) == sizeof( int32_t ), "Important ULP matcher assumption violated" ); Converter( float f ) { std::memcpy( &i, &f, sizeof( f ) ); } int32_t i; }; template <> struct Converter<double> { static_assert( sizeof( double ) == sizeof( int64_t ), "Important ULP matcher assumption violated" ); Converter( double d ) { std::memcpy( &i, &d, sizeof( d ) ); } int64_t i; }; template <typename T> auto convert( T t ) -> Converter<T> { return Converter<T>( t ); } template <typename FP> bool almostEqualUlps( FP lhs, FP rhs, int maxUlpDiff ) { // Comparison with NaN should always be false. // This way we can rule it out before getting into the ugly details if ( std::isnan( lhs ) || std::isnan( rhs ) ) { return false; } auto lc = convert( lhs ); auto rc = convert( rhs ); if ( ( lc.i < 0 ) != ( rc.i < 0 ) ) { // Potentially we can have +0 and -0 return lhs == rhs; } auto ulpDiff = std::abs( lc.i - rc.i ); return ulpDiff <= maxUlpDiff; } } namespace Catch { namespace Matchers { namespace Floating { WithinAbsMatcher::WithinAbsMatcher( double target, double margin ) : m_target{ target } , m_margin{ margin } { if ( m_margin < 0 ) { throw std::domain_error( "Allowed margin difference has to be >= 0" ); } } // Performs equivalent check of std::fabs(lhs - rhs) <= margin // But without the subtraction to allow for INFINITY in comparison bool WithinAbsMatcher::match( double const& matchee ) const { return ( matchee + m_margin >= m_target ) && ( m_target + m_margin >= matchee ); } std::string WithinAbsMatcher::describe() const { return "is within " + ::Catch::Detail::stringify( m_margin ) + " of " + ::Catch::Detail::stringify( m_target ); } WithinUlpsMatcher::WithinUlpsMatcher( double target, int ulps, FloatingPointKind baseType ) : m_target{ target } , m_ulps{ ulps } , m_type{ baseType } { if ( m_ulps < 0 ) { throw std::domain_error( "Allowed ulp difference has to be >= 0" ); } } bool WithinUlpsMatcher::match( double const& matchee ) const { switch ( m_type ) { case FloatingPointKind::Float: return almostEqualUlps<float>( static_cast<float>( matchee ), static_cast<float>( m_target ), m_ulps ); case FloatingPointKind::Double: return almostEqualUlps<double>( matchee, m_target, m_ulps ); default: throw std::domain_error( "Unknown FloatingPointKind value" ); } } std::string WithinUlpsMatcher::describe() const { return "is within " + std::to_string( m_ulps ) + " ULPs of " + ::Catch::Detail::stringify( m_target ) + ( ( m_type == FloatingPointKind::Float ) ? "f" : "" ); } } // namespace Floating Floating::WithinUlpsMatcher WithinULP( double target, int maxUlpDiff ) { return Floating::WithinUlpsMatcher( target, maxUlpDiff, Floating::FloatingPointKind::Double ); } Floating::WithinUlpsMatcher WithinULP( float target, int maxUlpDiff ) { return Floating::WithinUlpsMatcher( target, maxUlpDiff, Floating::FloatingPointKind::Float ); } Floating::WithinAbsMatcher WithinAbs( double target, double margin ) { return Floating::WithinAbsMatcher( target, margin ); } } // namespace Matchers } // namespace Catch // end catch_matchers_floating.cpp // start catch_matchers_generic.cpp std::string Catch::Matchers::Generic::Detail::finalizeDescription( const std::string& desc ) { if ( desc.empty() ) { return "matches undescribed predicate"; } else { return "matches predicate: \"" + desc + '"'; } } // end catch_matchers_generic.cpp // start catch_matchers_string.cpp #include <regex> namespace Catch { namespace Matchers { namespace StdString { CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ) , m_str( adjustString( str ) ) { } std::string CasedString::adjustString( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } std::string CasedString::caseSensitivitySuffix() const { return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)" : std::string(); } StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator ) : m_comparator( comparator ) , m_operation( operation ) { } std::string StringMatcherBase::describe() const { std::string description; description.reserve( 5 + m_operation.size() + m_comparator.m_str.size() + m_comparator.caseSensitivitySuffix().size() ); description += m_operation; description += ": \""; description += m_comparator.m_str; description += "\""; description += m_comparator.caseSensitivitySuffix(); return description; } EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) { } bool EqualsMatcher::match( std::string const& source ) const { return m_comparator.adjustString( source ) == m_comparator.m_str; } ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) { } bool ContainsMatcher::match( std::string const& source ) const { return contains( m_comparator.adjustString( source ), m_comparator.m_str ); } StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) { } bool StartsWithMatcher::match( std::string const& source ) const { return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); } EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) { } bool EndsWithMatcher::match( std::string const& source ) const { return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); } RegexMatcher::RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity ) : m_regex( std::move( regex ) ) , m_caseSensitivity( caseSensitivity ) { } bool RegexMatcher::match( std::string const& matchee ) const { auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax // option anyway if ( m_caseSensitivity == CaseSensitive::Choice::No ) { flags |= std::regex::icase; } auto reg = std::regex( m_regex, flags ); return std::regex_match( matchee, reg ); } std::string RegexMatcher::describe() const { return "matches " + ::Catch::Detail::stringify( m_regex ) + ( ( m_caseSensitivity == CaseSensitive::Choice::Yes ) ? " case sensitively" : " case insensitively" ); } } // namespace StdString StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity ) ); } StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity ) ); } StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity ) ); } StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity ) ); } StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity ) { return StdString::RegexMatcher( regex, caseSensitivity ); } } // namespace Matchers } // namespace Catch // end catch_matchers_string.cpp // start catch_message.cpp // start catch_uncaught_exceptions.h namespace Catch { bool uncaught_exceptions(); } // end namespace Catch // end catch_uncaught_exceptions.h namespace Catch { MessageInfo::MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ) : macroName( _macroName ) , lineInfo( _lineInfo ) , type( _type ) , sequence( ++globalCount ) { } bool MessageInfo::operator==( MessageInfo const& other ) const { return sequence == other.sequence; } bool MessageInfo::operator<( MessageInfo const& other ) const { return sequence < other.sequence; } // This may need protecting if threading support is added unsigned int MessageInfo::globalCount = 0; //////////////////////////////////////////////////////////////////////////// Catch::MessageBuilder::MessageBuilder( std::string const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ) : m_info( macroName, lineInfo, type ) { } //////////////////////////////////////////////////////////////////////////// ScopedMessage::ScopedMessage( MessageBuilder const& builder ) : m_info( builder.m_info ) { m_info.message = builder.m_stream.str(); getResultCapture().pushScopedMessage( m_info ); } ScopedMessage::~ScopedMessage() { if ( !uncaught_exceptions() ) { getResultCapture().popScopedMessage( m_info ); } } } // end namespace Catch // end catch_message.cpp // start catch_random_number_generator.cpp // start catch_random_number_generator.h #include <algorithm> namespace Catch { struct IConfig; void seedRng( IConfig const& config ); unsigned int rngSeed(); struct RandomNumberGenerator { using result_type = unsigned int; static constexpr result_type( min )() { return 0; } static constexpr result_type( max )() { return 1000000; } result_type operator()( result_type n ) const; result_type operator()() const; template <typename V> static void shuffle( V& vector ) { RandomNumberGenerator rng; std::shuffle( vector.begin(), vector.end(), rng ); } }; } // end catch_random_number_generator.h #include <cstdlib> namespace Catch { void seedRng( IConfig const& config ) { if ( config.rngSeed() != 0 ) std::srand( config.rngSeed() ); } unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); } RandomNumberGenerator::result_type RandomNumberGenerator:: operator()( result_type n ) const { return std::rand() % n; } RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const { return std::rand() % ( max )(); } } // end catch_random_number_generator.cpp // start catch_registry_hub.cpp // start catch_test_case_registry_impl.h #include <algorithm> #include <ios> #include <set> #include <vector> namespace Catch { class TestCase; struct IConfig; std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ); bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ); std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ); class TestRegistry : public ITestCaseRegistry { public: virtual ~TestRegistry() = default; virtual void registerTest( TestCase const& testCase ); std::vector<TestCase> const& getAllTests() const override; std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override; private: std::vector<TestCase> m_functions; mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder; mutable std::vector<TestCase> m_sortedFunctions; std::size_t m_unnamedCount = 0; std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised }; /////////////////////////////////////////////////////////////////////////// class TestInvokerAsFunction : public ITestInvoker { void ( *m_testAsFunction )(); public: TestInvokerAsFunction( void ( *testAsFunction )() ) noexcept; void invoke() const override; }; std::string extractClassName( StringRef const& classOrQualifiedMethodName ); /////////////////////////////////////////////////////////////////////////// } // end namespace Catch // end catch_test_case_registry_impl.h // start catch_reporter_registry.h #include <map> namespace Catch { class ReporterRegistry : public IReporterRegistry { public: ~ReporterRegistry() override; IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override; void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ); void registerListener( IReporterFactoryPtr const& factory ); FactoryMap const& getFactories() const override; Listeners const& getListeners() const override; private: FactoryMap m_factories; Listeners m_listeners; }; } // end catch_reporter_registry.h // start catch_tag_alias_registry.h // start catch_tag_alias.h #include <string> namespace Catch { struct TagAlias { TagAlias( std::string const& _tag, SourceLineInfo _lineInfo ); std::string tag; SourceLineInfo lineInfo; }; } // end namespace Catch // end catch_tag_alias.h #include <map> namespace Catch { class TagAliasRegistry : public ITagAliasRegistry { public: ~TagAliasRegistry() override; TagAlias const* find( std::string const& alias ) const override; std::string expandAliases( std::string const& unexpandedTestSpec ) const override; void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); private: std::map<std::string, TagAlias> m_registry; }; } // end namespace Catch // end catch_tag_alias_registry.h // start catch_startup_exception_registry.h #include <exception> #include <vector> namespace Catch { class StartupExceptionRegistry { public: void add( std::exception_ptr const& exception ) noexcept; std::vector<std::exception_ptr> const& getExceptions() const noexcept; private: std::vector<std::exception_ptr> m_exceptions; }; } // end namespace Catch // end catch_startup_exception_registry.h namespace Catch { namespace { class RegistryHub : public IRegistryHub, public IMutableRegistryHub, private NonCopyable { public: // IRegistryHub RegistryHub() = default; IReporterRegistry const& getReporterRegistry() const override { return m_reporterRegistry; } ITestCaseRegistry const& getTestCaseRegistry() const override { return m_testCaseRegistry; } IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override { return m_exceptionTranslatorRegistry; } ITagAliasRegistry const& getTagAliasRegistry() const override { return m_tagAliasRegistry; } StartupExceptionRegistry const& getStartupExceptionRegistry() const override { return m_exceptionRegistry; } public: // IMutableRegistryHub void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override { m_reporterRegistry.registerReporter( name, factory ); } void registerListener( IReporterFactoryPtr const& factory ) override { m_reporterRegistry.registerListener( factory ); } void registerTest( TestCase const& testInfo ) override { m_testCaseRegistry.registerTest( testInfo ); } void registerTranslator( const IExceptionTranslator* translator ) override { m_exceptionTranslatorRegistry.registerTranslator( translator ); } void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override { m_tagAliasRegistry.add( alias, tag, lineInfo ); } void registerStartupException() noexcept override { m_exceptionRegistry.add( std::current_exception() ); } private: TestRegistry m_testCaseRegistry; ReporterRegistry m_reporterRegistry; ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; TagAliasRegistry m_tagAliasRegistry; StartupExceptionRegistry m_exceptionRegistry; }; // Single, global, instance RegistryHub*& getTheRegistryHub() { static RegistryHub* theRegistryHub = nullptr; if ( !theRegistryHub ) theRegistryHub = new RegistryHub(); return theRegistryHub; } } IRegistryHub& getRegistryHub() { return *getTheRegistryHub(); } IMutableRegistryHub& getMutableRegistryHub() { return *getTheRegistryHub(); } void cleanUp() { delete getTheRegistryHub(); getTheRegistryHub() = nullptr; cleanUpContext(); ReusableStringStream::cleanup(); } std::string translateActiveException() { return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); } } // end namespace Catch // end catch_registry_hub.cpp // start catch_reporter_registry.cpp namespace Catch { ReporterRegistry::~ReporterRegistry() = default; IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const { auto it = m_factories.find( name ); if ( it == m_factories.end() ) return nullptr; return it->second->create( ReporterConfig( config ) ); } void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) { m_factories.emplace( name, factory ); } void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) { m_listeners.push_back( factory ); } IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const { return m_factories; } IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const { return m_listeners; } } // end catch_reporter_registry.cpp // start catch_result_type.cpp namespace Catch { bool isOk( ResultWas::OfType resultType ) { return ( resultType & ResultWas::FailureBit ) == 0; } bool isJustInfo( int flags ) { return flags == ResultWas::Info; } ResultDisposition::Flags operator|( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) ); } bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } } // end namespace Catch // end catch_result_type.cpp // start catch_run_context.cpp #include <algorithm> #include <cassert> #include <sstream> namespace Catch { class RedirectedStream { std::ostream& m_originalStream; std::ostream& m_redirectionStream; std::streambuf* m_prevBuf; public: RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ) : m_originalStream( originalStream ) , m_redirectionStream( redirectionStream ) , m_prevBuf( m_originalStream.rdbuf() ) { m_originalStream.rdbuf( m_redirectionStream.rdbuf() ); } ~RedirectedStream() { m_originalStream.rdbuf( m_prevBuf ); } }; class RedirectedStdOut { ReusableStringStream m_rss; RedirectedStream m_cout; public: RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) { } auto str() const -> std::string { return m_rss.str(); } }; // StdErr has two constituent streams in C++, std::cerr and std::clog // This means that we need to redirect 2 streams into 1 to keep proper // order of writes class RedirectedStdErr { ReusableStringStream m_rss; RedirectedStream m_cerr; RedirectedStream m_clog; public: RedirectedStdErr() : m_cerr( Catch::cerr(), m_rss.get() ) , m_clog( Catch::clog(), m_rss.get() ) { } auto str() const -> std::string { return m_rss.str(); } }; RunContext::RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter ) : m_runInfo( _config->name() ) , m_context( getCurrentMutableContext() ) , m_config( _config ) , m_reporter( std::move( reporter ) ) , m_lastAssertionInfo{ StringRef(), SourceLineInfo( "", 0 ), StringRef(), ResultDisposition::Normal } , m_includeSuccessfulResults( m_config->includeSuccessfulResults() ) { m_context.setRunner( this ); m_context.setConfig( m_config ); m_context.setResultCapture( this ); m_reporter->testRunStarting( m_runInfo ); } RunContext::~RunContext() { m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); } void RunContext::testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); } void RunContext::testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); } Totals RunContext::runTest( TestCase const& testCase ) { Totals prevTotals = m_totals; std::string redirectedCout; std::string redirectedCerr; auto const& testInfo = testCase.getTestCaseInfo(); m_reporter->testCaseStarting( testInfo ); m_activeTestCase = &testCase; ITracker& rootTracker = m_trackerContext.startRun(); assert( rootTracker.isSectionTracker() ); static_cast<SectionTracker&>( rootTracker ) .addInitialFilters( m_config->getSectionsToRun() ); do { m_trackerContext.startCycle(); m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) ); runCurrentTest( redirectedCout, redirectedCerr ); } while ( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); Totals deltaTotals = m_totals.delta( prevTotals ); if ( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) { deltaTotals.assertions.failed++; deltaTotals.testCases.passed--; deltaTotals.testCases.failed++; } m_totals.testCases += deltaTotals.testCases; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting() ) ); m_activeTestCase = nullptr; m_testCaseTracker = nullptr; return deltaTotals; } IConfigPtr RunContext::config() const { return m_config; } IStreamingReporter& RunContext::reporter() const { return *m_reporter; } void RunContext::assertionEnded( AssertionResult const& result ) { if ( result.getResultType() == ResultWas::Ok ) { m_totals.assertions.passed++; m_lastAssertionPassed = true; } else if ( !result.isOk() ) { m_lastAssertionPassed = false; if ( m_activeTestCase->getTestCaseInfo().okToFail() ) m_totals.assertions.failedButOk++; else m_totals.assertions.failed++; } else { m_lastAssertionPassed = true; } // We have no use for the return value (whether messages should be cleared), because // messages were made scoped // and should be let to clear themselves out. static_cast<void>( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ); // Reset working state resetAssertionInfo(); m_lastResult = result; } void RunContext::resetAssertionInfo() { m_lastAssertionInfo.macroName = StringRef(); m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr; } bool RunContext::sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) { ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) ); if ( !sectionTracker.isOpen() ) return false; m_activeSections.push_back( &sectionTracker ); m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; m_reporter->sectionStarting( sectionInfo ); assertions = m_totals.assertions; return true; } bool RunContext::testForMissingAssertions( Counts& assertions ) { if ( assertions.total() != 0 ) return false; if ( !m_config->warnAboutMissingAssertions() ) return false; if ( m_trackerContext.currentTracker().hasChildren() ) return false; m_totals.assertions.failed++; assertions.failed++; return true; } void RunContext::sectionEnded( SectionEndInfo const& endInfo ) { Counts assertions = m_totals.assertions - endInfo.prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if ( !m_activeSections.empty() ) { m_activeSections.back()->close(); m_activeSections.pop_back(); } m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) ); m_messages.clear(); } void RunContext::sectionEndedEarly( SectionEndInfo const& endInfo ) { if ( m_unfinishedSections.empty() ) m_activeSections.back()->fail(); else m_activeSections.back()->close(); m_activeSections.pop_back(); m_unfinishedSections.push_back( endInfo ); } void RunContext::benchmarkStarting( BenchmarkInfo const& info ) { m_reporter->benchmarkStarting( info ); } void RunContext::benchmarkEnded( BenchmarkStats const& stats ) { m_reporter->benchmarkEnded( stats ); } void RunContext::pushScopedMessage( MessageInfo const& message ) { m_messages.push_back( message ); } void RunContext::popScopedMessage( MessageInfo const& message ) { m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); } std::string RunContext::getCurrentTestName() const { return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string(); } const AssertionResult* RunContext::getLastResult() const { return &( *m_lastResult ); } void RunContext::exceptionEarlyReported() { m_shouldReportUnexpected = false; } void RunContext::handleFatalErrorCondition( StringRef message ) { // First notify reporter that bad things happened m_reporter->fatalErrorEncountered( message ); // Don't rebuild the result -- the stringification itself can cause more fatal errors // Instead, fake a result data. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } ); tempResult.message = message; AssertionResult result( m_lastAssertionInfo, tempResult ); assertionEnded( result ); handleUnfinishedSections(); // Recreate section for test case (as we will lose the one that was in scope) auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); Counts assertions; assertions.failed = 1; SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); m_reporter->sectionEnded( testCaseSectionStats ); auto const& testInfo = m_activeTestCase->getTestCaseInfo(); Totals deltaTotals; deltaTotals.testCases.failed = 1; deltaTotals.assertions.failed = 1; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, std::string(), std::string(), false ) ); m_totals.testCases.failed++; testGroupEnded( std::string(), m_totals, 1, 1 ); m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); } bool RunContext::lastAssertionPassed() { return m_lastAssertionPassed; } void RunContext::assertionPassed() { m_lastAssertionPassed = true; ++m_totals.assertions.passed; resetAssertionInfo(); } bool RunContext::aborting() const { return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() ); } void RunContext::runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); m_reporter->sectionStarting( testCaseSection ); Counts prevAssertions = m_totals.assertions; double duration = 0; m_shouldReportUnexpected = true; m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal }; seedRng( *m_config ); Timer timer; try { if ( m_reporter->getPreferences().shouldRedirectStdOut ) { RedirectedStdOut redirectedStdOut; RedirectedStdErr redirectedStdErr; timer.start(); invokeActiveTestCase(); redirectedCout += redirectedStdOut.str(); redirectedCerr += redirectedStdErr.str(); } else { timer.start(); invokeActiveTestCase(); } duration = timer.getElapsedSeconds(); } catch ( TestFailureException& ) { // This just means the test was aborted due to failure } catch ( ... ) { // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE // assertions // are reported without translation at the point of origin. if ( m_shouldReportUnexpected ) { AssertionReaction dummyReaction; handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction ); } } Counts assertions = m_totals.assertions - prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); m_testCaseTracker->close(); handleUnfinishedSections(); m_messages.clear(); SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); m_reporter->sectionEnded( testCaseSectionStats ); } void RunContext::invokeActiveTestCase() { FatalConditionHandler fatalConditionHandler; // Handle signals m_activeTestCase->invoke(); fatalConditionHandler.reset(); } void RunContext::handleUnfinishedSections() { // If sections ended prematurely due to an exception we stored their // infos here so we can tear them down outside the unwind process. for ( auto it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd; ++it ) sectionEnded( *it ); m_unfinishedSections.clear(); } void RunContext::handleExpr( AssertionInfo const& info, ITransientExpression const& expr, AssertionReaction& reaction ) { m_reporter->assertionStarting( info ); bool negated = isFalseTest( info.resultDisposition ); bool result = expr.getResult() != negated; if ( result ) { if ( !m_includeSuccessfulResults ) { assertionPassed(); } else { reportExpr( info, ResultWas::Ok, &expr, negated ); } } else { reportExpr( info, ResultWas::ExpressionFailed, &expr, negated ); populateReaction( reaction ); } } void RunContext::reportExpr( AssertionInfo const& info, ResultWas::OfType resultType, ITransientExpression const* expr, bool negated ) { m_lastAssertionInfo = info; AssertionResultData data( resultType, LazyExpression( negated ) ); AssertionResult assertionResult{ info, data }; assertionResult.m_resultData.lazyExpression.m_transientExpression = expr; assertionEnded( assertionResult ); } void RunContext::handleMessage( AssertionInfo const& info, ResultWas::OfType resultType, StringRef const& message, AssertionReaction& reaction ) { m_reporter->assertionStarting( info ); m_lastAssertionInfo = info; AssertionResultData data( resultType, LazyExpression( false ) ); data.message = message; AssertionResult assertionResult{ m_lastAssertionInfo, data }; assertionEnded( assertionResult ); if ( !assertionResult.isOk() ) populateReaction( reaction ); } void RunContext::handleUnexpectedExceptionNotThrown( AssertionInfo const& info, AssertionReaction& reaction ) { handleNonExpr( info, Catch::ResultWas::DidntThrowException, reaction ); } void RunContext::handleUnexpectedInflightException( AssertionInfo const& info, std::string const& message, AssertionReaction& reaction ) { m_lastAssertionInfo = info; AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); data.message = message; AssertionResult assertionResult{ info, data }; assertionEnded( assertionResult ); populateReaction( reaction ); } void RunContext::populateReaction( AssertionReaction& reaction ) { reaction.shouldDebugBreak = m_config->shouldDebugBreak(); reaction.shouldThrow = aborting() || ( m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal ); } void RunContext::handleIncomplete( AssertionInfo const& info ) { m_lastAssertionInfo = info; AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; AssertionResult assertionResult{ info, data }; assertionEnded( assertionResult ); } void RunContext::handleNonExpr( AssertionInfo const& info, ResultWas::OfType resultType, AssertionReaction& reaction ) { m_lastAssertionInfo = info; AssertionResultData data( resultType, LazyExpression( false ) ); AssertionResult assertionResult{ info, data }; assertionEnded( assertionResult ); if ( !assertionResult.isOk() ) populateReaction( reaction ); } IResultCapture& getResultCapture() { if ( auto* capture = getCurrentContext().getResultCapture() ) return *capture; else CATCH_INTERNAL_ERROR( "No result capture instance" ); } } // end catch_run_context.cpp // start catch_section.cpp namespace Catch { Section::Section( SectionInfo const& info ) : m_info( info ) , m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) { m_timer.start(); } Section::~Section() { if ( m_sectionIncluded ) { SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() ); if ( uncaught_exceptions() ) getResultCapture().sectionEndedEarly( endInfo ); else getResultCapture().sectionEnded( endInfo ); } } // This indicates whether the section should be executed or not Section::operator bool() const { return m_sectionIncluded; } } // end namespace Catch // end catch_section.cpp // start catch_section_info.cpp namespace Catch { SectionInfo::SectionInfo( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description ) : name( _name ) , description( _description ) , lineInfo( _lineInfo ) { } SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds ) : sectionInfo( _sectionInfo ) , prevAssertions( _prevAssertions ) , durationInSeconds( _durationInSeconds ) { } } // end namespace Catch // end catch_section_info.cpp // start catch_session.cpp // start catch_session.h #include <memory> namespace Catch { class Session : NonCopyable { public: Session(); ~Session() override; void showHelp() const; void libIdentify(); int applyCommandLine( int argc, char const* const* argv ); void useConfigData( ConfigData const& configData ); int run( int argc, char* argv[] ); #if defined( CATCH_CONFIG_WCHAR ) && defined( WIN32 ) && defined( UNICODE ) int run( int argc, wchar_t* const argv[] ); #endif int run(); clara::Parser const& cli() const; void cli( clara::Parser const& newParser ); ConfigData& configData(); Config& config(); private: int runInternal(); clara::Parser m_cli; ConfigData m_configData; std::shared_ptr<Config> m_config; bool m_startupExceptions = false; }; } // end namespace Catch // end catch_session.h // start catch_version.h #include <iosfwd> namespace Catch { // Versioning information struct Version { Version( Version const& ) = delete; Version& operator=( Version const& ) = delete; Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, char const* const _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null char const* const branchName; unsigned int const buildNumber; friend std::ostream& operator<<( std::ostream& os, Version const& version ); }; Version const& libraryVersion(); } // end catch_version.h #include <cstdlib> #include <iomanip> namespace Catch { namespace { const int MaxExitCode = 255; IStreamingReporterPtr createReporter( std::string const& reporterName, IConfigPtr const& config ) { auto reporter = Catch::getRegistryHub().getReporterRegistry().create( reporterName, config ); CATCH_ENFORCE( reporter, "No reporter registered with name: '" << reporterName << "'" ); return reporter; } #ifndef CATCH_CONFIG_DEFAULT_REPORTER #define CATCH_CONFIG_DEFAULT_REPORTER "console" #endif IStreamingReporterPtr makeReporter( std::shared_ptr<Config> const& config ) { auto const& reporterNames = config->getReporterNames(); if ( reporterNames.empty() ) return createReporter( CATCH_CONFIG_DEFAULT_REPORTER, config ); IStreamingReporterPtr reporter; for ( auto const& name : reporterNames ) addReporter( reporter, createReporter( name, config ) ); return reporter; } #undef CATCH_CONFIG_DEFAULT_REPORTER void addListeners( IStreamingReporterPtr& reporters, IConfigPtr const& config ) { auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners(); for ( auto const& listener : listeners ) addReporter( reporters, listener->create( Catch::ReporterConfig( config ) ) ); } Catch::Totals runTests( std::shared_ptr<Config> const& config ) { IStreamingReporterPtr reporter = makeReporter( config ); addListeners( reporter, config ); RunContext context( config, std::move( reporter ) ); Totals totals; context.testGroupStarting( config->name(), 1, 1 ); TestSpec testSpec = config->testSpec(); auto const& allTestCases = getAllTestCasesSorted( *config ); for ( auto const& testCase : allTestCases ) { if ( !context.aborting() && matchTest( testCase, testSpec, *config ) ) totals += context.runTest( testCase ); else context.reporter().skipTest( testCase ); } if ( config->warnAboutNoTests() && totals.testCases.total() == 0 ) { ReusableStringStream testConfig; bool first = true; for ( const auto& input : config->getTestsOrTags() ) { if ( !first ) { testConfig << ' '; } first = false; testConfig << input; } context.reporter().noMatchingTestCases( testConfig.str() ); totals.error = -1; } context.testGroupEnded( config->name(), totals, 1, 1 ); return totals; } void applyFilenamesAsTags( Catch::IConfig const& config ) { auto& tests = const_cast<std::vector<TestCase>&>( getAllTestCasesSorted( config ) ); for ( auto& testCase : tests ) { auto tags = testCase.tags; std::string filename = testCase.lineInfo.file; auto lastSlash = filename.find_last_of( "\\/" ); if ( lastSlash != std::string::npos ) { filename.erase( 0, lastSlash ); filename[0] = '#'; } auto lastDot = filename.find_last_of( '.' ); if ( lastDot != std::string::npos ) { filename.erase( lastDot ); } tags.push_back( std::move( filename ) ); setTags( testCase, tags ); } } } // anon namespace Session::Session() { static bool alreadyInstantiated = false; if ( alreadyInstantiated ) { try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); } catch ( ... ) { getMutableRegistryHub().registerStartupException(); } } const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions(); if ( !exceptions.empty() ) { m_startupExceptions = true; Colour colourGuard( Colour::Red ); Catch::cerr() << "Errors occurred during startup!" << '\n'; // iterate over all exceptions and notify user for ( const auto& ex_ptr : exceptions ) { try { std::rethrow_exception( ex_ptr ); } catch ( std::exception const& ex ) { Catch::cerr() << Column( ex.what() ).indent( 2 ) << '\n'; } } } alreadyInstantiated = true; m_cli = makeCommandLineParser( m_configData ); } Session::~Session() { Catch::cleanUp(); } void Session::showHelp() const { Catch::cout() << "\nCatch v" << libraryVersion() << "\n" << m_cli << std::endl << "For more detailed usage please see the project docs\n" << std::endl; } void Session::libIdentify() { Catch::cout() << std::left << std::setw( 16 ) << "description: " << "A Catch test executable\n" << std::left << std::setw( 16 ) << "category: " << "testframework\n" << std::left << std::setw( 16 ) << "framework: " << "Catch Test\n" << std::left << std::setw( 16 ) << "version: " << libraryVersion() << std::endl; } int Session::applyCommandLine( int argc, char const* const* argv ) { if ( m_startupExceptions ) return 1; auto result = m_cli.parse( clara::Args( argc, argv ) ); if ( !result ) { Catch::cerr() << Colour( Colour::Red ) << "\nError(s) in input:\n" << Column( result.errorMessage() ).indent( 2 ) << "\n\n"; Catch::cerr() << "Run with -? for usage\n" << std::endl; return MaxExitCode; } if ( m_configData.showHelp ) showHelp(); if ( m_configData.libIdentify ) libIdentify(); m_config.reset(); return 0; } void Session::useConfigData( ConfigData const& configData ) { m_configData = configData; m_config.reset(); } int Session::run( int argc, char* argv[] ) { if ( m_startupExceptions ) return 1; int returnCode = applyCommandLine( argc, argv ); if ( returnCode == 0 ) returnCode = run(); return returnCode; } #if defined( CATCH_CONFIG_WCHAR ) && defined( WIN32 ) && defined( UNICODE ) int Session::run( int argc, wchar_t* const argv[] ) { char** utf8Argv = new char*[argc]; for ( int i = 0; i < argc; ++i ) { int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL ); utf8Argv[i] = new char[bufSize]; WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL ); } int returnCode = run( argc, utf8Argv ); for ( int i = 0; i < argc; ++i ) delete[] utf8Argv[i]; delete[] utf8Argv; return returnCode; } #endif int Session::run() { if ( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) { Catch::cout() << "...waiting for enter/ return before starting" << std::endl; static_cast<void>( std::getchar() ); } int exitCode = runInternal(); if ( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) { Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl; static_cast<void>( std::getchar() ); } return exitCode; } clara::Parser const& Session::cli() const { return m_cli; } void Session::cli( clara::Parser const& newParser ) { m_cli = newParser; } ConfigData& Session::configData() { return m_configData; } Config& Session::config() { if ( !m_config ) m_config = std::make_shared<Config>( m_configData ); return *m_config; } int Session::runInternal() { if ( m_startupExceptions ) return 1; if ( m_configData.showHelp || m_configData.libIdentify ) return 0; try { config(); // Force config to be constructed seedRng( *m_config ); if ( m_configData.filenamesAsTags ) applyFilenamesAsTags( *m_config ); // Handle list request if ( Option<std::size_t> listed = list( config() ) ) return static_cast<int>( *listed ); auto totals = runTests( m_config ); // Note that on unices only the lower 8 bits are usually used, clamping // the return value to 255 prevents false negative when some multiple // of 256 tests has failed return ( std::min )( MaxExitCode, ( std::max )( totals.error, static_cast<int>( totals.assertions.failed ) ) ); } catch ( std::exception& ex ) { Catch::cerr() << ex.what() << std::endl; return MaxExitCode; } } } // end namespace Catch // end catch_session.cpp // start catch_startup_exception_registry.cpp namespace Catch { void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept { try { m_exceptions.push_back( exception ); } catch ( ... ) { // If we run out of memory during start-up there's really not a lot more we can // do about it std::terminate(); } } std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept { return m_exceptions; } } // end namespace Catch // end catch_startup_exception_registry.cpp // start catch_stream.cpp #include <cstdio> #include <fstream> #include <iostream> #include <memory> #include <sstream> #include <vector> #if defined( __clang__ ) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" #endif namespace Catch { Catch::IStream::~IStream() = default; namespace detail { namespace { template <typename WriterF, std::size_t bufferSize = 256> class StreamBufImpl : public std::streambuf { char data[bufferSize]; WriterF m_writer; public: StreamBufImpl() { setp( data, data + sizeof( data ) ); } ~StreamBufImpl() noexcept { StreamBufImpl::sync(); } private: int overflow( int c ) override { sync(); if ( c != EOF ) { if ( pbase() == epptr() ) m_writer( std::string( 1, static_cast<char>( c ) ) ); else sputc( static_cast<char>( c ) ); } return 0; } int sync() override { if ( pbase() != pptr() ) { m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) ); setp( pbase(), epptr() ); } return 0; } }; /////////////////////////////////////////////////////////////////////////// struct OutputDebugWriter { void operator()( std::string const& str ) { writeToDebugConsole( str ); } }; /////////////////////////////////////////////////////////////////////////// class FileStream : public IStream { mutable std::ofstream m_ofs; public: FileStream( StringRef filename ) { m_ofs.open( filename.c_str() ); CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" ); } ~FileStream() override = default; public: // IStream std::ostream& stream() const override { return m_ofs; } }; /////////////////////////////////////////////////////////////////////////// class CoutStream : public IStream { mutable std::ostream m_os; public: // Store the streambuf from cout up-front because // cout may get redirected when running tests CoutStream() : m_os( Catch::cout().rdbuf() ) { } ~CoutStream() override = default; public: // IStream std::ostream& stream() const override { return m_os; } }; /////////////////////////////////////////////////////////////////////////// class DebugOutStream : public IStream { std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf; mutable std::ostream m_os; public: DebugOutStream() : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ) , m_os( m_streamBuf.get() ) { } ~DebugOutStream() override = default; public: // IStream std::ostream& stream() const override { return m_os; } }; } } // namespace anon::detail /////////////////////////////////////////////////////////////////////////// auto makeStream( StringRef const& filename ) -> IStream const* { if ( filename.empty() ) return new detail::CoutStream(); else if ( filename[0] == '%' ) { if ( filename == "%debug" ) return new detail::DebugOutStream(); else CATCH_ERROR( "Unrecognised stream: '" << filename << "'" ); } else return new detail::FileStream( filename ); } // This class encapsulates the idea of a pool of ostringstreams that can be reused. struct StringStreams { std::vector<std::unique_ptr<std::ostringstream>> m_streams; std::vector<std::size_t> m_unused; std::ostringstream m_referenceStream; // Used for copy state/ flags from static StringStreams* s_instance; auto add() -> std::size_t { if ( m_unused.empty() ) { m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) ); return m_streams.size() - 1; } else { auto index = m_unused.back(); m_unused.pop_back(); return index; } } void release( std::size_t index ) { m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state m_unused.push_back( index ); } // !TBD: put in TLS static auto instance() -> StringStreams& { if ( !s_instance ) s_instance = new StringStreams(); return *s_instance; } static void cleanup() { delete s_instance; s_instance = nullptr; } }; StringStreams* StringStreams::s_instance = nullptr; void ReusableStringStream::cleanup() { StringStreams::cleanup(); } ReusableStringStream::ReusableStringStream() : m_index( StringStreams::instance().add() ) , m_oss( StringStreams::instance().m_streams[m_index].get() ) { } ReusableStringStream::~ReusableStringStream() { static_cast<std::ostringstream*>( m_oss )->str( "" ); m_oss->clear(); StringStreams::instance().release( m_index ); } auto ReusableStringStream::str() const -> std::string { return static_cast<std::ostringstream*>( m_oss )->str(); } /////////////////////////////////////////////////////////////////////////// #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions std::ostream& cout() { return std::cout; } std::ostream& cerr() { return std::cerr; } std::ostream& clog() { return std::clog; } #endif } #if defined( __clang__ ) #pragma clang diagnostic pop #endif // end catch_stream.cpp // start catch_string_manip.cpp #include <algorithm> #include <cctype> #include <cstring> #include <ostream> namespace Catch { bool startsWith( std::string const& s, std::string const& prefix ) { return s.size() >= prefix.size() && std::equal( prefix.begin(), prefix.end(), s.begin() ); } bool startsWith( std::string const& s, char prefix ) { return !s.empty() && s[0] == prefix; } bool endsWith( std::string const& s, std::string const& suffix ) { return s.size() >= suffix.size() && std::equal( suffix.rbegin(), suffix.rend(), s.rbegin() ); } bool endsWith( std::string const& s, char suffix ) { return !s.empty() && s[s.size() - 1] == suffix; } bool contains( std::string const& s, std::string const& infix ) { return s.find( infix ) != std::string::npos; } char toLowerCh( char c ) { return static_cast<char>( std::tolower( c ) ); } void toLowerInPlace( std::string& s ) { std::transform( s.begin(), s.end(), s.begin(), toLowerCh ); } std::string toLower( std::string const& s ) { std::string lc = s; toLowerInPlace( lc ); return lc; } std::string trim( std::string const& str ) { static char const* whitespaceChars = "\n\r\t "; std::string::size_type start = str.find_first_not_of( whitespaceChars ); std::string::size_type end = str.find_last_not_of( whitespaceChars ); return start != std::string::npos ? str.substr( start, 1 + end - start ) : std::string(); } bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { bool replaced = false; std::size_t i = str.find( replaceThis ); while ( i != std::string::npos ) { replaced = true; str = str.substr( 0, i ) + withThis + str.substr( i + replaceThis.size() ); if ( i < str.size() - withThis.size() ) i = str.find( replaceThis, i + withThis.size() ); else i = std::string::npos; } return replaced; } pluralise::pluralise( std::size_t count, std::string const& label ) : m_count( count ) , m_label( label ) { } std::ostream& operator<<( std::ostream& os, pluralise const& pluraliser ) { os << pluraliser.m_count << ' ' << pluraliser.m_label; if ( pluraliser.m_count != 1 ) os << 's'; return os; } } // end catch_string_manip.cpp // start catch_stringref.cpp #if defined( __clang__ ) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" #endif #include <cstdint> #include <cstring> #include <ostream> namespace { const uint32_t byte_2_lead = 0xC0; const uint32_t byte_3_lead = 0xE0; const uint32_t byte_4_lead = 0xF0; } namespace Catch { StringRef::StringRef( char const* rawChars ) noexcept : StringRef( rawChars, static_cast<StringRef::size_type>( std::strlen( rawChars ) ) ) { } StringRef::operator std::string() const { return std::string( m_start, m_size ); } void StringRef::swap( StringRef& other ) noexcept { std::swap( m_start, other.m_start ); std::swap( m_size, other.m_size ); std::swap( m_data, other.m_data ); } auto StringRef::c_str() const -> char const* { if ( isSubstring() ) const_cast<StringRef*>( this )->takeOwnership(); return m_start; } auto StringRef::currentData() const noexcept -> char const* { return m_start; } auto StringRef::isOwned() const noexcept -> bool { return m_data != nullptr; } auto StringRef::isSubstring() const noexcept -> bool { return m_start[m_size] != '\0'; } void StringRef::takeOwnership() { if ( !isOwned() ) { m_data = new char[m_size + 1]; memcpy( m_data, m_start, m_size ); m_data[m_size] = '\0'; m_start = m_data; } } auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef { if ( start < m_size ) return StringRef( m_start + start, size ); else return StringRef(); } auto StringRef::operator==( StringRef const& other ) const noexcept -> bool { return size() == other.size() && ( std::strncmp( m_start, other.m_start, size() ) == 0 ); } auto StringRef::operator!=( StringRef const& other ) const noexcept -> bool { return !operator==( other ); } auto StringRef::operator[]( size_type index ) const noexcept -> char { return m_start[index]; } auto StringRef::numberOfCharacters() const noexcept -> size_type { size_type noChars = m_size; // Make adjustments for uft encodings for ( size_type i = 0; i < m_size; ++i ) { char c = m_start[i]; if ( ( c & byte_2_lead ) == byte_2_lead ) { noChars--; if ( ( c & byte_3_lead ) == byte_3_lead ) noChars--; if ( ( c & byte_4_lead ) == byte_4_lead ) noChars--; } } return noChars; } auto operator+( StringRef const& lhs, StringRef const& rhs ) -> std::string { std::string str; str.reserve( lhs.size() + rhs.size() ); str += lhs; str += rhs; return str; } auto operator+( StringRef const& lhs, const char* rhs ) -> std::string { return std::string( lhs ) + std::string( rhs ); } auto operator+( char const* lhs, StringRef const& rhs ) -> std::string { return std::string( lhs ) + std::string( rhs ); } auto operator<<( std::ostream& os, StringRef const& str ) -> std::ostream& { return os.write( str.currentData(), str.size() ); } auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& { lhs.append( rhs.currentData(), rhs.size() ); return lhs; } } // namespace Catch #if defined( __clang__ ) #pragma clang diagnostic pop #endif // end catch_stringref.cpp // start catch_tag_alias.cpp namespace Catch { TagAlias::TagAlias( std::string const& _tag, SourceLineInfo _lineInfo ) : tag( _tag ) , lineInfo( _lineInfo ) { } } // end catch_tag_alias.cpp // start catch_tag_alias_autoregistrar.cpp namespace Catch { RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { try { getMutableRegistryHub().registerTagAlias( alias, tag, lineInfo ); } catch ( ... ) { // Do not throw when constructing global objects, instead register the exception // to be processed later getMutableRegistryHub().registerStartupException(); } } } // end catch_tag_alias_autoregistrar.cpp // start catch_tag_alias_registry.cpp #include <sstream> namespace Catch { TagAliasRegistry::~TagAliasRegistry() {} TagAlias const* TagAliasRegistry::find( std::string const& alias ) const { auto it = m_registry.find( alias ); if ( it != m_registry.end() ) return &( it->second ); else return nullptr; } std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { std::string expandedTestSpec = unexpandedTestSpec; for ( auto const& registryKvp : m_registry ) { std::size_t pos = expandedTestSpec.find( registryKvp.first ); if ( pos != std::string::npos ) { expandedTestSpec = expandedTestSpec.substr( 0, pos ) + registryKvp.second.tag + expandedTestSpec.substr( pos + registryKvp.first.size() ); } } return expandedTestSpec; } void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { CATCH_ENFORCE( startsWith( alias, "[@" ) && endsWith( alias, ']' ), "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo ); CATCH_ENFORCE( m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second, "error: tag alias, '" << alias << "' already registered.\n" << "\tFirst seen at: " << find( alias )->lineInfo << "\n" << "\tRedefined at: " << lineInfo ); } ITagAliasRegistry::~ITagAliasRegistry() {} ITagAliasRegistry const& ITagAliasRegistry::get() { return getRegistryHub().getTagAliasRegistry(); } } // end namespace Catch // end catch_tag_alias_registry.cpp // start catch_test_case_info.cpp #include <algorithm> #include <cctype> #include <exception> #include <sstream> namespace Catch { TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { if ( startsWith( tag, '.' ) || tag == "!hide" ) return TestCaseInfo::IsHidden; else if ( tag == "!throws" ) return TestCaseInfo::Throws; else if ( tag == "!shouldfail" ) return TestCaseInfo::ShouldFail; else if ( tag == "!mayfail" ) return TestCaseInfo::MayFail; else if ( tag == "!nonportable" ) return TestCaseInfo::NonPortable; else if ( tag == "!benchmark" ) return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden ); else return TestCaseInfo::None; } bool isReservedTag( std::string const& tag ) { return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] ); } void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { CATCH_ENFORCE( !isReservedTag( tag ), "Tag name: [" << tag << "] is not allowed.\n" << "Tag names starting with non alpha-numeric characters are reserved\n" << _lineInfo ); } TestCase makeTestCase( ITestInvoker* _testCase, std::string const& _className, NameAndTags const& nameAndTags, SourceLineInfo const& _lineInfo ) { bool isHidden = false; // Parse out tags std::vector<std::string> tags; std::string desc, tag; bool inTag = false; std::string _descOrTags = nameAndTags.tags; for ( char c : _descOrTags ) { if ( !inTag ) { if ( c == '[' ) inTag = true; else desc += c; } else { if ( c == ']' ) { TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); if ( ( prop & TestCaseInfo::IsHidden ) != 0 ) isHidden = true; else if ( prop == TestCaseInfo::None ) enforceNotReservedTag( tag, _lineInfo ); tags.push_back( tag ); tag.clear(); inTag = false; } else tag += c; } } if ( isHidden ) { tags.push_back( "." ); } TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo ); return TestCase( _testCase, std::move( info ) ); } void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) { std::sort( begin( tags ), end( tags ) ); tags.erase( std::unique( begin( tags ), end( tags ) ), end( tags ) ); testCaseInfo.lcaseTags.clear(); for ( auto const& tag : tags ) { std::string lcaseTag = toLower( tag ); testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); testCaseInfo.lcaseTags.push_back( lcaseTag ); } testCaseInfo.tags = std::move( tags ); } TestCaseInfo::TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::vector<std::string> const& _tags, SourceLineInfo const& _lineInfo ) : name( _name ) , className( _className ) , description( _description ) , lineInfo( _lineInfo ) , properties( None ) { setTags( *this, _tags ); } bool TestCaseInfo::isHidden() const { return ( properties & IsHidden ) != 0; } bool TestCaseInfo::throws() const { return ( properties & Throws ) != 0; } bool TestCaseInfo::okToFail() const { return ( properties & ( ShouldFail | MayFail ) ) != 0; } bool TestCaseInfo::expectedToFail() const { return ( properties & ( ShouldFail ) ) != 0; } std::string TestCaseInfo::tagsAsString() const { std::string ret; // '[' and ']' per tag std::size_t full_size = 2 * tags.size(); for ( const auto& tag : tags ) { full_size += tag.size(); } ret.reserve( full_size ); for ( const auto& tag : tags ) { ret.push_back( '[' ); ret.append( tag ); ret.push_back( ']' ); } return ret; } TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move( info ) ) , test( testCase ) { } TestCase TestCase::withName( std::string const& _newName ) const { TestCase other( *this ); other.name = _newName; return other; } void TestCase::invoke() const { test->invoke(); } bool TestCase::operator==( TestCase const& other ) const { return test.get() == other.test.get() && name == other.name && className == other.className; } bool TestCase::operator<( TestCase const& other ) const { return name < other.name; } TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; } } // end namespace Catch // end catch_test_case_info.cpp // start catch_test_case_registry_impl.cpp #include <sstream> namespace Catch { std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) { std::vector<TestCase> sorted = unsortedTestCases; switch ( config.runOrder() ) { case RunTests::InLexicographicalOrder: std::sort( sorted.begin(), sorted.end() ); break; case RunTests::InRandomOrder: seedRng( config ); RandomNumberGenerator::shuffle( sorted ); break; case RunTests::InDeclarationOrder: // already in declaration order break; } return sorted; } bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); } void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) { std::set<TestCase> seenFunctions; for ( auto const& function : functions ) { auto prev = seenFunctions.insert( function ); CATCH_ENFORCE( prev.second, "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n" << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" << "\tRedefined at " << function.getTestCaseInfo().lineInfo ); } } std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) { std::vector<TestCase> filtered; filtered.reserve( testCases.size() ); for ( auto const& testCase : testCases ) if ( matchTest( testCase, testSpec, config ) ) filtered.push_back( testCase ); return filtered; } std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) { return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); } void TestRegistry::registerTest( TestCase const& testCase ) { std::string name = testCase.getTestCaseInfo().name; if ( name.empty() ) { ReusableStringStream rss; rss << "Anonymous test case " << ++m_unnamedCount; return registerTest( testCase.withName( rss.str() ) ); } m_functions.push_back( testCase ); } std::vector<TestCase> const& TestRegistry::getAllTests() const { return m_functions; } std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const { if ( m_sortedFunctions.empty() ) enforceNoDuplicateTestCases( m_functions ); if ( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { m_sortedFunctions = sortTests( config, m_functions ); m_currentSortOrder = config.runOrder(); } return m_sortedFunctions; } /////////////////////////////////////////////////////////////////////////// TestInvokerAsFunction::TestInvokerAsFunction( void ( *testAsFunction )() ) noexcept : m_testAsFunction( testAsFunction ) { } void TestInvokerAsFunction::invoke() const { m_testAsFunction(); } std::string extractClassName( StringRef const& classOrQualifiedMethodName ) { std::string className = classOrQualifiedMethodName; if ( startsWith( className, '&' ) ) { std::size_t lastColons = className.rfind( "::" ); std::size_t penultimateColons = className.rfind( "::", lastColons - 1 ); if ( penultimateColons == std::string::npos ) penultimateColons = 1; className = className.substr( penultimateColons, lastColons - penultimateColons ); } return className; } } // end namespace Catch // end catch_test_case_registry_impl.cpp // start catch_test_case_tracker.cpp #include <assert.h> #include <algorithm> #include <memory> #include <sstream> #include <stdexcept> #if defined( __clang__ ) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" #endif namespace Catch { namespace TestCaseTracking { NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location ) : name( _name ) , location( _location ) { } ITracker::~ITracker() = default; TrackerContext& TrackerContext::instance() { static TrackerContext s_instance; return s_instance; } ITracker& TrackerContext::startRun() { m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr ); m_currentTracker = nullptr; m_runState = Executing; return *m_rootTracker; } void TrackerContext::endRun() { m_rootTracker.reset(); m_currentTracker = nullptr; m_runState = NotStarted; } void TrackerContext::startCycle() { m_currentTracker = m_rootTracker.get(); m_runState = Executing; } void TrackerContext::completeCycle() { m_runState = CompletedCycle; } bool TrackerContext::completedCycle() const { return m_runState == CompletedCycle; } ITracker& TrackerContext::currentTracker() { return *m_currentTracker; } void TrackerContext::setCurrentTracker( ITracker* tracker ) { m_currentTracker = tracker; } TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) { } bool TrackerBase::TrackerHasName::operator()( ITrackerPtr const& tracker ) const { return tracker->nameAndLocation().name == m_nameAndLocation.name && tracker->nameAndLocation().location == m_nameAndLocation.location; } TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) : m_nameAndLocation( nameAndLocation ) , m_ctx( ctx ) , m_parent( parent ) { } NameAndLocation const& TrackerBase::nameAndLocation() const { return m_nameAndLocation; } bool TrackerBase::isComplete() const { return m_runState == CompletedSuccessfully || m_runState == Failed; } bool TrackerBase::isSuccessfullyCompleted() const { return m_runState == CompletedSuccessfully; } bool TrackerBase::isOpen() const { return m_runState != NotStarted && !isComplete(); } bool TrackerBase::hasChildren() const { return !m_children.empty(); } void TrackerBase::addChild( ITrackerPtr const& child ) { m_children.push_back( child ); } ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) { auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) ); return ( it != m_children.end() ) ? *it : nullptr; } ITracker& TrackerBase::parent() { assert( m_parent ); // Should always be non-null except for root return *m_parent; } void TrackerBase::openChild() { if ( m_runState != ExecutingChildren ) { m_runState = ExecutingChildren; if ( m_parent ) m_parent->openChild(); } } bool TrackerBase::isSectionTracker() const { return false; } bool TrackerBase::isIndexTracker() const { return false; } void TrackerBase::open() { m_runState = Executing; moveToThis(); if ( m_parent ) m_parent->openChild(); } void TrackerBase::close() { // Close any still open children (e.g. generators) while ( &m_ctx.currentTracker() != this ) m_ctx.currentTracker().close(); switch ( m_runState ) { case NeedsAnotherRun: break; case Executing: m_runState = CompletedSuccessfully; break; case ExecutingChildren: if ( m_children.empty() || m_children.back()->isComplete() ) m_runState = CompletedSuccessfully; break; case NotStarted: case CompletedSuccessfully: case Failed: CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState ); default: CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState ); } moveToParent(); m_ctx.completeCycle(); } void TrackerBase::fail() { m_runState = Failed; if ( m_parent ) m_parent->markAsNeedingAnotherRun(); moveToParent(); m_ctx.completeCycle(); } void TrackerBase::markAsNeedingAnotherRun() { m_runState = NeedsAnotherRun; } void TrackerBase::moveToParent() { assert( m_parent ); m_ctx.setCurrentTracker( m_parent ); } void TrackerBase::moveToThis() { m_ctx.setCurrentTracker( this ); } SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) : TrackerBase( nameAndLocation, ctx, parent ) { if ( parent ) { while ( !parent->isSectionTracker() ) parent = &parent->parent(); SectionTracker& parentSection = static_cast<SectionTracker&>( *parent ); addNextFilters( parentSection.m_filters ); } } bool SectionTracker::isSectionTracker() const { return true; } SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) { std::shared_ptr<SectionTracker> section; ITracker& currentTracker = ctx.currentTracker(); if ( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { assert( childTracker ); assert( childTracker->isSectionTracker() ); section = std::static_pointer_cast<SectionTracker>( childTracker ); } else { section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker ); currentTracker.addChild( section ); } if ( !ctx.completedCycle() ) section->tryOpen(); return *section; } void SectionTracker::tryOpen() { if ( !isComplete() && ( m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) ) open(); } void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) { if ( !filters.empty() ) { m_filters.push_back( "" ); // Root - should never be consulted m_filters.push_back( "" ); // Test Case - not a section filter m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); } } void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) { if ( filters.size() > 1 ) m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() ); } IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size ) : TrackerBase( nameAndLocation, ctx, parent ) , m_size( size ) { } bool IndexTracker::isIndexTracker() const { return true; } IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) { std::shared_ptr<IndexTracker> tracker; ITracker& currentTracker = ctx.currentTracker(); if ( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { assert( childTracker ); assert( childTracker->isIndexTracker() ); tracker = std::static_pointer_cast<IndexTracker>( childTracker ); } else { tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size ); currentTracker.addChild( tracker ); } if ( !ctx.completedCycle() && !tracker->isComplete() ) { if ( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun ) tracker->moveNext(); tracker->open(); } return *tracker; } int IndexTracker::index() const { return m_index; } void IndexTracker::moveNext() { m_index++; m_children.clear(); } void IndexTracker::close() { TrackerBase::close(); if ( m_runState == CompletedSuccessfully && m_index < m_size - 1 ) m_runState = Executing; } } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; using TestCaseTracking::IndexTracker; } // namespace Catch #if defined( __clang__ ) #pragma clang diagnostic pop #endif // end catch_test_case_tracker.cpp // start catch_test_registry.cpp namespace Catch { auto makeTestInvoker( void ( *testAsFunction )() ) noexcept -> ITestInvoker* { return new ( std::nothrow ) TestInvokerAsFunction( testAsFunction ); } NameAndTags::NameAndTags( StringRef const& name_, StringRef const& tags_ ) noexcept : name( name_ ) , tags( tags_ ) { } AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept { try { getMutableRegistryHub().registerTest( makeTestCase( invoker, extractClassName( classOrMethod ), nameAndTags, lineInfo ) ); } catch ( ... ) { // Do not throw when constructing global objects, instead register the exception // to be processed later getMutableRegistryHub().registerStartupException(); } } AutoReg::~AutoReg() = default; } // end catch_test_registry.cpp // start catch_test_spec.cpp #include <algorithm> #include <memory> #include <string> #include <vector> namespace Catch { TestSpec::Pattern::~Pattern() = default; TestSpec::NamePattern::~NamePattern() = default; TestSpec::TagPattern::~TagPattern() = default; TestSpec::ExcludedPattern::~ExcludedPattern() = default; TestSpec::NamePattern::NamePattern( std::string const& name ) : m_wildcardPattern( toLower( name ), CaseSensitive::No ) { } bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const { return m_wildcardPattern.matches( toLower( testCase.name ) ); } TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) { } bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const { return std::find( begin( testCase.lcaseTags ), end( testCase.lcaseTags ), m_tag ) != end( testCase.lcaseTags ); } TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) { } bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const { // All patterns in a filter must match for the filter to be a match for ( auto const& pattern : m_patterns ) { if ( !pattern->matches( testCase ) ) return false; } return true; } bool TestSpec::hasFilters() const { return !m_filters.empty(); } bool TestSpec::matches( TestCaseInfo const& testCase ) const { // A TestSpec matches if any filter matches for ( auto const& filter : m_filters ) if ( filter.matches( testCase ) ) return true; return false; } } // end catch_test_spec.cpp // start catch_test_spec_parser.cpp namespace Catch { TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) { } TestSpecParser& TestSpecParser::parse( std::string const& arg ) { m_mode = None; m_exclusion = false; m_start = std::string::npos; m_arg = m_tagAliases->expandAliases( arg ); m_escapeChars.clear(); for ( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) visitChar( m_arg[m_pos] ); if ( m_mode == Name ) addPattern<TestSpec::NamePattern>(); return *this; } TestSpec TestSpecParser::testSpec() { addFilter(); return m_testSpec; } void TestSpecParser::visitChar( char c ) { if ( m_mode == None ) { switch ( c ) { case ' ': return; case '~': m_exclusion = true; return; case '[': return startNewMode( Tag, ++m_pos ); case '"': return startNewMode( QuotedName, ++m_pos ); case '\\': return escape(); default: startNewMode( Name, m_pos ); break; } } if ( m_mode == Name ) { if ( c == ',' ) { addPattern<TestSpec::NamePattern>(); addFilter(); } else if ( c == '[' ) { if ( subString() == "exclude:" ) m_exclusion = true; else addPattern<TestSpec::NamePattern>(); startNewMode( Tag, ++m_pos ); } else if ( c == '\\' ) escape(); } else if ( m_mode == EscapedName ) m_mode = Name; else if ( m_mode == QuotedName && c == '"' ) addPattern<TestSpec::NamePattern>(); else if ( m_mode == Tag && c == ']' ) addPattern<TestSpec::TagPattern>(); } void TestSpecParser::startNewMode( Mode mode, std::size_t start ) { m_mode = mode; m_start = start; } void TestSpecParser::escape() { if ( m_mode == None ) m_start = m_pos; m_mode = EscapedName; m_escapeChars.push_back( m_pos ); } std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); } void TestSpecParser::addFilter() { if ( !m_currentFilter.m_patterns.empty() ) { m_testSpec.m_filters.push_back( m_currentFilter ); m_currentFilter = TestSpec::Filter(); } } TestSpec parseTestSpec( std::string const& arg ) { return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); } } // namespace Catch // end catch_test_spec_parser.cpp // start catch_timer.cpp #include <chrono> static const uint64_t nanosecondsInSecond = 1000000000; namespace Catch { auto getCurrentNanosecondsSinceEpoch() -> uint64_t { return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ) .count(); } auto estimateClockResolution() -> uint64_t { uint64_t sum = 0; static const uint64_t iterations = 1000000; auto startTime = getCurrentNanosecondsSinceEpoch(); for ( std::size_t i = 0; i < iterations; ++i ) { uint64_t ticks; uint64_t baseTicks = getCurrentNanosecondsSinceEpoch(); do { ticks = getCurrentNanosecondsSinceEpoch(); } while ( ticks == baseTicks ); auto delta = ticks - baseTicks; sum += delta; // If we have been calibrating for over 3 seconds -- the clock // is terrible and we should move on. // TBD: How to signal that the measured resolution is probably wrong? if ( ticks > startTime + 3 * nanosecondsInSecond ) { return sum / i; } } // We're just taking the mean, here. To do better we could take the std. dev and // exclude outliers // - and potentially do more iterations if there's a high variance. return sum / iterations; } auto getEstimatedClockResolution() -> uint64_t { static auto s_resolution = estimateClockResolution(); return s_resolution; } void Timer::start() { m_nanoseconds = getCurrentNanosecondsSinceEpoch(); } auto Timer::getElapsedNanoseconds() const -> uint64_t { return getCurrentNanosecondsSinceEpoch() - m_nanoseconds; } auto Timer::getElapsedMicroseconds() const -> uint64_t { return getElapsedNanoseconds() / 1000; } auto Timer::getElapsedMilliseconds() const -> unsigned int { return static_cast<unsigned int>( getElapsedMicroseconds() / 1000 ); } auto Timer::getElapsedSeconds() const -> double { return getElapsedMicroseconds() / 1000000.0; } } // namespace Catch // end catch_timer.cpp // start catch_tostring.cpp #if defined( __clang__ ) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wglobal-constructors" #endif // Enable specific decls locally #if !defined( CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER ) #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER #endif #include <cmath> #include <iomanip> namespace Catch { namespace Detail { const std::string unprintableString = "{?}"; namespace { const int hexThreshold = 255; struct Endianness { enum Arch { Big, Little }; static Arch which() { union _ { int asInt; char asChar[sizeof( int )]; } u; u.asInt = 1; return ( u.asChar[sizeof( int ) - 1] == 1 ) ? Big : Little; } }; } std::string rawMemoryToString( const void* object, std::size_t size ) { // Reverse order for little endian architectures int i = 0, end = static_cast<int>( size ), inc = 1; if ( Endianness::which() == Endianness::Little ) { i = end - 1; end = inc = -1; } unsigned char const* bytes = static_cast<unsigned char const*>( object ); ReusableStringStream rss; rss << "0x" << std::setfill( '0' ) << std::hex; for ( ; i != end; i += inc ) rss << std::setw( 2 ) << static_cast<unsigned>( bytes[i] ); return rss.str(); } } template <typename T> std::string fpToString( T value, int precision ) { if ( std::isnan( value ) ) { return "nan"; } ReusableStringStream rss; rss << std::setprecision( precision ) << std::fixed << value; std::string d = rss.str(); std::size_t i = d.find_last_not_of( '0' ); if ( i != std::string::npos && i != d.size() - 1 ) { if ( d[i] == '.' ) i++; d = d.substr( 0, i + 1 ); } return d; } //// ======================================================= //// // // Out-of-line defs for full specialization of StringMaker // //// ======================================================= //// std::string StringMaker<std::string>::convert( const std::string& str ) { if ( !getCurrentContext().getConfig()->showInvisibles() ) { return '"' + str + '"'; } std::string s( "\"" ); for ( char c : str ) { switch ( c ) { case '\n': s.append( "\\n" ); break; case '\t': s.append( "\\t" ); break; default: s.push_back( c ); break; } } s.append( "\"" ); return s; } #ifdef CATCH_CONFIG_WCHAR std::string StringMaker<std::wstring>::convert( const std::wstring& wstr ) { std::string s; s.reserve( wstr.size() ); for ( auto c : wstr ) { s += ( c <= 0xff ) ? static_cast<char>( c ) : '?'; } return ::Catch::Detail::stringify( s ); } #endif std::string StringMaker<char const*>::convert( char const* str ) { if ( str ) { return ::Catch::Detail::stringify( std::string{ str } ); } else { return { "{null string}" }; } } std::string StringMaker<char*>::convert( char* str ) { if ( str ) { return ::Catch::Detail::stringify( std::string{ str } ); } else { return { "{null string}" }; } } #ifdef CATCH_CONFIG_WCHAR std::string StringMaker<wchar_t const*>::convert( wchar_t const* str ) { if ( str ) { return ::Catch::Detail::stringify( std::wstring{ str } ); } else { return { "{null string}" }; } } std::string StringMaker<wchar_t*>::convert( wchar_t* str ) { if ( str ) { return ::Catch::Detail::stringify( std::wstring{ str } ); } else { return { "{null string}" }; } } #endif std::string StringMaker<int>::convert( int value ) { return ::Catch::Detail::stringify( static_cast<long long>( value ) ); } std::string StringMaker<long>::convert( long value ) { return ::Catch::Detail::stringify( static_cast<long long>( value ) ); } std::string StringMaker<long long>::convert( long long value ) { ReusableStringStream rss; rss << value; if ( value > Detail::hexThreshold ) { rss << " (0x" << std::hex << value << ')'; } return rss.str(); } std::string StringMaker<unsigned int>::convert( unsigned int value ) { return ::Catch::Detail::stringify( static_cast<unsigned long long>( value ) ); } std::string StringMaker<unsigned long>::convert( unsigned long value ) { return ::Catch::Detail::stringify( static_cast<unsigned long long>( value ) ); } std::string StringMaker<unsigned long long>::convert( unsigned long long value ) { ReusableStringStream rss; rss << value; if ( value > Detail::hexThreshold ) { rss << " (0x" << std::hex << value << ')'; } return rss.str(); } std::string StringMaker<bool>::convert( bool b ) { return b ? "true" : "false"; } std::string StringMaker<char>::convert( char value ) { if ( value == '\r' ) { return "'\\r'"; } else if ( value == '\f' ) { return "'\\f'"; } else if ( value == '\n' ) { return "'\\n'"; } else if ( value == '\t' ) { return "'\\t'"; } else if ( '\0' <= value && value < ' ' ) { return ::Catch::Detail::stringify( static_cast<unsigned int>( value ) ); } else { char chstr[] = "' '"; chstr[1] = value; return chstr; } } std::string StringMaker<signed char>::convert( signed char c ) { return ::Catch::Detail::stringify( static_cast<char>( c ) ); } std::string StringMaker<unsigned char>::convert( unsigned char c ) { return ::Catch::Detail::stringify( static_cast<char>( c ) ); } std::string StringMaker<std::nullptr_t>::convert( std::nullptr_t ) { return "nullptr"; } std::string StringMaker<float>::convert( float value ) { return fpToString( value, 5 ) + 'f'; } std::string StringMaker<double>::convert( double value ) { return fpToString( value, 10 ); } std::string ratio_string<std::atto>::symbol() { return "a"; } std::string ratio_string<std::femto>::symbol() { return "f"; } std::string ratio_string<std::pico>::symbol() { return "p"; } std::string ratio_string<std::nano>::symbol() { return "n"; } std::string ratio_string<std::micro>::symbol() { return "u"; } std::string ratio_string<std::milli>::symbol() { return "m"; } } // end namespace Catch #if defined( __clang__ ) #pragma clang diagnostic pop #endif // end catch_tostring.cpp // start catch_totals.cpp namespace Catch { Counts Counts::operator-( Counts const& other ) const { Counts diff; diff.passed = passed - other.passed; diff.failed = failed - other.failed; diff.failedButOk = failedButOk - other.failedButOk; return diff; } Counts& Counts::operator+=( Counts const& other ) { passed += other.passed; failed += other.failed; failedButOk += other.failedButOk; return *this; } std::size_t Counts::total() const { return passed + failed + failedButOk; } bool Counts::allPassed() const { return failed == 0 && failedButOk == 0; } bool Counts::allOk() const { return failed == 0; } Totals Totals::operator-( Totals const& other ) const { Totals diff; diff.assertions = assertions - other.assertions; diff.testCases = testCases - other.testCases; return diff; } Totals& Totals::operator+=( Totals const& other ) { assertions += other.assertions; testCases += other.testCases; return *this; } Totals Totals::delta( Totals const& prevTotals ) const { Totals diff = *this - prevTotals; if ( diff.assertions.failed > 0 ) ++diff.testCases.failed; else if ( diff.assertions.failedButOk > 0 ) ++diff.testCases.failedButOk; else ++diff.testCases.passed; return diff; } } // end catch_totals.cpp // start catch_uncaught_exceptions.cpp #include <exception> namespace Catch { bool uncaught_exceptions() { #if defined( CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS ) return std::uncaught_exceptions() > 0; #else return std::uncaught_exception(); #endif } } // end namespace Catch // end catch_uncaught_exceptions.cpp // start catch_version.cpp #include <ostream> namespace Catch { Version::Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, char const* const _branchName, unsigned int _buildNumber ) : majorVersion( _majorVersion ) , minorVersion( _minorVersion ) , patchNumber( _patchNumber ) , branchName( _branchName ) , buildNumber( _buildNumber ) { } std::ostream& operator<<( std::ostream& os, Version const& version ) { os << version.majorVersion << '.' << version.minorVersion << '.' << version.patchNumber; // branchName is never null -> 0th char is \0 if it is empty if ( version.branchName[0] ) { os << '-' << version.branchName << '.' << version.buildNumber; } return os; } Version const& libraryVersion() { static Version version( 2, 2, 2, "", 0 ); return version; } } // end catch_version.cpp // start catch_wildcard_pattern.cpp #include <sstream> namespace Catch { WildcardPattern::WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ) , m_pattern( adjustCase( pattern ) ) { if ( startsWith( m_pattern, '*' ) ) { m_pattern = m_pattern.substr( 1 ); m_wildcard = WildcardAtStart; } if ( endsWith( m_pattern, '*' ) ) { m_pattern = m_pattern.substr( 0, m_pattern.size() - 1 ); m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd ); } } bool WildcardPattern::matches( std::string const& str ) const { switch ( m_wildcard ) { case NoWildcard: return m_pattern == adjustCase( str ); case WildcardAtStart: return endsWith( adjustCase( str ), m_pattern ); case WildcardAtEnd: return startsWith( adjustCase( str ), m_pattern ); case WildcardAtBothEnds: return contains( adjustCase( str ), m_pattern ); default: CATCH_INTERNAL_ERROR( "Unknown enum" ); } } std::string WildcardPattern::adjustCase( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } } // end catch_wildcard_pattern.cpp // start catch_xmlwriter.cpp #include <iomanip> using uchar = unsigned char; namespace Catch { namespace { size_t trailingBytes( unsigned char c ) { if ( ( c & 0xE0 ) == 0xC0 ) { return 2; } if ( ( c & 0xF0 ) == 0xE0 ) { return 3; } if ( ( c & 0xF8 ) == 0xF0 ) { return 4; } CATCH_INTERNAL_ERROR( "Invalid multibyte utf-8 start byte encountered" ); } uint32_t headerValue( unsigned char c ) { if ( ( c & 0xE0 ) == 0xC0 ) { return c & 0x1F; } if ( ( c & 0xF0 ) == 0xE0 ) { return c & 0x0F; } if ( ( c & 0xF8 ) == 0xF0 ) { return c & 0x07; } CATCH_INTERNAL_ERROR( "Invalid multibyte utf-8 start byte encountered" ); } void hexEscapeChar( std::ostream& os, unsigned char c ) { os << "\\x" << std::uppercase << std::hex << std::setfill( '0' ) << std::setw( 2 ) << static_cast<int>( c ); } } // anonymous namespace XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) : m_str( str ) , m_forWhat( forWhat ) { } void XmlEncode::encodeTo( std::ostream& os ) const { // Apostrophe escaping not necessary if we always use " to write attributes // (see: http://www.w3.org/TR/xml/#syntax) for ( std::size_t idx = 0; idx < m_str.size(); ++idx ) { uchar c = m_str[idx]; switch ( c ) { case '<': os << "&lt;"; break; case '&': os << "&amp;"; break; case '>': // See: http://www.w3.org/TR/xml/#syntax if ( idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']' ) os << "&gt;"; else os << c; break; case '\"': if ( m_forWhat == ForAttributes ) os << "&quot;"; else os << c; break; default: // Check for control characters and invalid utf-8 // Escape control characters in standard ascii // see // http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 if ( c < 0x09 || ( c > 0x0D && c < 0x20 ) || c == 0x7F ) { hexEscapeChar( os, c ); break; } // Plain ASCII: Write it to stream if ( c < 0x7F ) { os << c; break; } // UTF-8 territory // Check if the encoding is valid and if it is not, hex escape bytes. // Important: We do not check the exact decoded values for validity, only the // encoding format // First check that this bytes is a valid lead byte: // This means that it is not encoded as 1111 1XXX // Or as 10XX XXXX if ( c < 0xC0 || c >= 0xF8 ) { hexEscapeChar( os, c ); break; } auto encBytes = trailingBytes( c ); // Are there enough bytes left to avoid accessing out-of-bounds memory? if ( idx + encBytes - 1 >= m_str.size() ) { hexEscapeChar( os, c ); break; } // The header is valid, check data // The next encBytes bytes must together be a valid utf-8 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) bool valid = true; uint32_t value = headerValue( c ); for ( std::size_t n = 1; n < encBytes; ++n ) { uchar nc = m_str[idx + n]; valid &= ( ( nc & 0xC0 ) == 0x80 ); value = ( value << 6 ) | ( nc & 0x3F ); } if ( // Wrong bit pattern of following bytes ( !valid ) || // Overlong encodings ( value < 0x80 ) || ( 0x80 <= value && value < 0x800 && encBytes > 2 ) || ( 0x800 < value && value < 0x10000 && encBytes > 3 ) || // Encoded value out of range ( value >= 0x110000 ) ) { hexEscapeChar( os, c ); break; } // If we got here, this is in fact a valid(ish) utf-8 sequence for ( std::size_t n = 0; n < encBytes; ++n ) { os << m_str[idx + n]; } idx += encBytes - 1; break; } } } std::ostream& operator<<( std::ostream& os, XmlEncode const& xmlEncode ) { xmlEncode.encodeTo( os ); return os; } XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) : m_writer( writer ) { } XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept : m_writer( other.m_writer ) { other.m_writer = nullptr; } XmlWriter::ScopedElement& XmlWriter::ScopedElement:: operator=( ScopedElement&& other ) noexcept { if ( m_writer ) { m_writer->endElement(); } m_writer = other.m_writer; other.m_writer = nullptr; return *this; } XmlWriter::ScopedElement::~ScopedElement() { if ( m_writer ) m_writer->endElement(); } XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { m_writer->writeText( text, indent ); return *this; } XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) { writeDeclaration(); } XmlWriter::~XmlWriter() { while ( !m_tags.empty() ) endElement(); } XmlWriter& XmlWriter::startElement( std::string const& name ) { ensureTagClosed(); newlineIfNecessary(); m_os << m_indent << '<' << name; m_tags.push_back( name ); m_indent += " "; m_tagIsOpen = true; return *this; } XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { ScopedElement scoped( this ); startElement( name ); return scoped; } XmlWriter& XmlWriter::endElement() { newlineIfNecessary(); m_indent = m_indent.substr( 0, m_indent.size() - 2 ); if ( m_tagIsOpen ) { m_os << "/>"; m_tagIsOpen = false; } else { m_os << m_indent << "</" << m_tags.back() << ">"; } m_os << std::endl; m_tags.pop_back(); return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { if ( !name.empty() && !attribute.empty() ) m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; return *this; } XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { if ( !text.empty() ) { bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if ( tagWasOpen && indent ) m_os << m_indent; m_os << XmlEncode( text ); m_needsNewline = true; } return *this; } XmlWriter& XmlWriter::writeComment( std::string const& text ) { ensureTagClosed(); m_os << m_indent << "<!--" << text << "-->"; m_needsNewline = true; return *this; } void XmlWriter::writeStylesheetRef( std::string const& url ) { m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n"; } XmlWriter& XmlWriter::writeBlankLine() { ensureTagClosed(); m_os << '\n'; return *this; } void XmlWriter::ensureTagClosed() { if ( m_tagIsOpen ) { m_os << ">" << std::endl; m_tagIsOpen = false; } } void XmlWriter::writeDeclaration() { m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; } void XmlWriter::newlineIfNecessary() { if ( m_needsNewline ) { m_os << std::endl; m_needsNewline = false; } } } // end catch_xmlwriter.cpp // start catch_reporter_bases.cpp #include <assert.h> #include <cfloat> #include <cstdio> #include <cstring> #include <memory> namespace Catch { void prepareExpandedExpression( AssertionResult& result ) { result.getExpandedExpression(); } // Because formatting using c++ streams is stateful, drop down to C is required // Alternatively we could use stringstream, but its performance is... not good. std::string getFormattedDuration( double duration ) { // Max exponent + 1 is required to represent the whole part // + 1 for decimal point // + 3 for the 3 decimal places // + 1 for null terminator const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; char buffer[maxDoubleSize]; // Save previous errno, to prevent sprintf from overwriting it ErrnoGuard guard; #ifdef _MSC_VER sprintf_s( buffer, "%.3f", duration ); #else sprintf( buffer, "%.3f", duration ); #endif return std::string( buffer ); } TestEventListenerBase::TestEventListenerBase( ReporterConfig const& _config ) : StreamingReporterBase( _config ) { } void TestEventListenerBase::assertionStarting( AssertionInfo const& ) {} bool TestEventListenerBase::assertionEnded( AssertionStats const& ) { return false; } } // end namespace Catch // end catch_reporter_bases.cpp // start catch_reporter_compact.cpp namespace { #ifdef CATCH_PLATFORM_MAC const char* failedString() { return "FAILED"; } const char* passedString() { return "PASSED"; } #else const char* failedString() { return "failed"; } const char* passedString() { return "passed"; } #endif // Colour::LightGrey Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } std::string bothOrAll( std::size_t count ) { return count == 1 ? std::string() : count == 2 ? "both " : "all "; } } // anon namespace namespace Catch { namespace { // Colour, message variants: // - white: No tests ran. // - red: Failed [both/all] N test cases, failed [both/all] M assertions. // - white: Passed [both/all] N test cases (no assertions). // - red: Failed N tests cases, failed M assertions. // - green: Passed [both/all] N tests cases with M assertions. void printTotals( std::ostream& out, const Totals& totals ) { if ( totals.testCases.total() == 0 ) { out << "No tests ran."; } else if ( totals.testCases.failed == totals.testCases.total() ) { Colour colour( Colour::ResultError ); const std::string qualify_assertions_failed = totals.assertions.failed == totals.assertions.total() ? bothOrAll( totals.assertions.failed ) : std::string(); out << "Failed " << bothOrAll( totals.testCases.failed ) << pluralise( totals.testCases.failed, "test case" ) << ", " "failed " << qualify_assertions_failed << pluralise( totals.assertions.failed, "assertion" ) << '.'; } else if ( totals.assertions.total() == 0 ) { out << "Passed " << bothOrAll( totals.testCases.total() ) << pluralise( totals.testCases.total(), "test case" ) << " (no assertions)."; } else if ( totals.assertions.failed ) { Colour colour( Colour::ResultError ); out << "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.'; } else { Colour colour( Colour::ResultSuccess ); out << "Passed " << bothOrAll( totals.testCases.passed ) << pluralise( totals.testCases.passed, "test case" ) << " with " << pluralise( totals.assertions.passed, "assertion" ) << '.'; } } // Implementation of CompactReporter formatting class AssertionPrinter { public: AssertionPrinter& operator=( AssertionPrinter const& ) = delete; AssertionPrinter( AssertionPrinter const& ) = delete; AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ) , result( _stats.assertionResult ) , messages( _stats.infoMessages ) , itMessage( _stats.infoMessages.begin() ) , printInfoMessages( _printInfoMessages ) { } void print() { printSourceInfo(); itMessage = messages.begin(); switch ( result.getResultType() ) { case ResultWas::Ok: printResultType( Colour::ResultSuccess, passedString() ); printOriginalExpression(); printReconstructedExpression(); if ( !result.hasExpression() ) printRemainingMessages( Colour::None ); else printRemainingMessages(); break; case ResultWas::ExpressionFailed: if ( result.isOk() ) printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) ); else printResultType( Colour::Error, failedString() ); printOriginalExpression(); printReconstructedExpression(); printRemainingMessages(); break; case ResultWas::ThrewException: printResultType( Colour::Error, failedString() ); printIssue( "unexpected exception with message:" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::FatalErrorCondition: printResultType( Colour::Error, failedString() ); printIssue( "fatal error condition with message:" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::DidntThrowException: printResultType( Colour::Error, failedString() ); printIssue( "expected exception, got none" ); printExpressionWas(); printRemainingMessages(); break; case ResultWas::Info: printResultType( Colour::None, "info" ); printMessage(); printRemainingMessages(); break; case ResultWas::Warning: printResultType( Colour::None, "warning" ); printMessage(); printRemainingMessages(); break; case ResultWas::ExplicitFailure: printResultType( Colour::Error, failedString() ); printIssue( "explicitly" ); printRemainingMessages( Colour::None ); break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: printResultType( Colour::Error, "** internal error **" ); break; } } private: void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << ':'; } void printResultType( Colour::Code colour, std::string const& passOrFail ) const { if ( !passOrFail.empty() ) { { Colour colourGuard( colour ); stream << ' ' << passOrFail; } stream << ':'; } } void printIssue( std::string const& issue ) const { stream << ' ' << issue; } void printExpressionWas() { if ( result.hasExpression() ) { stream << ';'; { Colour colour( dimColour() ); stream << " expression was:"; } printOriginalExpression(); } } void printOriginalExpression() const { if ( result.hasExpression() ) { stream << ' ' << result.getExpression(); } } void printReconstructedExpression() const { if ( result.hasExpandedExpression() ) { { Colour colour( dimColour() ); stream << " for: "; } stream << result.getExpandedExpression(); } } void printMessage() { if ( itMessage != messages.end() ) { stream << " '" << itMessage->message << '\''; ++itMessage; } } void printRemainingMessages( Colour::Code colour = dimColour() ) { if ( itMessage == messages.end() ) return; // using messages.end() directly yields (or auto) compilation error: std::vector<MessageInfo>::const_iterator itEnd = messages.end(); const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) ); { Colour colourGuard( colour ); stream << " with " << pluralise( N, "message" ) << ':'; } for ( ; itMessage != itEnd; ) { // If this assertion is a warning ignore any INFO messages if ( printInfoMessages || itMessage->type != ResultWas::Info ) { stream << " '" << itMessage->message << '\''; if ( ++itMessage != itEnd ) { Colour colourGuard( dimColour() ); stream << " and"; } } } } private: std::ostream& stream; AssertionResult const& result; std::vector<MessageInfo> messages; std::vector<MessageInfo>::const_iterator itMessage; bool printInfoMessages; }; } // anon namespace std::string CompactReporter::getDescription() { return "Reports test results on a single line, suitable for IDEs"; } ReporterPreferences CompactReporter::getPreferences() const { ReporterPreferences prefs; prefs.shouldRedirectStdOut = false; return prefs; } void CompactReporter::noMatchingTestCases( std::string const& spec ) { stream << "No test cases matched '" << spec << '\'' << std::endl; } void CompactReporter::assertionStarting( AssertionInfo const& ) {} bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if ( !m_config->includeSuccessfulResults() && result.isOk() ) { if ( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } void CompactReporter::sectionEnded( SectionStats const& _sectionStats ) { if ( m_config->showDurations() == ShowDurations::Always ) { stream << getFormattedDuration( _sectionStats.durationInSeconds ) << " s: " << _sectionStats.sectionInfo.name << std::endl; } } void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) { printTotals( stream, _testRunStats.totals ); stream << '\n' << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } CompactReporter::~CompactReporter() {} CATCH_REGISTER_REPORTER( "compact", CompactReporter ) } // end namespace Catch // end catch_reporter_compact.cpp // start catch_reporter_console.cpp #include <cfloat> #include <cstdio> #if defined( _MSC_VER ) #pragma warning( push ) #pragma warning( disable : 4061 ) // Not all labels are EXPLICITLY handled in switch // Note that 4062 (not all labels are handled // and default is missing) is enabled #endif namespace Catch { namespace { // Formatter impl for ConsoleReporter class ConsoleAssertionPrinter { public: ConsoleAssertionPrinter& operator=( ConsoleAssertionPrinter const& ) = delete; ConsoleAssertionPrinter( ConsoleAssertionPrinter const& ) = delete; ConsoleAssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ) , stats( _stats ) , result( _stats.assertionResult ) , colour( Colour::None ) , message( result.getMessage() ) , messages( _stats.infoMessages ) , printInfoMessages( _printInfoMessages ) { switch ( result.getResultType() ) { case ResultWas::Ok: colour = Colour::Success; passOrFail = "PASSED"; // if( result.hasMessage() ) if ( _stats.infoMessages.size() == 1 ) messageLabel = "with message"; if ( _stats.infoMessages.size() > 1 ) messageLabel = "with messages"; break; case ResultWas::ExpressionFailed: if ( result.isOk() ) { colour = Colour::Success; passOrFail = "FAILED - but was ok"; } else { colour = Colour::Error; passOrFail = "FAILED"; } if ( _stats.infoMessages.size() == 1 ) messageLabel = "with message"; if ( _stats.infoMessages.size() > 1 ) messageLabel = "with messages"; break; case ResultWas::ThrewException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to unexpected exception with "; if ( _stats.infoMessages.size() == 1 ) messageLabel += "message"; if ( _stats.infoMessages.size() > 1 ) messageLabel += "messages"; break; case ResultWas::FatalErrorCondition: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "due to a fatal error condition"; break; case ResultWas::DidntThrowException: colour = Colour::Error; passOrFail = "FAILED"; messageLabel = "because no exception was thrown where one was expected"; break; case ResultWas::Info: messageLabel = "info"; break; case ResultWas::Warning: messageLabel = "warning"; break; case ResultWas::ExplicitFailure: passOrFail = "FAILED"; colour = Colour::Error; if ( _stats.infoMessages.size() == 1 ) messageLabel = "explicitly with message"; if ( _stats.infoMessages.size() > 1 ) messageLabel = "explicitly with messages"; break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: passOrFail = "** internal error **"; colour = Colour::Error; break; } } void print() const { printSourceInfo(); if ( stats.totals.assertions.total() > 0 ) { if ( result.isOk() ) stream << '\n'; printResultType(); printOriginalExpression(); printReconstructedExpression(); } else { stream << '\n'; } printMessage(); } private: void printResultType() const { if ( !passOrFail.empty() ) { Colour colourGuard( colour ); stream << passOrFail << ":\n"; } } void printOriginalExpression() const { if ( result.hasExpression() ) { Colour colourGuard( Colour::OriginalExpression ); stream << " "; stream << result.getExpressionInMacro(); stream << '\n'; } } void printReconstructedExpression() const { if ( result.hasExpandedExpression() ) { stream << "with expansion:\n"; Colour colourGuard( Colour::ReconstructedExpression ); stream << Column( result.getExpandedExpression() ).indent( 2 ) << '\n'; } } void printMessage() const { if ( !messageLabel.empty() ) stream << messageLabel << ':' << '\n'; for ( auto const& msg : messages ) { // If this assertion is a warning ignore any INFO messages if ( printInfoMessages || msg.type != ResultWas::Info ) stream << Column( msg.message ).indent( 2 ) << '\n'; } } void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << ": "; } std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; Colour::Code colour; std::string passOrFail; std::string messageLabel; std::string message; std::vector<MessageInfo> messages; bool printInfoMessages; }; std::size_t makeRatio( std::size_t number, std::size_t total ) { std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; return ( ratio == 0 && number > 0 ) ? 1 : ratio; } std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { if ( i > j && i > k ) return i; else if ( j > k ) return j; else return k; } struct ColumnInfo { enum Justification { Left, Right }; std::string name; int width; Justification justification; }; struct ColumnBreak { }; struct RowBreak { }; class Duration { enum class Unit { Auto, Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes }; static const uint64_t s_nanosecondsInAMicrosecond = 1000; static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond; static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond; static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond; uint64_t m_inNanoseconds; Unit m_units; public: explicit Duration( uint64_t inNanoseconds, Unit units = Unit::Auto ) : m_inNanoseconds( inNanoseconds ) , m_units( units ) { if ( m_units == Unit::Auto ) { if ( m_inNanoseconds < s_nanosecondsInAMicrosecond ) m_units = Unit::Nanoseconds; else if ( m_inNanoseconds < s_nanosecondsInAMillisecond ) m_units = Unit::Microseconds; else if ( m_inNanoseconds < s_nanosecondsInASecond ) m_units = Unit::Milliseconds; else if ( m_inNanoseconds < s_nanosecondsInAMinute ) m_units = Unit::Seconds; else m_units = Unit::Minutes; } } auto value() const -> double { switch ( m_units ) { case Unit::Microseconds: return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMicrosecond ); case Unit::Milliseconds: return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMillisecond ); case Unit::Seconds: return m_inNanoseconds / static_cast<double>( s_nanosecondsInASecond ); case Unit::Minutes: return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMinute ); default: return static_cast<double>( m_inNanoseconds ); } } auto unitsAsString() const -> std::string { switch ( m_units ) { case Unit::Nanoseconds: return "ns"; case Unit::Microseconds: return "µs"; case Unit::Milliseconds: return "ms"; case Unit::Seconds: return "s"; case Unit::Minutes: return "m"; default: return "** internal error **"; } } friend auto operator<<( std::ostream& os, Duration const& duration ) -> std::ostream& { return os << duration.value() << " " << duration.unitsAsString(); } }; } // end anon namespace class TablePrinter { std::ostream& m_os; std::vector<ColumnInfo> m_columnInfos; std::ostringstream m_oss; int m_currentColumn = -1; bool m_isOpen = false; public: TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos ) : m_os( os ) , m_columnInfos( std::move( columnInfos ) ) { } auto columnInfos() const -> std::vector<ColumnInfo> const& { return m_columnInfos; } void open() { if ( !m_isOpen ) { m_isOpen = true; *this << RowBreak(); for ( auto const& info : m_columnInfos ) *this << info.name << ColumnBreak(); *this << RowBreak(); m_os << Catch::getLineOfChars<'-'>() << "\n"; } } void close() { if ( m_isOpen ) { *this << RowBreak(); m_os << std::endl; m_isOpen = false; } } template <typename T> friend TablePrinter& operator<<( TablePrinter& tp, T const& value ) { tp.m_oss << value; return tp; } friend TablePrinter& operator<<( TablePrinter& tp, ColumnBreak ) { auto colStr = tp.m_oss.str(); // This takes account of utf8 encodings auto strSize = Catch::StringRef( colStr ).numberOfCharacters(); tp.m_oss.str( "" ); tp.open(); if ( tp.m_currentColumn == static_cast<int>( tp.m_columnInfos.size() - 1 ) ) { tp.m_currentColumn = -1; tp.m_os << "\n"; } tp.m_currentColumn++; auto colInfo = tp.m_columnInfos[tp.m_currentColumn]; auto padding = ( strSize + 2 < static_cast<std::size_t>( colInfo.width ) ) ? std::string( colInfo.width - ( strSize + 2 ), ' ' ) : std::string(); if ( colInfo.justification == ColumnInfo::Left ) tp.m_os << colStr << padding << " "; else tp.m_os << padding << colStr << " "; return tp; } friend TablePrinter& operator<<( TablePrinter& tp, RowBreak ) { if ( tp.m_currentColumn > 0 ) { tp.m_os << "\n"; tp.m_currentColumn = -1; } return tp; } }; ConsoleReporter::ConsoleReporter( ReporterConfig const& config ) : StreamingReporterBase( config ) , m_tablePrinter( new TablePrinter( config.stream(), { { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left }, { "iters", 8, ColumnInfo::Right }, { "elapsed ns", 14, ColumnInfo::Right }, { "average", 14, ColumnInfo::Right } } ) ) { } ConsoleReporter::~ConsoleReporter() = default; std::string ConsoleReporter::getDescription() { return "Reports test results as plain lines of text"; } void ConsoleReporter::noMatchingTestCases( std::string const& spec ) { stream << "No test cases matched '" << spec << '\'' << std::endl; } void ConsoleReporter::assertionStarting( AssertionInfo const& ) {} bool ConsoleReporter::assertionEnded( AssertionStats const& _assertionStats ) { AssertionResult const& result = _assertionStats.assertionResult; bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); // Drop out if result was successful but we're not printing them. if ( !includeResults && result.getResultType() != ResultWas::Warning ) return false; lazyPrint(); ConsoleAssertionPrinter printer( stream, _assertionStats, includeResults ); printer.print(); stream << std::endl; return true; } void ConsoleReporter::sectionStarting( SectionInfo const& _sectionInfo ) { m_headerPrinted = false; StreamingReporterBase::sectionStarting( _sectionInfo ); } void ConsoleReporter::sectionEnded( SectionStats const& _sectionStats ) { m_tablePrinter->close(); if ( _sectionStats.missingAssertions ) { lazyPrint(); Colour colour( Colour::ResultError ); if ( m_sectionStack.size() > 1 ) stream << "\nNo assertions in section"; else stream << "\nNo assertions in test case"; stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; } if ( m_config->showDurations() == ShowDurations::Always ) { stream << getFormattedDuration( _sectionStats.durationInSeconds ) << " s: " << _sectionStats.sectionInfo.name << std::endl; } if ( m_headerPrinted ) { m_headerPrinted = false; } StreamingReporterBase::sectionEnded( _sectionStats ); } void ConsoleReporter::benchmarkStarting( BenchmarkInfo const& info ) { lazyPrintWithoutClosingBenchmarkTable(); auto nameCol = Column( info.name ) .width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) ); bool firstLine = true; for ( auto line : nameCol ) { if ( !firstLine ) ( *m_tablePrinter ) << ColumnBreak() << ColumnBreak() << ColumnBreak(); else firstLine = false; ( *m_tablePrinter ) << line << ColumnBreak(); } } void ConsoleReporter::benchmarkEnded( BenchmarkStats const& stats ) { Duration average( stats.elapsedTimeInNanoseconds / stats.iterations ); ( *m_tablePrinter ) << stats.iterations << ColumnBreak() << stats.elapsedTimeInNanoseconds << ColumnBreak() << average << ColumnBreak(); } void ConsoleReporter::testCaseEnded( TestCaseStats const& _testCaseStats ) { m_tablePrinter->close(); StreamingReporterBase::testCaseEnded( _testCaseStats ); m_headerPrinted = false; } void ConsoleReporter::testGroupEnded( TestGroupStats const& _testGroupStats ) { if ( currentGroupInfo.used ) { printSummaryDivider(); stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; printTotals( _testGroupStats.totals ); stream << '\n' << std::endl; } StreamingReporterBase::testGroupEnded( _testGroupStats ); } void ConsoleReporter::testRunEnded( TestRunStats const& _testRunStats ) { printTotalsDivider( _testRunStats.totals ); printTotals( _testRunStats.totals ); stream << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } void ConsoleReporter::lazyPrint() { m_tablePrinter->close(); lazyPrintWithoutClosingBenchmarkTable(); } void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() { if ( !currentTestRunInfo.used ) lazyPrintRunInfo(); if ( !currentGroupInfo.used ) lazyPrintGroupInfo(); if ( !m_headerPrinted ) { printTestCaseAndSectionHeader(); m_headerPrinted = true; } } void ConsoleReporter::lazyPrintRunInfo() { stream << '\n' << getLineOfChars<'~'>() << '\n'; Colour colour( Colour::SecondaryText ); stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion() << " host application.\n" << "Run with -? for options\n\n"; if ( m_config->rngSeed() != 0 ) stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; currentTestRunInfo.used = true; } void ConsoleReporter::lazyPrintGroupInfo() { if ( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { printClosedHeader( "Group: " + currentGroupInfo->name ); currentGroupInfo.used = true; } } void ConsoleReporter::printTestCaseAndSectionHeader() { assert( !m_sectionStack.empty() ); printOpenHeader( currentTestCaseInfo->name ); if ( m_sectionStack.size() > 1 ) { Colour colourGuard( Colour::Headers ); auto it = m_sectionStack.begin() + 1, // Skip first section (test case) itEnd = m_sectionStack.end(); for ( ; it != itEnd; ++it ) printHeaderString( it->name, 2 ); } SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; if ( !lineInfo.empty() ) { stream << getLineOfChars<'-'>() << '\n'; Colour colourGuard( Colour::FileName ); stream << lineInfo << '\n'; } stream << getLineOfChars<'.'>() << '\n' << std::endl; } void ConsoleReporter::printClosedHeader( std::string const& _name ) { printOpenHeader( _name ); stream << getLineOfChars<'.'>() << '\n'; } void ConsoleReporter::printOpenHeader( std::string const& _name ) { stream << getLineOfChars<'-'>() << '\n'; { Colour colourGuard( Colour::Headers ); printHeaderString( _name ); } } // if string has a : in first line will set indent to follow it on // subsequent lines void ConsoleReporter::printHeaderString( std::string const& _string, std::size_t indent ) { std::size_t i = _string.find( ": " ); if ( i != std::string::npos ) i += 2; else i = 0; stream << Column( _string ).indent( indent + i ).initialIndent( indent ) << '\n'; } struct SummaryColumn { SummaryColumn( std::string _label, Colour::Code _colour ) : label( std::move( _label ) ) , colour( _colour ) { } SummaryColumn addRow( std::size_t count ) { ReusableStringStream rss; rss << count; std::string row = rss.str(); for ( auto& oldRow : rows ) { while ( oldRow.size() < row.size() ) oldRow = ' ' + oldRow; while ( oldRow.size() > row.size() ) row = ' ' + row; } rows.push_back( row ); return *this; } std::string label; Colour::Code colour; std::vector<std::string> rows; }; void ConsoleReporter::printTotals( Totals const& totals ) { if ( totals.testCases.total() == 0 ) { stream << Colour( Colour::Warning ) << "No tests ran\n"; } else if ( totals.assertions.total() > 0 && totals.testCases.allPassed() ) { stream << Colour( Colour::ResultSuccess ) << "All tests passed"; stream << " (" << pluralise( totals.assertions.passed, "assertion" ) << " in " << pluralise( totals.testCases.passed, "test case" ) << ')' << '\n'; } else { std::vector<SummaryColumn> columns; columns.push_back( SummaryColumn( "", Colour::None ) .addRow( totals.testCases.total() ) .addRow( totals.assertions.total() ) ); columns.push_back( SummaryColumn( "passed", Colour::Success ) .addRow( totals.testCases.passed ) .addRow( totals.assertions.passed ) ); columns.push_back( SummaryColumn( "failed", Colour::ResultError ) .addRow( totals.testCases.failed ) .addRow( totals.assertions.failed ) ); columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) .addRow( totals.testCases.failedButOk ) .addRow( totals.assertions.failedButOk ) ); printSummaryRow( "test cases", columns, 0 ); printSummaryRow( "assertions", columns, 1 ); } } void ConsoleReporter::printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) { for ( auto col : cols ) { std::string value = col.rows[row]; if ( col.label.empty() ) { stream << label << ": "; if ( value != "0" ) stream << value; else stream << Colour( Colour::Warning ) << "- none -"; } else if ( value != "0" ) { stream << Colour( Colour::LightGrey ) << " | "; stream << Colour( col.colour ) << value << ' ' << col.label; } } stream << '\n'; } void ConsoleReporter::printTotalsDivider( Totals const& totals ) { if ( totals.testCases.total() > 0 ) { std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); while ( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1 ) findMax( failedRatio, failedButOkRatio, passedRatio )++; while ( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1 ) findMax( failedRatio, failedButOkRatio, passedRatio )--; stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); if ( totals.testCases.allPassed() ) stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); else stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); } else { stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH - 1, '=' ); } stream << '\n'; } void ConsoleReporter::printSummaryDivider() { stream << getLineOfChars<'-'>() << '\n'; } CATCH_REGISTER_REPORTER( "console", ConsoleReporter ) } // end namespace Catch #if defined( _MSC_VER ) #pragma warning( pop ) #endif // end catch_reporter_console.cpp // start catch_reporter_junit.cpp #include <assert.h> #include <algorithm> #include <ctime> #include <sstream> namespace Catch { namespace { std::string getCurrentTimestamp() { // Beware, this is not reentrant because of backward compatibility issues // Also, UTC only, again because of backward compatibility (%z is C++11) time_t rawtime; std::time( &rawtime ); auto const timeStampSize = sizeof( "2017-01-16T17:06:45Z" ); #ifdef _MSC_VER std::tm timeInfo = {}; gmtime_s( &timeInfo, &rawtime ); #else std::tm* timeInfo; timeInfo = std::gmtime( &rawtime ); #endif char timeStamp[timeStampSize]; const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; #ifdef _MSC_VER std::strftime( timeStamp, timeStampSize, fmt, &timeInfo ); #else std::strftime( timeStamp, timeStampSize, fmt, timeInfo ); #endif return std::string( timeStamp ); } std::string fileNameTag( const std::vector<std::string>& tags ) { auto it = std::find_if( begin( tags ), end( tags ), []( std::string const& tag ) { return tag.front() == '#'; } ); if ( it != tags.end() ) return it->substr( 1 ); return std::string(); } } // anonymous namespace JunitReporter::JunitReporter( ReporterConfig const& _config ) : CumulativeReporterBase( _config ) , xml( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = true; } JunitReporter::~JunitReporter() {} std::string JunitReporter::getDescription() { return "Reports test results in an XML format that looks like Ant's junitreport " "target"; } void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {} void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) { CumulativeReporterBase::testRunStarting( runInfo ); xml.startElement( "testsuites" ); } void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) { suiteTimer.start(); stdOutForSuite.clear(); stdErrForSuite.clear(); unexpectedExceptions = 0; CumulativeReporterBase::testGroupStarting( groupInfo ); } void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) { m_okToFail = testCaseInfo.okToFail(); } bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) { if ( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) unexpectedExceptions++; return CumulativeReporterBase::assertionEnded( assertionStats ); } void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { stdOutForSuite += testCaseStats.stdOut; stdErrForSuite += testCaseStats.stdErr; CumulativeReporterBase::testCaseEnded( testCaseStats ); } void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { double suiteTime = suiteTimer.getElapsedSeconds(); CumulativeReporterBase::testGroupEnded( testGroupStats ); writeGroup( *m_testGroups.back(), suiteTime ); } void JunitReporter::testRunEndedCumulative() { xml.endElement(); } void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) { XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); TestGroupStats const& stats = groupNode.value; xml.writeAttribute( "name", stats.groupInfo.name ); xml.writeAttribute( "errors", unexpectedExceptions ); xml.writeAttribute( "failures", stats.totals.assertions.failed - unexpectedExceptions ); xml.writeAttribute( "tests", stats.totals.assertions.total() ); xml.writeAttribute( "hostname", "tbd" ); // !TBD if ( m_config->showDurations() == ShowDurations::Never ) xml.writeAttribute( "time", "" ); else xml.writeAttribute( "time", suiteTime ); xml.writeAttribute( "timestamp", getCurrentTimestamp() ); // Write test cases for ( auto const& child : groupNode.children ) writeTestCase( *child ); xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false ); xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false ); } void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) { TestCaseStats const& stats = testCaseNode.value; // All test cases have exactly one section - which represents the // test case itself. That section may have 0-n nested sections assert( testCaseNode.children.size() == 1 ); SectionNode const& rootSection = *testCaseNode.children.front(); std::string className = stats.testInfo.className; if ( className.empty() ) { className = fileNameTag( stats.testInfo.tags ); if ( className.empty() ) className = "global"; } if ( !m_config->name().empty() ) className = m_config->name() + "." + className; writeSection( className, "", rootSection ); } void JunitReporter::writeSection( std::string const& className, std::string const& rootName, SectionNode const& sectionNode ) { std::string name = trim( sectionNode.stats.sectionInfo.name ); if ( !rootName.empty() ) name = rootName + '/' + name; if ( !sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty() ) { XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); if ( className.empty() ) { xml.writeAttribute( "classname", name ); xml.writeAttribute( "name", "root" ); } else { xml.writeAttribute( "classname", className ); xml.writeAttribute( "name", name ); } xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) ); writeAssertions( sectionNode ); if ( !sectionNode.stdOut.empty() ) xml.scopedElement( "system-out" ) .writeText( trim( sectionNode.stdOut ), false ); if ( !sectionNode.stdErr.empty() ) xml.scopedElement( "system-err" ) .writeText( trim( sectionNode.stdErr ), false ); } for ( auto const& childNode : sectionNode.childSections ) if ( className.empty() ) writeSection( name, "", *childNode ); else writeSection( className, name, *childNode ); } void JunitReporter::writeAssertions( SectionNode const& sectionNode ) { for ( auto const& assertion : sectionNode.assertions ) writeAssertion( assertion ); } void JunitReporter::writeAssertion( AssertionStats const& stats ) { AssertionResult const& result = stats.assertionResult; if ( !result.isOk() ) { std::string elementName; switch ( result.getResultType() ) { case ResultWas::ThrewException: case ResultWas::FatalErrorCondition: elementName = "error"; break; case ResultWas::ExplicitFailure: elementName = "failure"; break; case ResultWas::ExpressionFailed: elementName = "failure"; break; case ResultWas::DidntThrowException: elementName = "failure"; break; // We should never see these here: case ResultWas::Info: case ResultWas::Warning: case ResultWas::Ok: case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: elementName = "internalError"; break; } XmlWriter::ScopedElement e = xml.scopedElement( elementName ); xml.writeAttribute( "message", result.getExpandedExpression() ); xml.writeAttribute( "type", result.getTestMacroName() ); ReusableStringStream rss; if ( !result.getMessage().empty() ) rss << result.getMessage() << '\n'; for ( auto const& msg : stats.infoMessages ) if ( msg.type == ResultWas::Info ) rss << msg.message << '\n'; rss << "at " << result.getSourceInfo(); xml.writeText( rss.str(), false ); } } CATCH_REGISTER_REPORTER( "junit", JunitReporter ) } // end namespace Catch // end catch_reporter_junit.cpp // start catch_reporter_multi.cpp namespace Catch { void MultipleReporters::add( IStreamingReporterPtr&& reporter ) { m_reporters.push_back( std::move( reporter ) ); } ReporterPreferences MultipleReporters::getPreferences() const { return m_reporters[0]->getPreferences(); } std::set<Verbosity> MultipleReporters::getSupportedVerbosities() { return std::set<Verbosity>{}; } void MultipleReporters::noMatchingTestCases( std::string const& spec ) { for ( auto const& reporter : m_reporters ) reporter->noMatchingTestCases( spec ); } void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) { for ( auto const& reporter : m_reporters ) reporter->benchmarkStarting( benchmarkInfo ); } void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) { for ( auto const& reporter : m_reporters ) reporter->benchmarkEnded( benchmarkStats ); } void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) { for ( auto const& reporter : m_reporters ) reporter->testRunStarting( testRunInfo ); } void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) { for ( auto const& reporter : m_reporters ) reporter->testGroupStarting( groupInfo ); } void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) { for ( auto const& reporter : m_reporters ) reporter->testCaseStarting( testInfo ); } void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) { for ( auto const& reporter : m_reporters ) reporter->sectionStarting( sectionInfo ); } void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) { for ( auto const& reporter : m_reporters ) reporter->assertionStarting( assertionInfo ); } // The return value indicates if the messages buffer should be cleared: bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) { bool clearBuffer = false; for ( auto const& reporter : m_reporters ) clearBuffer |= reporter->assertionEnded( assertionStats ); return clearBuffer; } void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) { for ( auto const& reporter : m_reporters ) reporter->sectionEnded( sectionStats ); } void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) { for ( auto const& reporter : m_reporters ) reporter->testCaseEnded( testCaseStats ); } void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) { for ( auto const& reporter : m_reporters ) reporter->testGroupEnded( testGroupStats ); } void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) { for ( auto const& reporter : m_reporters ) reporter->testRunEnded( testRunStats ); } void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) { for ( auto const& reporter : m_reporters ) reporter->skipTest( testInfo ); } bool MultipleReporters::isMulti() const { return true; } } // end namespace Catch // end catch_reporter_multi.cpp // start catch_reporter_xml.cpp #if defined( _MSC_VER ) #pragma warning( push ) #pragma warning( disable : 4061 ) // Not all labels are EXPLICITLY handled in switch // Note that 4062 (not all labels are handled // and default is missing) is enabled #endif namespace Catch { XmlReporter::XmlReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ) , m_xml( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = true; } XmlReporter::~XmlReporter() = default; std::string XmlReporter::getDescription() { return "Reports test results as an XML document"; } std::string XmlReporter::getStylesheetRef() const { return std::string(); } void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) { m_xml.writeAttribute( "filename", sourceInfo.file ) .writeAttribute( "line", sourceInfo.line ); } void XmlReporter::noMatchingTestCases( std::string const& s ) { StreamingReporterBase::noMatchingTestCases( s ); } void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) { StreamingReporterBase::testRunStarting( testInfo ); std::string stylesheetRef = getStylesheetRef(); if ( !stylesheetRef.empty() ) m_xml.writeStylesheetRef( stylesheetRef ); m_xml.startElement( "Catch" ); if ( !m_config->name().empty() ) m_xml.writeAttribute( "name", m_config->name() ); } void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) { StreamingReporterBase::testGroupStarting( groupInfo ); m_xml.startElement( "Group" ).writeAttribute( "name", groupInfo.name ); } void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) { StreamingReporterBase::testCaseStarting( testInfo ); m_xml.startElement( "TestCase" ) .writeAttribute( "name", trim( testInfo.name ) ) .writeAttribute( "description", testInfo.description ) .writeAttribute( "tags", testInfo.tagsAsString() ); writeSourceInfo( testInfo.lineInfo ); if ( m_config->showDurations() == ShowDurations::Always ) m_testCaseTimer.start(); m_xml.ensureTagClosed(); } void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) { StreamingReporterBase::sectionStarting( sectionInfo ); if ( m_sectionDepth++ > 0 ) { m_xml.startElement( "Section" ) .writeAttribute( "name", trim( sectionInfo.name ) ) .writeAttribute( "description", sectionInfo.description ); writeSourceInfo( sectionInfo.lineInfo ); m_xml.ensureTagClosed(); } } void XmlReporter::assertionStarting( AssertionInfo const& ) {} bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) { AssertionResult const& result = assertionStats.assertionResult; bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); if ( includeResults || result.getResultType() == ResultWas::Warning ) { // Print any info messages in <Info> tags. for ( auto const& msg : assertionStats.infoMessages ) { if ( msg.type == ResultWas::Info && includeResults ) { m_xml.scopedElement( "Info" ).writeText( msg.message ); } else if ( msg.type == ResultWas::Warning ) { m_xml.scopedElement( "Warning" ).writeText( msg.message ); } } } // Drop out if result was successful but we're not printing them. if ( !includeResults && result.getResultType() != ResultWas::Warning ) return true; // Print the expression if there is one. if ( result.hasExpression() ) { m_xml.startElement( "Expression" ) .writeAttribute( "success", result.succeeded() ) .writeAttribute( "type", result.getTestMacroName() ); writeSourceInfo( result.getSourceInfo() ); m_xml.scopedElement( "Original" ).writeText( result.getExpression() ); m_xml.scopedElement( "Expanded" ).writeText( result.getExpandedExpression() ); } // And... Print a result applicable to each result type. switch ( result.getResultType() ) { case ResultWas::ThrewException: m_xml.startElement( "Exception" ); writeSourceInfo( result.getSourceInfo() ); m_xml.writeText( result.getMessage() ); m_xml.endElement(); break; case ResultWas::FatalErrorCondition: m_xml.startElement( "FatalErrorCondition" ); writeSourceInfo( result.getSourceInfo() ); m_xml.writeText( result.getMessage() ); m_xml.endElement(); break; case ResultWas::Info: m_xml.scopedElement( "Info" ).writeText( result.getMessage() ); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: m_xml.startElement( "Failure" ); writeSourceInfo( result.getSourceInfo() ); m_xml.writeText( result.getMessage() ); m_xml.endElement(); break; default: break; } if ( result.hasExpression() ) m_xml.endElement(); return true; } void XmlReporter::sectionEnded( SectionStats const& sectionStats ) { StreamingReporterBase::sectionEnded( sectionStats ); if ( --m_sectionDepth > 0 ) { XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); e.writeAttribute( "successes", sectionStats.assertions.passed ); e.writeAttribute( "failures", sectionStats.assertions.failed ); e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); m_xml.endElement(); } } void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { StreamingReporterBase::testCaseEnded( testCaseStats ); XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); if ( !testCaseStats.stdOut.empty() ) m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false ); if ( !testCaseStats.stdErr.empty() ) m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false ); m_xml.endElement(); } void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { StreamingReporterBase::testGroupEnded( testGroupStats ); // TODO: Check testGroupStats.aborting and act accordingly. m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); m_xml.endElement(); } void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) { StreamingReporterBase::testRunEnded( testRunStats ); m_xml.scopedElement( "OverallResults" ) .writeAttribute( "successes", testRunStats.totals.assertions.passed ) .writeAttribute( "failures", testRunStats.totals.assertions.failed ) .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); m_xml.endElement(); } CATCH_REGISTER_REPORTER( "xml", XmlReporter ) } // end namespace Catch #if defined( _MSC_VER ) #pragma warning( pop ) #endif // end catch_reporter_xml.cpp namespace Catch { LeakDetector leakDetector; } #ifdef __clang__ #pragma clang diagnostic pop #endif // end catch_impl.hpp #endif #ifdef CATCH_CONFIG_MAIN // start catch_default_main.hpp #ifndef __OBJC__ #if defined( CATCH_CONFIG_WCHAR ) && defined( WIN32 ) && defined( _UNICODE ) \ && !defined( DO_NOT_USE_WMAIN ) // Standard C/C++ Win32 Unicode wmain entry point extern "C" int wmain( int argc, wchar_t* argv[], wchar_t* [] ) { #else // Standard C/C++ main entry point int main( int argc, char* argv[] ) { #endif return Catch::Session().run( argc, argv ); } #else // __OBJC__ // Objective-C entry point int main( int argc, char* const argv[] ) { #if !CATCH_ARC_ENABLED NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; #endif Catch::registerTestMethods(); int result = Catch::Session().run( argc, (char**)argv ); #if !CATCH_ARC_ENABLED [pool drain]; #endif return result; } #endif // __OBJC__ // end catch_default_main.hpp #endif #if !defined( CATCH_CONFIG_IMPL_ONLY ) #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED #undef CLARA_CONFIG_MAIN #endif #if !defined( CATCH_CONFIG_DISABLE ) ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( ... ) \ INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_REQUIRE_FALSE( ... ) \ INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", \ Catch::ResultDisposition::Normal \ | Catch::ResultDisposition::FalseTest, \ __VA_ARGS__ ) #define CATCH_REQUIRE_THROWS( ... ) \ INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, \ "", __VA_ARGS__ ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) \ INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, \ Catch::ResultDisposition::Normal, expr ) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) \ INTERNAL_CATCH_THROWS_STR_MATCHES( \ "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) \ INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, \ Catch::ResultDisposition::Normal, matcher, expr ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_REQUIRE_NOTHROW( ... ) \ INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, \ __VA_ARGS__ ) #define CATCH_CHECK( ... ) \ INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, \ __VA_ARGS__ ) #define CATCH_CHECK_FALSE( ... ) \ INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", \ Catch::ResultDisposition::ContinueOnFailure \ | Catch::ResultDisposition::FalseTest, \ __VA_ARGS__ ) #define CATCH_CHECKED_IF( ... ) \ INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, \ __VA_ARGS__ ) #define CATCH_CHECKED_ELSE( ... ) \ INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", \ Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_CHECK_NOFAIL( ... ) \ INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", \ Catch::ResultDisposition::ContinueOnFailure \ | Catch::ResultDisposition::SuppressFail, \ __VA_ARGS__ ) #define CATCH_CHECK_THROWS( ... ) \ INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", \ Catch::ResultDisposition::ContinueOnFailure, "", \ __VA_ARGS__ ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) \ INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, \ Catch::ResultDisposition::ContinueOnFailure, expr ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) \ INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", \ Catch::ResultDisposition::ContinueOnFailure, \ matcher, expr ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) \ INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, \ Catch::ResultDisposition::ContinueOnFailure, \ matcher, expr ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_CHECK_NOTHROW( ... ) \ INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", \ Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CATCH_CHECK_THAT( arg, matcher ) \ INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, \ Catch::ResultDisposition::ContinueOnFailure, arg ) #define CATCH_REQUIRE_THAT( arg, matcher ) \ INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, \ Catch::ResultDisposition::Normal, arg ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) #define CATCH_WARN( msg ) \ INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, \ Catch::ResultDisposition::ContinueOnFailure, msg ) #define CATCH_CAPTURE( msg ) \ INTERNAL_CATCH_INFO( "CATCH_CAPTURE", \ #msg " := " << ::Catch::Detail::stringify( msg ) ) #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define CATCH_TEST_CASE_METHOD( className, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) \ INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) \ INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define CATCH_FAIL( ... ) \ INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, \ Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define CATCH_FAIL_CHECK( ... ) \ INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \ Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_SUCCEED( ... ) \ INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, \ Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() // "BDD-style" convenience wrappers #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) #define CATCH_SCENARIO_METHOD( className, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: " ) + desc ) #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: " ) + desc ) #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: " ) + desc ) #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: " ) + desc ) #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: " ) + desc ) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( ... ) \ INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define REQUIRE_FALSE( ... ) \ INTERNAL_CATCH_TEST( "REQUIRE_FALSE", \ Catch::ResultDisposition::Normal \ | Catch::ResultDisposition::FalseTest, \ __VA_ARGS__ ) #define REQUIRE_THROWS( ... ) \ INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, \ __VA_ARGS__ ) #define REQUIRE_THROWS_AS( expr, exceptionType ) \ INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, \ Catch::ResultDisposition::Normal, expr ) #define REQUIRE_THROWS_WITH( expr, matcher ) \ INTERNAL_CATCH_THROWS_STR_MATCHES( \ "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) \ INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, \ Catch::ResultDisposition::Normal, matcher, expr ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define REQUIRE_NOTHROW( ... ) \ INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, \ __VA_ARGS__ ) #define CHECK( ... ) \ INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, \ __VA_ARGS__ ) #define CHECK_FALSE( ... ) \ INTERNAL_CATCH_TEST( "CHECK_FALSE", \ Catch::ResultDisposition::ContinueOnFailure \ | Catch::ResultDisposition::FalseTest, \ __VA_ARGS__ ) #define CHECKED_IF( ... ) \ INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, \ __VA_ARGS__ ) #define CHECKED_ELSE( ... ) \ INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, \ __VA_ARGS__ ) #define CHECK_NOFAIL( ... ) \ INTERNAL_CATCH_TEST( "CHECK_NOFAIL", \ Catch::ResultDisposition::ContinueOnFailure \ | Catch::ResultDisposition::SuppressFail, \ __VA_ARGS__ ) #define CHECK_THROWS( ... ) \ INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, \ __VA_ARGS__ ) #define CHECK_THROWS_AS( expr, exceptionType ) \ INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, \ Catch::ResultDisposition::ContinueOnFailure, expr ) #define CHECK_THROWS_WITH( expr, matcher ) \ INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", \ Catch::ResultDisposition::ContinueOnFailure, \ matcher, expr ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) \ INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, \ Catch::ResultDisposition::ContinueOnFailure, \ matcher, expr ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CHECK_NOTHROW( ... ) \ INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", \ Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CHECK_THAT( arg, matcher ) \ INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, \ Catch::ResultDisposition::ContinueOnFailure, arg ) #define REQUIRE_THAT( arg, matcher ) \ INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) #define WARN( msg ) \ INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, \ Catch::ResultDisposition::ContinueOnFailure, msg ) #define CAPTURE( msg ) \ INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify( msg ) ) #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define TEST_CASE_METHOD( className, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define METHOD_AS_TEST_CASE( method, ... ) \ INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define REGISTER_TEST_CASE( Function, ... ) \ INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define FAIL( ... ) \ INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, \ Catch::ResultDisposition::Normal, __VA_ARGS__ ) #define FAIL_CHECK( ... ) \ INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \ Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define SUCCEED( ... ) \ INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, \ Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) \ INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) // "BDD-style" convenience wrappers #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) #define SCENARIO_METHOD( className, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) #define GIVEN( desc ) SECTION( std::string( " Given: " ) + desc ) #define WHEN( desc ) SECTION( std::string( " When: " ) + desc ) #define AND_WHEN( desc ) SECTION( std::string( "And when: " ) + desc ) #define THEN( desc ) SECTION( std::string( " Then: " ) + desc ) #define AND_THEN( desc ) SECTION( std::string( " And: " ) + desc ) using Catch::Detail::Approx; #else ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( ... ) (void)( 0 ) #define CATCH_REQUIRE_FALSE( ... ) (void)( 0 ) #define CATCH_REQUIRE_THROWS( ... ) (void)( 0 ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)( 0 ) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)( 0 ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)( 0 ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_REQUIRE_NOTHROW( ... ) (void)( 0 ) #define CATCH_CHECK( ... ) (void)( 0 ) #define CATCH_CHECK_FALSE( ... ) (void)( 0 ) #define CATCH_CHECKED_IF( ... ) if ( __VA_ARGS__ ) #define CATCH_CHECKED_ELSE( ... ) if ( !( __VA_ARGS__ ) ) #define CATCH_CHECK_NOFAIL( ... ) (void)( 0 ) #define CATCH_CHECK_THROWS( ... ) (void)( 0 ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)( 0 ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)( 0 ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)( 0 ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_CHECK_NOTHROW( ... ) (void)( 0 ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CATCH_CHECK_THAT( arg, matcher ) (void)( 0 ) #define CATCH_REQUIRE_THAT( arg, matcher ) (void)( 0 ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CATCH_INFO( msg ) (void)( 0 ) #define CATCH_WARN( msg ) (void)( 0 ) #define CATCH_CAPTURE( msg ) (void)( 0 ) #define CATCH_TEST_CASE( ... ) \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define CATCH_TEST_CASE_METHOD( className, ... ) \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)( 0 ) #define CATCH_SECTION( ... ) #define CATCH_FAIL( ... ) (void)( 0 ) #define CATCH_FAIL_CHECK( ... ) (void)( 0 ) #define CATCH_SUCCEED( ... ) (void)( 0 ) #define CATCH_ANON_TEST_CASE() \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) // "BDD-style" convenience wrappers #define CATCH_SCENARIO( ... ) \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define CATCH_SCENARIO_METHOD( className, ... ) \ INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) #define CATCH_GIVEN( desc ) #define CATCH_WHEN( desc ) #define CATCH_AND_WHEN( desc ) #define CATCH_THEN( desc ) #define CATCH_AND_THEN( desc ) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( ... ) (void)( 0 ) #define REQUIRE_FALSE( ... ) (void)( 0 ) #define REQUIRE_THROWS( ... ) (void)( 0 ) #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)( 0 ) #define REQUIRE_THROWS_WITH( expr, matcher ) (void)( 0 ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)( 0 ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define REQUIRE_NOTHROW( ... ) (void)( 0 ) #define CHECK( ... ) (void)( 0 ) #define CHECK_FALSE( ... ) (void)( 0 ) #define CHECKED_IF( ... ) if ( __VA_ARGS__ ) #define CHECKED_ELSE( ... ) if ( !( __VA_ARGS__ ) ) #define CHECK_NOFAIL( ... ) (void)( 0 ) #define CHECK_THROWS( ... ) (void)( 0 ) #define CHECK_THROWS_AS( expr, exceptionType ) (void)( 0 ) #define CHECK_THROWS_WITH( expr, matcher ) (void)( 0 ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)( 0 ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define CHECK_NOTHROW( ... ) (void)( 0 ) #if !defined( CATCH_CONFIG_DISABLE_MATCHERS ) #define CHECK_THAT( arg, matcher ) (void)( 0 ) #define REQUIRE_THAT( arg, matcher ) (void)( 0 ) #endif // CATCH_CONFIG_DISABLE_MATCHERS #define INFO( msg ) (void)( 0 ) #define WARN( msg ) (void)( 0 ) #define CAPTURE( msg ) (void)( 0 ) #define TEST_CASE( ... ) \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define TEST_CASE_METHOD( className, ... ) \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define METHOD_AS_TEST_CASE( method, ... ) #define REGISTER_TEST_CASE( Function, ... ) (void)( 0 ) #define SECTION( ... ) #define FAIL( ... ) (void)( 0 ) #define FAIL_CHECK( ... ) (void)( 0 ) #define SUCCEED( ... ) (void)( 0 ) #define ANON_TEST_CASE() \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) \ INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( \ INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) // "BDD-style" convenience wrappers #define SCENARIO( ... ) \ INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) #define SCENARIO_METHOD( className, ... ) \ INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) #define GIVEN( desc ) #define WHEN( desc ) #define AND_WHEN( desc ) #define THEN( desc ) #define AND_THEN( desc ) using Catch::Detail::Approx; #endif #endif // ! CATCH_CONFIG_IMPL_ONLY // start catch_reenable_warnings.h #ifdef __clang__ #ifdef __ICC // icpc defines the __clang__ macro #pragma warning( pop ) #else #pragma clang diagnostic pop #endif #elif defined __GNUC__ #pragma GCC diagnostic pop #endif // end catch_reenable_warnings.h // end catch.hpp #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
[ "jnarsing@umich.edu" ]
jnarsing@umich.edu
515ff98124d5ab6d4e1cbe8b327c04948b4422a0
edac7317c6123c8baa831a5454ae8d91b3351dbf
/src/tokenizer.cpp
ea1aa43342e67f3f5a4969f82bd1ffd73ea2ea2d
[ "Apache-2.0" ]
permissive
tushartushar/tokenizer
199373841ef7592cee9b9fd0fc479a7caa730c1e
db6c55f71944f2ce414c931854f29696f6026b9a
refs/heads/master
2020-03-12T00:54:04.857857
2018-05-17T13:43:20
2018-05-17T13:43:20
130,361,099
0
0
null
2018-04-20T12:47:14
2018-04-20T12:47:14
null
UTF-8
C++
false
false
3,309
cpp
/*- * Copyright 2014 Diomidis Spinellis * * 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 <cstring> #include <string> #include <fstream> #include <iostream> #include <ostream> #include <vector> #include "errno.h" #include "unistd.h" #include "CTokenizer.h" #include "CppTokenizer.h" #include "CSharpTokenizer.h" #include "JavaTokenizer.h" // Process and print the metrics of stdin static void process_file(const std::string lang, const std::vector<std::string> opt, std::string filename, char processing_type) { CharSource cs; TokenizerBase *t; if (lang == "" || lang == "Java") t = new JavaTokenizer(cs, filename, opt); else if (lang == "C") t = new CTokenizer(cs, filename, opt); else if (lang == "CSharp" || lang == "C#") t = new CSharpTokenizer(cs, filename, opt); else if (lang == "C++") t = new CppTokenizer(cs, filename, opt); else { std::cerr << "Unknown language specified." << std::endl; std::cerr << "The following languages are supported:" << std::endl; std::cerr << "\tC" << std::endl; std::cerr << "\tCSharp (or C#)" << std::endl; std::cerr << "\tC++" << std::endl; std::cerr << "\tJava" << std::endl; exit(1); } switch (processing_type) { case 'c': t->code_tokenize(); break; case 'n': t->numeric_tokenize(); break; case 's': t->symbolic_tokenize(); break; default: std::cerr << "Unknown processing type specified." << std::endl; std::cerr << "The following processing types are supported:" << std::endl; std::cerr << "\tc: output code; one token per line" << std::endl; std::cerr << "\tn: output numeric values" << std::endl; std::cerr << "\ts: output token symbols" << std::endl; exit(1); } } /* Calculate and print C metrics for the standard input */ int main(int argc, char * const argv[]) { std::ifstream in; int opt; std::string lang = ""; std::vector<std::string> processing_opt; char processing_type = 'n'; while ((opt = getopt(argc, argv, "l:o:t:")) != -1) switch (opt) { case 'l': lang = optarg; break; case 'o': processing_opt.push_back(optarg); break; case 't': processing_type = *optarg; break; default: /* ? */ std::cerr << "Usage: " << argv[0] << "[-s] [-l lang] [-o opt] [file ...]" << std::endl; exit(EXIT_FAILURE); } if (!argv[optind]) { process_file(lang, processing_opt, "-", processing_type); exit(EXIT_SUCCESS); } // Read from file, if specified while (argv[optind]) { in.open(argv[optind], std::ifstream::in); if (!in.good()) { std::cerr << "Unable to open " << argv[optind] << ": " << strerror(errno) << std::endl; exit(EXIT_FAILURE); } std::cin.rdbuf(in.rdbuf()); process_file(lang, processing_opt, argv[optind], processing_type); in.close(); optind++; } exit(EXIT_SUCCESS); }
[ "dds@aueb.gr" ]
dds@aueb.gr
f88e565ed72726f136513b1c84dfe762fa25ebda
6f874ccb136d411c8ec7f4faf806a108ffc76837
/code/VCSamples/VC2008Samples/MFC/advanced/collect/colledoc.cpp
1c3eb686e35a80901e31cf73f849f23224308d84
[ "MIT" ]
permissive
JetAr/ZDoc
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
e81a3adc354ec33345e9a3303f381dcb1b02c19d
refs/heads/master
2022-07-26T23:06:12.021611
2021-07-11T13:45:57
2021-07-11T13:45:57
33,112,803
8
8
null
null
null
null
UTF-8
C++
false
false
6,948
cpp
// colledoc.cpp : implementation of the CCollectDoc class // // This is a part of the Microsoft Foundation Classes C++ library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "collect.h" #include "colledoc.h" #include "resource.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMyStruct void CMyStruct::FormatMyStruct(CString& str) { str.Format(_T("{%i, %.4f, %s}"), m_int, m_float, (LPCTSTR)m_str); } #if _MSC_VER > 1020 template <> void AFXAPI SerializeElements<CMyStruct*>(CArchive& ar, CMyStruct** ppElements, INT_PTR nCount) #else void SerializeElements(CArchive& ar, CMyStruct** ppElements, int nCount) #endif { // Since SerializeElements is always called by the framework with nCount=1 // for a CMap<>, it is a good idea to implement SerializeElement to handle // nCount>1, in case you decide to reuse it for a CArray<> with the same // element type. if (ar.IsStoring()) { for (int i = 0; i < nCount; i++) { CMyStruct* pMyStruct = *(ppElements + i); WORD w = (WORD)pMyStruct->m_int; ar << w; ar << pMyStruct->m_float; ar << pMyStruct->m_str; nCount--; } } else { for (int i = 0; i < nCount; i++) { CMyStruct* pMyStruct = new CMyStruct; *(ppElements + i) = pMyStruct; WORD w; ar >> w; pMyStruct->m_int = w; ar >> pMyStruct->m_float; ar >> pMyStruct->m_str; } } } ///////////////////////////////////////////////////////////////////////////// // CMyObject IMPLEMENT_SERIAL(CMyObject, CObject, 0) CMyObject::CMyObject() { } CMyObject::~CMyObject() { } void CMyObject::FormatMyObject(CString& str) { str.Format(_T("{%i, %.4f, %s}"), m_int, m_float, (LPCTSTR)m_str); } void CMyObject::Serialize(CArchive& ar) { WORD w; if (ar.IsStoring()) { w = (WORD)m_int; ar << w; ar << m_float; ar << m_str; } else { ar >> w; m_int = w; ar >> m_float; ar >> m_str; } } ///////////////////////////////////////////////////////////////////////////// // CCollectDoc IMPLEMENT_DYNCREATE(CCollectDoc, CDocument) BEGIN_MESSAGE_MAP(CCollectDoc, CDocument) //{{AFX_MSG_MAP(CCollectDoc) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCollectDoc construction/destruction CCollectDoc::CCollectDoc() { } CCollectDoc::~CCollectDoc() { } BOOL CCollectDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; CString strFirst; strFirst.LoadString(IDS_INITIAL_STRING); m_stringList.AddTail(strFirst); CMyStruct* pMyStruct = new CMyStruct(); pMyStruct->m_int = 1234; pMyStruct->m_float = 12.34f; pMyStruct->m_str.LoadString(IDS_INITIAL_STRING); m_mystructList.AddTail(pMyStruct); m_intList.AddTail(100); m_dwArray.Add(100000); CMyObject* pMyObject = new CMyObject(); pMyObject->m_int = 5678; pMyObject->m_float = 56.78f; pMyObject->m_str.LoadString(IDS_INITIAL_STRING); m_myobArray.Add(pMyObject); CPoint pt(10,10); m_ptArray.Add(pt); CString strKey, strValue; strKey.LoadString(IDS_INITIAL_KEY); strValue.LoadString(IDS_INITIAL_VALUE); m_mapStringToString[strKey] = strValue; CMyObject* pMyObject2 = new CMyObject(); pMyObject2->m_int = 1357; pMyObject2->m_float = 13.57f; pMyObject2->m_str.LoadString(IDS_INITIAL_STRING); m_mapStringToMyObject[strKey] = pMyObject2; CMyStruct* pMyStruct2 = new CMyStruct(); pMyStruct2->m_int = 2468; pMyStruct2->m_float = 24.68f; pMyStruct2->m_str.LoadString(IDS_INITIAL_STRING); m_mapDWordToMyStruct[100] = pMyStruct2; return TRUE; } void CCollectDoc::DeleteContents() { m_stringList.RemoveAll(); POSITION pos = m_mystructList.GetHeadPosition(); while (pos != NULL) { delete m_mystructList.GetNext(pos); } m_mystructList.RemoveAll(); m_intList.RemoveAll(); m_dwArray.RemoveAll(); for (int n = 0; n < m_myobArray.GetSize(); n++) { delete m_myobArray[n]; } m_myobArray.RemoveAll(); m_mapStringToString.RemoveAll(); m_ptArray.RemoveAll(); pos = m_mapStringToMyObject.GetStartPosition(); while (pos != NULL) { CString str; CMyObject* pMyObject; m_mapStringToMyObject.GetNextAssoc(pos, str, pMyObject); delete pMyObject; } m_mapStringToMyObject.RemoveAll(); pos = m_mapDWordToMyStruct.GetStartPosition(); while (pos != NULL) { DWORD dwKey; CMyStruct* pMyStruct; m_mapDWordToMyStruct.GetNextAssoc(pos, dwKey, pMyStruct); delete pMyStruct; } m_mapDWordToMyStruct.RemoveAll(); } ///////////////////////////////////////////////////////////////////////////// // CCollectDoc serialization void CCollectDoc::Serialize(CArchive& ar) { POSITION pos; WORD nCount; WORD w; m_stringList.Serialize(ar); if (ar.IsStoring()) { nCount = (WORD)m_mystructList.GetCount(); ar << nCount; pos = m_mystructList.GetHeadPosition(); while (pos != NULL) { CMyStruct* pMyStruct = m_mystructList.GetNext(pos); w = (WORD)pMyStruct->m_int; ar << w; ar << pMyStruct->m_float; ar << pMyStruct->m_str; nCount--; } ASSERT(nCount == 0); } else { ar >> nCount; while (nCount-- > 0) { CMyStruct* pMyStruct = new CMyStruct; ar >> w; pMyStruct->m_int = w; ar >> pMyStruct->m_float; ar >> pMyStruct->m_str; m_mystructList.AddTail(pMyStruct); } } m_intList.Serialize(ar); m_dwArray.Serialize(ar); m_myobArray.Serialize(ar); m_ptArray.Serialize(ar); m_mapStringToString.Serialize(ar); m_mapStringToMyObject.Serialize(ar); m_mapDWordToMyStruct.Serialize(ar); } ///////////////////////////////////////////////////////////////////////////// // CCollectDoc diagnostics #ifdef _DEBUG void CCollectDoc::AssertValid() const { CDocument::AssertValid(); } void CCollectDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CCollectDoc commands
[ "126.org@gmail.com" ]
126.org@gmail.com
e30392eaf85d27420366bf2b9f8917a56a8d8885
93ae503d2a0ddc2845157917b78d107eb9e2c5cb
/UserInterface/PythonApplicationModule.cpp
7b493087002f9e4debac88002977b6cc9e49248a
[]
no_license
Nevisor/Client
517f41bc68521e5ad289863c6ce9c53a129db335
fce5997464d9923c7f92205d78f1b83dfcd62918
refs/heads/master
2020-03-19T20:23:46.772525
2018-06-11T09:03:32
2018-06-11T09:03:32
136,899,661
1
1
null
null
null
null
UHC
C++
false
false
55,905
cpp
#include "StdAfx.h" #include "Resource.h" #include "PythonApplication.h" #include "../EterLib/Camera.h" extern bool PERF_CHECKER_RENDER_GAME; extern D3DXCOLOR g_fSpecularColor; extern BOOL bVisibleNotice = true; extern BOOL bTestServerFlag = FALSE; extern int TWOHANDED_WEWAPON_ATT_SPEED_DECREASE_VALUE = 0; #ifdef USE_OPENID extern int openid_test; #endif PyObject* appShowWebPage(PyObject* poSelf, PyObject* poArgs) { char* szWebPage; if (!PyTuple_GetString(poArgs, 0, &szWebPage)) return Py_BuildException(); PyObject* poRect=PyTuple_GetItem(poArgs, 1); if (!PyTuple_Check(poRect)) return Py_BuildException(); RECT rcWebPage; rcWebPage.left=PyInt_AsLong(PyTuple_GetItem(poRect, 0)); rcWebPage.top=PyInt_AsLong(PyTuple_GetItem(poRect, 1)); rcWebPage.right=PyInt_AsLong(PyTuple_GetItem(poRect, 2)); rcWebPage.bottom=PyInt_AsLong(PyTuple_GetItem(poRect, 3)); CPythonApplication::Instance().ShowWebPage( szWebPage, rcWebPage ); return Py_BuildNone(); } PyObject* appMoveWebPage(PyObject* poSelf, PyObject* poArgs) { PyObject* poRect=PyTuple_GetItem(poArgs, 0); if (!PyTuple_Check(poRect)) return Py_BuildException(); RECT rcWebPage; rcWebPage.left=PyInt_AsLong(PyTuple_GetItem(poRect, 0)); rcWebPage.top=PyInt_AsLong(PyTuple_GetItem(poRect, 1)); rcWebPage.right=PyInt_AsLong(PyTuple_GetItem(poRect, 2)); rcWebPage.bottom=PyInt_AsLong(PyTuple_GetItem(poRect, 3)); CPythonApplication::Instance().MoveWebPage(rcWebPage); return Py_BuildNone(); } PyObject* appHideWebPage(PyObject* poSelf, PyObject* poArgs) { CPythonApplication::Instance().HideWebPage(); return Py_BuildNone(); } PyObject * appIsWebPageMode(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().IsWebPageMode()); } PyObject* appEnablePerformanceTime(PyObject* poSelf, PyObject* poArgs) { char* szMode; if (!PyTuple_GetString(poArgs, 0, &szMode)) return Py_BuildException(); int nEnable; if (!PyTuple_GetInteger(poArgs, 1, &nEnable)) return Py_BuildException(); bool isEnable=nEnable ? true : false; if (strcmp(szMode, "RENDER_GAME")==0) PERF_CHECKER_RENDER_GAME = isEnable; return Py_BuildNone(); } ///////////////////////////////////////////////////// extern BOOL HAIR_COLOR_ENABLE; extern BOOL USE_ARMOR_SPECULAR; extern BOOL USE_WEAPON_SPECULAR; extern BOOL SKILL_EFFECT_UPGRADE_ENABLE; extern BOOL RIDE_HORSE_ENABLE; extern double g_specularSpd; // TEXTTAIL_LIVINGTIME_CONTROL extern void TextTail_SetLivingTime(long livingTime); PyObject* appSetTextTailLivingTime(PyObject* poSelf, PyObject* poArgs) { float livingTime; if (!PyTuple_GetFloat(poArgs, 0, &livingTime)) return Py_BuildException(); TextTail_SetLivingTime(livingTime*1000); return Py_BuildNone(); } // END_OF_TEXTTAIL_LIVINGTIME_CONTROL PyObject* appSetHairColorEnable(PyObject* poSelf, PyObject* poArgs) { int nEnable; if (!PyTuple_GetInteger(poArgs, 0, &nEnable)) return Py_BuildException(); HAIR_COLOR_ENABLE=nEnable; return Py_BuildNone(); } PyObject* appSetArmorSpecularEnable(PyObject* poSelf, PyObject* poArgs) { int nEnable; if (!PyTuple_GetInteger(poArgs, 0, &nEnable)) return Py_BuildException(); USE_ARMOR_SPECULAR=nEnable; return Py_BuildNone(); } PyObject* appSetWeaponSpecularEnable(PyObject* poSelf, PyObject* poArgs) { int nEnable; if (!PyTuple_GetInteger(poArgs, 0, &nEnable)) return Py_BuildException(); USE_WEAPON_SPECULAR=nEnable; return Py_BuildNone(); } PyObject* appSetSkillEffectUpgradeEnable(PyObject* poSelf, PyObject* poArgs) { int nEnable; if (!PyTuple_GetInteger(poArgs, 0, &nEnable)) return Py_BuildException(); SKILL_EFFECT_UPGRADE_ENABLE=nEnable; return Py_BuildNone(); } PyObject* SetTwoHandedWeaponAttSpeedDecreaseValue(PyObject* poSelf, PyObject* poArgs) { int iValue; if (!PyTuple_GetInteger(poArgs, 0, &iValue)) return Py_BuildException(); TWOHANDED_WEWAPON_ATT_SPEED_DECREASE_VALUE = iValue; return Py_BuildNone(); } PyObject* appSetRideHorseEnable(PyObject* poSelf, PyObject* poArgs) { int nEnable; if (!PyTuple_GetInteger(poArgs, 0, &nEnable)) return Py_BuildException(); RIDE_HORSE_ENABLE=nEnable; return Py_BuildNone(); } PyObject* appSetCameraMaxDistance(PyObject* poSelf, PyObject* poArgs) { float fMax; if (!PyTuple_GetFloat(poArgs, 0, &fMax)) return Py_BuildException(); CCamera::SetCameraMaxDistance(fMax); return Py_BuildNone(); } PyObject* appSetControlFP(PyObject* poSelf, PyObject* poArgs) { _controlfp( _PC_24, _MCW_PC ); return Py_BuildNone(); } PyObject* appSetSpecularSpeed(PyObject* poSelf, PyObject* poArgs) { float fSpeed; if (!PyTuple_GetFloat(poArgs, 0, &fSpeed)) return Py_BuildException(); g_specularSpd = fSpeed; return Py_BuildNone(); } PyObject * appSetMinFog(PyObject * poSelf, PyObject * poArgs) { float fMinFog; if (!PyTuple_GetFloat(poArgs, 0, &fMinFog)) return Py_BuildException(); CPythonApplication::Instance().SetMinFog(fMinFog); return Py_BuildNone(); } PyObject* appSetFrameSkip(PyObject* poSelf, PyObject* poArgs) { int nFrameSkip; if (!PyTuple_GetInteger(poArgs, 0, &nFrameSkip)) return Py_BuildException(); CPythonApplication::Instance().SetFrameSkip(nFrameSkip ? true : false); return Py_BuildNone(); } // LOCALE PyObject* appForceSetLocale(PyObject* poSelf, PyObject* poArgs) { char* szName; if (!PyTuple_GetString(poArgs, 0, &szName)) return Py_BuildException(); char* szLocalePath; if (!PyTuple_GetString(poArgs, 1, &szLocalePath)) return Py_BuildException(); LocaleService_ForceSetLocale(szName, szLocalePath); return Py_BuildNone(); } PyObject* appGetLocaleServiceName(PyObject* poSelf, PyObject* poArgs) { return Py_BuildValue("s", LocaleService_GetName()); } // bool LoadLocaleData(const char* localePath); PyObject* appSetCHEONMA(PyObject* poSelf, PyObject* poArgs) { int enable; if (!PyTuple_GetInteger(poArgs, 0, &enable)) return Py_BuildException(); LocaleService_SetCHEONMA(enable ? true : false); return Py_BuildNone(); } PyObject* appIsCHEONMA(PyObject* poSelf, PyObject* poArgs) { return Py_BuildValue("i", LocaleService_IsCHEONMA()); } #include "../eterBase/tea.h" PyObject* appLoadLocaleAddr(PyObject* poSelf, PyObject* poArgs) { char* addrPath; if (!PyTuple_GetString(poArgs, 0, &addrPath)) return Py_BuildException(); FILE* fp = fopen(addrPath, "rb"); if (!fp) return Py_BuildException(); fseek(fp, 0, SEEK_END); int size = ftell(fp); char* enc = (char*)_alloca(size); fseek(fp, 0, SEEK_SET); fread(enc, size, 1, fp); fclose(fp); static const unsigned char key[16] = { 0x82, 0x1b, 0x34, 0xae, 0x12, 0x3b, 0xfb, 0x17, 0xd7, 0x2c, 0x39, 0xae, 0x41, 0x98, 0xf1, 0x63 }; char* buf = (char*)_alloca(size); //int decSize = tea_decrypt((unsigned long*)buf, (const unsigned long*)enc, (const unsigned long*)key, size); unsigned int retSize = *(unsigned int*)buf; char* ret = buf + sizeof(unsigned int); return Py_BuildValue("s#", ret, retSize); } PyObject* appLoadLocaleData(PyObject* poSelf, PyObject* poArgs) { char* localePath; if (!PyTuple_GetString(poArgs, 0, &localePath)) return Py_BuildException(); return Py_BuildValue("i", LoadLocaleData(localePath)); } PyObject* appGetLocaleName(PyObject* poSelf, PyObject* poArgs) { return Py_BuildValue("s", LocaleService_GetLocaleName()); } PyObject* appGetLocalePath(PyObject* poSelf, PyObject* poArgs) { return Py_BuildValue("s", LocaleService_GetLocalePath()); } // END_OF_LOCALE PyObject* appGetDefaultCodePage(PyObject* poSelf, PyObject* poArgs) { return Py_BuildValue("i", LocaleService_GetCodePage()); } #ifdef __VTUNE__ PyObject* appGetImageInfo(PyObject* poSelf, PyObject* poArgs) { char* szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); return Py_BuildValue("iii", 0, 0, 0); } #else #include <il/il.h> PyObject* appGetImageInfo(PyObject* poSelf, PyObject* poArgs) { char* szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); BOOL canLoad=FALSE; ILuint uWidth=0; ILuint uHeight=0; ILuint uImg; ilGenImages(1, &uImg); ilBindImage(uImg); if (ilLoad(IL_TYPE_UNKNOWN, szFileName)) { canLoad=TRUE; uWidth=ilGetInteger(IL_IMAGE_WIDTH); uHeight=ilGetInteger(IL_IMAGE_HEIGHT); } ilDeleteImages(1, &uImg); return Py_BuildValue("iii", canLoad, uWidth, uHeight); } #endif #include "../EterPack/EterPackManager.h" PyObject* appIsExistFile(PyObject* poSelf, PyObject* poArgs) { char* szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); bool isExist=CEterPackManager::Instance().isExist(szFileName); return Py_BuildValue("i", isExist); } PyObject* appGetFileList(PyObject* poSelf, PyObject* poArgs) { char* szFilter; if (!PyTuple_GetString(poArgs, 0, &szFilter)) return Py_BuildException(); PyObject* poList=PyList_New(0); WIN32_FIND_DATA wfd; memset(&wfd, 0, sizeof(wfd)); HANDLE hFind = FindFirstFile(szFilter, &wfd); if (hFind != INVALID_HANDLE_VALUE) { do { PyObject* poFileName=PyString_FromString(wfd.cFileName) ; PyList_Append(poList, poFileName); } while (FindNextFile(hFind, &wfd)); FindClose(hFind); } return poList; } PyObject* appUpdateGame(PyObject* poSelf, PyObject* poArgs) { CPythonApplication::Instance().UpdateGame(); return Py_BuildNone(); } PyObject* appRenderGame(PyObject* poSelf, PyObject* poArgs) { CPythonApplication::Instance().RenderGame(); return Py_BuildNone(); } PyObject* appSetMouseHandler(PyObject* poSelf, PyObject* poArgs) { PyObject* poHandler; if (!PyTuple_GetObject(poArgs, 0, &poHandler)) return Py_BuildException(); CPythonApplication::Instance().SetMouseHandler(poHandler); return Py_BuildNone(); } PyObject* appCreate(PyObject* poSelf, PyObject* poArgs) { char* szName; if (!PyTuple_GetString(poArgs, 0, &szName)) return Py_BuildException(); int width; if (!PyTuple_GetInteger(poArgs, 1, &width)) return Py_BuildException(); int height; if (!PyTuple_GetInteger(poArgs, 2, &height)) return Py_BuildException(); int Windowed; if (!PyTuple_GetInteger(poArgs, 3, &Windowed)) return Py_BuildException(); CPythonApplication& rkApp=CPythonApplication::Instance(); if (!rkApp.Create(poSelf, szName, width, height, Windowed)) { //return Py_BuildNone(); return NULL; } return Py_BuildNone(); } PyObject* appLoop(PyObject* poSelf, PyObject* poArgs) { CPythonApplication::Instance().Loop(); return Py_BuildNone(); } PyObject* appGetInfo(PyObject* poSelf, PyObject* poArgs) { int nInfo; if (!PyTuple_GetInteger(poArgs, 0, &nInfo)) return Py_BuildException(); std::string stInfo; CPythonApplication::Instance().GetInfo(nInfo, &stInfo); return Py_BuildValue("s", stInfo.c_str()); } PyObject* appProcess(PyObject* poSelf, PyObject* poArgs) { if (CPythonApplication::Instance().Process()) return Py_BuildValue("i", 1); return Py_BuildValue("i", 0); } PyObject* appAbort(PyObject* poSelf, PyObject* poArgs) { CPythonApplication::Instance().Abort(); return Py_BuildNone(); } PyObject* appExit(PyObject* poSelf, PyObject* poArgs) { CPythonApplication::Instance().Exit(); return Py_BuildNone(); } PyObject * appSetCamera(PyObject * poSelf, PyObject * poArgs) { float Distance; if (!PyTuple_GetFloat(poArgs, 0, &Distance)) return Py_BuildException(); float Pitch; if (!PyTuple_GetFloat(poArgs, 1, &Pitch)) return Py_BuildException(); float Rotation; if (!PyTuple_GetFloat(poArgs, 2, &Rotation)) return Py_BuildException(); float fDestinationHeight; if (!PyTuple_GetFloat(poArgs, 3, &fDestinationHeight)) return Py_BuildException(); CPythonApplication::Instance().SetCamera(Distance, Pitch, Rotation, fDestinationHeight); return Py_BuildNone(); } PyObject * appGetCamera(PyObject * poSelf, PyObject * poArgs) { float Distance, Pitch, Rotation, DestinationHeight; CPythonApplication::Instance().GetCamera(&Distance, &Pitch, &Rotation, &DestinationHeight); return Py_BuildValue("ffff", Distance, Pitch, Rotation, DestinationHeight); } PyObject * appGetCameraPitch(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("f", CPythonApplication::Instance().GetPitch()); } PyObject * appGetCameraRotation(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("f", CPythonApplication::Instance().GetRotation()); } PyObject * appGetTime(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("f", CPythonApplication::Instance().GetGlobalTime()); } PyObject * appGetGlobalTime(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetServerTime()); } PyObject * appGetGlobalTimeStamp(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetServerTimeStamp()); } PyObject * appGetUpdateFPS(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetUpdateFPS()); } PyObject * appGetRenderFPS(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetRenderFPS()); } PyObject * appRotateCamera(PyObject * poSelf, PyObject * poArgs) { int iDirection; if (!PyTuple_GetInteger(poArgs, 0, &iDirection)) return Py_BuildException(); CPythonApplication::Instance().RotateCamera(iDirection); return Py_BuildNone(); } PyObject * appPitchCamera(PyObject * poSelf, PyObject * poArgs) { int iDirection; if (!PyTuple_GetInteger(poArgs, 0, &iDirection)) return Py_BuildException(); CPythonApplication::Instance().PitchCamera(iDirection); return Py_BuildNone(); } PyObject * appZoomCamera(PyObject * poSelf, PyObject * poArgs) { int iDirection; if (!PyTuple_GetInteger(poArgs, 0, &iDirection)) return Py_BuildException(); CPythonApplication::Instance().ZoomCamera(iDirection); return Py_BuildNone(); } PyObject * appMovieRotateCamera(PyObject * poSelf, PyObject * poArgs) { int iDirection; if (!PyTuple_GetInteger(poArgs, 0, &iDirection)) return Py_BuildException(); CPythonApplication::Instance().MovieRotateCamera(iDirection); return Py_BuildNone(); } PyObject * appMoviePitchCamera(PyObject * poSelf, PyObject * poArgs) { int iDirection; if (!PyTuple_GetInteger(poArgs, 0, &iDirection)) return Py_BuildException(); CPythonApplication::Instance().MoviePitchCamera(iDirection); return Py_BuildNone(); } PyObject * appMovieZoomCamera(PyObject * poSelf, PyObject * poArgs) { int iDirection; if (!PyTuple_GetInteger(poArgs, 0, &iDirection)) return Py_BuildException(); CPythonApplication::Instance().MovieZoomCamera(iDirection); return Py_BuildNone(); } PyObject * appMovieResetCamera(PyObject * poSelf, PyObject * poArgs) { CPythonApplication::Instance().MovieResetCamera(); return Py_BuildNone(); } PyObject * appGetFaceSpeed(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("f", CPythonApplication::Instance().GetFaceSpeed()); } PyObject * appGetRenderTime(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("fi", CPythonApplication::Instance().GetAveRenderTime(), CPythonApplication::Instance().GetCurRenderTime()); } PyObject * appGetUpdateTime(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetCurUpdateTime()); } PyObject * appGetLoad(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetLoad()); } PyObject * appGetFaceCount(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetFaceCount()); } PyObject * appGetAvaiableTextureMememory(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CGraphicBase::GetAvailableTextureMemory()); } PyObject * appSetFPS(PyObject * poSelf, PyObject * poArgs) { int iFPS; if (!PyTuple_GetInteger(poArgs, 0, &iFPS)) return Py_BuildException(); CPythonApplication::Instance().SetFPS(iFPS); return Py_BuildNone(); } PyObject * appSetGlobalCenterPosition(PyObject * poSelf, PyObject * poArgs) { int x; if (!PyTuple_GetInteger(poArgs, 0, &x)) return Py_BuildException(); int y; if (!PyTuple_GetInteger(poArgs, 1, &y)) return Py_BuildException(); CPythonApplication::Instance().SetGlobalCenterPosition(x, y); return Py_BuildNone(); } PyObject * appSetCenterPosition(PyObject * poSelf, PyObject * poArgs) { float fx; if (!PyTuple_GetFloat(poArgs, 0, &fx)) return Py_BuildException(); float fy; if (!PyTuple_GetFloat(poArgs, 1, &fy)) return Py_BuildException(); float fz; if (!PyTuple_GetFloat(poArgs, 2, &fz)) return Py_BuildException(); CPythonApplication::Instance().SetCenterPosition(fx, -fy, fz); return Py_BuildNone(); } PyObject * appGetCursorPosition(PyObject * poSelf, PyObject * poArgs) { long lx, ly; UI::CWindowManager& rkWndMgr=UI::CWindowManager::Instance(); rkWndMgr.GetMousePosition(lx, ly); return Py_BuildValue("ii", lx, ly); } PyObject * appRunPythonFile(PyObject * poSelf, PyObject * poArgs) { char *szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); bool ret = CPythonLauncher::Instance().RunFile(szFileName); return Py_BuildValue("i", ret); } PyObject * appIsPressed(PyObject * poSelf, PyObject * poArgs) { int iKey; if (!PyTuple_GetInteger(poArgs, 0, &iKey)) return Py_BuildException(); return Py_BuildValue("i", CPythonApplication::Instance().IsPressed(iKey)); } PyObject * appSetCursor(PyObject * poSelf, PyObject * poArgs) { /* char * szName; if (!PyTuple_GetString(poArgs, 0, &szName)) return Py_BuildException(); if (!CPythonApplication::Instance().SetHardwareCursor(szName)) return Py_BuildException("Wrong Cursor Name [%s]", szName); */ int iCursorNum; if (!PyTuple_GetInteger(poArgs, 0, &iCursorNum)) return Py_BuildException(); if (!CPythonApplication::Instance().SetCursorNum(iCursorNum)) return Py_BuildException("Wrong Cursor Name [%d]", iCursorNum); return Py_BuildNone(); } PyObject * appGetCursor(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", CPythonApplication::Instance().GetCursorNum()); } PyObject * appShowCursor(PyObject * poSelf, PyObject * poArgs) { CPythonApplication::Instance().SetCursorVisible(TRUE); return Py_BuildNone(); } PyObject * appHideCursor(PyObject * poSelf, PyObject * poArgs) { CPythonApplication::Instance().SetCursorVisible(FALSE); return Py_BuildNone(); } PyObject * appIsShowCursor(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", TRUE == CPythonApplication::Instance().GetCursorVisible()); } PyObject * appIsLiarCursorOn(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", TRUE == CPythonApplication::Instance().GetLiarCursorOn()); } PyObject * appSetSoftwareCursor(PyObject * poSelf, PyObject * poArgs) { CPythonApplication::Instance().SetCursorMode(CPythonApplication::CURSOR_MODE_SOFTWARE); return Py_BuildNone(); } PyObject * appSetHardwareCursor(PyObject * poSelf, PyObject * poArgs) { CPythonApplication::Instance().SetCursorMode(CPythonApplication::CURSOR_MODE_HARDWARE); return Py_BuildNone(); } PyObject * appSetConnectData(PyObject * poSelf, PyObject * poArgs) { char * szIP; if (!PyTuple_GetString(poArgs, 0, &szIP)) return Py_BuildException(); int iPort; if (!PyTuple_GetInteger(poArgs, 1, &iPort)) return Py_BuildException(); CPythonApplication::Instance().SetConnectData(szIP, iPort); return Py_BuildNone(); } PyObject * appGetConnectData(PyObject * poSelf, PyObject * poArgs) { std::string strIP; int iPort; CPythonApplication::Instance().GetConnectData(strIP, iPort); return Py_BuildValue("si", strIP.c_str(), iPort); } PyObject * appGetRandom(PyObject * poSelf, PyObject * poArgs) { int from; if (!PyTuple_GetInteger(poArgs, 0, &from)) return Py_BuildException(); int to; if (!PyTuple_GetInteger(poArgs, 1, &to)) return Py_BuildException(); if (from > to) { int tmp = from; from = to; to = tmp; } return Py_BuildValue("i", random_range(from, to)); } PyObject * appGetRotatingDirection(PyObject * poSelf, PyObject * poArgs) { float fSource; if (!PyTuple_GetFloat(poArgs, 0, &fSource)) return Py_BuildException(); float fTarget; if (!PyTuple_GetFloat(poArgs, 1, &fTarget)) return Py_BuildException(); return Py_BuildValue("i", GetRotatingDirection(fSource, fTarget)); } PyObject * appGetDegreeDifference(PyObject * poSelf, PyObject * poArgs) { float fSource; if (!PyTuple_GetFloat(poArgs, 0, &fSource)) return Py_BuildException(); float fTarget; if (!PyTuple_GetFloat(poArgs, 1, &fTarget)) return Py_BuildException(); return Py_BuildValue("f", GetDegreeDifference(fSource, fTarget)); } PyObject * appSleep(PyObject * poSelf, PyObject * poArgs) { int iTime; if (!PyTuple_GetInteger(poArgs, 0, &iTime)) return Py_BuildException(); Sleep(iTime); return Py_BuildNone(); } PyObject * appSetDefaultFontName(PyObject * poSelf, PyObject * poArgs) { char * szFontName; if (!PyTuple_GetString(poArgs, 0, &szFontName)) return Py_BuildException(); // DEFAULT_FONT DefaultFont_SetName(szFontName); // END_OF_DEFAULT_FONT return Py_BuildNone(); } PyObject * appSetGuildSymbolPath(PyObject * poSelf, PyObject * poArgs) { char * szPathName; if (!PyTuple_GetString(poArgs, 0, &szPathName)) return Py_BuildException(); SetGuildSymbolPath(szPathName); return Py_BuildNone(); } PyObject * appEnableSpecialCameraMode(PyObject * poSelf, PyObject * poArgs) { CPythonApplication::Instance().EnableSpecialCameraMode(); return Py_BuildNone(); } PyObject * appSetCameraSpeed(PyObject * poSelf, PyObject * poArgs) { int iPercentage; if (!PyTuple_GetInteger(poArgs, 0, &iPercentage)) return Py_BuildException(); CPythonApplication::Instance().SetCameraSpeed(iPercentage); CCamera * pCamera = CCameraManager::Instance().GetCurrentCamera(); if (pCamera) pCamera->SetResistance(float(iPercentage) / 100.0f); return Py_BuildNone(); } PyObject * appIsFileExist(PyObject * poSelf, PyObject * poArgs) { char * szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); return Py_BuildValue("i", -1 != _access(szFileName, 0)); } PyObject * appSetCameraSetting(PyObject * poSelf, PyObject * poArgs) { int ix; if (!PyTuple_GetInteger(poArgs, 0, &ix)) return Py_BuildException(); int iy; if (!PyTuple_GetInteger(poArgs, 1, &iy)) return Py_BuildException(); int iz; if (!PyTuple_GetInteger(poArgs, 2, &iz)) return Py_BuildException(); int iZoom; if (!PyTuple_GetInteger(poArgs, 3, &iZoom)) return Py_BuildException(); int iRotation; if (!PyTuple_GetInteger(poArgs, 4, &iRotation)) return Py_BuildException(); int iPitch; if (!PyTuple_GetInteger(poArgs, 5, &iPitch)) return Py_BuildException(); CPythonApplication::SCameraSetting CameraSetting; ZeroMemory(&CameraSetting, sizeof(CameraSetting)); CameraSetting.v3CenterPosition.x = float(ix); CameraSetting.v3CenterPosition.y = float(iy); CameraSetting.v3CenterPosition.z = float(iz); CameraSetting.fZoom = float(iZoom); CameraSetting.fRotation = float(iRotation); CameraSetting.fPitch = float(iPitch); CPythonApplication::Instance().SetEventCamera(CameraSetting); return Py_BuildNone(); } PyObject * appSaveCameraSetting(PyObject * poSelf, PyObject * poArgs) { char * szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); CPythonApplication::Instance().SaveCameraSetting(szFileName); return Py_BuildNone(); } PyObject * appLoadCameraSetting(PyObject * poSelf, PyObject * poArgs) { char * szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); bool bResult = CPythonApplication::Instance().LoadCameraSetting(szFileName); return Py_BuildValue("i", bResult); } PyObject * appSetDefaultCamera(PyObject * poSelf, PyObject * poArgs) { CPythonApplication::Instance().SetDefaultCamera(); return Py_BuildNone(); } PyObject * appSetSightRange(PyObject * poSelf, PyObject * poArgs) { int iRange; if (!PyTuple_GetInteger(poArgs, 0, &iRange)) return Py_BuildException(); CPythonApplication::Instance().SetForceSightRange(iRange); return Py_BuildNone(); } extern int g_iAccumulationTime; PyObject * apptestGetAccumulationTime(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", g_iAccumulationTime); } PyObject * apptestResetAccumulationTime(PyObject * poSelf, PyObject * poArgs) { g_iAccumulationTime = 0; return Py_BuildNone(); } PyObject * apptestSetSpecularColor(PyObject * poSelf, PyObject * poArgs) { float fr; if (!PyTuple_GetFloat(poArgs, 0, &fr)) return Py_BuildException(); float fg; if (!PyTuple_GetFloat(poArgs, 1, &fg)) return Py_BuildException(); float fb; if (!PyTuple_GetFloat(poArgs, 2, &fb)) return Py_BuildException(); g_fSpecularColor = D3DXCOLOR(fr, fg, fb, 1.0f); return Py_BuildNone(); } PyObject * appSetVisibleNotice(PyObject * poSelf, PyObject * poArgs) { int iFlag; if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) return Py_BuildException(); bVisibleNotice = iFlag; return Py_BuildNone(); } PyObject * appIsVisibleNotice(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", bVisibleNotice); } PyObject * appEnableTestServerFlag(PyObject * poSelf, PyObject * poArgs) { bTestServerFlag = TRUE; return Py_BuildNone(); } PyObject * appIsEnableTestServerFlag(PyObject * poSelf, PyObject * poArgs) { return Py_BuildValue("i", bTestServerFlag); } class CTextLineLoader { public: CTextLineLoader(const char * c_szFileName) { const VOID* pvData; CMappedFile kFile; if (!CEterPackManager::Instance().Get(kFile, c_szFileName, &pvData)) return; m_kTextFileLoader.Bind(kFile.Size(), pvData); } DWORD GetLineCount() { return m_kTextFileLoader.GetLineCount(); } const char * GetLine(DWORD dwIndex) { if (dwIndex >= GetLineCount()) return ""; return m_kTextFileLoader.GetLineString(dwIndex).c_str(); } protected: CMemoryTextFileLoader m_kTextFileLoader; }; PyObject * appOpenTextFile(PyObject * poSelf, PyObject * poArgs) { char * szFileName; if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BuildException(); CTextLineLoader * pTextLineLoader = new CTextLineLoader(szFileName); return Py_BuildValue("i", (int)pTextLineLoader); } PyObject * appCloseTextFile(PyObject * poSelf, PyObject * poArgs) { int iHandle; if (!PyTuple_GetInteger(poArgs, 0, &iHandle)) return Py_BuildException(); CTextLineLoader * pTextFileLoader = (CTextLineLoader *)iHandle; delete pTextFileLoader; return Py_BuildNone(); } PyObject * appGetTextFileLineCount(PyObject * poSelf, PyObject * poArgs) { int iHandle; if (!PyTuple_GetInteger(poArgs, 0, &iHandle)) return Py_BuildException(); CTextLineLoader * pTextFileLoader = (CTextLineLoader *)iHandle; return Py_BuildValue("i", pTextFileLoader->GetLineCount()); } PyObject * appGetTextFileLine(PyObject * poSelf, PyObject * poArgs) { int iHandle; if (!PyTuple_GetInteger(poArgs, 0, &iHandle)) return Py_BuildException(); int iLineIndex; if (!PyTuple_GetInteger(poArgs, 1, &iLineIndex)) return Py_BuildException(); CTextLineLoader * pTextFileLoader = (CTextLineLoader *)iHandle; return Py_BuildValue("s", pTextFileLoader->GetLine(iLineIndex)); } PyObject * appSetGuildMarkPath(PyObject * poSelf, PyObject * poArgs) { char * path; if (!PyTuple_GetString(poArgs, 0, &path)) return Py_BuildException(); char newPath[256]; char * ext = strstr(path, ".tga"); if (ext) { int extPos = ext - path; strncpy(newPath, path, extPos); newPath[extPos] = '\0'; } else strncpy(newPath, path, sizeof(newPath)-1); CGuildMarkManager::Instance().SetMarkPathPrefix(newPath); return Py_BuildNone(); } PyObject* appIsDevStage(PyObject* poSelf, PyObject* poArgs) { int nIsDevelopmentStage = 0; #if defined(LOCALE_SERVICE_STAGE_DEVELOPMENT) nIsDevelopmentStage = 1; #endif return Py_BuildValue("i", nIsDevelopmentStage); } PyObject* appIsTestStage(PyObject* poSelf, PyObject* poArgs) { int nIsTestStage = 0; #if defined(LOCALE_SERVICE_STAGE_TEST) nIsTestStage = 1; #endif return Py_BuildValue("i", nIsTestStage); } PyObject* appIsLiveStage(PyObject* poSelf, PyObject* poArgs) { int nIsLiveStage = 0; #if !defined(LOCALE_SERVICE_STAGE_TEST) && !defined(LOCALE_SERVICE_STAGE_DEVELOPMENT) nIsLiveStage = 1; #endif return Py_BuildValue("i", nIsLiveStage); } PyObject* appLogoOpen(PyObject* poSelf, PyObject* poArgs) { char* szName; if (!PyTuple_GetString(poArgs, 0, &szName)) return Py_BuildException(); int nIsSuccess = 1; //CPythonApplication::Instance().OnLogoOpen(szName); CMovieMan::Instance().PlayLogo(szName); return Py_BuildValue("i", nIsSuccess); } PyObject* appLogoUpdate(PyObject* poSelf, PyObject* poArgs) { int nIsRun = 0; //CPythonApplication::Instance().OnLogoUpdate(); return Py_BuildValue("i", nIsRun); } PyObject* appLogoRender(PyObject* poSelf, PyObject* poArgs) { //CPythonApplication::Instance().OnLogoRender(); return Py_BuildNone(); } PyObject* appLogoClose(PyObject* poSelf, PyObject* poArgs) { //CPythonApplication::Instance().OnLogoClose(); return Py_BuildNone(); } void initapp() { static PyMethodDef s_methods[] = { { "IsDevStage", appIsDevStage, METH_VARARGS }, { "IsTestStage", appIsTestStage, METH_VARARGS }, { "IsLiveStage", appIsLiveStage, METH_VARARGS }, // TEXTTAIL_LIVINGTIME_CONTROL { "SetTextTailLivingTime", appSetTextTailLivingTime, METH_VARARGS }, // END_OF_TEXTTAIL_LIVINGTIME_CONTROL { "EnablePerformanceTime", appEnablePerformanceTime, METH_VARARGS }, { "SetHairColorEnable", appSetHairColorEnable, METH_VARARGS }, { "SetArmorSpecularEnable", appSetArmorSpecularEnable, METH_VARARGS }, { "SetWeaponSpecularEnable", appSetWeaponSpecularEnable, METH_VARARGS }, { "SetSkillEffectUpgradeEnable",appSetSkillEffectUpgradeEnable, METH_VARARGS }, { "SetTwoHandedWeaponAttSpeedDecreaseValue", SetTwoHandedWeaponAttSpeedDecreaseValue, METH_VARARGS }, { "SetRideHorseEnable", appSetRideHorseEnable, METH_VARARGS }, { "SetCameraMaxDistance", appSetCameraMaxDistance, METH_VARARGS }, { "SetMinFog", appSetMinFog, METH_VARARGS }, { "SetFrameSkip", appSetFrameSkip, METH_VARARGS }, { "GetImageInfo", appGetImageInfo, METH_VARARGS }, { "GetInfo", appGetInfo, METH_VARARGS }, { "UpdateGame", appUpdateGame, METH_VARARGS }, { "RenderGame", appRenderGame, METH_VARARGS }, { "Loop", appLoop, METH_VARARGS }, { "Create", appCreate, METH_VARARGS }, { "Process", appProcess, METH_VARARGS }, { "Exit", appExit, METH_VARARGS }, { "Abort", appAbort, METH_VARARGS }, { "SetMouseHandler", appSetMouseHandler, METH_VARARGS }, { "IsExistFile", appIsExistFile, METH_VARARGS }, { "GetFileList", appGetFileList, METH_VARARGS }, { "SetCamera", appSetCamera, METH_VARARGS }, { "GetCamera", appGetCamera, METH_VARARGS }, { "GetCameraPitch", appGetCameraPitch, METH_VARARGS }, { "GetCameraRotation", appGetCameraRotation, METH_VARARGS }, { "GetTime", appGetTime, METH_VARARGS }, { "GetGlobalTime", appGetGlobalTime, METH_VARARGS }, { "GetGlobalTimeStamp", appGetGlobalTimeStamp, METH_VARARGS }, { "GetUpdateFPS", appGetUpdateFPS, METH_VARARGS }, { "GetRenderFPS", appGetRenderFPS, METH_VARARGS }, { "RotateCamera", appRotateCamera, METH_VARARGS }, { "PitchCamera", appPitchCamera, METH_VARARGS }, { "ZoomCamera", appZoomCamera, METH_VARARGS }, { "MovieRotateCamera", appMovieRotateCamera, METH_VARARGS }, { "MoviePitchCamera", appMoviePitchCamera, METH_VARARGS }, { "MovieZoomCamera", appMovieZoomCamera, METH_VARARGS }, { "MovieResetCamera", appMovieResetCamera, METH_VARARGS }, { "GetAvailableTextureMemory", appGetAvaiableTextureMememory, METH_VARARGS }, { "GetRenderTime", appGetRenderTime, METH_VARARGS }, { "GetUpdateTime", appGetUpdateTime, METH_VARARGS }, { "GetLoad", appGetLoad, METH_VARARGS }, { "GetFaceSpeed", appGetFaceSpeed, METH_VARARGS }, { "GetFaceCount", appGetFaceCount, METH_VARARGS }, { "SetFPS", appSetFPS, METH_VARARGS }, { "SetGlobalCenterPosition", appSetGlobalCenterPosition, METH_VARARGS }, { "SetCenterPosition", appSetCenterPosition, METH_VARARGS }, { "GetCursorPosition", appGetCursorPosition, METH_VARARGS }, { "GetRandom", appGetRandom, METH_VARARGS }, { "RunPythonFile", appRunPythonFile, METH_VARARGS }, { "IsWebPageMode", appIsWebPageMode, METH_VARARGS }, { "ShowWebPage", appShowWebPage, METH_VARARGS }, { "MoveWebPage", appMoveWebPage, METH_VARARGS }, { "HideWebPage", appHideWebPage, METH_VARARGS }, { "IsPressed", appIsPressed, METH_VARARGS }, { "SetCursor", appSetCursor, METH_VARARGS }, { "GetCursor", appGetCursor, METH_VARARGS }, { "ShowCursor", appShowCursor, METH_VARARGS }, { "HideCursor", appHideCursor, METH_VARARGS }, { "IsShowCursor", appIsShowCursor, METH_VARARGS }, { "IsLiarCursorOn", appIsLiarCursorOn, METH_VARARGS }, { "SetSoftwareCursor", appSetSoftwareCursor, METH_VARARGS }, { "SetHardwareCursor", appSetHardwareCursor, METH_VARARGS }, { "SetConnectData", appSetConnectData, METH_VARARGS }, { "GetConnectData", appGetConnectData, METH_VARARGS }, { "GetRotatingDirection", appGetRotatingDirection, METH_VARARGS }, { "GetDegreeDifference", appGetDegreeDifference, METH_VARARGS }, { "Sleep", appSleep, METH_VARARGS }, { "SetDefaultFontName", appSetDefaultFontName, METH_VARARGS }, { "SetGuildSymbolPath", appSetGuildSymbolPath, METH_VARARGS }, { "EnableSpecialCameraMode", appEnableSpecialCameraMode, METH_VARARGS }, { "SetCameraSpeed", appSetCameraSpeed, METH_VARARGS }, { "SaveCameraSetting", appSaveCameraSetting, METH_VARARGS }, { "LoadCameraSetting", appLoadCameraSetting, METH_VARARGS }, { "SetDefaultCamera", appSetDefaultCamera, METH_VARARGS }, { "SetCameraSetting", appSetCameraSetting, METH_VARARGS }, { "SetSightRange", appSetSightRange, METH_VARARGS }, { "IsFileExist", appIsFileExist, METH_VARARGS }, { "OpenTextFile", appOpenTextFile, METH_VARARGS }, { "CloseTextFile", appCloseTextFile, METH_VARARGS }, { "GetTextFileLineCount", appGetTextFileLineCount, METH_VARARGS }, { "GetTextFileLine", appGetTextFileLine, METH_VARARGS }, // LOCALE { "GetLocaleServiceName", appGetLocaleServiceName, METH_VARARGS }, { "GetLocaleName", appGetLocaleName, METH_VARARGS }, { "GetLocalePath", appGetLocalePath, METH_VARARGS }, { "ForceSetLocale", appForceSetLocale, METH_VARARGS }, // END_OF_LOCALE // CHEONMA { "LoadLocaleAddr", appLoadLocaleAddr, METH_VARARGS }, { "LoadLocaleData", appLoadLocaleData, METH_VARARGS }, { "SetCHEONMA", appSetCHEONMA, METH_VARARGS }, { "IsCHEONMA", appIsCHEONMA, METH_VARARGS }, // END_OF_CHEONMA { "GetDefaultCodePage", appGetDefaultCodePage, METH_VARARGS }, { "SetControlFP", appSetControlFP, METH_VARARGS }, { "SetSpecularSpeed", appSetSpecularSpeed, METH_VARARGS }, { "testGetAccumulationTime", apptestGetAccumulationTime, METH_VARARGS }, { "testResetAccumulationTime", apptestResetAccumulationTime, METH_VARARGS }, { "testSetSpecularColor", apptestSetSpecularColor, METH_VARARGS }, { "SetVisibleNotice", appSetVisibleNotice, METH_VARARGS }, { "IsVisibleNotice", appIsVisibleNotice, METH_VARARGS }, { "EnableTestServerFlag", appEnableTestServerFlag, METH_VARARGS }, { "IsEnableTestServerFlag", appIsEnableTestServerFlag, METH_VARARGS }, { "SetGuildMarkPath", appSetGuildMarkPath, METH_VARARGS }, { "OnLogoUpdate", appLogoUpdate, METH_VARARGS }, { "OnLogoRender", appLogoRender, METH_VARARGS }, { "OnLogoOpen", appLogoOpen, METH_VARARGS }, { "OnLogoClose", appLogoClose, METH_VARARGS }, { NULL, NULL }, }; PyObject * poModule = Py_InitModule("app", s_methods); PyModule_AddIntConstant(poModule, "INFO_ITEM", CPythonApplication::INFO_ITEM); PyModule_AddIntConstant(poModule, "INFO_ACTOR", CPythonApplication::INFO_ACTOR); PyModule_AddIntConstant(poModule, "INFO_EFFECT", CPythonApplication::INFO_EFFECT); PyModule_AddIntConstant(poModule, "INFO_TEXTTAIL", CPythonApplication::INFO_TEXTTAIL); PyModule_AddIntConstant(poModule, "DEGREE_DIRECTION_SAME", DEGREE_DIRECTION_SAME); PyModule_AddIntConstant(poModule, "DEGREE_DIRECTION_RIGHT", DEGREE_DIRECTION_RIGHT); PyModule_AddIntConstant(poModule, "DEGREE_DIRECTION_LEFT", DEGREE_DIRECTION_LEFT); PyModule_AddIntConstant(poModule, "VK_LEFT", VK_LEFT); PyModule_AddIntConstant(poModule, "VK_RIGHT", VK_RIGHT); PyModule_AddIntConstant(poModule, "VK_UP", VK_UP); PyModule_AddIntConstant(poModule, "VK_DOWN", VK_DOWN); PyModule_AddIntConstant(poModule, "VK_HOME", VK_HOME); PyModule_AddIntConstant(poModule, "VK_END", VK_END); PyModule_AddIntConstant(poModule, "VK_DELETE", VK_DELETE); PyModule_AddIntConstant(poModule, "DIK_ESCAPE", DIK_ESCAPE); PyModule_AddIntConstant(poModule, "DIK_ESC", DIK_ESCAPE); // 편의를 위해 PyModule_AddIntConstant(poModule, "DIK_1", DIK_1); PyModule_AddIntConstant(poModule, "DIK_2", DIK_2); PyModule_AddIntConstant(poModule, "DIK_3", DIK_3); PyModule_AddIntConstant(poModule, "DIK_4", DIK_4); PyModule_AddIntConstant(poModule, "DIK_5", DIK_5); PyModule_AddIntConstant(poModule, "DIK_6", DIK_6); PyModule_AddIntConstant(poModule, "DIK_7", DIK_7); PyModule_AddIntConstant(poModule, "DIK_8", DIK_8); PyModule_AddIntConstant(poModule, "DIK_9", DIK_9); PyModule_AddIntConstant(poModule, "DIK_0", DIK_0); PyModule_AddIntConstant(poModule, "DIK_MINUS", DIK_MINUS); /* - on main keyboard */ PyModule_AddIntConstant(poModule, "DIK_EQUALS", DIK_EQUALS); PyModule_AddIntConstant(poModule, "DIK_BACK", DIK_BACK); /* backspace */ PyModule_AddIntConstant(poModule, "DIK_TAB", DIK_TAB); PyModule_AddIntConstant(poModule, "DIK_Q", DIK_Q); PyModule_AddIntConstant(poModule, "DIK_W", DIK_W); PyModule_AddIntConstant(poModule, "DIK_E", DIK_E); PyModule_AddIntConstant(poModule, "DIK_R", DIK_R); PyModule_AddIntConstant(poModule, "DIK_T", DIK_T); PyModule_AddIntConstant(poModule, "DIK_Y", DIK_Y); PyModule_AddIntConstant(poModule, "DIK_U", DIK_U); PyModule_AddIntConstant(poModule, "DIK_I", DIK_I); PyModule_AddIntConstant(poModule, "DIK_O", DIK_O); PyModule_AddIntConstant(poModule, "DIK_P", DIK_P); PyModule_AddIntConstant(poModule, "DIK_LBRACKET", DIK_LBRACKET); PyModule_AddIntConstant(poModule, "DIK_RBRACKET", DIK_RBRACKET); PyModule_AddIntConstant(poModule, "DIK_RETURN", DIK_RETURN); /* Enter on main keyboard */ PyModule_AddIntConstant(poModule, "DIK_LCONTROL", DIK_LCONTROL); PyModule_AddIntConstant(poModule, "DIK_A", DIK_A); PyModule_AddIntConstant(poModule, "DIK_S", DIK_S); PyModule_AddIntConstant(poModule, "DIK_D", DIK_D); PyModule_AddIntConstant(poModule, "DIK_F", DIK_F); PyModule_AddIntConstant(poModule, "DIK_G", DIK_G); PyModule_AddIntConstant(poModule, "DIK_H", DIK_H); PyModule_AddIntConstant(poModule, "DIK_J", DIK_J); PyModule_AddIntConstant(poModule, "DIK_K", DIK_K); PyModule_AddIntConstant(poModule, "DIK_L", DIK_L); PyModule_AddIntConstant(poModule, "DIK_SEMICOLON", DIK_SEMICOLON); PyModule_AddIntConstant(poModule, "DIK_APOSTROPHE", DIK_APOSTROPHE); PyModule_AddIntConstant(poModule, "DIK_GRAVE", DIK_GRAVE); /* accent grave */ PyModule_AddIntConstant(poModule, "DIK_LSHIFT", DIK_LSHIFT); PyModule_AddIntConstant(poModule, "DIK_BACKSLASH", DIK_BACKSLASH); PyModule_AddIntConstant(poModule, "DIK_Z", DIK_Z); PyModule_AddIntConstant(poModule, "DIK_X", DIK_X); PyModule_AddIntConstant(poModule, "DIK_C", DIK_C); PyModule_AddIntConstant(poModule, "DIK_V", DIK_V); PyModule_AddIntConstant(poModule, "DIK_B", DIK_B); PyModule_AddIntConstant(poModule, "DIK_N", DIK_N); PyModule_AddIntConstant(poModule, "DIK_M", DIK_M); PyModule_AddIntConstant(poModule, "DIK_COMMA", DIK_COMMA); PyModule_AddIntConstant(poModule, "DIK_PERIOD", DIK_PERIOD); /* . on main keyboard */ PyModule_AddIntConstant(poModule, "DIK_SLASH", DIK_SLASH); /* / on main keyboard */ PyModule_AddIntConstant(poModule, "DIK_RSHIFT", DIK_RSHIFT); PyModule_AddIntConstant(poModule, "DIK_MULTIPLY", DIK_MULTIPLY); /* * on numeric keypad */ PyModule_AddIntConstant(poModule, "DIK_LALT", DIK_LMENU); /* left Alt */ PyModule_AddIntConstant(poModule, "DIK_SPACE", DIK_SPACE); PyModule_AddIntConstant(poModule, "DIK_CAPITAL", DIK_CAPITAL); PyModule_AddIntConstant(poModule, "DIK_F1", DIK_F1); PyModule_AddIntConstant(poModule, "DIK_F2", DIK_F2); PyModule_AddIntConstant(poModule, "DIK_F3", DIK_F3); PyModule_AddIntConstant(poModule, "DIK_F4", DIK_F4); PyModule_AddIntConstant(poModule, "DIK_F5", DIK_F5); PyModule_AddIntConstant(poModule, "DIK_F6", DIK_F6); PyModule_AddIntConstant(poModule, "DIK_F7", DIK_F7); PyModule_AddIntConstant(poModule, "DIK_F8", DIK_F8); PyModule_AddIntConstant(poModule, "DIK_F9", DIK_F9); PyModule_AddIntConstant(poModule, "DIK_F10", DIK_F10); PyModule_AddIntConstant(poModule, "DIK_NUMLOCK", DIK_NUMLOCK); PyModule_AddIntConstant(poModule, "DIK_SCROLL", DIK_SCROLL); /* Scroll Lock */ PyModule_AddIntConstant(poModule, "DIK_NUMPAD7", DIK_NUMPAD7); PyModule_AddIntConstant(poModule, "DIK_NUMPAD8", DIK_NUMPAD8); PyModule_AddIntConstant(poModule, "DIK_NUMPAD9", DIK_NUMPAD9); PyModule_AddIntConstant(poModule, "DIK_SUBTRACT", DIK_SUBTRACT); /* - on numeric keypad */ PyModule_AddIntConstant(poModule, "DIK_NUMPAD4", DIK_NUMPAD4); PyModule_AddIntConstant(poModule, "DIK_NUMPAD5", DIK_NUMPAD5); PyModule_AddIntConstant(poModule, "DIK_NUMPAD6", DIK_NUMPAD6); PyModule_AddIntConstant(poModule, "DIK_ADD", DIK_ADD); /* + on numeric keypad */ PyModule_AddIntConstant(poModule, "DIK_NUMPAD1", DIK_NUMPAD1); PyModule_AddIntConstant(poModule, "DIK_NUMPAD2", DIK_NUMPAD2); PyModule_AddIntConstant(poModule, "DIK_NUMPAD3", DIK_NUMPAD3); PyModule_AddIntConstant(poModule, "DIK_NUMPAD0", DIK_NUMPAD0); PyModule_AddIntConstant(poModule, "DIK_DECIMAL", DIK_DECIMAL); /* . on numeric keypad */ PyModule_AddIntConstant(poModule, "DIK_F11", DIK_F11); PyModule_AddIntConstant(poModule, "DIK_F12", DIK_F12); PyModule_AddIntConstant(poModule, "DIK_NEXTTRACK", DIK_NEXTTRACK); /* Next Track */ PyModule_AddIntConstant(poModule, "DIK_NUMPADENTER", DIK_NUMPADENTER); /* Enter on numeric keypad */ PyModule_AddIntConstant(poModule, "DIK_RCONTROL", DIK_RCONTROL); PyModule_AddIntConstant(poModule, "DIK_MUTE", DIK_MUTE); /* Mute */ PyModule_AddIntConstant(poModule, "DIK_CALCULATOR", DIK_CALCULATOR); /* Calculator */ PyModule_AddIntConstant(poModule, "DIK_PLAYPAUSE", DIK_PLAYPAUSE); /* Play / Pause */ PyModule_AddIntConstant(poModule, "DIK_MEDIASTOP", DIK_MEDIASTOP); /* Media Stop */ PyModule_AddIntConstant(poModule, "DIK_VOLUMEDOWN", DIK_VOLUMEDOWN); /* Volume - */ PyModule_AddIntConstant(poModule, "DIK_VOLUMEUP", DIK_VOLUMEUP); /* Volume + */ PyModule_AddIntConstant(poModule, "DIK_WEBHOME", DIK_WEBHOME); /* Web home */ PyModule_AddIntConstant(poModule, "DIK_NUMPADCOMMA", DIK_NUMPADCOMMA); /* , on numeric keypad (NEC PC98) */ PyModule_AddIntConstant(poModule, "DIK_DIVIDE", DIK_DIVIDE); /* / on numeric keypad */ PyModule_AddIntConstant(poModule, "DIK_SYSRQ", DIK_SYSRQ); PyModule_AddIntConstant(poModule, "DIK_RALT", DIK_RMENU); /* right Alt */ PyModule_AddIntConstant(poModule, "DIK_PAUSE", DIK_PAUSE); /* Pause */ PyModule_AddIntConstant(poModule, "DIK_HOME", DIK_HOME); /* Home on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_UP", DIK_UP); /* UpArrow on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_PGUP", DIK_PRIOR); /* PgUp on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_LEFT", DIK_LEFT); /* LeftArrow on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_RIGHT", DIK_RIGHT); /* RightArrow on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_END", DIK_END); /* End on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_DOWN", DIK_DOWN); /* DownArrow on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_PGDN", DIK_NEXT); /* PgDn on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_INSERT", DIK_INSERT); /* Insert on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_DELETE", DIK_DELETE); /* Delete on arrow keypad */ PyModule_AddIntConstant(poModule, "DIK_LWIN", DIK_LWIN); /* Left Windows key */ PyModule_AddIntConstant(poModule, "DIK_RWIN", DIK_RWIN); /* Right Windows key */ PyModule_AddIntConstant(poModule, "DIK_APPS", DIK_APPS); /* AppMenu key */ // Cursor PyModule_AddIntConstant(poModule, "NORMAL", CPythonApplication::CURSOR_SHAPE_NORMAL); PyModule_AddIntConstant(poModule, "ATTACK", CPythonApplication::CURSOR_SHAPE_ATTACK); PyModule_AddIntConstant(poModule, "TARGET", CPythonApplication::CURSOR_SHAPE_TARGET); PyModule_AddIntConstant(poModule, "TALK", CPythonApplication::CURSOR_SHAPE_TALK); PyModule_AddIntConstant(poModule, "CANT_GO", CPythonApplication::CURSOR_SHAPE_CANT_GO); PyModule_AddIntConstant(poModule, "PICK", CPythonApplication::CURSOR_SHAPE_PICK); PyModule_AddIntConstant(poModule, "DOOR", CPythonApplication::CURSOR_SHAPE_DOOR); PyModule_AddIntConstant(poModule, "CHAIR", CPythonApplication::CURSOR_SHAPE_CHAIR); PyModule_AddIntConstant(poModule, "MAGIC", CPythonApplication::CURSOR_SHAPE_MAGIC); PyModule_AddIntConstant(poModule, "BUY", CPythonApplication::CURSOR_SHAPE_BUY); PyModule_AddIntConstant(poModule, "SELL", CPythonApplication::CURSOR_SHAPE_SELL); PyModule_AddIntConstant(poModule, "CAMERA_ROTATE", CPythonApplication::CURSOR_SHAPE_CAMERA_ROTATE); PyModule_AddIntConstant(poModule, "HSIZE", CPythonApplication::CURSOR_SHAPE_HSIZE); PyModule_AddIntConstant(poModule, "VSIZE", CPythonApplication::CURSOR_SHAPE_VSIZE); PyModule_AddIntConstant(poModule, "HVSIZE", CPythonApplication::CURSOR_SHAPE_HVSIZE); PyModule_AddIntConstant(poModule, "CAMERA_TO_POSITIVE", CPythonApplication::CAMERA_TO_POSITIVE); PyModule_AddIntConstant(poModule, "CAMERA_TO_NEGATIVE", CPythonApplication::CAMERA_TO_NEGITIVE); PyModule_AddIntConstant(poModule, "CAMERA_STOP", CPythonApplication::CAMERA_STOP); #ifdef ENABLE_COSTUME_SYSTEM PyModule_AddIntConstant(poModule, "ENABLE_COSTUME_SYSTEM", 1); #else PyModule_AddIntConstant(poModule, "ENABLE_COSTUME_SYSTEM", 0); #endif #ifdef ENABLE_ENERGY_SYSTEM PyModule_AddIntConstant(poModule, "ENABLE_ENERGY_SYSTEM", 1); #else PyModule_AddIntConstant(poModule, "ENABLE_ENERGY_SYSTEM", 0); #endif #ifdef ENABLE_DRAGON_SOUL_SYSTEM PyModule_AddIntConstant(poModule, "ENABLE_DRAGON_SOUL_SYSTEM", 1); #else PyModule_AddIntConstant(poModule, "ENABLE_DRAGON_SOUL_SYSTEM", 0); #endif #ifdef ENABLE_NEW_EQUIPMENT_SYSTEM PyModule_AddIntConstant(poModule, "ENABLE_NEW_EQUIPMENT_SYSTEM", 1); #else PyModule_AddIntConstant(poModule, "ENABLE_NEW_EQUIPMENT_SYSTEM", 0); #endif PyModule_AddIntConstant(poModule, "BR_SERVER_CONSOLIDATION_MESSAGE", 0); PyModule_AddIntConstant(poModule, "BR_SYSTEM_MESSAGE", 0); PyModule_AddIntConstant(poModule, "ENABLE_10TH_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_12ZI", 0); PyModule_AddIntConstant(poModule, "ENABLE_2016_VALENTINE", 0); PyModule_AddIntConstant(poModule, "ENABLE_2017_RAMADAN", 0); PyModule_AddIntConstant(poModule, "ENABLE_678TH_SKILL", 0); PyModule_AddIntConstant(poModule, "ENABLE_ACCE_SECOND_COSTUME_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_ACCUMULATE_DAMAGE_DISPLAY", 0); PyModule_AddIntConstant(poModule, "ENABLE_AI_FLAG_REFLECT", 0); PyModule_AddIntConstant(poModule, "ENABLE_AUTO_ATTACK", 0); PyModule_AddIntConstant(poModule, "ENABLE_AUTO_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_BALANCE_IMPROVING", 0); PyModule_AddIntConstant(poModule, "ENABLE_BATTLE_FIELD", 0); PyModule_AddIntConstant(poModule, "ENABLE_BOSS_BOX", 0); PyModule_AddIntConstant(poModule, "ENABLE_CARNIVAL2016", 0); PyModule_AddIntConstant(poModule, "ENABLE_CHANGED_ATTR", 0); PyModule_AddIntConstant(poModule, "ENABLE_CHANGE_LOOK_ITEM_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_CHANGE_LOOK_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_CHANNEL_LIST", 0); PyModule_AddIntConstant(poModule, "ENABLE_CHEQUE_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_COSTUME_ATTR_RENEWAL_SECOND", 0); //PyModule_AddIntConstant(poModule, "ENABLE_COSTUME_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_DELETE_FAILURE_TYPE", 0); PyModule_AddIntConstant(poModule, "ENABLE_DETAILS_UI", 0); //PyModule_AddIntConstant(poModule, "ENABLE_DRAGON_SOUL_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_DS_PASSWORD", 0); PyModule_AddIntConstant(poModule, "ENABLE_ELEMENT_ADD", 0); //PyModule_AddIntConstant(poModule, "ENABLE_ENERGY_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_ENVIRONMENT_EFFECT_OPTION", 0); PyModule_AddIntConstant(poModule, "ENABLE_EXP_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_EXTEND_INVEN_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_EXTEND_MALLBOX", 0); PyModule_AddIntConstant(poModule, "ENABLE_FISH_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_FLOWER_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_FOG_FIX", 0); PyModule_AddIntConstant(poModule, "ENABLE_GEM_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_GROWTH_PET_HATCHING_MONEY_CHANGE", 0); PyModule_AddIntConstant(poModule, "ENABLE_GROWTH_PET_SKILL_DEL", 0); PyModule_AddIntConstant(poModule, "ENABLE_GROWTH_PET_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_GUILDRENEWAL_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_GUILD_DRAGONLAIR_PARTY_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_GUILD_DRAGONLAIR_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_GUILD_MARK_RENEWAL", 0); PyModule_AddIntConstant(poModule, "ENABLE_HELP_RENEWAL", 0); PyModule_AddIntConstant(poModule, "ENABLE_INPUT_CANCEL", 0); PyModule_AddIntConstant(poModule, "ENABLE_INPUT_WIDTH_CHECK_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_KEYCHANGE_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_LUCKY_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_MAILBOX", 0); PyModule_AddIntConstant(poModule, "ENABLE_MESSENGER_BLOCK", 0); PyModule_AddIntConstant(poModule, "ENABLE_MESSENGER_LOCK_FIX", 0); PyModule_AddIntConstant(poModule, "ENABLE_MINI_GAME_OKEY_NORMAL", 0); PyModule_AddIntConstant(poModule, "ENABLE_MINI_GAME_YUTNORI", 0); PyModule_AddIntConstant(poModule, "ENABLE_MONSTER_BACK", 0); PyModule_AddIntConstant(poModule, "ENABLE_MONSTER_CARD", 0); PyModule_AddIntConstant(poModule, "ENABLE_MOVE_CHANNEL", 0); PyModule_AddIntConstant(poModule, "ENABLE_MOVE_COSTUME_ATTR", 0); PyModule_AddIntConstant(poModule, "ENABLE_MYSHOP_DECO", 0); //PyModule_AddIntConstant(poModule, "ENABLE_NEW_EQUIPMENT_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_NEW_HALLOWEEN_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_NEW_USER_CARE", 0); PyModule_AddIntConstant(poModule, "ENABLE_OX_RENEWAL", 0); PyModule_AddIntConstant(poModule, "ENABLE_PARTY_CHANNEL_FIX", 0); PyModule_AddIntConstant(poModule, "ENABLE_PARTY_LEADER_RENEWAL", 0); PyModule_AddIntConstant(poModule, "ENABLE_PARTY_MATCH", 0); PyModule_AddIntConstant(poModule, "ENABLE_PENDANT", 0); PyModule_AddIntConstant(poModule, "ENABLE_PEPSI_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_PICK_ROD_REFINE_RENEWAL", 0); PyModule_AddIntConstant(poModule, "ENABLE_PLAYER_PER_ACCOUNT5", 0); PyModule_AddIntConstant(poModule, "ENABLE_PRIVATESHOP_SEARCH_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_PVP_BALANCE", 0); PyModule_AddIntConstant(poModule, "ENABLE_PVP_ONOFF", 0); PyModule_AddIntConstant(poModule, "ENABLE_PVP_TOURNAMENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_PVP_TOURNAMENT_GF", 0); PyModule_AddIntConstant(poModule, "ENABLE_QUIVER_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_RANKING_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_RANKING_SYSTEM_PARTY", 0); PyModule_AddIntConstant(poModule, "ENABLE_REFINE_MSG_ADD", 0); PyModule_AddIntConstant(poModule, "ENABLE_RESEARCHER_ELIXIR_FIX", 0); PyModule_AddIntConstant(poModule, "ENABLE_SAFEBOX_IMPROVING", 0); PyModule_AddIntConstant(poModule, "ENABLE_SECOND_GUILDRENEWAL_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_SERVER_SELECT_RENEWAL", 0); PyModule_AddIntConstant(poModule, "ENABLE_SET_ITEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_SLOT_COVER_IMAGE_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_SOCKET_STRING3", 0); PyModule_AddIntConstant(poModule, "ENABLE_SOUL_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_SPECIAL_GACHA", 0); PyModule_AddIntConstant(poModule, "ENABLE_STEAM", 0); PyModule_AddIntConstant(poModule, "ENABLE_STONE_OF_BLESS", 0); PyModule_AddIntConstant(poModule, "ENABLE_STRUCTURE_VIEW_MODE", 0); PyModule_AddIntConstant(poModule, "ENABLE_SUMMER_EVENT", 0); PyModule_AddIntConstant(poModule, "ENABLE_USER_SITUATION_NOTICE", 0); PyModule_AddIntConstant(poModule, "ENABLE_WEAPON_COSTUME_SYSTEM", 0); PyModule_AddIntConstant(poModule, "ENABLE_WEB_LINKED_BANNER", 0); PyModule_AddIntConstant(poModule, "ENABLE_WEB_LINKED_BANNER_LIMIT_REMOVE", 0); PyModule_AddIntConstant(poModule, "ENABLE_WOLFMAN_CHARACTER", 0); //PyModule_AddIntConstant(poModule, "LOCALE_SERVICE_EUROPE", 0); //PyModule_AddIntConstant(poModule, "LOCALE_SERVICE_SINGAPORE", 0); PyModule_AddIntConstant(poModule, "LOGIN_COUNT_DOWN_UI_MODIFY", 0); PyModule_AddIntConstant(poModule, "LOGIN_TYPE_STEAM", 0); PyModule_AddIntConstant(poModule, "POPUPDIALOG_MODIFY", 0); PyModule_AddIntConstant(poModule, "WJ_ENABLE_PICKUP_ITEM_EFFECT", 0); PyModule_AddIntConstant(poModule, "WJ_ENABLE_TRADABLE_ICON", 0); PyModule_AddIntConstant(poModule, "WJ_MULTI_TEXTLINE", 0); PyModule_AddIntConstant(poModule, "WJ_NEW_USER_CARE", 0); PyModule_AddIntConstant(poModule, "WJ_SHOW_MOB_INFO", 0); PyModule_AddIntConstant(poModule, "WJ_SHOW_NPC_QUEST_NAME", 0); PyModule_AddIntConstant(poModule, "WJ_SHOW_PARTY_ON_MINIMAP", 0); #ifdef USE_OPENID PyModule_AddIntConstant(poModule, "USE_OPENID", 1); if (openid_test) PyModule_AddIntConstant(poModule, "OPENID_TEST", 1); else PyModule_AddIntConstant(poModule, "OPENID_TEST", 0); #else PyModule_AddIntConstant(poModule, "USE_OPENID", 0); PyModule_AddIntConstant(poModule, "OPENID_TEST", 0); #endif /* USE_OPENID */ }
[ "DominXw@outlook.com" ]
DominXw@outlook.com
699721dc5b20f894cfa22cac1fad89f5734969ac
c1d8cefebd8f85fe9a70ae18d6726e8e42a6fe3a
/02_c++2.0/c++11/08_智能指针/test2.cpp
7705c068b15d101630fa2b6cfc7643e89d99ba86
[]
no_license
leomaokai/MyCpp
7df0b4097561774c9050e9eed27134202b011c3a
e81b0ba50c7de046ee63af47accd2897b5e289ee
refs/heads/master
2023-02-19T11:14:58.697566
2021-01-22T16:50:13
2021-01-22T16:50:13
289,039,519
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
//test2.cpp #include<memory> #include<iostream> using namespace std; int main() { unique_ptr<int> ptr1(new int); unique_ptr<int> ptr2(std::move(ptr1));//使用了右值引用的拷贝构造 ptr2=std::move(ptr1);//使用了右值引用的operator=赋值重载函数 return 0; }
[ "leomaokai@163.com" ]
leomaokai@163.com
5d54128ce492945cb8ba207892d11ad12b14e894
5d37cf9e33b72b05ebcf9ee6d797c7a5c65ecc2d
/Option-Pricing-Model/Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/VI.3/PlainOption/EuropeanOption.cpp
2edf30d9a69baf289c0d8e68385d668e55625b79
[ "MIT" ]
permissive
bondxue/Option-Pricing-Model
ca00503b27350fa36cbfe430dd752974ab5c0b01
5f22df0ff31e90fd536eb216c5af19c697fb87b2
refs/heads/master
2020-05-15T18:44:50.725463
2019-04-21T17:02:22
2019-04-21T17:02:22
182,437,415
2
1
null
null
null
null
UTF-8
C++
false
false
3,141
cpp
// EurpeanOption.cpp // // Author: Daniel Duffy // // (C) Datasim Component Technology BV 2003-2011 // #include "EuropeanOption.hpp" #include <cmath> #include <iostream> //////////// Gaussian functions ///////////////////////////////// // In general, we would use similar functions in Boost::Math Toolkit double EuropeanOption::n(double x) const { double A = 1.0/sqrt(2.0 * 3.1415); return A * exp(-x*x*0.5); } double EuropeanOption::N(double x) const { // The approximation to the cumulative normal distribution double a1 = 0.4361836; double a2 = -0.1201676; double a3 = 0.9372980; double k = 1.0/(1.0 + (0.33267 * x)); if (x >= 0.0) { return 1.0 - n(x)* (a1*k + (a2*k*k) + (a3*k*k*k)); } else { return 1.0 - N(-x); } } // Kernel Functions (Haug) double EuropeanOption::CallPrice(double U) const { double tmp = sig * sqrt(T); double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp; double d2 = d1 - tmp; return (U * exp((b-r)*T) * N(d1)) - (K * exp(-r * T)* N(d2)); } double EuropeanOption::PutPrice(double U) const { double tmp = sig * sqrt(T); double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp; double d2 = d1 - tmp; return (K * exp(-r * T)* N(-d2)) - (U * exp((b-r)*T) * N(-d1)); } double EuropeanOption::CallDelta(double U) const { double tmp = sig * sqrt(T); double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp; return exp((b-r)*T) * N(d1); } double EuropeanOption::PutDelta(double U) const { double tmp = sig * sqrt(T); double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp; return exp((b-r)*T) * (N(d1) - 1.0); } ///////////////////////////////////////////////////////////////////////////////////// void EuropeanOption::init() { // Initialise all default values // Default values r = 0.05; sig= 0.2; K = 110.0; T = 0.5; b = r; // Black and Scholes stock option model (1973) optType = "C"; // European Call Option (this is the default type) } void EuropeanOption::copy( const EuropeanOption& o2) { r = o2.r; sig = o2.sig; K = o2.K; T = o2.T; b = o2.b; optType = o2.optType; } EuropeanOption::EuropeanOption() { // Default call option init(); } EuropeanOption::EuropeanOption(const EuropeanOption& o2) { // Copy constructor copy(o2); } EuropeanOption::EuropeanOption (const string& optionType) { // Create option type init(); optType = optionType; if (optType == "c") optType = "C"; } EuropeanOption::~EuropeanOption() { } EuropeanOption& EuropeanOption::operator = (const EuropeanOption& option2) { if (this == &option2) return *this; copy (option2); return *this; } // Functions that calculate option price and sensitivities double EuropeanOption::Price(double U) const { if (optType == "C") { cout << "calling call\n"; return CallPrice(U); } else { cout << "calling put\n"; return PutPrice(U); } } double EuropeanOption::Delta(double U) const { if (optType == "C") return CallDelta(U); else return PutDelta(U); } // Modifier functions void EuropeanOption::toggle() { // Change option type (C/P, P/C) if (optType == "C") optType = "P"; else optType = "C"; }
[ "menghengxue@gmail.com" ]
menghengxue@gmail.com
ad4cb27bd7946891db42125f36fef60224ef88c7
374f122c4439d651740aef63cc21ae4de471ca8d
/cocos2d/tests/performance-tests/Classes/Profile.cpp
1836cc44c4fe2fd56e2fb5a756801d0ea1f8f2c2
[ "MIT" ]
permissive
vladubogdan/LevelHelper2-Cocos2d-X.v3
5983d0c37ebc61cf73c0f95959662ade60c6a338
6ee54482d7ee0627a6f7ec54a26cf8fdbe4fb3f2
refs/heads/master
2016-09-15T08:38:51.909423
2016-05-15T05:07:44
2016-05-15T05:07:44
20,055,666
8
2
null
2016-04-02T08:27:16
2014-05-22T09:36:16
C++
UTF-8
C++
false
false
8,132
cpp
#include "Profile.h" #include "json/document.h" #include "json/prettywriter.h" #include "json/stringbuffer.h" #include "platform/CCFileUtils.h" #include "cocos2d.h" #include <time.h> #define LOG_FILE_NAME_FMT "PerformanceLog-%s-%s.json" #define PLIST_FILE_NAME "PerformanceLog.plist" #define KEY_DEVICE "device" #define KEY_ENGINE_VERSION "engineVersion" #define KEY_RESULTS "results" #define KEY_CONDITION_HEADERS "conditionHeaders" #define KEY_RESULT_HEADERS "resultHeaders" #define KEY_FILE_VERSION "fileVersion" #define KEY_OS_VERSION "osVersion" #define KEY_TIMESTAMP "timeStamp" #define FILE_VERSION 1 #define USE_PRETTY_OUTPUT_FORMAT 0 #define USE_JSON_FORMAT 1 // For different device & os, change these values // TODO : get device info automatically #define DEVICE_NAME "DeviceName" #define OS_VERSION "SystemVersion" static Profile* s_profile = nullptr; USING_NS_CC; // tools methods std::string genStr(const char* format, ...) { va_list arg_ptr; va_start(arg_ptr, format); char buf[MAX_LOG_LENGTH]; vsnprintf(buf, MAX_LOG_LENGTH - 3, format, arg_ptr); va_end(arg_ptr); return buf; } std::vector<std::string> genStrVector(const char* str1, ...) { std::vector<std::string> ret; va_list arg_ptr; const char* str = str1; va_start(arg_ptr, str1); while (nullptr != str) { std::string strObj = str; ret.push_back(strObj); str = va_arg(arg_ptr, const char*); } va_end(arg_ptr); return ret; } // declare the methods rapidjson::Value valueVectorToJson(cocos2d::ValueVector & theVector, rapidjson::Document::AllocatorType& allocator); rapidjson::Value valueMapToJson(cocos2d::ValueMap & theMap, rapidjson::Document::AllocatorType& allocator); rapidjson::Value convertToJsonValue(cocos2d::Value & value, rapidjson::Document::AllocatorType& allocator) { rapidjson::Value theJsonValue; auto type = value.getType(); switch (type) { case cocos2d::Value::Type::STRING: theJsonValue.SetString(value.asString().c_str(), allocator); break; case cocos2d::Value::Type::MAP: theJsonValue = valueMapToJson(value.asValueMap(), allocator); break; case cocos2d::Value::Type::VECTOR: theJsonValue = valueVectorToJson(value.asValueVector(), allocator); break; case cocos2d::Value::Type::INTEGER: theJsonValue.SetInt(value.asInt()); break; case cocos2d::Value::Type::BOOLEAN: theJsonValue.SetBool(value.asBool()); break; case cocos2d::Value::Type::FLOAT: case cocos2d::Value::Type::DOUBLE: theJsonValue.SetDouble(value.asDouble()); break; default: break; } return theJsonValue; } rapidjson::Value valueMapToJson(cocos2d::ValueMap & theMap, rapidjson::Document::AllocatorType& allocator) { rapidjson::Value ret(rapidjson::kObjectType); for (ValueMap::iterator iter = theMap.begin(); iter != theMap.end(); ++iter) { auto key = iter->first; rapidjson::Value theJsonKey(rapidjson::kStringType); theJsonKey.SetString(key.c_str(), allocator); cocos2d::Value value = iter->second; rapidjson::Value theJsonValue = convertToJsonValue(value, allocator); ret.AddMember(theJsonKey, theJsonValue, allocator); } return ret; } rapidjson::Value valueVectorToJson(cocos2d::ValueVector & theVector, rapidjson::Document::AllocatorType& allocator) { rapidjson::Value ret(rapidjson::kArrayType); auto vectorSize = theVector.size(); for (int i = 0; i < vectorSize; i++) { cocos2d::Value value = theVector[i]; rapidjson::Value theJsonValue = convertToJsonValue(value, allocator); ret.PushBack(theJsonValue, allocator); } return ret; } Profile* Profile::getInstance() { if (nullptr == s_profile) { s_profile = new Profile(); } return s_profile; } void Profile::destroyInstance() { CC_SAFE_DELETE(s_profile); } Profile::Profile() { } Profile::~Profile() { } void Profile::testCaseBegin(std::string testName, std::vector<std::string> condHeaders, std::vector<std::string> retHeaders) { curTestName = testName; ValueVector conds; for (int i = 0; i < condHeaders.size(); i++) { conds.push_back(Value(condHeaders[i])); } ValueVector rets; for (int j = 0; j < retHeaders.size(); j++) { rets.push_back(Value(retHeaders[j])); } auto findValue = testData.find(curTestName); if (findValue != testData.end()) { auto curMap = findValue->second.asValueMap(); curMap[KEY_CONDITION_HEADERS] = Value(conds); curMap[KEY_RESULT_HEADERS] = Value(rets); if (curMap.find(KEY_RESULTS) != curMap.end()) curTestResults = curMap[KEY_RESULTS].asValueVector(); else curTestResults.clear(); } else { ValueMap theData; theData[KEY_CONDITION_HEADERS] = conds; theData[KEY_RESULT_HEADERS] = rets; testData[curTestName] = Value(theData); curTestResults.clear(); } } void Profile::addTestResult(std::vector<std::string> conditions, std::vector<std::string> results) { ValueVector curRet; for (int i = 0; i < conditions.size(); i++) { curRet.push_back(Value(conditions[i])); } for (int j = 0; j < results.size(); j++) { curRet.push_back(Value(results[j])); } curTestResults.push_back(Value(curRet)); } void Profile::testCaseEnd() { // add the result of current test case into the testData. ValueMap theData = testData[curTestName].asValueMap(); theData[KEY_RESULTS] = curTestResults; testData[curTestName] = Value(theData); } void Profile::flush() { // record the format version testData[KEY_FILE_VERSION] = Value(FILE_VERSION); testData[KEY_DEVICE] = Value(DEVICE_NAME); testData[KEY_OS_VERSION] = Value(OS_VERSION); testData[KEY_ENGINE_VERSION] = Value(cocos2d::cocos2dVersion()); time_t t = time(0); localtime(&t); testData[KEY_TIMESTAMP] = Value(genStr("%ld", t)); #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID std::string checkPath = "/mnt/sdcard/PerfTest"; auto writablePath = checkPath; if (! cocos2d::FileUtils::getInstance()->isDirectoryExist(checkPath)) { auto createRet = cocos2d::FileUtils::getInstance()->createDirectory(checkPath); if (! createRet) { writablePath = cocos2d::FileUtils::getInstance()->getWritablePath(); } } cocos2d::log("write path : %s", writablePath.c_str()); #else auto writablePath = cocos2d::FileUtils::getInstance()->getWritablePath(); #endif #if USE_JSON_FORMAT char timeStr[64]; strftime(timeStr, sizeof(timeStr), "%Y-%m-%d-%H%M", localtime(&t)); std::string fileName = genStr(LOG_FILE_NAME_FMT, DEVICE_NAME, timeStr); std::string fullPath = genStr("%s/%s", writablePath.c_str(), fileName.c_str()); rapidjson::Document document; rapidjson::Document::AllocatorType& allocator = document.GetAllocator(); rapidjson::Value theData = valueMapToJson(testData, allocator); rapidjson::StringBuffer buffer; #if USE_PRETTY_OUTPUT_FORMAT // write pretty format json rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); #else // #else USE_PRETTY_OUTPUT_FORMAT // write json in one line rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); #endif // #endif USE_PRETTY_OUTPUT_FORMAT theData.Accept(writer); auto out = buffer.GetString(); FILE *fp = fopen(fullPath.c_str(), "w"); fputs(out, fp); fclose(fp); #else // #else USE_JSON_FORMAT // Write the test data into plist file. std::string plistFullPath = genStr("%s/%s", writablePath.c_str(), PLIST_FILE_NAME); cocos2d::FileUtils::getInstance()->writeValueMapToFile(testData, plistFullPath); #endif // #endif USE_JSON_FORMAT }
[ "bogdanvladu@Bogdans-MacBook-Pro.local" ]
bogdanvladu@Bogdans-MacBook-Pro.local
8205352c874aacae8bccbb03e262ec2f604bc5ff
385649614fc0b5179e1c5b0657fac84debacf5ef
/src/base_socket.cpp
9805d3bf8b235ddc93aeceb2fcd7a198fd8ad676
[ "MIT" ]
permissive
gitmark/bravo
4ad6068e021f96ad71cb145e9c0c0763ee7e445f
20adcf254be4757df2124bcf0d01a43cc0e615ba
refs/heads/master
2021-01-13T12:17:04.754266
2019-06-29T21:48:52
2019-06-29T21:48:52
78,316,221
0
0
null
null
null
null
UTF-8
C++
false
false
1,942
cpp
/******************************************************************************* MIT License Copyright (c) 2017 Mark Elrod 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 <bravo/base_socket.h> namespace bravo { #ifdef _WIN32 class WSInit { public: WSInit() { WSAStartup(MAKEWORD(2, 2), &wsaData); } ~WSInit() { WSACleanup(); } WSAData wsaData; }; void* init_sockets() { static WSInit wsinit; return &wsinit; } #else void* init_sockets() { return nullptr; } #endif std::string base_socket::error_string(socket_error e) { return error_string((int)e); } std::string base_socket::error_string(int e) { if(!e) return socket_error_strings_[e]; e -= error_start_; if (e < 1 && e >= ((int)socket_error::max_error - error_start_)) e = 0; return socket_error_strings_[e]; } }
[ "git-mark@helixport.com" ]
git-mark@helixport.com
87b0fa488fccb7071831f02f08768955e53e29a0
33965e8f0bbb38ebb4647ba7aa6976af11ffa3c7
/strategy/ConstructionPlanning.cpp
cfd394ad9cd3409264de22c91e60219cb4474b25
[]
no_license
TraceMyers/FrogFish
8f5545c4ad1f80b23b64eeaeab7464cf31ba8ba3
a3f6c2f92e3502e90537b2706fa6b7d46b08414b
refs/heads/master
2022-05-01T00:34:50.158608
2022-04-08T14:19:17
2022-04-08T14:19:17
231,499,129
1
0
null
null
null
null
UTF-8
C++
false
false
5,545
cpp
#include "ConstructionPlanning.h" #include "../production/BuildGraph.h" #include "../basic/Bases.h" #include "../basic/Units.h" #include "../basic/UnitData.h" #include "../test/TestMessage.h" #include "BWEM/bwem.h" using namespace Production; namespace Strategy::ConstructionPlanning { namespace { ConstructionPlan plans[64]; uint64_t used_plans_field = 0; int _plans_count = 0; int get_free_plans_index() { uint64_t bit_checker = 1; int i = 0; while(bit_checker > 0) { if (!(used_plans_field & bit_checker)) { used_plans_field ^= bit_checker; break; } bit_checker <<= 1; i += 1; } return i; } } // TODO: use logic to make decisions int make_construction_plan(const Production::BuildOrder::Item& item) { const std::vector<const BWEM::Base *> &bases = Basic::Bases::self_bases(); const BWEM::Base *construction_base = nullptr; BWAPI::Unit builder = nullptr; const BWAPI::UnitType& type = item.unit_type(); BWAPI::TilePosition build_tp; for (auto &base : bases) { auto &base_workers = Basic::Bases::workers(base); if (base_workers.size() > 0) { construction_base = base; for (auto &worker : base_workers) { auto& worker_data = Basic::Units::data(worker); if (worker_data.u_task == Basic::Refs::MINERALS && worker_data.build_status == NONE) { builder = worker; break; } } } if (construction_base != nullptr && builder != nullptr) { break; } } if (construction_base == nullptr) { DBGMSG("ConstructionPlanning::make_construction_plan(): Couldn't find base for construction! Building type: %s", type.c_str()); return NO_BASE; } else if (builder == nullptr) { DBGMSG("ConstructionPlanning::make_construction_plan(): Couldn't find builder for construction! Building type: %s", type.c_str()); return NO_BUILDER; } if (type == BWAPI::UnitTypes::Zerg_Extractor) { build_tp = Production::BuildGraph::get_geyser_tilepos(construction_base); } else { build_tp = Production::BuildGraph::get_build_tilepos( construction_base, type.tileWidth(), type.tileHeight() ); } if (build_tp == BWAPI::TilePositions::None) { DBGMSG("ConstructionPlanning::make_construction_plan(): Couldn't find builder for construction! Building type: %s", type.c_str()); return NO_LOCATION; } int plan_ID = get_free_plans_index(); plans[plan_ID].set_base(construction_base); plans[plan_ID].set_builder(builder); plans[plan_ID].set_item(item); plans[plan_ID].set_tilepos(build_tp); ++_plans_count; return plan_ID; } int make_expansion_plan() { // rather than per-map, do generalized model so it can stay up without maintenance // So, what features of a map are potentially deciding factors? (maybe run regression here // to decide on the features) // For each expansion from 2nd to 4th: // - proximity by ground to main // - proximity by ground to another base // - proximity by air to main // - proximity by air to average base position // - proximity by air to average enemy base position // - enemy race // - enemy air attack happens within the next two minutes (on any friendly base) // - enemy drop happens within the next two minutes (on any friendly base) // - current average distance of enemy units to exp base // - shares a choke with center of the map // - shares a choke with another base // // - create unsupervized learning set of match army composition classes // - for example, ZvP, (50% zergling, etc.) vs (30% zealot, etc.) may end up being one class // - use these for later deciding on army composition // - reduce classes to smaller number for use here (maybe 5 per matchup) // - each of these is tested for interaction with the above features, as well as each // feature on its own return 0; } const ConstructionPlan &get_plan(int ID) { return plans[ID]; } int find_plan(const Production::BuildOrder::Item &item) { uint64_t field_checker = 1; int i = 0; while(field_checker > 0) { if (field_checker & used_plans_field) { if(plans[i].get_item() == item) { return i; } } field_checker <<= 1; ++i; } return (int)NO_PLAN; } void destroy_plan(int ID) { uint64_t ID_field_num = 1 << ID; --_plans_count; used_plans_field ^= ID_field_num; } void set_extractor_flag(int ID, bool value) { plans[ID].set_extractor_transition(value); } void replace_null_builder_with_extractor(int ID, BWAPI::Unit extractor) { plans[ID].set_builder(extractor); } int plans_count() { return _plans_count; } }
[ "18mm@protonmail.com" ]
18mm@protonmail.com
1aa415070eeb7ff4c312c6017764b424c64d042b
40fc1a9100f271b289539c56af49d415ef2f4688
/3dParty/boost_1_32_0/boost/mpl/size.hpp
38a66d00f60cb087caaa8a60daced2d60477f26b
[]
no_license
radtek/sqltools-1
3c671993fef89cfc582dfb6f2b665b4e62d09aca
887452f25dad2f51d2f620b4fb77d1d69f3d3f13
refs/heads/master
2021-02-26T12:51:09.123428
2019-12-03T11:51:20
2019-12-03T11:51:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,149
hpp
#ifndef BOOST_MPL_SIZE_HPP_INCLUDED #define BOOST_MPL_SIZE_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/oedt/oedt/3dParty/boost_1_32_0/boost/mpl/size.hpp,v $ // $Date: 2005/10/11 02:00:20 $ // $Revision: 1.1.1.1 $ #include <boost/mpl/size_fwd.hpp> #include <boost/mpl/sequence_tag.hpp> #include <boost/mpl/aux_/size_impl.hpp> #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/lambda_support.hpp> #include <boost/mpl/aux_/msvc_eti_base.hpp> namespace boost { namespace mpl { template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) > struct size : aux::msvc_eti_base< typename size_impl< typename sequence_tag<Sequence>::type > ::template apply< Sequence >::type >::type { BOOST_MPL_AUX_LAMBDA_SUPPORT(1, size, (Sequence)) }; BOOST_MPL_AUX_NA_SPEC(1, size) }} #endif // BOOST_MPL_SIZE_HPP_INCLUDED
[ "26166377+lflfm@users.noreply.github.com" ]
26166377+lflfm@users.noreply.github.com
3865c84743f3848c994c8863e4870da4e07de12d
29ee99e854185fc57cdaf1a0787f49dd0ac0b6f4
/tensorflow/compiler/xla/tests/deconstruct_tuple_test.cc
e1435cf8abd8575c0b1049aa7154b4da38d82ea0
[ "Apache-2.0" ]
permissive
zhspgood/tensorflow
a3e6389dd6d19dc4aec4ec93f017734ad1c8e378
348367a88e02a9e1750738b11a8e0784b2eb6b65
refs/heads/master
2020-03-27T17:19:13.604197
2018-08-31T04:12:31
2018-08-31T04:16:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,715
cc
/* Copyright 2017 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 <vector> #include "tensorflow/compiler/xla/client/global_data.h" #include "tensorflow/compiler/xla/client/local_client.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/client/xla_computation.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/test_helpers.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/test_macros.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/test.h" namespace xla { namespace { using ::testing::ContainsRegex; using ::testing::HasSubstr; class DeconstructTupleTest : public ClientLibraryTestBase { protected: // Build and execute the given computation then verify the results can be // transferred from the device successfully. std::unique_ptr<GlobalData> ExecuteAndCheckTransfer( XlaBuilder* builder, absl::Span<GlobalData* const> arguments) { XlaComputation computation = builder->Build().ConsumeValueOrDie(); auto global_data = client_->Execute(computation, arguments, &execution_options_) .ConsumeValueOrDie(); TF_CHECK_OK(client_->Transfer(*global_data).status()); return global_data; } }; TEST_F(DeconstructTupleTest, DeconstructTuple) { XlaBuilder builder(TestName()); auto const1 = ConstantR1<float>(&builder, {1.0, 2.0, 3.0, 4.0}); auto const2 = ConstantR1<float>(&builder, {2.0, 4.0, 6.0, 8.0}); Tuple(&builder, {const1, const2}); auto global_data = ExecuteAndCheckTransfer(&builder, {}); auto result_status = client_->DeconstructTuple(*global_data); EXPECT_TRUE(result_status.ok()); // Try copying the elements back and comparing it auto handles = result_status.ConsumeValueOrDie(); std::unique_ptr<Literal> literal; TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[0])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[1])); LiteralTestUtil::ExpectR1Equal<float>({2.0, 4.0, 6.0, 8.0}, *literal); } TEST_F(DeconstructTupleTest, DeconstructTupleTwice) { XlaBuilder builder(TestName()); auto const1 = ConstantR1<float>(&builder, {1.0, 2.0, 3.0, 4.0}); auto const2 = ConstantR1<float>(&builder, {2.0, 4.0, 6.0, 8.0}); Tuple(&builder, {const1, const2}); auto global_data = ExecuteAndCheckTransfer(&builder, {}); auto result_status1 = client_->DeconstructTuple(*global_data); EXPECT_TRUE(result_status1.ok()); auto result_status2 = client_->DeconstructTuple(*global_data); EXPECT_TRUE(result_status2.ok()); auto handles1 = result_status1.ConsumeValueOrDie(); auto handles2 = result_status2.ConsumeValueOrDie(); std::unique_ptr<Literal> literal; TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles1[0])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles1[1])); LiteralTestUtil::ExpectR1Equal<float>({2.0, 4.0, 6.0, 8.0}, *literal); handles1[0].reset(); handles1[1].reset(); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles2[0])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles2[1])); LiteralTestUtil::ExpectR1Equal<float>({2.0, 4.0, 6.0, 8.0}, *literal); } XLA_TEST_F(DeconstructTupleTest, DeconstructTupleRepeatedElement) { XlaBuilder builder(TestName()); auto const1 = ConstantR1<float>(&builder, {1.0, 2.0, 3.0, 4.0}); auto const2 = ConstantR1<float>(&builder, {2.0, 4.0, 6.0, 8.0}); Tuple(&builder, {const1, const2, const2, const1}); auto global_data = ExecuteAndCheckTransfer(&builder, {}); auto result_status = client_->DeconstructTuple(*global_data); EXPECT_TRUE(result_status.ok()); // Verify the returned GlobalDataHandle arrays have repeated elements like the // tuple does. That is, in the returned vector of handles, handle[0] should be // the same as handle[3] and handle[1] should be the same as handle[2]. auto handles = result_status.ConsumeValueOrDie(); std::unique_ptr<Literal> literal; TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[0])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[1])); LiteralTestUtil::ExpectR1Equal<float>({2.0, 4.0, 6.0, 8.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[2])); LiteralTestUtil::ExpectR1Equal<float>({2.0, 4.0, 6.0, 8.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[3])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); } TEST_F(DeconstructTupleTest, DeconstructTupleThenDeallocate) { XlaBuilder builder(TestName()); auto const1 = ConstantR1<float>(&builder, {1.0, 2.0, 3.0, 4.0}); auto const2 = ConstantR1<float>(&builder, {2.0, 4.0, 6.0, 8.0}); Tuple(&builder, {const1, const2, const1}); auto global_data = ExecuteAndCheckTransfer(&builder, {}); auto result_status = client_->DeconstructTuple(*global_data); EXPECT_TRUE(result_status.ok()); auto handles = result_status.ConsumeValueOrDie(); // Deallocate the tuple, then try copying the elements back. The elements // should not have been deallocated because of reference counting. global_data.reset(); std::unique_ptr<Literal> literal; TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[0])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[1])); LiteralTestUtil::ExpectR1Equal<float>({2.0, 4.0, 6.0, 8.0}, *literal); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[2])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); /// Try deallocating one of the repeated elements, then copy handles[0].reset(); TF_ASSERT_OK_AND_ASSIGN(literal, client_->Transfer(*handles[2])); LiteralTestUtil::ExpectR1Equal<float>({1.0, 2.0, 3.0, 4.0}, *literal); } TEST_F(DeconstructTupleTest, DeconstructNonTuple) { XlaBuilder builder(TestName()); ConstantR1<float>(&builder, {1.0, 2.0, 3.0, 4.0}); auto global_data = ExecuteAndCheckTransfer(&builder, {}); auto result_status = client_->DeconstructTuple(*global_data); EXPECT_FALSE(result_status.ok()); EXPECT_THAT(result_status.status().error_message(), ContainsRegex("global data handle .* is not a tuple")); } XLA_TEST_F(DeconstructTupleTest, DeconstructTupleFromParam) { XlaBuilder builder(TestName()); std::unique_ptr<Literal> param0_literal = LiteralUtil::CreateR1<float>({3.14f, -100.25f}); std::unique_ptr<GlobalData> param0_data = client_->TransferToServer(*param0_literal).ConsumeValueOrDie(); auto p = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {2}), "param0"); Tuple(&builder, {p}); auto global_data = ExecuteAndCheckTransfer(&builder, {param0_data.get()}); auto result_status = client_->DeconstructTuple(*global_data); EXPECT_TRUE(result_status.ok()); auto handles = result_status.ConsumeValueOrDie(); EXPECT_NE(handles[0]->handle().handle(), param0_data->handle().handle()); } XLA_TEST_F(DeconstructTupleTest, DeconstructNestedTuple) { XlaBuilder builder(TestName()); auto const1 = ConstantR1<float>(&builder, {1.0, 2.0, 3.0, 4.0}); auto const2 = ConstantR1<float>(&builder, {2.0, 4.0, 6.0, 8.0}); Tuple(&builder, {Tuple(&builder, {const1, const2}), const1}); auto global_data = ExecuteAndCheckTransfer(&builder, {}); auto result_status = client_->DeconstructTuple(*global_data); EXPECT_FALSE(result_status.ok()); EXPECT_THAT(result_status.status().error_message(), HasSubstr("Deconstructing nested tuples is not implemented")); } } // namespace } // namespace xla
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
464f6f922f791f1e26ff720668b49b9c45c6cd0d
b27f55a41fb810e8000fa476bede668a444f20ef
/lc-1048.cpp
819987558af6df5c1a64563e526803fd3740728a
[]
no_license
aryanmali/dsa-code-snippets
cb7b0e90c0e2051f3e715133d1510b4753d0409f
983d9b5114e97c7f86069c68ee77be3d40fd6878
refs/heads/main
2023-04-26T07:01:10.463434
2021-05-23T06:08:05
2021-05-23T06:08:05
355,400,782
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
//https://leetcode.com/problems/longest-string-chain/ class Solution { vector<vector<int>> adj; vector<int> dp; int dfs(int curr) { if(dp[curr] > 0) return dp[curr]; dp[curr] = 1; for(auto v:adj[curr]) dp[curr] = max(dp[curr],dfs(v)+1); return dp[curr]; } public: int longestStrChain(vector<string>& words) { int n = words.size(); adj.clear(); adj.resize(n); dp.clear(); dp.resize(n); unordered_map<string, int> mp; for(int i=0;i<n;i++) mp[words[i]] = i; for(int i=0;i<n;i++) { string s = words[i]; for(int j=0;j<s.size();j++) { string tmp = s.substr(0,j) + s.substr(j+1); if(mp.count(tmp)) adj[mp[tmp]].push_back(i); } } int ans=0; for(int i=0;i<n;i++) ans = max(ans,dfs(i)); return ans; } };
[ "aryanmali@users.noreply.github.com" ]
aryanmali@users.noreply.github.com
cf36d05c7396ae1dad3a85bd7a916e2117a87447
9950bbd03b94419e4a9d01377233a2b8e7339cc4
/src/gui/ClusteringResultPrototypeViewWidget.cpp
1fc74a033749797ba9b63bc345b69dff3bb1e27d
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
goldbdaniel/inventory-extraction
fc14ab9565ce00b99f9f180bb9bdb36db6aa7bb5
de605eed1044b13ae73e7a3f8bfb76c0dc28df10
refs/heads/master
2023-03-16T01:43:07.453906
2020-06-12T09:41:38
2020-06-12T09:42:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,897
cpp
/* * ClusteringResultPrototypeViewWidget.cpp * * Created on: 20.07.2010 * */ #include "ClusteringResultPrototypeViewWidget.hpp" #include "ext/cluster/cluster.h" namespace impact_tr4 { ClusteringResultPrototypeViewWidget::ClusteringResultPrototypeViewWidget( QWidget *parent /*= 0*/ ) : QWidget(parent) { mpClusteringResult = 0x0; mpDocument = 0x0; // create global layout: mpGlobalLayout = new QVBoxLayout(); // add top Label for cluster prototype widget: QLabel *label = new QLabel("Cluster Prototypes"); QFont labelFont("Arial", 12, QFont::Bold); label->setFont(labelFont); mpGlobalLayout->addWidget(label); // add prototype list widget: mpPrototypeViewListWidget = new PrototypeViewListWidget(0x0, this); connect(mpPrototypeViewListWidget, SIGNAL(showClusterViewWidget(CharClustIt)), this, SLOT(showClusterViewWidget(CharClustIt))); connect(mpPrototypeViewListWidget, SIGNAL(mergeWithCluster(CharClustIt, CharClustIt)), this, SLOT(mergeWithCluster(CharClustIt, CharClustIt))); connect(mpPrototypeViewListWidget, SIGNAL(mergeClusters(std::vector<CharClustIt>, CharClustIt)), this, SLOT(mergeClusters(std::vector<CharClustIt>, CharClustIt))); connect(mpPrototypeViewListWidget, SIGNAL(moveToCluster(CharClustIt, CharClustIt, std::vector<ImageCharIt>&)), this, SLOT(moveToCluster(CharClustIt, CharClustIt,std::vector<ImageCharIt>&))); // mpGlobalLayout->addWidget(mpPrototypeViewListWidget); // add cluster summary widget: mpClusterSummaryLayout = new QVBoxLayout(); scrollareaClusterSummary = new QScrollArea(this); mpInternalClusterSummaryWidget = new QWidget; mpInternalClusterSummaryWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); mpInternalClusterSummaryWidget->setLayout(mpClusterSummaryLayout); scrollareaClusterSummary->setWidget(mpInternalClusterSummaryWidget); scrollareaClusterSummary->setMaximumWidth(420); QHBoxLayout *pTopLayout = new QHBoxLayout(); pTopLayout->addWidget(mpPrototypeViewListWidget); pTopLayout->addWidget(scrollareaClusterSummary); scrollareaClusterSummary->setVisible(false); mpGlobalLayout->addLayout(pTopLayout); // add buttons: mpMergeSelectedClustersButton = new QPushButton("Merge selected clusters"); mpMergeSelectedClustersButton->setFixedSize(mpMergeSelectedClustersButton->sizeHint()); connect(mpMergeSelectedClustersButton, SIGNAL(clicked()), this, SLOT(mergeSelectedClusters())); mpRemoveSelectedClustersButton = new QPushButton("Remove selected clusters"); mpRemoveSelectedClustersButton->setFixedSize(mpRemoveSelectedClustersButton->sizeHint()); connect(mpRemoveSelectedClustersButton, SIGNAL(clicked()), this, SLOT(removeSelectedClusters())); mpAddEmptyClusterButton = new QPushButton("Add empty cluster"); mpAddEmptyClusterButton->setFixedSize(mpAddEmptyClusterButton->sizeHint()); connect(mpAddEmptyClusterButton, SIGNAL(clicked()), this, SLOT(addEmptyCluster())); mpRemoveEmptyClustersButton = new QPushButton("Remove empty clusters"); mpRemoveEmptyClustersButton->setFixedSize(mpRemoveEmptyClustersButton->sizeHint()); connect(mpRemoveEmptyClustersButton, SIGNAL(clicked()), this, SLOT(removeEmptyClusters())); QPushButton *pShowTrashButton = new QPushButton("Show trash cluster"); pShowTrashButton->setFixedSize(pShowTrashButton->sizeHint()); connect(pShowTrashButton, SIGNAL(clicked()), this, SLOT(showTrashCluster())); mpShowUnsortedButton = new QPushButton("Show clusters unsorted"); mpShowUnsortedButton->setFixedSize(mpShowUnsortedButton->sizeHint()); connect(mpShowUnsortedButton, SIGNAL(clicked()), this, SLOT(showUnsorted())); mpSortByNearestNeighborButton = new QPushButton("Sort clusters by nearest neighbor on selected item"); mpSortByNearestNeighborButton->setFixedSize(mpSortByNearestNeighborButton->sizeHint()); connect(mpSortByNearestNeighborButton, SIGNAL(clicked()), this, SLOT(sortByNearestNeighbor())); mpSortBySizeDescendingButton = new QPushButton("Sort clusters by their size (descending)"); mpSortBySizeDescendingButton->setFixedSize(mpSortBySizeDescendingButton->sizeHint()); connect(mpSortBySizeDescendingButton, SIGNAL(clicked()), this, SLOT(sortBySizeDescending())); mpSortBySizeAscendingButton = new QPushButton("Sort clusters by their size (ascending)"); mpSortBySizeAscendingButton->setFixedSize(mpSortBySizeAscendingButton->sizeHint()); connect(mpSortBySizeAscendingButton, SIGNAL(clicked()), this, SLOT(sortBySizeAscending())); QLabel *pIconSizeLabel = new QLabel("Icon Size: "); pIconSizeLabel->setFixedSize(pIconSizeLabel->sizeHint()); mpIconSizeSpinBox = new QSpinBox(); mpIconSizeSpinBox->setValue(60); mpIconSizeSpinBox->setRange(1, 99); connect(mpIconSizeSpinBox, SIGNAL(valueChanged(int)), mpPrototypeViewListWidget, SLOT(updateIconSize(int))); mpIconSizeSlider = new QSlider(Qt::Horizontal); mpIconSizeSlider->setRange(1, 99); mpIconSizeSlider->setValue(60); connect(mpIconSizeSlider, SIGNAL(valueChanged(int)), mpPrototypeViewListWidget, SLOT(updateIconSize(int))); connect(mpIconSizeSlider, SIGNAL(valueChanged(int)), mpIconSizeSpinBox, SLOT(setValue(int))); connect(mpIconSizeSpinBox, SIGNAL(valueChanged(int)), mpIconSizeSlider, SLOT(setValue(int))); // Labelling stuff: QLabel *pLabelLabel = new QLabel("Unicode Label = "); pLabelLabel->setFixedSize(pLabelLabel->sizeHint()); mpLabelLineEdit = new QLineEdit("0"); mpLabelLineEdit->setFixedWidth(100); mpLabelLineEdit->setToolTip("Specify unicode as 4 digit hexadecimal unicode number"); QRegExp rx( "[0-9A-Fa-f]{1,4}" ); // regular expression for unicode QValidator *validator = new QRegExpValidator( rx, this ); mpLabelLineEdit->setValidator(validator); connect(mpLabelLineEdit, SIGNAL(returnPressed()), this, SLOT(labelCurrentCluster())); mpLabelButton = new QPushButton("Label!"); connect(mpLabelButton, SIGNAL(clicked()), this, SLOT(labelCurrentCluster())); // CONFIGURE EDITING WIDGETS GROUPBOX: QGroupBox *pEditGroupBox = new QGroupBox("Editing options"); QHBoxLayout *pEditLayout1 = new QHBoxLayout(); pEditLayout1->addWidget(pLabelLabel); pEditLayout1->addWidget(mpLabelLineEdit); pEditLayout1->addWidget(mpLabelButton); pEditLayout1->addWidget(mpMergeSelectedClustersButton); pEditLayout1->addWidget(mpAddEmptyClusterButton); pEditLayout1->addWidget(mpRemoveEmptyClustersButton); pEditLayout1->addWidget(mpRemoveSelectedClustersButton); QHBoxLayout *pEditLayout2 = new QHBoxLayout(); QLabel *pReclusterLabel = new QLabel("Re-cluster by prototypes "); pReclusterLabel->setFixedSize(pReclusterLabel->sizeHint()); mpReclusterHierarchicalSpinBox = new QSpinBox(); mpReclusterHierarchicalSpinBox->setMinimum(1); mpReclusterHierarchicalSpinBox->setMaximum(999999); mpReclusterHierarchicalSpinBox->setValue(60); mpReclusterHierarchicalSpinBox->setPrefix("New nr. of clusters = "); mpReclusterHierarchicalButton = new QPushButton("Re-cluster!"); mpReclusterHierarchicalButton->setToolTip(("Re-clusters the clustering result using the " "prototype images and an agglomerative hierarchical clustering scheme with average linking to a specified" " nr. of clusters")); connect(mpReclusterHierarchicalButton, SIGNAL(clicked()), this, SLOT(reClustering())); pEditLayout2->addWidget(pReclusterLabel); pEditLayout2->addWidget(mpReclusterHierarchicalSpinBox); pEditLayout2->addWidget(mpReclusterHierarchicalButton); QPushButton *pRestoreButton = new QPushButton("Restore old clustering"); pRestoreButton->setToolTip("Restores the clustering result to the state before the last editing operation."); connect(pRestoreButton, SIGNAL(clicked()), this, SLOT(restoreBackupClustering())); pEditLayout2->addWidget(pRestoreButton); QVBoxLayout *pGlobalEditLayout = new QVBoxLayout(); pGlobalEditLayout->addLayout(pEditLayout1); pGlobalEditLayout->addLayout(pEditLayout2); pEditGroupBox->setLayout(pGlobalEditLayout); // CONFIGURE VIEWING WIDGETS GROUPBOX: QGroupBox *pViewGroupBox = new QGroupBox("Viewing options"); QHBoxLayout *pViewLayout1 = new QHBoxLayout(); pViewLayout1->addWidget(pIconSizeLabel); pViewLayout1->addWidget(mpIconSizeSpinBox); pViewLayout1->addWidget(mpIconSizeSlider); QHBoxLayout *pViewLayout2 = new QHBoxLayout(); pViewLayout2->addWidget(pShowTrashButton); pViewLayout2->addWidget(mpShowUnsortedButton); pViewLayout2->addWidget(mpSortByNearestNeighborButton); pViewLayout2->addWidget(mpSortBySizeDescendingButton); pViewLayout2->addWidget(mpSortBySizeAscendingButton); QHBoxLayout *pViewLayout3 = new QHBoxLayout(); mpSizeThreshLowSpinBox = new QSpinBox(); mpSizeThreshLowSpinBox->setRange(0,1e3); mpSizeThreshLowSpinBox->setValue(1); mpSizeThreshLowSpinBox->setEnabled(false); mpSizeThreshHighSpinBox = new QSpinBox(); mpSizeThreshHighSpinBox->setRange(0,1e3); mpSizeThreshHighSpinBox->setValue(10); mpSizeThreshHighSpinBox->setEnabled(false); // mpSizeThreshSpinBox->setPrefix("Show only clusters with size <= "); mpSizeCheckBox = new QCheckBox("Show all"); mpSizeCheckBox->setChecked(true); connect(mpSizeCheckBox, SIGNAL(toggled(bool)), mpSizeThreshLowSpinBox, SLOT(setDisabled(bool))); connect(mpSizeCheckBox, SIGNAL(toggled(bool)), mpSizeThreshHighSpinBox, SLOT(setDisabled(bool))); pViewLayout3->addWidget(new QLabel("Show only clusters w. size from")); pViewLayout3->addWidget(mpSizeThreshLowSpinBox); pViewLayout3->addWidget(new QLabel("to")); pViewLayout3->addWidget(mpSizeThreshHighSpinBox); pViewLayout3->addWidget(mpSizeCheckBox); mpReloadViewsButton = new QPushButton("Reload views"); connect(mpReloadViewsButton, SIGNAL(clicked()), this, SLOT(reloadViews())); pViewLayout3->addWidget(mpReloadViewsButton); QVBoxLayout *pGlobalViewLayout = new QVBoxLayout(); pGlobalViewLayout->addLayout(pViewLayout1); pGlobalViewLayout->addLayout(pViewLayout2); pGlobalViewLayout->addLayout(pViewLayout3); pViewGroupBox->setLayout(pGlobalViewLayout); // ADD STUFF TO GLOBAL LAYOUT: mpGlobalLayout->addWidget(pEditGroupBox); mpGlobalLayout->addWidget(pViewGroupBox); mDummyClustering.addEmptyCluster(&mDummyDocument); // add cluster view widget: mpClusterViewWidget = new ClusterViewWidget(mDummyClustering.begin(), this); // connect(mpClusterViewWidget, SIGNAL(moveToCluster(CharClustIt, CharClustIt, std::vector<std::list<ImageChar*>::iterator>&)), this, SLOT(moveToCluster(CharClustIt, CharClustIt,std::vector<std::list<ImageChar*>::iterator>&))); // connect(mpClusterViewWidget, SIGNAL(mergeWithCluster(CharClustIt, CharClustIt)), this, SLOT(mergeWithCluster(CharClustIt, CharClustIt))); connect(mpClusterViewWidget, SIGNAL(removeCluster(CharClustIt)), this, SLOT(removeCluster(CharClustIt))); connect(mpClusterViewWidget, SIGNAL(moveToTrashCluster(CharClustIt, std::vector<ImageCharIt>&)), this, SLOT(moveToTrashCluster(CharClustIt, std::vector<ImageCharIt>&))); mpGlobalLayout->addWidget(mpClusterViewWidget); this->setLayout(mpGlobalLayout); this->show(); } int ClusteringResultPrototypeViewWidget::findClusterSummaryWidgetIndex(CharClustIt clustIt) { for (int i=0; i<mClusterSummaryList.count(); ++i) { ClusterSummaryWidget* curr_item = (ClusterSummaryWidget*)(mClusterSummaryList.at(i)); if (curr_item->clustIt() == clustIt) return i; } return -1; // std::cerr << "Item has not been found!" << std::endl; // throw Exception("Item has not been found!"); } void ClusteringResultPrototypeViewWidget::openClusteringResult(ClusteringResult *pClusteringResult, Document *pDocument) { // clear clustering result clearClusteringResult(); // necessary?? (...most probably yes!) // store and display new clustering result mpClusteringResult = pClusteringResult; mpDocument = pDocument; if (mpClusteringResult->isEmpty()) { mpPrototypeViewListWidget->setClusteringResult(&this->mDummyClustering); mpClusterViewWidget->setCluster(this->mDummyClustering.begin()); return; } std::cout << "opening clustering result, nr of clusters = " << mpClusteringResult->nClusters() << std::endl; int i=0; for (CharClustIt clust_it = mpClusteringResult->begin(); clust_it != mpClusteringResult->end(); ++clust_it) { // std::cout << "adding cluster summary widget " << std::endl; addClusterSummaryWidget(i, clust_it); ++i; } // end for all clusters i mpPrototypeViewListWidget->setClusteringResult(mpClusteringResult); mpClusterViewWidget->setCluster(mpClusteringResult->begin()); if (pDocument != mpDocument) { // if new document: store backup mClusteringResultBackup.deleteClustering(); mClusteringResultBackup = *mpClusteringResult; } return; } void ClusteringResultPrototypeViewWidget::clearClusteringResult() { while (!mClusterSummaryList.empty()) { delete mClusterSummaryList.takeFirst(); // std::cout << mClusterSummaryList.size() << std::endl; } // clear items of cluster summary widgets: scrollareaClusterSummary->takeWidget(); delete mpInternalClusterSummaryWidget; mpClusterSummaryLayout = new QVBoxLayout(); mpInternalClusterSummaryWidget = new QWidget; mpInternalClusterSummaryWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); mpInternalClusterSummaryWidget->setLayout(mpClusterSummaryLayout); scrollareaClusterSummary->setWidget(mpInternalClusterSummaryWidget); // clear prototype widget: mpPrototypeViewListWidget->setClusteringResult(&this->mDummyClustering); // clear cluster view widget: mpClusterViewWidget->setCluster(this->mDummyClustering.begin()); // clear data: mpClusteringResult = 0x0; mpDocument = 0x0; return; } // end clearClusteringResult() ClusterSummaryWidget* ClusteringResultPrototypeViewWidget::addClusterSummaryWidget(int number, CharClustIt clustIt) { ClusterSummaryWidget *pClusterSummaryWidget = new ClusterSummaryWidget(clustIt, mpInternalClusterSummaryWidget); // connect SIGNALS/SLOTS: connect(pClusterSummaryWidget, SIGNAL(showClusterViewWidget(CharClustIt)), this, SLOT(showClusterViewWidget(CharClustIt))); connect(pClusterSummaryWidget, SIGNAL(moveToCluster(CharClustIt, CharClustIt, std::vector<ImageCharIt>&)), this, SLOT(moveToCluster(CharClustIt, CharClustIt,std::vector<ImageCharIt>&))); mClusterSummaryList.append(pClusterSummaryWidget); mpClusterSummaryLayout->addWidget(pClusterSummaryWidget); mpInternalClusterSummaryWidget->resize(mpInternalClusterSummaryWidget->sizeHint()); return pClusterSummaryWidget; } void ClusteringResultPrototypeViewWidget::showClusterViewWidget(CharClustIt clustIt) { // std::cout << "showClusterViewWidget, index = " << i << std::endl; if (!hasClusteringResult()) return; // printf("address of mpClusteringResult = 0x%x, mCurrentClusterIndex=%d\n", mpClusteringResult, mCurrentClusterIndex); mpClusterViewWidget->setCluster(clustIt); return; } // showClusterViewWidget(int i) void ClusteringResultPrototypeViewWidget::showTrashCluster() { showClusterViewWidget(mpClusteringResult->getTrashCluster()); return; } ClusteringResult* ClusteringResultPrototypeViewWidget::getClusteringResult() { return mpClusteringResult; } void ClusteringResultPrototypeViewWidget::reClustering() { // FIXME: move code to ClusteringResult class // std::cout << "reclustering!" << std::endl; try { // make backup: mClusteringResultBackup = *mpClusteringResult; int nClusters = mpReclusterHierarchicalSpinBox->value(); std::cout << "nr of new clusters = " << nClusters << std::endl; mpClusteringResult->reClusterHierarchical(nClusters); std::cout << "opening clustering result" << std::endl; this->openClusteringResult(mpClusteringResult, mpDocument); emit refreshInfoGroupBox(); } catch (Exception e) { std::cerr << "An exception has occured in ClusteringResultPrototypeViewWidget::reClustering: " << e.what() << std::endl; QMessageBox::critical(this,"An error has occured re-clustering!", e.what() ); } return; } void ClusteringResultPrototypeViewWidget::labelCurrentCluster() { // std::cout << "labelling current clustering" << std::endl; QString labelText = mpLabelLineEdit->text(); if (labelText.isEmpty()) { // std::cout << "empty label text... jump out" << std::endl; return; } labelText.toUpper(); // not needed ... testing purpose bool ok; unsigned int unicode = labelText.toUInt(&ok, 16); if (!ok) { throw Exception("Fatal error converting string to unicode - should not happen..."); } CharClustIt currentClustIt = mpClusterViewWidget->getClusterIterator(); (*currentClustIt)->setUnicodeLabel(unicode); // UPDATE VIEWS IN CLUSTER PROTOTYPE AND CLUSTER SUMMARY WIDGET: int prototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(currentClustIt); if (prototypeIndex != -1) { mpPrototypeViewListWidget->updatePrototype(prototypeIndex); mpPrototypeViewListWidget->updateLabel(prototypeIndex); int summaryIndex = findClusterSummaryWidgetIndex(currentClustIt); mClusterSummaryList.at(summaryIndex)->reload(); } return; } void ClusteringResultPrototypeViewWidget::moveToCluster(CharClustIt from, CharClustIt to, std::vector<ImageCharIt>& iterators) { if (from == to) return; // make backup: mClusteringResultBackup = *mpClusteringResult; mpClusteringResult->moveElements(from, to, iterators); //std::cout << "moved elements, now updating!!" << std::endl; // update prototype widgets: int fromPrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(from); if (fromPrototypeIndex != -1) mpPrototypeViewListWidget->updatePrototype(fromPrototypeIndex); int toPrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(to); if (toPrototypeIndex != -1) mpPrototypeViewListWidget->updatePrototype(toPrototypeIndex); // update cluster summary widgets: #if 1 int fromSummaryIndex = findClusterSummaryWidgetIndex(from); if (fromSummaryIndex != -1) mClusterSummaryList.at(fromSummaryIndex)->reload(); int toSummaryIndex = findClusterSummaryWidgetIndex(to); if (toSummaryIndex != -1) mClusterSummaryList.at(toSummaryIndex)->reload(); #endif emit showClusterViewWidget(from); emit refreshInfoGroupBox(); return; } void ClusteringResultPrototypeViewWidget::moveToTrashCluster(CharClustIt from, std::vector<ImageCharIt>& iterators) { std::cout << "moving to trash cluster" << std::endl; if (from == mpClusteringResult->getTrashCluster()) { return; } mpClusteringResult->moveToTrash(from, iterators); int fromPrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(from); if (fromPrototypeIndex != -1) mpPrototypeViewListWidget->updatePrototype(fromPrototypeIndex); int fromSummaryIndex = findClusterSummaryWidgetIndex(from); if (fromSummaryIndex != -1) mClusterSummaryList.at(fromSummaryIndex)->reload(); emit showClusterViewWidget(from); emit refreshInfoGroupBox(); return; } void ClusteringResultPrototypeViewWidget::mergeWithCluster(CharClustIt from, CharClustIt to) { if (from == to) return; mpClusteringResult->mergeClusters(from, to); // update prototype widget: int fromPrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(from); mpPrototypeViewListWidget->takeItem(fromPrototypeIndex); int toPrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(to); mpPrototypeViewListWidget->updatePrototype(toPrototypeIndex); // update cluster summary widgets: int fromSummaryIndex = findClusterSummaryWidgetIndex(from); delete mClusterSummaryList.takeAt(fromSummaryIndex); int toSummaryIndex = findClusterSummaryWidgetIndex(to); mClusterSummaryList.at(toSummaryIndex)->reload(); showClusterViewWidget(to); mpInternalClusterSummaryWidget->resize(mpInternalClusterSummaryWidget->sizeHint()); emit refreshInfoGroupBox(); return; } void ClusteringResultPrototypeViewWidget::mergeClusters(std::vector<CharClustIt> from, CharClustIt to) { // make backup: mClusteringResultBackup = *mpClusteringResult; #if 0 // old version -> unefficient for many from clusters for (int i=0; i<from.size(); ++i) { if (from[i] != to) { this->mergeWithCluster(from[i], to); // if (from[i] < to) to--; // adopt to index if removed cluster was before // // adopt rest of from indices if removed cluster was before: // for (int j=i+1; j<from.size(); ++j) { // if (from[i] < from[j]) from[j]--; // } } } mpInternalClusterSummaryWidget->resize(mpInternalClusterSummaryWidget->sizeHint()); emit refreshInfoGroupBox(); #else for (int i=0; i<from.size(); ++i) { if (from[i] != to) { mpClusteringResult->mergeClusters(from[i], to); // take from item from prototype view widget: int fromPrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(from[i]); mpPrototypeViewListWidget->takeItem(fromPrototypeIndex); // take from item from cluster summary widget: int fromSummaryIndex = findClusterSummaryWidgetIndex(from[i]); delete mClusterSummaryList.takeAt(fromSummaryIndex); } } // update prototype for to element in prototype view widget: int toPrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(to); mpPrototypeViewListWidget->updatePrototype(toPrototypeIndex); // update cluster summary widget for to item: int toSummaryIndex = findClusterSummaryWidgetIndex(to); mClusterSummaryList.at(toSummaryIndex)->reload(); // show cluster view widget of to item: showClusterViewWidget(to); mpInternalClusterSummaryWidget->resize(mpInternalClusterSummaryWidget->sizeHint()); emit refreshInfoGroupBox(); #endif return; } void ClusteringResultPrototypeViewWidget::mergeSelectedClusters() { if (mpClusteringResult==0x0) return; // determine selected clusters: QList<QListWidgetItem*> selItems = mpPrototypeViewListWidget->selectedItems(); if (selItems.size()<=1) return; QList<QListWidgetItem*>::iterator it = selItems.begin(); CharClustIt to = ((ClusterListWidgetItem *)(*it))->mClustIt; ++it; std::vector<CharClustIt> from; for (; it!=selItems.end(); ++it) { from.push_back(((ClusterListWidgetItem *)(*it))->mClustIt); } this->mergeClusters(from, to); return; } void ClusteringResultPrototypeViewWidget::removeSelectedClusters() { if (mpClusteringResult==0x0) return; // determine selected clusters: QList<QListWidgetItem*> selItems = mpPrototypeViewListWidget->selectedItems(); if (selItems.size()<1) return; if (selItems.size() == mpClusteringResult->nClusters()) { QMessageBox::information(this, "Cannot remove all clusters", "Cannot remove all clusters from clustering!"); return; } // make backup: mClusteringResultBackup = *mpClusteringResult; QList<QListWidgetItem*>::iterator it = selItems.begin(); for (; it!=selItems.end(); ++it) { // update prototype widget: int removePrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(((ClusterListWidgetItem *)(*it))->mClustIt); mpPrototypeViewListWidget->takeItem(removePrototypeIndex); // update cluster summary widgets: int removeSummaryIndex = this->findClusterSummaryWidgetIndex(((ClusterListWidgetItem *)(*it))->mClustIt); delete mClusterSummaryList.takeAt(removeSummaryIndex); // actually remove cluster from clustering: mpClusteringResult->removeCluster(((ClusterListWidgetItem *)(*it))->mClustIt); } // show content of first cluster: showClusterViewWidget(mpClusteringResult->begin()); mpInternalClusterSummaryWidget->resize(mpInternalClusterSummaryWidget->sizeHint()); emit refreshInfoGroupBox(); return; } void ClusteringResultPrototypeViewWidget::removeCluster(CharClustIt clustIt) { // make backup: mClusteringResultBackup = *mpClusteringResult; // ask if seriously want to remove an empty(!) cluster: if ( !(*clustIt)->empty() ) if ( QMessageBox::question(this, "Cluster not empty", "Do really want to remove this non-empty cluster?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) { return; } mpClusteringResult->removeCluster(clustIt); // update prototype widget: int removePrototypeIndex = mpPrototypeViewListWidget->findClusterItemIndex(clustIt); mpPrototypeViewListWidget->takeItem(removePrototypeIndex); // update cluster summary widgets: int removeSummaryIndex = this->findClusterSummaryWidgetIndex(clustIt); delete mClusterSummaryList.takeAt(removeSummaryIndex); showClusterViewWidget(mpClusteringResult->begin()); mpInternalClusterSummaryWidget->resize(mpInternalClusterSummaryWidget->sizeHint()); emit refreshInfoGroupBox(); return; } // end removeCluster void ClusteringResultPrototypeViewWidget::addEmptyCluster() { // add empty cluster to clustering result: if (hasClusteringResult() && mpDocument != 0x0) { mpClusteringResult->addEmptyCluster(mpDocument); // update prototype widget: mpPrototypeViewListWidget->addEmptyCluster(); // update cluster summary widgets: int lastIndex = mpClusteringResult->nClusters()-1; CharClustIt clustItEnd = mpClusteringResult->end(); --clustItEnd; addClusterSummaryWidget(lastIndex, clustItEnd); } mpInternalClusterSummaryWidget->resize(mpInternalClusterSummaryWidget->sizeHint()); emit refreshInfoGroupBox(); return; } // end addEmptyCluster() void ClusteringResultPrototypeViewWidget::removeEmptyClusters() { if (hasClusteringResult()) { mpClusteringResult->removeEmptyClusters(); this->openClusteringResult(mpClusteringResult, mpDocument); } // end if hasClusteringResult() return; } // end removeEmptyClusters() void ClusteringResultPrototypeViewWidget::showUnsorted() { int sizeThreshLow = mpSizeThreshLowSpinBox->value(); int sizeThreshHigh = mpSizeThreshHighSpinBox->value(); if (mpSizeCheckBox->isChecked()) { // if show all check box is checked, set thresh to 0, s.t. all clusters are shown! sizeThreshLow = -1; sizeThreshHigh = -1; } mpPrototypeViewListWidget->updateList(sizeThreshLow, sizeThreshHigh); return; } void ClusteringResultPrototypeViewWidget::sortByNearestNeighbor() { // determine selected clusters: QList<QListWidgetItem*> selItems = mpPrototypeViewListWidget->selectedItems(); if (selItems.size()<1) return; // of none selected, jump out QList<QListWidgetItem*>::iterator it = selItems.begin(); // sort by first in list this->mpClusteringResult->computePrototypeFeatures(); // recompute features; FIXME: unefficient: on demand?? std::vector<CharClustIt> kNNSorting; mpClusteringResult->computekNNSorting(((ClusterListWidgetItem*)(*it))->mClustIt, kNNSorting); int sizeThreshLow = mpSizeThreshLowSpinBox->value(); int sizeThreshHigh = mpSizeThreshHighSpinBox->value(); if (mpSizeCheckBox->isChecked()) { // if show all check box is checked, set thresh to 0, s.t. all clusters are shown! sizeThreshLow = -1; sizeThreshHigh = -1; } mpPrototypeViewListWidget->updateListWithOrdering(kNNSorting, sizeThreshLow, sizeThreshHigh); return; } void ClusteringResultPrototypeViewWidget::sortBySizeDescending() { std::cout << "sorting by size descending" << std::endl; std::vector<CharClustIt> sizeSorting; mpClusteringResult->computeSizeSorting(sizeSorting); // reverse sorting, s.t. largest cluster is first: std::reverse(sizeSorting.begin(), sizeSorting.end()); int sizeThreshLow = mpSizeThreshLowSpinBox->value(); int sizeThreshHigh = mpSizeThreshHighSpinBox->value(); if (mpSizeCheckBox->isChecked()) { // if show all check box is checked, set thresh to 0, s.t. all clusters are shown! sizeThreshLow = -1; sizeThreshHigh = -1; } mpPrototypeViewListWidget->updateListWithOrdering(sizeSorting, sizeThreshLow, sizeThreshHigh); return; } void ClusteringResultPrototypeViewWidget::sortBySizeAscending() { std::cout << "sorting by size descending" << std::endl; std::vector<CharClustIt> sizeSortingAscending; mpClusteringResult->computeSizeSorting(sizeSortingAscending); int sizeThreshLow = mpSizeThreshLowSpinBox->value(); int sizeThreshHigh = mpSizeThreshHighSpinBox->value(); if (mpSizeCheckBox->isChecked()) { // if show all check box is checked, set thresh to 0, s.t. all clusters are shown! sizeThreshLow = -1; sizeThreshHigh = -1; } mpPrototypeViewListWidget->updateListWithOrdering(sizeSortingAscending, sizeThreshLow, sizeThreshHigh); return; } void ClusteringResultPrototypeViewWidget::restoreBackupClustering() { if (mpClusteringResult != 0x0 && !mClusteringResultBackup.isEmpty() ) { // std::cout << "n of c in backup = " << mClusteringResultBackup.nClusters() << std::endl; mpClusteringResult->deleteClustering(); *mpClusteringResult = mClusteringResultBackup; this->openClusteringResult(mpClusteringResult, mpDocument); emit refreshInfoGroupBox(); } return; } void ClusteringResultPrototypeViewWidget::reloadViews() { std::cout << "reloading views..." << std::endl; for (int i=0; i < mpPrototypeViewListWidget->count(); ++i) { std::cout << "i = " << i << std::endl; ((ClusterListWidgetItem *)(mpPrototypeViewListWidget->item(i)))->updatePrototypeImage(); } for (int i=0; i<this->mClusterSummaryList.size(); ++i) { std::cout << "i = " << i << std::endl; mClusterSummaryList.at(i)->updatePrototypeImage(); } return; } } // end of namespace impact_tr4
[ "jkloe@jkloe.com" ]
jkloe@jkloe.com