text
string
size
int64
token_count
int64
/*============================================================================== Copyright 2018 by Roland Rabien For more information visit www.rabiensoftware.com ==============================================================================*/ // Your project must contain an AppConfig.h file with your project-specific settings in it, // and your header search path must make it accessible to the module's files. #include "AppConfig.h" #ifdef _WIN32 #include <Windows.h> #include <ctime> #endif //============================================================================== #include "gin_metadata.h" //============================================================================== namespace gin { using namespace juce; using juce::Rectangle; using juce::MemoryBlock; #include "metadata/libjpegpng.cpp" #include "metadata/commentmetadata.cpp" #include "metadata/exifmetadata.cpp" #include "metadata/imagemetadata.cpp" #include "metadata/iptcmetadata.cpp" #include "metadata/xmpmetadata.cpp" }
1,010
260
//https://www.codechef.com/problems/GDOG #include <bits/stdc++.h> #define ll long long int using namespace std; int main() { #ifdef DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base ::sync_with_stdio(false); cin.tie(0); int t, n, k; cin >> t; while (t--) { cin >> n >> k; int max = INT_MIN, temp; for (int i = 1; i <= k; i++) { temp = n - (n / i) * i; if (temp > max) { max = temp; } } cout << max << endl; } return 0; }
622
235
#include <string> class HasPtr { public: HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) {} HasPtr(const HasPtr &has_ptr) : ps(new std::string(*(has_ptr.ps))), i(has_ptr.i) {} private: std::string *ps; int i; };
282
113
//q11727.cpp - 2011/10/11 //accepted at 2011/10/11 //run time = 0.000 #include <stdio.h> using namespace std; int salary[3] = {}; int top = 0; void sort(int inputNum){ int i; for(i = top-1; i >= 0 && salary[i] > inputNum; i--){ salary[i+1] = salary[i]; } i += 1; salary[i] = inputNum; top += 1; } int main(){ #ifndef ONLINE_JUDGE freopen("q11727.in", "r", stdin); freopen("q11727.out", "w", stdout); #endif int caseNum, currentCase = 0, tmp; scanf("%d", &caseNum); while(caseNum-- > 0){ top = 0; for(int j=0;j<3;j++){ scanf("%d", &tmp); sort(tmp); } printf("Case %d: %d\n", ++currentCase, salary[1]); } return 0; }
692
368
#include<iostream> #include<queue> using namespace std; class SinglyLinkedListNode { public: char key; SinglyLinkedListNode * left; SinglyLinkedListNode * right; SinglyLinkedListNode(char node_data) { this -> key = node_data; this -> left = NULL; this -> right = NULL; } }; class SinglyLinkedList { public: SinglyLinkedListNode * root; queue q; SinglyLinkedList() { this -> root = NULL; } void insert_node_left(char node_data, SinglyLinkedListNode * ptr ) { /*code to insert new node at the end in linked list having node_data*/ this -> tail -> next = ptr1; this -> tail = ptr1; } }; void print_singly_linked_list(SinglyLinkedListNode * node) { /*code to print linked list separated by single space*/ SinglyLinkedListNode * walker = node; while (walker != NULL) { cout << walker -> data << " "; walker = walker -> next; } cout<<endl; } SinglyLinkedListNode * removeDuplicates(SinglyLinkedListNode * head) { /*code to remove duplicates*/ SinglyLinkedListNode * w1 = head; SinglyLinkedListNode * w2 = head -> next; while (w2 != NULL) { if (w1 -> data == w2 -> data) { SinglyLinkedListNode * temp = w2; w2 = w2 -> next; w1 -> next = w2; delete temp; } else { w1 = w1 -> next; w2 = w2 -> next; } } return head; } int main() { int test_cases; cin >> test_cases; SinglyLinkedListNode * listfinal[test_cases]; for (int i = 0; i < test_cases; i++) { SinglyLinkedList * LS = new SinglyLinkedList(); /*code to read input and insert node in linked list*/ int num_node; cin >> num_node; for (int a = 0; a < num_node; a++) { int value; cin >> value; if (a == 0) { SinglyLinkedListNode * ptr = new SinglyLinkedListNode(value); LS -> head = ptr; LS -> tail = ptr; } else { LS -> insert_node(value); } } LS -> head = removeDuplicates(LS -> head); listfinal[i] = LS -> head; } for (int i = 0; i < test_cases; i++) { print_singly_linked_list(listfinal[i]); cout << endl; } return 0; }
2,133
772
// FB Alpha Rohga Armor Force / Wizard Fire / Nitro Ball / Schmeiser Robo driver module // Based on MAME driver by Bryan McPhail #include "tiles_generic.h" #include "m68000_intf.h" #include "h6280_intf.h" #include "deco16ic.h" #include "msm6295.h" #include "burn_ym2151.h" static UINT8 *AllMem; static UINT8 *MemEnd; static UINT8 *AllRam; static UINT8 *RamEnd; static UINT8 *Drv68KROM; static UINT8 *DrvHucROM; static UINT8 *DrvGfxROM0; static UINT8 *DrvGfxROM1; static UINT8 *DrvGfxROM2; static UINT8 *DrvGfxROM3; static UINT8 *DrvGfxROM4; static UINT8 *DrvSndROM0; static UINT8 *DrvSndROM1; static UINT8 *Drv68KRAM; static UINT8 *DrvHucRAM; static UINT8 *DrvPalRAM; static UINT8 *DrvPalBuf; static UINT8 *DrvSprRAM; static UINT8 *DrvSprRAM2; static UINT8 *DrvSprBuf; static UINT8 *DrvSprBuf2; static UINT8 *DrvPrtRAM; static UINT32 *DrvPalette; static UINT8 DrvRecalc; static UINT8 *flipscreen; static UINT8 DrvJoy1[16]; static UINT8 DrvJoy2[16]; static UINT8 DrvJoy3[16]; static UINT8 DrvDips[3]; static UINT8 DrvReset; static UINT16 DrvInputs[4]; static UINT16 *tempdraw[2]; static INT32 DrvOkiBank; static struct BurnInputInfo RohgaInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" }, {"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3" }, {"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" }, {"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" }, {"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" }, {"P2 Button 3", BIT_DIGITAL, DrvJoy1 + 14, "p2 fire 3" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, {"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" }, }; STDINPUTINFO(Rohga) static struct BurnInputInfo WizdfireInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" }, {"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" }, {"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" }, {"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, }; STDINPUTINFO(Wizdfire) static struct BurnInputInfo NitrobalInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy2 + 0, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" }, {"P2 Coin", BIT_DIGITAL, DrvJoy2 + 1, "p2 coin" }, {"P2 Start", BIT_DIGITAL, DrvJoy1 + 15, "p2 start" }, {"P2 Up", BIT_DIGITAL, DrvJoy1 + 8, "p2 up" }, {"P2 Down", BIT_DIGITAL, DrvJoy1 + 9, "p2 down" }, {"P2 Left", BIT_DIGITAL, DrvJoy1 + 10, "p2 left" }, {"P2 Right", BIT_DIGITAL, DrvJoy1 + 11, "p2 right" }, {"P2 Button 1", BIT_DIGITAL, DrvJoy1 + 12, "p2 fire 1" }, {"P2 Button 2", BIT_DIGITAL, DrvJoy1 + 13, "p2 fire 2" }, {"P3 Coin", BIT_DIGITAL, DrvJoy3 + 7, "p3 coin" }, {"P3 Up", BIT_DIGITAL, DrvJoy3 + 0, "p3 up" }, {"P3 Down", BIT_DIGITAL, DrvJoy3 + 1, "p3 down" }, {"P3 Left", BIT_DIGITAL, DrvJoy3 + 2, "p3 left" }, {"P3 Right", BIT_DIGITAL, DrvJoy3 + 3, "p3 right" }, {"P3 Button 1", BIT_DIGITAL, DrvJoy3 + 4, "p3 fire 1" }, {"P3 Button 2", BIT_DIGITAL, DrvJoy3 + 5, "p3 fire 2" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Service", BIT_DIGITAL, DrvJoy2 + 2, "service" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, }; STDINPUTINFO(Nitrobal) static struct BurnDIPInfo RohgaDIPList[]= { {0x14, 0xff, 0xff, 0xff, NULL }, {0x15, 0xff, 0xff, 0x7f, NULL }, {0x16, 0xff, 0xff, 0xff, NULL }, {0 , 0xfe, 0 , 8, "Coin A" }, {0x14, 0x01, 0x07, 0x00, "3 Coins 1 Credits" }, {0x14, 0x01, 0x07, 0x01, "2 Coins 1 Credits" }, {0x14, 0x01, 0x07, 0x07, "1 Coin 1 Credits" }, {0x14, 0x01, 0x07, 0x06, "1 Coin 2 Credits" }, {0x14, 0x01, 0x07, 0x05, "1 Coin 3 Credits" }, {0x14, 0x01, 0x07, 0x04, "1 Coin 4 Credits" }, {0x14, 0x01, 0x07, 0x03, "1 Coin 5 Credits" }, {0x14, 0x01, 0x07, 0x02, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 8, "Coin B" }, {0x14, 0x01, 0x38, 0x00, "3 Coins 1 Credits" }, {0x14, 0x01, 0x38, 0x08, "2 Coins 1 Credits" }, {0x14, 0x01, 0x38, 0x38, "1 Coin 1 Credits" }, {0x14, 0x01, 0x38, 0x30, "1 Coin 2 Credits" }, {0x14, 0x01, 0x38, 0x28, "1 Coin 3 Credits" }, {0x14, 0x01, 0x38, 0x20, "1 Coin 4 Credits" }, {0x14, 0x01, 0x38, 0x18, "1 Coin 5 Credits" }, {0x14, 0x01, 0x38, 0x10, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x14, 0x01, 0x40, 0x40, "Off" }, {0x14, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" }, {0x14, 0x01, 0x80, 0x80, "Off" }, {0x14, 0x01, 0x80, 0x00, "On" }, {0 , 0xfe, 0 , 4, "Player's Vitality" }, {0x15, 0x01, 0x30, 0x30, "Normal" }, {0x15, 0x01, 0x30, 0x20, "Low" }, {0x15, 0x01, 0x30, 0x10, "Lowest" }, {0x15, 0x01, 0x30, 0x00, "High" }, {0 , 0xfe, 0 , 2, "Allow Continue" }, {0x15, 0x01, 0x40, 0x40, "Off" }, {0x15, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x15, 0x01, 0x80, 0x80, "Off" }, {0x15, 0x01, 0x80, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Stage Clear Bonus" }, {0x16, 0x01, 0x01, 0x01, "Off" }, {0x16, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 4, "Enemy's Vitality" }, {0x16, 0x01, 0x0c, 0x08, "Low" }, {0x16, 0x01, 0x0c, 0x0c, "Normal" }, {0x16, 0x01, 0x0c, 0x04, "High" }, {0x16, 0x01, 0x0c, 0x00, "Highest" }, {0 , 0xfe, 0 , 4, "Enemy Encounter Rate" }, {0x16, 0x01, 0x30, 0x20, "Low" }, {0x16, 0x01, 0x30, 0x30, "Normal" }, {0x16, 0x01, 0x30, 0x10, "High" }, {0x16, 0x01, 0x30, 0x00, "Highest" }, {0 , 0xfe, 0 , 4, "Enemy's Weapon Speed" }, {0x16, 0x01, 0xc0, 0x80, "Slow" }, {0x16, 0x01, 0xc0, 0xc0, "Normal" }, {0x16, 0x01, 0xc0, 0x40, "Fast" }, {0x16, 0x01, 0xc0, 0x00, "Fastest" }, }; STDDIPINFO(Rohga) static struct BurnDIPInfo SchmeisrDIPList[]= { {0x14, 0xff, 0xff, 0xff, NULL }, {0x15, 0xff, 0xff, 0xff, NULL }, {0x16, 0xff, 0xff, 0xff, NULL }, {0 , 0xfe, 0 , 8, "Coin A" }, {0x14, 0x01, 0x07, 0x00, "3 Coins 1 Credits" }, {0x14, 0x01, 0x07, 0x01, "2 Coins 1 Credits" }, {0x14, 0x01, 0x07, 0x07, "1 Coin 1 Credits" }, {0x14, 0x01, 0x07, 0x06, "1 Coin 2 Credits" }, {0x14, 0x01, 0x07, 0x05, "1 Coin 3 Credits" }, {0x14, 0x01, 0x07, 0x04, "1 Coin 4 Credits" }, {0x14, 0x01, 0x07, 0x03, "1 Coin 5 Credits" }, {0x14, 0x01, 0x07, 0x02, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 8, "Coin B" }, {0x14, 0x01, 0x38, 0x00, "3 Coins 1 Credits" }, {0x14, 0x01, 0x38, 0x08, "2 Coins 1 Credits" }, {0x14, 0x01, 0x38, 0x38, "1 Coin 1 Credits" }, {0x14, 0x01, 0x38, 0x30, "1 Coin 2 Credits" }, {0x14, 0x01, 0x38, 0x28, "1 Coin 3 Credits" }, {0x14, 0x01, 0x38, 0x20, "1 Coin 4 Credits" }, {0x14, 0x01, 0x38, 0x18, "1 Coin 5 Credits" }, {0x14, 0x01, 0x38, 0x10, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x14, 0x01, 0x40, 0x40, "Off" }, {0x14, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Service Mode" }, {0x14, 0x01, 0x80, 0x80, "Off" }, {0x14, 0x01, 0x80, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x15, 0x01, 0x04, 0x00, "Off" }, {0x15, 0x01, 0x04, 0x04, "On" }, {0 , 0xfe, 0 , 2, "Freeze Screen" }, {0x16, 0x01, 0x20, 0x20, "Off" }, {0x16, 0x01, 0x20, 0x00, "On" }, }; STDDIPINFO(Schmeisr) static struct BurnDIPInfo WizdfireDIPList[]= { {0x12, 0xff, 0xff, 0xff, NULL }, {0x13, 0xff, 0xff, 0x7f, NULL }, {0 , 0xfe, 0 , 8, "Coin A" }, {0x12, 0x01, 0x07, 0x00, "3 Coins 1 Credits" }, {0x12, 0x01, 0x07, 0x01, "2 Coins 1 Credits" }, {0x12, 0x01, 0x07, 0x07, "1 Coin 1 Credits" }, {0x12, 0x01, 0x07, 0x06, "1 Coin 2 Credits" }, {0x12, 0x01, 0x07, 0x05, "1 Coin 3 Credits" }, {0x12, 0x01, 0x07, 0x04, "1 Coin 4 Credits" }, {0x12, 0x01, 0x07, 0x03, "1 Coin 5 Credits" }, {0x12, 0x01, 0x07, 0x02, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 8, "Coin B" }, {0x12, 0x01, 0x38, 0x00, "3 Coins 1 Credits" }, {0x12, 0x01, 0x38, 0x08, "2 Coins 1 Credits" }, {0x12, 0x01, 0x38, 0x38, "1 Coin 1 Credits" }, {0x12, 0x01, 0x38, 0x30, "1 Coin 2 Credits" }, {0x12, 0x01, 0x38, 0x28, "1 Coin 3 Credits" }, {0x12, 0x01, 0x38, 0x20, "1 Coin 4 Credits" }, {0x12, 0x01, 0x38, 0x18, "1 Coin 5 Credits" }, {0x12, 0x01, 0x38, 0x10, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x12, 0x01, 0x40, 0x40, "Off" }, {0x12, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" }, {0x12, 0x01, 0x80, 0x80, "Off" }, {0x12, 0x01, 0x80, 0x00, "On" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x13, 0x01, 0x03, 0x00, "2" }, {0x13, 0x01, 0x03, 0x01, "3" }, {0x13, 0x01, 0x03, 0x03, "4" }, {0x13, 0x01, 0x03, 0x02, "5" }, {0 , 0xfe, 0 , 4, "Difficulty" }, {0x13, 0x01, 0x0c, 0x08, "Easy" }, {0x13, 0x01, 0x0c, 0x0c, "Normal" }, {0x13, 0x01, 0x0c, 0x04, "Hard" }, {0x13, 0x01, 0x0c, 0x00, "Hardest" }, {0 , 0xfe, 0 , 4, "Magic Gauge Speed" }, {0x13, 0x01, 0x30, 0x00, "Very Slow" }, {0x13, 0x01, 0x30, 0x10, "Slow" }, {0x13, 0x01, 0x30, 0x30, "Normal" }, {0x13, 0x01, 0x30, 0x20, "Fast" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x13, 0x01, 0x80, 0x80, "Off" }, {0x13, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Wizdfire) static struct BurnDIPInfo NitrobalDIPList[]= { {0x19, 0xff, 0xff, 0xff, NULL }, {0x1a, 0xff, 0xff, 0x7f, NULL }, {0 , 0xfe, 0 , 8, "Coin A" }, {0x19, 0x01, 0x07, 0x00, "3 Coins 1 Credits" }, {0x19, 0x01, 0x07, 0x01, "2 Coins 1 Credits" }, {0x19, 0x01, 0x07, 0x07, "1 Coin 1 Credits" }, {0x19, 0x01, 0x07, 0x06, "1 Coin 2 Credits" }, {0x19, 0x01, 0x07, 0x05, "1 Coin 3 Credits" }, {0x19, 0x01, 0x07, 0x04, "1 Coin 4 Credits" }, {0x19, 0x01, 0x07, 0x03, "1 Coin 5 Credits" }, {0x19, 0x01, 0x07, 0x02, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 8, "Coin B" }, {0x19, 0x01, 0x38, 0x00, "3 Coins 1 Credits" }, {0x19, 0x01, 0x38, 0x08, "2 Coins 1 Credits" }, {0x19, 0x01, 0x38, 0x38, "1 Coin 1 Credits" }, {0x19, 0x01, 0x38, 0x30, "1 Coin 2 Credits" }, {0x19, 0x01, 0x38, 0x28, "1 Coin 3 Credits" }, {0x19, 0x01, 0x38, 0x20, "1 Coin 4 Credits" }, {0x19, 0x01, 0x38, 0x18, "1 Coin 5 Credits" }, {0x19, 0x01, 0x38, 0x10, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x19, 0x01, 0x40, 0x40, "Off" }, {0x19, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "2 Credits to Start, 1 to Continue" }, {0x19, 0x01, 0x80, 0x80, "Off" }, {0x19, 0x01, 0x80, 0x00, "On" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x1a, 0x01, 0x03, 0x01, "1" }, {0x1a, 0x01, 0x03, 0x00, "2" }, {0x1a, 0x01, 0x03, 0x03, "3" }, {0x1a, 0x01, 0x03, 0x02, "4" }, {0 , 0xfe, 0 , 4, "Difficulty?" }, {0x1a, 0x01, 0x0c, 0x08, "Easy" }, {0x1a, 0x01, 0x0c, 0x0c, "Normal" }, {0x1a, 0x01, 0x0c, 0x04, "Hard" }, {0x1a, 0x01, 0x0c, 0x00, "Hardest" }, {0 , 0xfe, 0 , 2, "Split Coin Chutes" }, {0x1a, 0x01, 0x10, 0x10, "Off" }, {0x1a, 0x01, 0x10, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Players" }, {0x1a, 0x01, 0x20, 0x20, "2" }, {0x1a, 0x01, 0x20, 0x00, "3" }, {0 , 0xfe, 0 , 2, "Shot Button to Start" }, {0x1a, 0x01, 0x40, 0x40, "Off" }, {0x1a, 0x01, 0x40, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x1a, 0x01, 0x80, 0x80, "Off" }, {0x1a, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Nitrobal) void __fastcall rohga_main_write_word(UINT32 address, UINT16 data) { deco16_write_control_word(0, address, 0x200000, data) deco16_write_control_word(1, address, 0x240000, data) switch (address) { case 0x2800a8: deco16_soundlatch = data & 0xff; h6280SetIRQLine(0, H6280_IRQSTATUS_ACK); return; case 0x300000: memcpy (DrvSprBuf2, DrvSprBuf, 0x800); memcpy (DrvSprBuf, DrvSprRAM, 0x800); return; case 0x31000a: memcpy (DrvPalBuf, DrvPalRAM, 0x2000); return; case 0x321100: // schmeisr SekSetIRQLine(6, SEK_IRQSTATUS_NONE); return; case 0x322000: deco16_priority = data; return; } if ((address & 0xffff000) == 0x280000) { deco16_104_rohga_prot_w(address, data, 0xffff); return; } } void __fastcall rohga_main_write_byte(UINT32 address, UINT8 data) { switch (address) { case 0x2800a9: deco16_soundlatch = data; h6280SetIRQLine(0, H6280_IRQSTATUS_ACK); return; case 0x300000: case 0x300001: memcpy (DrvSprBuf2, DrvSprBuf, 0x800); memcpy (DrvSprBuf, DrvSprRAM, 0x800); return; case 0x31000a: case 0x31000b: memcpy (DrvPalBuf, DrvPalRAM, 0x2000); return; case 0x321100: // schmeisr case 0x321101: SekSetIRQLine(6, SEK_IRQSTATUS_NONE); return; case 0x322000: case 0x322001: deco16_priority = data; return; } if ((address & 0xffff000) == 0x280000) { deco16_104_rohga_prot_w(address, data, 0x00ff << ((address & 1) << 3)); return; } } UINT16 __fastcall rohga_main_read_word(UINT32 address) { switch (address) { case 0x2c0000: case 0x300000: // schmeisr return DrvDips[2]; case 0x310002: // schmeisr return (DrvInputs[1] & 0x07) | (deco16_vblank & 0x08); case 0x321100: SekSetIRQLine(6, SEK_IRQSTATUS_NONE); return 0; } if ((address & 0xffff000) == 0x280000) { return deco16_104_rohga_prot_r(address); } return 0; } UINT8 __fastcall rohga_main_read_byte(UINT32 address) { switch (address) { case 0x2c0000: case 0x2c0001: case 0x300000: // schmeisr case 0x300001: return DrvDips[2]; case 0x310002: // schmeisr case 0x310003: return (DrvInputs[1] & 0x07) | (deco16_vblank & 0x08); case 0x321100: case 0x321101: SekSetIRQLine(6, SEK_IRQSTATUS_NONE); return 0; } if ((address & 0xffff000) == 0x280000) { return deco16_104_rohga_prot_r(address) >> ((~address & 1) << 3); } return 0; } void __fastcall wizdfire_main_write_word(UINT32 address, UINT16 data) { deco16_write_control_word(0, address, 0x300000, data) deco16_write_control_word(1, address, 0x310000, data) switch (address) { case 0x350000: memcpy (DrvSprBuf, DrvSprRAM, 0x800); return; case 0x370000: memcpy (DrvSprBuf2, DrvSprRAM2, 0x800); return; case 0x380008: memcpy (DrvPalBuf, DrvPalRAM, 0x2000); return; case 0x320000: deco16_priority = data; return; case 0x320004: SekSetIRQLine(6, SEK_IRQSTATUS_NONE); return; case 0xfe4150: case 0xff4260: // nitrobal case 0xff4a60: deco16_soundlatch = data & 0xff; h6280SetIRQLine(0, H6280_IRQSTATUS_ACK); return; } if ((address & 0xffff000) == 0xfe4000) { deco16_prot_ram[(address & 0x7ff)/2] = data; return; } if ((address & 0xffff000) == 0xff4000) { deco16_146_nitroball_prot_w(address, data, 0xffff); return; } } void __fastcall wizdfire_main_write_byte(UINT32 address, UINT8 data) { switch (address) { case 0x350000: case 0x350001: memcpy (DrvSprBuf, DrvSprRAM, 0x800); return; case 0x370000: case 0x370001: memcpy (DrvSprBuf2, DrvSprRAM2, 0x800); return; case 0x380008: case 0x380009: memcpy (DrvPalBuf, DrvPalRAM, 0x2000); return; case 0x320000: case 0x320001: deco16_priority = data; return; case 0x320004: case 0x320005: SekSetIRQLine(6, SEK_IRQSTATUS_NONE); return; case 0xfe4151: case 0xff4261: // nitrobal case 0xff4a61: deco16_soundlatch = data; h6280SetIRQLine(0, H6280_IRQSTATUS_ACK); return; } if ((address & 0xffff000) == 0xfe4000) { DrvPrtRAM[(address & 0x7ff)^1] = data; return; } if ((address & 0xffff000) == 0xff4000) { deco16_146_nitroball_prot_w(address, data, 0x00ff << ((address & 1) << 3)); return; } } UINT16 __fastcall wizdfire_main_read_word(UINT32 address) { if (address == 0x320000) return DrvInputs[2]; if ((address & 0xffff800) == 0xfe4000) { return deco16_104_prot_r(address); } if ((address & 0xffff000) == 0xff4000) { return deco16_146_nitroball_prot_r(address); } return 0; } UINT8 __fastcall wizdfire_main_read_byte(UINT32 address) { if (address == 0x320000 || address == 0x320001) return DrvInputs[2] >> ((~address & 1) << 3); if ((address & 0xffff800) == 0xfe4000) { return deco16_104_prot_r(address) >> ((~address & 1) << 3); } if ((address & 0xffff000) == 0xff4000) { return deco16_146_nitroball_prot_r(address) >> ((~address & 1) << 3); } return 0; } static void DrvYM2151WritePort(UINT32, UINT32 data) { if ((data & 0x01) != (UINT32)(DrvOkiBank & 0x01)) { memcpy (DrvSndROM0, DrvSndROM0 + 0x40000 + ((data & 0x01) >> 0) * 0x40000, 0x40000); } if ((data & 0x02) != (UINT32)(DrvOkiBank & 0x02)) { memcpy (DrvSndROM1, DrvSndROM1 + 0x40000 + ((data & 0x02) >> 1) * 0x40000, 0x40000); } DrvOkiBank = data; } static INT32 rohga_bank_callback( const INT32 bank ) { return ((bank >> 4) & 0x3) << 12; } static INT32 DrvDoReset() { memset (AllRam, 0, RamEnd - AllRam); SekOpen(0); SekReset(); SekClose(); deco16SoundReset(); deco16Reset(); DrvOkiBank = -1; DrvYM2151WritePort(0, 3); return 0; } static INT32 MemIndex() { UINT8 *Next; Next = AllMem; Drv68KROM = Next; Next += 0x200000; DrvHucROM = Next; Next += 0x010000; DrvGfxROM0 = Next; Next += 0x080000; DrvGfxROM1 = Next; Next += 0x400000; DrvGfxROM2 = Next; Next += 0x400000; DrvGfxROM3 = Next; Next += 0x800000; DrvGfxROM4 = Next; Next += 0x100000; MSM6295ROM = Next; DrvSndROM0 = Next; Next += 0x100000; DrvSndROM1 = Next; Next += 0x0c0000; tempdraw[0] = (UINT16*)Next; Next += 320 * 240 * sizeof(UINT16); tempdraw[1] = (UINT16*)Next; Next += 320 * 240 * sizeof(UINT16); DrvPalette = (UINT32*)Next; Next += 0x0800 * sizeof(UINT32); AllRam = Next; Drv68KRAM = Next; Next += 0x024000; DrvHucRAM = Next; Next += 0x002000; DrvSprRAM2 = Next; Next += 0x000800; DrvSprRAM = Next; Next += 0x000800; DrvSprBuf2 = Next; Next += 0x000800; DrvSprBuf = Next; Next += 0x000800; deco16_prot_ram = (UINT16*)Next; DrvPrtRAM = Next; Next += 0x000800; deco16_buffer_ram = (UINT16*)Next; Next += 0x000800; DrvPalRAM = Next; Next += 0x002000; DrvPalBuf = Next; Next += 0x002000; flipscreen = Next; Next += 0x000001; RamEnd = Next; MemEnd = Next; return 0; } static INT32 DrvSpriteDecode() { INT32 Plane[6] = { 0x400000*8+8, 0x400000*8, 0x200000*8+8, 0x200000*8, 8, 0 }; INT32 XOffs[16] = { 7,6,5,4,3,2,1,0, 32*8+7, 32*8+6, 32*8+5, 32*8+4, 32*8+3, 32*8+2, 32*8+1, 32*8+0 }; INT32 YOffs[16] = { 15*16, 14*16, 13*16, 12*16, 11*16, 10*16, 9*16, 8*16, 7*16, 6*16, 5*16, 4*16, 3*16, 2*16, 1*16, 0*16}; UINT8 *tmp = (UINT8*)BurnMalloc(0x600000); if (tmp == NULL) { return 1; } memcpy (tmp, DrvGfxROM3, 0x600000); GfxDecode(0x8000, 6, 16, 16, Plane, XOffs, YOffs, 0x200, tmp, DrvGfxROM3); BurnFree (tmp); return 0; } static INT32 RohgaInit() { BurnSetRefreshRate(58.00); AllMem = NULL; MemIndex(); INT32 nLen = MemEnd - (UINT8 *)0; if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x100001, 2, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x100000, 3, 2)) return 1; if (BurnLoadRom(DrvHucROM + 0x000000, 4, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000000, 5, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000001, 6, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 7, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x080000, 8, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x000000, 9, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x100000, 10, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x000000, 11, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x100000, 12, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x200000, 13, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x300000, 14, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x400000, 15, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x500000, 16, 1)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x040000, 17, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x040000, 18, 1)) return 1; deco56_decrypt_gfx(DrvGfxROM0, 0x020000); deco56_decrypt_gfx(DrvGfxROM1, 0x100000); deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1); deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0); deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0); DrvSpriteDecode(); } deco16Init(0, 0, 1); deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2); deco16_set_color_base(2, 512); deco16_set_color_base(3, 768); deco16_set_global_offsets(0, 8); deco16_set_bank_callback(0, rohga_bank_callback); deco16_set_bank_callback(1, rohga_bank_callback); deco16_set_bank_callback(2, rohga_bank_callback); deco16_set_bank_callback(3, rohga_bank_callback); SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM); SekMapMemory(deco16_pf_ram[0], 0x3c0000, 0x3c1fff, SM_RAM); SekMapMemory(deco16_pf_ram[1], 0x3c2000, 0x3c2fff, SM_RAM); SekMapMemory(deco16_pf_ram[2], 0x3c4000, 0x3c4fff, SM_RAM); SekMapMemory(deco16_pf_ram[3], 0x3c6000, 0x3c6fff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[0], 0x3c8000, 0x3c8fff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[0], 0x3c9000, 0x3c9fff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[1], 0x3ca000, 0x3cafff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[1], 0x3cb000, 0x3cbfff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[2], 0x3cc000, 0x3ccfff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[2], 0x3cd000, 0x3cdfff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[3], 0x3ce000, 0x3cefff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[3], 0x3cf000, 0x3cffff, SM_RAM); SekMapMemory(DrvSprRAM, 0x3d0000, 0x3d07ff, SM_RAM); SekMapMemory(DrvPalRAM, 0x3e0000, 0x3e1fff, SM_RAM); SekMapMemory(Drv68KRAM, 0x3f0000, 0x3f3fff, SM_RAM); SekSetWriteWordHandler(0, rohga_main_write_word); SekSetWriteByteHandler(0, rohga_main_write_byte); SekSetReadWordHandler(0, rohga_main_read_word); SekSetReadByteHandler(0, rohga_main_read_byte); SekClose(); deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.78, 1006875, 1.00, 2013750, 0.40); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.78, BURN_SND_ROUTE_LEFT); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.78, BURN_SND_ROUTE_RIGHT); GenericTilesInit(); DrvDoReset(); return 0; } static INT32 WizdfireInit() { BurnSetRefreshRate(58.00); AllMem = NULL; MemIndex(); INT32 nLen = MemEnd - (UINT8 *)0; if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x040001, 2, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x040000, 3, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x080001, 4, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x080000, 5, 2)) return 1; if (BurnLoadRom(DrvHucROM + 0x000000, 6, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000000, 7, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000001, 8, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 9, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x100000, 10, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x000000, 11, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x080000, 12, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x000000, 13, 2)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x000001, 14, 2)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x200000, 15, 2)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x200001, 16, 2)) return 1; if (BurnLoadRom(DrvGfxROM4 + 0x000000, 17, 2)) return 1; if (BurnLoadRom(DrvGfxROM4 + 0x000001, 18, 2)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x040000, 19, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x040000, 20, 1)) return 1; deco74_decrypt_gfx(DrvGfxROM0, 0x020000); deco74_decrypt_gfx(DrvGfxROM1, 0x200000); deco74_decrypt_gfx(DrvGfxROM2, 0x100000); deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1); deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x200000, 0); deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x100000, 0); deco16_sprite_decode(DrvGfxROM3, 0x400000); deco16_sprite_decode(DrvGfxROM4, 0x100000); } deco16Init(0, 0, 1); deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x200000 * 2, DrvGfxROM2, 0x100000 * 2); deco16_set_color_base(2, 512); deco16_set_color_base(3, 768); deco16_set_global_offsets(0, 8); deco16_set_bank_callback(0, rohga_bank_callback); deco16_set_bank_callback(1, rohga_bank_callback); deco16_set_bank_callback(2, rohga_bank_callback); deco16_set_bank_callback(3, rohga_bank_callback); SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM); SekMapMemory(deco16_pf_ram[0], 0x200000, 0x200fff, SM_RAM); SekMapMemory(deco16_pf_ram[1], 0x202000, 0x202fff, SM_RAM); SekMapMemory(deco16_pf_ram[2], 0x208000, 0x208fff, SM_RAM); SekMapMemory(deco16_pf_ram[3], 0x20a000, 0x20afff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[2], 0x20c000, 0x20c7ff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[3], 0x20e000, 0x20e7ff, SM_RAM); SekMapMemory(DrvSprRAM, 0x340000, 0x3407ff, SM_RAM); SekMapMemory(DrvSprRAM2, 0x360000, 0x3607ff, SM_RAM); SekMapMemory(DrvPalRAM, 0x380000, 0x381fff, SM_RAM); SekMapMemory(Drv68KRAM, 0xfdc000, 0xfe3fff, SM_RAM); SekMapMemory(Drv68KRAM + 0x8000, 0xfe4800, 0xffffff, SM_RAM); SekSetWriteWordHandler(0, wizdfire_main_write_word); SekSetWriteByteHandler(0, wizdfire_main_write_byte); SekSetReadWordHandler(0, wizdfire_main_read_word); SekSetReadByteHandler(0, wizdfire_main_read_byte); SekClose(); deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT); GenericTilesInit(); DrvDoReset(); return 0; } static INT32 SchmeisrInit() { BurnSetRefreshRate(58.00); AllMem = NULL; MemIndex(); INT32 nLen = MemEnd - (UINT8 *)0; if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1; if (BurnLoadRom(DrvHucROM + 0x000000, 2, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 3, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x080000, 4, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x000000, 5, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x100000, 6, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x000000, 7, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x100000, 8, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x200000, 9, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x300000, 10, 1)) return 1; if (BurnLoadRom(DrvSndROM0 + 0x040000, 11, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x040000, 12, 1)) return 1; deco74_decrypt_gfx(DrvGfxROM1, 0x100000); memcpy (DrvGfxROM0 + 0x000000, DrvGfxROM1 + 0x000000, 0x020000); memcpy (DrvGfxROM0 + 0x020000, DrvGfxROM1 + 0x080000, 0x020000); deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x040000, 1); deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0); deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0); DrvSpriteDecode(); } deco16Init(0, 0, 1); deco16_set_graphics(DrvGfxROM0, 0x40000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2); deco16_set_color_base(2, 512); deco16_set_color_base(3, 768); deco16_set_global_offsets(0, 8); deco16_set_bank_callback(0, rohga_bank_callback); deco16_set_bank_callback(1, rohga_bank_callback); deco16_set_bank_callback(2, rohga_bank_callback); deco16_set_bank_callback(3, rohga_bank_callback); SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM); SekMapMemory(deco16_pf_ram[0], 0x3c0000, 0x3c1fff, SM_RAM); SekMapMemory(deco16_pf_ram[1], 0x3c2000, 0x3c2fff, SM_RAM); SekMapMemory(deco16_pf_ram[2], 0x3c4000, 0x3c4fff, SM_RAM); SekMapMemory(deco16_pf_ram[3], 0x3c6000, 0x3c6fff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[0], 0x3c8000, 0x3c8fff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[0], 0x3c9000, 0x3c9fff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[1], 0x3ca000, 0x3cafff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[1], 0x3cb000, 0x3cbfff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[2], 0x3cc000, 0x3ccfff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[2], 0x3cd000, 0x3cdfff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[3], 0x3ce000, 0x3cefff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[3], 0x3cf000, 0x3cffff, SM_RAM); SekMapMemory(DrvSprRAM, 0x3d0000, 0x3d07ff, SM_RAM); SekMapMemory(DrvPalRAM, 0x3e0000, 0x3e1fff, SM_RAM); SekMapMemory(DrvPalRAM, 0x3e2000, 0x3e3fff, SM_RAM); SekMapMemory(Drv68KRAM, 0xff0000, 0xff7fff, SM_RAM); SekSetWriteWordHandler(0, rohga_main_write_word); SekSetWriteByteHandler(0, rohga_main_write_byte); SekSetReadWordHandler(0, rohga_main_read_word); SekSetReadByteHandler(0, rohga_main_read_byte); SekClose(); deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT); GenericTilesInit(); DrvDoReset(); return 0; } static INT32 NitrobalInit() { BurnSetRefreshRate(58.00); AllMem = NULL; MemIndex(); INT32 nLen = MemEnd - (UINT8 *)0; if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(Drv68KROM + 0x000001, 0, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x000000, 1, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x040001, 2, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x040000, 3, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x080001, 4, 2)) return 1; if (BurnLoadRom(Drv68KROM + 0x080000, 5, 2)) return 1; if (BurnLoadRom(DrvHucROM + 0x000000, 6, 1)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000000, 7, 2)) return 1; if (BurnLoadRom(DrvGfxROM0 + 0x000001, 8, 2)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x000000, 9, 1)) return 1; if (BurnLoadRom(DrvGfxROM1 + 0x080000, 10, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x000000, 11, 1)) return 1; if (BurnLoadRom(DrvGfxROM2 + 0x100000, 12, 1)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x000000, 13, 2)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x000001, 14, 2)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x200000, 15, 2)) return 1; if (BurnLoadRom(DrvGfxROM3 + 0x200001, 16, 2)) return 1; BurnByteswap(DrvGfxROM3, 0x400000); if (BurnLoadRom(DrvGfxROM4 + 0x000000, 17, 2)) return 1; if (BurnLoadRom(DrvGfxROM4 + 0x000001, 18, 2)) return 1; BurnByteswap(DrvGfxROM4, 0x080000); if (BurnLoadRom(DrvSndROM0 + 0x040000, 19, 1)) return 1; if (BurnLoadRom(DrvSndROM1 + 0x040000, 20, 1)) return 1; deco56_decrypt_gfx(DrvGfxROM0, 0x020000); deco56_decrypt_gfx(DrvGfxROM1, 0x100000); deco74_decrypt_gfx(DrvGfxROM2, 0x200000); deco16_tile_decode(DrvGfxROM0, DrvGfxROM0, 0x020000, 1); deco16_tile_decode(DrvGfxROM1, DrvGfxROM1, 0x100000, 0); deco16_tile_decode(DrvGfxROM2, DrvGfxROM2, 0x200000, 0); deco16_sprite_decode(DrvGfxROM3, 0x400000); deco16_sprite_decode(DrvGfxROM4, 0x080000); } deco16Init(0, 0, 0); deco16_set_graphics(DrvGfxROM0, 0x20000 * 2, DrvGfxROM1, 0x100000 * 2, DrvGfxROM2, 0x200000 * 2); deco16_set_color_base(2, 512); deco16_set_color_mask(2, 0); deco16_set_color_base(3, 512); deco16_set_color_mask(3, 0); deco16_set_global_offsets(0, 8); deco16_set_bank_callback(0, rohga_bank_callback); deco16_set_bank_callback(1, rohga_bank_callback); deco16_set_bank_callback(2, rohga_bank_callback); deco16_set_bank_callback(3, rohga_bank_callback); SekInit(0, 0x68000); SekOpen(0); SekMapMemory(Drv68KROM, 0x000000, 0x1fffff, SM_ROM); SekMapMemory(deco16_pf_ram[0], 0x200000, 0x200fff, SM_RAM); SekMapMemory(deco16_pf_ram[0], 0x201000, 0x201fff, SM_RAM); SekMapMemory(deco16_pf_ram[1], 0x202000, 0x2027ff, SM_RAM); SekMapMemory(deco16_pf_ram[1], 0x202800, 0x202fff, SM_RAM); SekMapMemory(deco16_pf_ram[2], 0x208000, 0x2087ff, SM_RAM); SekMapMemory(deco16_pf_ram[2], 0x208800, 0x208fff, SM_RAM); SekMapMemory(deco16_pf_ram[3], 0x20a000, 0x20a7ff, SM_RAM); SekMapMemory(deco16_pf_ram[3], 0x20a800, 0x20afff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[0], 0x204000, 0x2047ff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[1], 0x206000, 0x2067ff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[2], 0x20c000, 0x20c7ff, SM_RAM); SekMapMemory(deco16_pf_rowscroll[3], 0x20e000, 0x20e7ff, SM_RAM); SekMapMemory(DrvSprRAM, 0x340000, 0x3407ff, SM_RAM); SekMapMemory(DrvSprRAM2, 0x360000, 0x3607ff, SM_RAM); SekMapMemory(DrvPalRAM, 0x380000, 0x381fff, SM_RAM); SekMapMemory(Drv68KRAM, 0xfec000, 0xff3fff, SM_RAM); SekMapMemory(Drv68KRAM + 0x8000, 0xff8000, 0xffffff, SM_RAM); SekSetWriteWordHandler(0, wizdfire_main_write_word); SekSetWriteByteHandler(0, wizdfire_main_write_byte); SekSetReadWordHandler(0, wizdfire_main_read_word); SekSetReadByteHandler(0, wizdfire_main_read_byte); SekClose(); deco16SoundInit(DrvHucROM, DrvHucRAM, 2685000, 0, DrvYM2151WritePort, 0.80, 1006875, 1.00, 2013750, 0.40); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_1, 0.80, BURN_SND_ROUTE_LEFT); BurnYM2151SetRoute(BURN_SND_YM2151_YM2151_ROUTE_2, 0.80, BURN_SND_ROUTE_RIGHT); GenericTilesInit(); DrvDoReset(); return 0; } static INT32 DrvExit() { GenericTilesExit(); deco16Exit(); SekExit(); deco16SoundExit(); BurnFree (AllMem); return 0; } static void rohga_draw_sprites(UINT8 *ram, INT32 is_schmeisr) { UINT16 *spriteptr = (UINT16*)ram; for (INT32 offs = 0x400 - 4; offs >= 0; offs -= 4) { INT32 inc, mult, pri = 0; INT32 sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]); if (!sprite) continue; INT32 x = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]); switch (x & 0x6000) { case 0x0000: pri = 0; break; case 0x4000: pri = 0xf0; break; case 0x6000: pri = 0xf0 | 0xcc; break; case 0x2000: pri = 0; break; } INT32 y = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]); if ((y & 0x1000) && (nCurrentFrame & 1)) continue; // flash INT32 colour = (((x >> 9) & 0xf) << 6); if (is_schmeisr) colour += ((x & 0x8000) >> 15) << 4; INT32 fx = y & 0x2000; INT32 fy = y & 0x4000; INT32 multi = (1 << ((y & 0x0600) >> 9)) - 1; x = x & 0x01ff; y = y & 0x01ff; if (x >= 320) x -= 512; if (y >= 256) y -= 512; sprite &= ~multi; if (fy) inc = -1; else { sprite += multi; inc = 1; } if (*flipscreen) { x = 304 - x; y = 240 - y; if (fx) fx = 0; else fx = 1; if (fy) fy = 0; else fy = 1; mult = -16; } else mult = +16; while (multi >= 0) { deco16_draw_prio_sprite(pTransDraw, DrvGfxROM3, (sprite - multi * inc) & 0x7fff, colour + 0x400, x, y + mult * multi, fx, fy, pri); multi--; } } } static void wizdfire_draw_sprites(UINT8 *ram, UINT8 *gfx, INT32 coloff, INT32 mode, INT32 bank) { UINT16 *spriteptr = (UINT16*)ram; for (INT32 offs = 0; offs < 0x400; offs += 4) { INT32 inc, mult, prio = 0, alpha = 0xff; INT32 sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]); if (!sprite) continue; INT32 x = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]); switch (mode) { case 4: if ((x & 0xc000) != 0xc000) continue; prio = 0x08; break; case 3: if ((x & 0xc000) != 0x8000) continue; prio = 0x10; break; case 2: if ((x & 0x8000) != 0x8000) continue; prio = 0x20; break; case 1: case 0: default: if ((x & 0x8000) != 0) continue; prio = 0x40; break; } INT32 y = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]); if ((y & 0x1000) && (nCurrentFrame & 1)) continue; // flash INT32 colour = (x >> 9) & 0x1f; if (bank == 4 && colour & 0x10) { alpha = 0x80; colour &= 0xf; } INT32 fx = y & 0x2000; INT32 fy = y & 0x4000; INT32 multi = (1 << ((y & 0x0600) >> 9)) - 1; x = x & 0x01ff; y = y & 0x01ff; if (x >= 320) x -= 512; if (y >= 256) y -= 512; sprite &= ~multi; if (fy) inc = -1; else { sprite += multi; inc = 1; } if (*flipscreen) { x = 304 - x; y = 240 - y; mult = -16; } else { mult = +16; fx = !fx; fy = !fy; } if (bank == 3) { sprite &= 0x7fff; } else { sprite &= 0x0fff; } while (multi >= 0) { deco16_draw_prio_sprite(pTransDraw, gfx, sprite - multi * inc, (colour << 4) + coloff, x, y + mult * multi, fx, fy, -1); #if 0 drawgfx_alpha(bitmap,cliprect,machine->gfx[bank], sprite - multi * inc, colour, fx,fy, x,y + mult * multi, 0,alpha); #endif multi--; } } } static void nitrobal_draw_sprites(UINT8 *ram, INT32 gfxbank, INT32 /*bpp*/) { // if (bpp != (nBurnBpp & 0x04)) return; UINT16 *spriteptr = (UINT16*)ram; INT32 offs = 0x3fc; INT32 end = -4; INT32 inc = -4; UINT8 *gfx; while (offs != end) { INT32 x, y, sprite, colour, fx, fy, w, h, sx, sy, x_mult, y_mult, tilemap_pri, sprite_pri, coloff; INT32 alpha = 0xff; sprite = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 3]); if (!sprite) { offs += inc; continue; } sx = BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 1]); h = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0xf000) >> 12; w = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0x0f00) >> 8; sy = BURN_ENDIAN_SWAP_INT16(spriteptr[offs]); if ((sy & 0x2000) && (nCurrentFrame & 1)) { offs += inc; continue; } colour = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) >> 0) & 0x1f; if (gfxbank == 3) { switch (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 2]) & 0xe0) { case 0xc0: tilemap_pri = 8; break; case 0x80: tilemap_pri = 32; break; case 0x20: tilemap_pri = 32; break; case 0x40: tilemap_pri = 8; break; case 0xa0: tilemap_pri = 32; break; case 0x00: tilemap_pri = 128; break; default: tilemap_pri = 128; break; } sprite_pri = 1; gfx = DrvGfxROM3; coloff = 0x400; } else { if (deco16_priority) tilemap_pri = 8; else tilemap_pri = 64; sprite_pri = 2; gfx = DrvGfxROM4; coloff = 0x600; if (colour & 0x10) { alpha = 0x80; colour &= 0x0f; } } fx = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 0]) & 0x4000); fy = (BURN_ENDIAN_SWAP_INT16(spriteptr[offs + 0]) & 0x8000); if (!*flipscreen) { if (fx) fx = 0; else fx = 1; if (fy) fy = 0; else fy = 1; sx = sx & 0x01ff; sy = sy & 0x01ff; if (sx > 0x180) sx = -(0x200 - sx); if (sy > 0x180) sy = -(0x200 - sy); if (fx) { x_mult = -16; sx += 16 * w; } else { x_mult = 16; sx -= 16; } if (fy) { y_mult = -16; sy += 16 * h; } else { y_mult = 16; sy -= 16; } } else { sx = sx & 0x01ff; sy = sy & 0x01ff; if (sx & 0x100) sx = -(0x100 - (sx & 0xff)); if (sy & 0x100) sy = -(0x100 - (sy & 0xff)); sx = 304 - sx; sy = 240 - sy; if (sx >= 432) sx -= 512; if (sy >= 384) sy -= 512; if (fx) { x_mult = -16; sx += 16; } else { x_mult = 16; sx -= 16 * w; } if (fy) { y_mult = -16; sy += 16; } else { y_mult = 16; sy -= 16 * h; } } if (gfxbank == 3) { sprite &= 0x7fff; } else { sprite &= 0x0fff; } for (x = 0; x < w; x++) { for (y = 0; y < h; y++) { //if (!bpp) { deco16_draw_prio_sprite(pTransDraw, gfx, sprite + y + h * x, (colour << 4) + coloff, sx + x_mult * (w-x), sy + y_mult * (h-y), fx, fy, tilemap_pri, sprite_pri); //} else { // deco16_draw_alphaprio_sprite(DrvPalette, gfx, sprite + y + h * x, (colour << 4) + coloff, sx + x_mult * (w-x), sy + y_mult * (h-y), fx, fy, tilemap_pri, sprite_pri, alpha); //} } } offs += inc; } } static void draw_combined_playfield_step1() { UINT8 *tptr = deco16_pf_rowscroll[3]; deco16_pf_rowscroll[3] = deco16_pf_rowscroll[2]; deco16_draw_layer(2, tempdraw[0], 0x10000); deco16_draw_layer(3, tempdraw[1], 0x10000); deco16_pf_rowscroll[3] = tptr; } static void draw_combined_playfield(INT32 color, INT32 priority) // opaque { UINT16 *src0 = tempdraw[0]; UINT16 *src1 = tempdraw[1]; UINT16 *dest = pTransDraw; UINT8 *prio = deco16_prio_map; for (INT32 y = 0; y < nScreenHeight; y++) { for (INT32 x = 0; x < nScreenWidth; x++) { dest[x] = color | (src0[x] & 0x0f) | ((src1[x] & 0x0f) << 4); prio[x] = priority; } src0 += nScreenWidth; src1 += nScreenWidth; dest += nScreenWidth; prio += 512; } } static void update_rohga(INT32 is_schmeisr) { // if (DrvRecalc) { deco16_palette_recalculate(DrvPalette, DrvPalRAM); DrvRecalc = 0; // } deco16_pf12_update(); deco16_pf34_update(); for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) { pTransDraw[i] = 0x300; } if ((deco16_priority & 0x03) == 0) { draw_combined_playfield_step1(); } deco16_clear_prio_map(); switch (deco16_priority & 3) { case 0: if (deco16_priority & 4) { draw_combined_playfield(0x300, DECO16_LAYER_PRIORITY(3)); } else { deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01)); deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x02)); } deco16_draw_layer(1, pTransDraw, DECO16_LAYER_PRIORITY(0x04)); break; case 1: deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01)); deco16_draw_layer(1, pTransDraw, DECO16_LAYER_PRIORITY(0x02)); deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x04)); break; case 2: deco16_draw_layer(1, pTransDraw, DECO16_LAYER_OPAQUE | DECO16_LAYER_PRIORITY(0x01)); deco16_draw_layer(3, pTransDraw, DECO16_LAYER_PRIORITY(0x02)); deco16_draw_layer(2, pTransDraw, DECO16_LAYER_PRIORITY(0x04)); break; } if (nSpriteEnable & 1) rohga_draw_sprites(DrvSprBuf2, is_schmeisr); deco16_draw_layer(0, pTransDraw, 0); BurnTransferCopy(DrvPalette); } static INT32 RohgaDraw() { update_rohga(0); return 0; } static INT32 SchmeisrDraw() { update_rohga(1); return 0; } static INT32 WizdfireDraw() { // if (DrvRecalc) { deco16_palette_recalculate(DrvPalette, DrvPalRAM); DrvRecalc = 0; // } deco16_pf12_update(); deco16_pf34_update(); for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) { pTransDraw[i] = 0x200; } if (nBurnLayer & 1) deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE); if (nSpriteEnable & 1) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 4, 3); if (nBurnLayer & 2) deco16_draw_layer(1, pTransDraw, 0); if (nSpriteEnable & 2) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 3, 3); if ((deco16_priority & 0x1f) == 0x1f) { if (nBurnLayer & 4) deco16_draw_layer(2, pTransDraw, 0); // tilemap draw alpha 0x80... } else { if (nBurnLayer & 4) deco16_draw_layer(2, pTransDraw, 0); } if (nSpriteEnable & 4) wizdfire_draw_sprites(DrvSprBuf, DrvGfxROM3, 0x400, 0, 3); if (nSpriteEnable & 8) wizdfire_draw_sprites(DrvSprBuf2, DrvGfxROM4, 0x600, 2, 4); if (nSpriteEnable & 16) wizdfire_draw_sprites(DrvSprBuf2, DrvGfxROM4, 0x600, 1, 4); if (nBurnLayer & 8) deco16_draw_layer(0, pTransDraw, 0); BurnTransferCopy(DrvPalette); return 0; } static INT32 NitrobalDraw() { // if (DrvRecalc) { deco16_palette_recalculate(DrvPalette, DrvPalRAM); DrvRecalc = 0; // } deco16_pf12_update(); deco16_pf34_update(); for (INT32 i = 0; i < nScreenWidth * nScreenHeight; i++) { pTransDraw[i] = 0x200; } draw_combined_playfield_step1(); deco16_clear_prio_map(); draw_combined_playfield(0x200, 0); if (nBurnLayer & 1)deco16_draw_layer(3, pTransDraw, DECO16_LAYER_OPAQUE); deco16_draw_layer(1, pTransDraw, 16); nitrobal_draw_sprites(DrvSprBuf , 3, 0); nitrobal_draw_sprites(DrvSprBuf2, 4, 0); deco16_draw_layer(0, pTransDraw, DECO16_LAYER_PRIORITY(0xff)); BurnTransferCopy(DrvPalette); // nitrobal_draw_sprites(DrvSprBuf , 3, 4); // nitrobal_draw_sprites(DrvSprBuf2, 4, 4); return 0; } static INT32 DrvFrame() { if (DrvReset) { DrvDoReset(); } { deco16_prot_inputs = DrvInputs; memset (DrvInputs, 0xff, 4 * sizeof(UINT16)); for (INT32 i = 0; i < 16; i++) { DrvInputs[0] ^= (DrvJoy1[i] & 1) << i; DrvInputs[1] ^= (DrvJoy2[i] & 1) << i; DrvInputs[3] ^= (DrvJoy3[i] & 1) << i; } DrvInputs[2] = (DrvDips[1] << 8) | (DrvDips[0] << 0); } INT32 nInterleave = 256; INT32 nSoundBufferPos = 0; INT32 nCyclesTotal[2] = { 14000000 / 58, 2685000 / 58 }; INT32 nCyclesDone[2] = { 0, 0 }; h6280NewFrame(); SekOpen(0); h6280Open(0); deco16_vblank = 0; for (INT32 i = 0; i < nInterleave; i++) { nCyclesDone[0] += SekRun(nCyclesTotal[0] / nInterleave); nCyclesDone[1] += h6280Run(nCyclesTotal[1] / nInterleave); if (i == 240) deco16_vblank = 0x08; if (pBurnSoundOut) { INT32 nSegmentLength = nBurnSoundLen / nInterleave; INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); deco16SoundUpdate(pSoundBuf, nSegmentLength); nSoundBufferPos += nSegmentLength; } } SekSetIRQLine(6, SEK_IRQSTATUS_ACK); if (pBurnSoundOut) { INT32 nSegmentLength = nBurnSoundLen - nSoundBufferPos; INT16* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1); if (nSegmentLength) { deco16SoundUpdate(pSoundBuf, nSegmentLength); } } h6280Close(); SekClose(); if (pBurnDraw) { BurnDrvRedraw(); } return 0; } static INT32 DrvScan(INT32 nAction, INT32 *pnMin) { struct BurnArea ba; if (pnMin != NULL) { *pnMin = 0x029722; } if (nAction & ACB_MEMORY_RAM) { memset(&ba, 0, sizeof(ba)); ba.Data = AllRam; ba.nLen = RamEnd-AllRam; ba.szName = "All Ram"; BurnAcb(&ba); } if (nAction & ACB_DRIVER_DATA) { SekScan(nAction); deco16SoundScan(nAction, pnMin); deco16Scan(); SCAN_VAR(DrvOkiBank); INT32 bank = DrvOkiBank; DrvOkiBank = -1; DrvYM2151WritePort(0, bank); } return 0; } // Rohga Armor Force (Asia/Europe v5.0) static struct BurnRomInfo rohgaRomDesc[] = { { "ht-00-1.2a", 0x040000, 0x1ed84a67, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "ht-03-1.2d", 0x040000, 0x84e7ebf6, 1 | BRF_PRG | BRF_ESS }, // 1 { "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2 { "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3 { "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code { "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters { "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6 { "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles { "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8 { "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles { "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10 { "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites { "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12 { "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13 { "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14 { "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15 { "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16 { "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0 { "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1 { "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs }; STD_ROM_PICK(rohga) STD_ROM_FN(rohga) struct BurnDriver BurnDrvRohga = { "rohga", NULL, NULL, NULL, "1991", "Rohga Armor Force (Asia/Europe v5.0)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0, NULL, rohgaRomInfo, rohgaRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo, RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Rohga Armor Force (Asia/Europe v3.0 Set 1) static struct BurnRomInfo rohga1RomDesc[] = { { "jd00.bin", 0x040000, 0xe046c77a, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "jd03.bin", 0x040000, 0x2c5120b8, 1 | BRF_PRG | BRF_ESS }, // 1 { "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2 { "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3 { "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code { "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters { "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6 { "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles { "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8 { "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles { "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10 { "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites { "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12 { "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13 { "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14 { "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15 { "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16 { "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0 { "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1 { "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs }; STD_ROM_PICK(rohga1) STD_ROM_FN(rohga1) struct BurnDriver BurnDrvRohga1 = { "rohga1", "rohga", NULL, NULL, "1991", "Rohga Armor Force (Asia/Europe v3.0 Set 1)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0, NULL, rohga1RomInfo, rohga1RomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo, RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Rohga Armor Force (Asia/Europe v3.0 Set 2) static struct BurnRomInfo rohga2RomDesc[] = { { "hts-00-3.2a", 0x040000, 0x154f02ec, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "hts-03-3.2d", 0x040000, 0x5e69d3d8, 1 | BRF_PRG | BRF_ESS }, // 1 { "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2 { "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3 { "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code { "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters { "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6 { "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles { "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8 { "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles { "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10 { "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites { "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12 { "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13 { "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14 { "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15 { "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16 { "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0 { "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1 { "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs }; STD_ROM_PICK(rohga2) STD_ROM_FN(rohga2) struct BurnDriver BurnDrvRohga2 = { "rohga2", "rohga", NULL, NULL, "1991", "Rohga Armor Force (Asia/Europe v3.0 Set 2)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0, NULL, rohga2RomInfo, rohga2RomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo, RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Rohga Armor Force (Hong Kong v3.0) static struct BurnRomInfo rohgahRomDesc[] = { { "jd00-2.2a", 0x040000, 0xec70646a, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "jd03-2.2d", 0x040000, 0x11d4c9a2, 1 | BRF_PRG | BRF_ESS }, // 1 { "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2 { "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3 { "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code { "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters { "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6 { "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles { "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8 { "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles { "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10 { "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites { "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12 { "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13 { "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14 { "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15 { "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16 { "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0 { "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1 { "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs }; STD_ROM_PICK(rohgah) STD_ROM_FN(rohgah) struct BurnDriver BurnDrvRohgah = { "rohgah", "rohga", NULL, NULL, "1991", "Rohga Armor Force (Hong Kong v3.0)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0, NULL, rohgahRomInfo, rohgahRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo, RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Rohga Armor Force (US v1.0) static struct BurnRomInfo rohgauRomDesc[] = { { "ha00.2a", 0x040000, 0xd8d13052, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "ha03.2d", 0x040000, 0x5f683bbf, 1 | BRF_PRG | BRF_ESS }, // 1 { "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2 { "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3 { "ha04.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code { "ha01.13a", 0x010000, 0xfb8f8519, 3 | BRF_GRA }, // 5 Characters { "ha02.14a", 0x010000, 0xaa47c17f, 3 | BRF_GRA }, // 6 { "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles { "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8 { "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles { "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10 { "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites { "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12 { "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13 { "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14 { "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15 { "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16 { "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0 { "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1 { "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs }; STD_ROM_PICK(rohgau) STD_ROM_FN(rohgau) struct BurnDriver BurnDrvRohgau = { "rohgau", "rohga", NULL, NULL, "1991", "Rohga Armor Force (US v1.0)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0, NULL, rohgauRomInfo, rohgauRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo, RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Wolf Fang -Kuhga 2001- (Japan) static struct BurnRomInfo wolffangRomDesc[] = { { "hw_00-1.2a", 0x040000, 0x69dc611e, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "hw_03-1.2d", 0x040000, 0xb66d9680, 1 | BRF_PRG | BRF_ESS }, // 1 { "mam00.8a", 0x080000, 0x0fa440a6, 1 | BRF_PRG | BRF_ESS }, // 2 { "mam07.8d", 0x080000, 0xf8bc7f20, 1 | BRF_PRG | BRF_ESS }, // 3 { "hw_04-.18p", 0x010000, 0xeb6608eb, 2 | BRF_PRG | BRF_ESS }, // 4 Huc6280 Code { "hw_01-.13a", 0x010000, 0xd9810ca4, 3 | BRF_GRA }, // 5 Characters { "hw_02-.14a", 0x010000, 0x2a27ac8e, 3 | BRF_GRA }, // 6 { "mam01.10a", 0x080000, 0xdbf4fbcc, 4 | BRF_GRA }, // 7 Foreground Tiles { "mam02.11a", 0x080000, 0xb1fac481, 4 | BRF_GRA }, // 8 { "mam08.17d", 0x100000, 0xca97a83f, 5 | BRF_GRA }, // 9 Background Tiles { "mam09.18d", 0x100000, 0x3f57d56f, 5 | BRF_GRA }, // 10 { "mam05.19a", 0x100000, 0x307a2cd1, 6 | BRF_GRA }, // 11 Sprites { "mam06.20a", 0x100000, 0xa1119a2d, 6 | BRF_GRA }, // 12 { "mam10.19d", 0x100000, 0x99f48f9f, 6 | BRF_GRA }, // 13 { "mam11.20d", 0x100000, 0xc3f12859, 6 | BRF_GRA }, // 14 { "mam03.17a", 0x100000, 0xfc4dfd48, 6 | BRF_GRA }, // 15 { "mam04.18a", 0x100000, 0x7d3b38bf, 6 | BRF_GRA }, // 16 { "mam13.15p", 0x080000, 0x525b9461, 8 | BRF_SND }, // 17 OKI M6295 Samples 0 { "mam12.14p", 0x080000, 0x6f00b791, 7 | BRF_SND }, // 18 OKI M6295 Samples 1 { "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 19 Unused PROMs }; STD_ROM_PICK(wolffang) STD_ROM_FN(wolffang) struct BurnDriver BurnDrvWolffang = { "wolffang", "rohga", NULL, NULL, "1991", "Wolf Fang -Kuhga 2001- (Japan)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT | GBF_PLATFORM, 0, NULL, wolffangRomInfo, wolffangRomName, NULL, NULL, RohgaInputInfo, RohgaDIPInfo, RohgaInit, DrvExit, DrvFrame, RohgaDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Wizard Fire (Over Sea v2.1) static struct BurnRomInfo wizdfireRomDesc[] = { { "je-01.3d", 0x020000, 0xb6d62367, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "je-00.3a", 0x020000, 0xf33de278, 1 | BRF_PRG | BRF_ESS }, // 1 { "je-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2 { "je-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3 { "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4 { "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5 { "je-06.20r", 0x010000, 0x79042546, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code { "je-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters { "je-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8 { "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles { "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10 { "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles { "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12 { "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A { "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14 { "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15 { "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16 { "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B { "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18 { "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0 { "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1 { "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs }; STD_ROM_PICK(wizdfire) STD_ROM_FN(wizdfire) struct BurnDriver BurnDrvWizdfire = { "wizdfire", NULL, NULL, NULL, "1992", "Wizard Fire (Over Sea v2.1)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0, NULL, wizdfireRomInfo, wizdfireRomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo, WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Wizard Fire (US v1.1) static struct BurnRomInfo wizdfireuRomDesc[] = { { "jf-01.3d", 0x020000, 0xbde42a41, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "jf-00.3a", 0x020000, 0xbca3c995, 1 | BRF_PRG | BRF_ESS }, // 1 { "jf-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2 { "jf-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3 { "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4 { "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5 { "jf-06.20r", 0x010000, 0x79042546, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code { "jf-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters { "jf-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8 { "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles { "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10 { "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles { "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12 { "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A { "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14 { "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15 { "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16 { "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B { "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18 { "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0 { "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1 { "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs }; STD_ROM_PICK(wizdfireu) STD_ROM_FN(wizdfireu) struct BurnDriver BurnDrvWizdfireu = { "wizdfireu", "wizdfire", NULL, NULL, "1992", "Wizard Fire (US v1.1)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0, NULL, wizdfireuRomInfo, wizdfireuRomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo, WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Dark Seal 2 (Japan v2.1) static struct BurnRomInfo darkseal2RomDesc[] = { { "jb-01-3.3d", 0x020000, 0x82308c01, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "jb-00-3.3a", 0x020000, 0x1d38113a, 1 | BRF_PRG | BRF_ESS }, // 1 { "jb-03.5d", 0x020000, 0x5217d404, 1 | BRF_PRG | BRF_ESS }, // 2 { "jb-02.5a", 0x020000, 0x36a1ce28, 1 | BRF_PRG | BRF_ESS }, // 3 { "mas13", 0x080000, 0x7e5256ce, 1 | BRF_PRG | BRF_ESS }, // 4 { "mas12", 0x080000, 0x005bd499, 1 | BRF_PRG | BRF_ESS }, // 5 { "jb-06.20r", 0x010000, 0x2066a1dd, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code { "jb-04.10d", 0x010000, 0x73cba800, 3 | BRF_GRA }, // 7 Characters { "jb-05.12d", 0x010000, 0x22e2c49d, 3 | BRF_GRA }, // 8 { "mas00", 0x100000, 0x3d011034, 4 | BRF_GRA }, // 9 Foreground Tiles { "mas01", 0x100000, 0x6d0c9d0b, 4 | BRF_GRA }, // 10 { "mas02", 0x080000, 0xaf00e620, 5 | BRF_GRA }, // 11 Background Tiles { "mas03", 0x080000, 0x2fe61ea2, 5 | BRF_GRA }, // 12 { "mas04", 0x100000, 0x1e56953b, 6 | BRF_GRA }, // 13 Sprite Bank A { "mas05", 0x100000, 0x3826b8f8, 6 | BRF_GRA }, // 14 { "mas06", 0x100000, 0x3b8bbd45, 6 | BRF_GRA }, // 15 { "mas07", 0x100000, 0x31303769, 6 | BRF_GRA }, // 16 { "mas08", 0x080000, 0xe224fb7a, 7 | BRF_GRA }, // 17 Sprite Bank B { "mas09", 0x080000, 0x5f6deb41, 7 | BRF_GRA }, // 18 { "mas10", 0x080000, 0x6edc06a7, 8 | BRF_SND }, // 19 OKI M6295 Samples 0 { "mas11", 0x080000, 0xc2f0a4f2, 9 | BRF_SND }, // 20 OKI M6295 Samples 1 { "mb7122h.16l", 0x000400, 0x2bee57cc, 0 | BRF_OPT }, // 21 Unused PROMs }; STD_ROM_PICK(darkseal2) STD_ROM_FN(darkseal2) struct BurnDriver BurnDrvDarkseal2 = { "darkseal2", "wizdfire", NULL, NULL, "1992", "Dark Seal 2 (Japan v2.1)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_DATAEAST, GBF_SCRFIGHT, 0, NULL, darkseal2RomInfo, darkseal2RomName, NULL, NULL, WizdfireInputInfo, WizdfireDIPInfo, WizdfireInit, DrvExit, DrvFrame, WizdfireDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Schmeiser Robo (Japan) static struct BurnRomInfo schmeisrRomDesc[] = { { "sr001j.8a", 0x080000, 0xed31f3ff, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "sr006j.8d", 0x080000, 0x9e9cfa5d, 1 | BRF_PRG | BRF_ESS }, // 1 { "sr013.18p", 0x010000, 0x4ac00cbb, 2 | BRF_PRG | BRF_ESS }, // 2 Huc6280 Code { "sr002-74.9a", 0x080000, 0x97e15c7b, 3 | BRF_GRA }, // 3 Foreground Tiles { "sr003-74.11a", 0x080000, 0xea367971, 3 | BRF_GRA }, // 4 { "sr007.17d", 0x100000, 0x886f80c7, 4 | BRF_GRA }, // 5 Background Tiles { "sr008.18d", 0x100000, 0xa74cbc90, 4 | BRF_GRA }, // 6 { "sr004.19a", 0x100000, 0xe25434a1, 5 | BRF_GRA }, // 7 Sprites { "sr005.20a", 0x100000, 0x1630033b, 5 | BRF_GRA }, // 8 { "sr009.19d", 0x100000, 0x7b9d982f, 5 | BRF_GRA }, // 9 { "sr010.20d", 0x100000, 0x6e9e5352, 5 | BRF_GRA }, // 10 { "sr012.15p", 0x080000, 0x38843d4d, 7 | BRF_SND }, // 12 OKI M6295 Samples 0 { "sr011.14p", 0x080000, 0x81805616, 6 | BRF_SND }, // 11 OKI M6295 Samples 1 { "hb-00.11p", 0x000200, 0xb7a7baad, 0 | BRF_OPT }, // 13 Unused PROMs }; STD_ROM_PICK(schmeisr) STD_ROM_FN(schmeisr) struct BurnDriver BurnDrvSchmeisr = { "schmeisr", NULL, NULL, NULL, "1993", "Schmeiser Robo (Japan)\0",NULL, "Hot B", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_PREFIX_DATAEAST, GBF_VSFIGHT, 0, NULL, schmeisrRomInfo, schmeisrRomName, NULL, NULL, RohgaInputInfo, SchmeisrDIPInfo, SchmeisrInit, DrvExit, DrvFrame, SchmeisrDraw, DrvScan, &DrvRecalc, 0x800, 320, 240, 4, 3 }; // Nitro Ball (US) static struct BurnRomInfo nitrobalRomDesc[] = { { "jl01-4.d3", 0x020000, 0x0414e409, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "jl00-4.b3", 0x020000, 0xdd9e2bcc, 1 | BRF_PRG | BRF_ESS }, // 1 { "jl03-4.d5", 0x020000, 0xea264ac5, 1 | BRF_PRG | BRF_ESS }, // 2 { "jl02-4.b5", 0x020000, 0x74047997, 1 | BRF_PRG | BRF_ESS }, // 3 { "jl05-2.d6", 0x040000, 0xb820fa20, 1 | BRF_PRG | BRF_ESS }, // 4 { "jl04-2.b6", 0x040000, 0x1fd8995b, 1 | BRF_PRG | BRF_ESS }, // 5 { "jl08.r20", 0x010000, 0x93d93fe1, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code { "jl06.d10", 0x010000, 0x91cf668e, 3 | BRF_GRA }, // 7 Characters { "jl07.d12", 0x010000, 0xe61d0e42, 3 | BRF_GRA }, // 8 { "mav00.b10", 0x080000, 0x34785d97, 4 | BRF_GRA }, // 9 Foreground Tiles { "mav01.b12", 0x080000, 0x8b531b16, 4 | BRF_GRA }, // 10 { "mav02.b16", 0x100000, 0x20723bf7, 5 | BRF_GRA }, // 11 Background Tiles { "mav03.e16", 0x100000, 0xef6195f0, 5 | BRF_GRA }, // 12 { "mav05.e19", 0x100000, 0xd92d769c, 6 | BRF_GRA }, // 13 Sprite Bank A { "mav04.b19", 0x100000, 0x8ba48385, 6 | BRF_GRA }, // 14 { "mav07.e20", 0x080000, 0x5fc10ccd, 6 | BRF_GRA }, // 15 { "mav06.b20", 0x080000, 0xae6201a5, 6 | BRF_GRA }, // 16 { "mav09.e23", 0x040000, 0x1ce7b51a, 7 | BRF_GRA }, // 17 Sprite Bank B { "mav08.b23", 0x040000, 0x64966576, 7 | BRF_GRA }, // 18 { "mav10.r17", 0x080000, 0x8ad734b0, 8 | BRF_SND }, // 19 OKI M6295 Samples 0 { "mav11.r19", 0x080000, 0xef513908, 9 | BRF_SND }, // 20 OKI M6295 Samples 1 { "jn-00.17l", 0x000400, 0x6ac77b84, 0 | BRF_OPT }, // 21 Unused PROMs }; STD_ROM_PICK(nitrobal) STD_ROM_FN(nitrobal) struct BurnDriver BurnDrvNitrobal = { "nitrobal", NULL, NULL, NULL, "1992", "Nitro Ball (US)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 3, HARDWARE_PREFIX_DATAEAST, GBF_SHOOT, 0, NULL, nitrobalRomInfo, nitrobalRomName, NULL, NULL, NitrobalInputInfo, NitrobalDIPInfo, NitrobalInit, DrvExit, DrvFrame, NitrobalDraw, DrvScan, &DrvRecalc, 0x800, 240, 320, 3, 4 }; // Gun Ball (Japan) static struct BurnRomInfo gunballRomDesc[] = { { "jc01.3d", 0x020000, 0x61bfa998, 1 | BRF_PRG | BRF_ESS }, // 0 68k Code { "jc00.3b", 0x020000, 0x73ba8f74, 1 | BRF_PRG | BRF_ESS }, // 1 { "jc03.5d", 0x020000, 0x19231612, 1 | BRF_PRG | BRF_ESS }, // 2 { "jc02.5b", 0x020000, 0xa254f34c, 1 | BRF_PRG | BRF_ESS }, // 3 { "jc05-3.6d", 0x040000, 0xf750a709, 1 | BRF_PRG | BRF_ESS }, // 4 { "jc04-3.6b", 0x040000, 0xad711767, 1 | BRF_PRG | BRF_ESS }, // 5 { "jl08.r20", 0x010000, 0x93d93fe1, 2 | BRF_PRG | BRF_ESS }, // 6 Huc6280 Code { "jl06.d10", 0x010000, 0x91cf668e, 3 | BRF_GRA }, // 7 Characters { "jl07.d12", 0x010000, 0xe61d0e42, 3 | BRF_GRA }, // 8 { "mav00.b10", 0x080000, 0x34785d97, 4 | BRF_GRA }, // 9 Foreground Tiles { "mav01.b12", 0x080000, 0x8b531b16, 4 | BRF_GRA }, // 10 { "mav02.b16", 0x100000, 0x20723bf7, 5 | BRF_GRA }, // 11 Background Tiles { "mav03.e16", 0x100000, 0xef6195f0, 5 | BRF_GRA }, // 12 { "mav05.e19", 0x100000, 0xd92d769c, 6 | BRF_GRA }, // 13 Sprite Bank A { "mav04.b19", 0x100000, 0x8ba48385, 6 | BRF_GRA }, // 14 { "mav07.e20", 0x080000, 0x5fc10ccd, 6 | BRF_GRA }, // 15 { "mav06.b20", 0x080000, 0xae6201a5, 6 | BRF_GRA }, // 16 { "mav09.e23", 0x040000, 0x1ce7b51a, 7 | BRF_GRA }, // 17 Sprite Bank B { "mav08.b23", 0x040000, 0x64966576, 7 | BRF_GRA }, // 18 { "mav10.r17", 0x080000, 0x8ad734b0, 8 | BRF_SND }, // 19 OKI M6295 Samples 0 { "mav11.r19", 0x080000, 0xef513908, 9 | BRF_SND }, // 20 OKI M6295 Samples 1 { "jn-00.17l", 0x000400, 0x6ac77b84, 0 | BRF_OPT }, // 21 Unused PROMs }; STD_ROM_PICK(gunball) STD_ROM_FN(gunball) struct BurnDriver BurnDrvGunball = { "gunball", "nitrobal", NULL, NULL, "1992", "Gun Ball (Japan)\0", NULL, "Data East Corporation", "DECO IC16", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL, 3, HARDWARE_PREFIX_DATAEAST, GBF_SHOOT, 0, NULL, gunballRomInfo, gunballRomName, NULL, NULL, NitrobalInputInfo, NitrobalDIPInfo, NitrobalInit, DrvExit, DrvFrame, NitrobalDraw, DrvScan, &DrvRecalc, 0x800, 240, 320, 3, 4 };
73,441
46,469
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/connect/model/VocabularyLanguageCode.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace Connect { namespace Model { namespace VocabularyLanguageCodeMapper { static const int ar_AE_HASH = HashingUtils::HashString("ar-AE"); static const int de_CH_HASH = HashingUtils::HashString("de-CH"); static const int de_DE_HASH = HashingUtils::HashString("de-DE"); static const int en_AB_HASH = HashingUtils::HashString("en-AB"); static const int en_AU_HASH = HashingUtils::HashString("en-AU"); static const int en_GB_HASH = HashingUtils::HashString("en-GB"); static const int en_IE_HASH = HashingUtils::HashString("en-IE"); static const int en_IN_HASH = HashingUtils::HashString("en-IN"); static const int en_US_HASH = HashingUtils::HashString("en-US"); static const int en_WL_HASH = HashingUtils::HashString("en-WL"); static const int es_ES_HASH = HashingUtils::HashString("es-ES"); static const int es_US_HASH = HashingUtils::HashString("es-US"); static const int fr_CA_HASH = HashingUtils::HashString("fr-CA"); static const int fr_FR_HASH = HashingUtils::HashString("fr-FR"); static const int hi_IN_HASH = HashingUtils::HashString("hi-IN"); static const int it_IT_HASH = HashingUtils::HashString("it-IT"); static const int ja_JP_HASH = HashingUtils::HashString("ja-JP"); static const int ko_KR_HASH = HashingUtils::HashString("ko-KR"); static const int pt_BR_HASH = HashingUtils::HashString("pt-BR"); static const int pt_PT_HASH = HashingUtils::HashString("pt-PT"); static const int zh_CN_HASH = HashingUtils::HashString("zh-CN"); VocabularyLanguageCode GetVocabularyLanguageCodeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == ar_AE_HASH) { return VocabularyLanguageCode::ar_AE; } else if (hashCode == de_CH_HASH) { return VocabularyLanguageCode::de_CH; } else if (hashCode == de_DE_HASH) { return VocabularyLanguageCode::de_DE; } else if (hashCode == en_AB_HASH) { return VocabularyLanguageCode::en_AB; } else if (hashCode == en_AU_HASH) { return VocabularyLanguageCode::en_AU; } else if (hashCode == en_GB_HASH) { return VocabularyLanguageCode::en_GB; } else if (hashCode == en_IE_HASH) { return VocabularyLanguageCode::en_IE; } else if (hashCode == en_IN_HASH) { return VocabularyLanguageCode::en_IN; } else if (hashCode == en_US_HASH) { return VocabularyLanguageCode::en_US; } else if (hashCode == en_WL_HASH) { return VocabularyLanguageCode::en_WL; } else if (hashCode == es_ES_HASH) { return VocabularyLanguageCode::es_ES; } else if (hashCode == es_US_HASH) { return VocabularyLanguageCode::es_US; } else if (hashCode == fr_CA_HASH) { return VocabularyLanguageCode::fr_CA; } else if (hashCode == fr_FR_HASH) { return VocabularyLanguageCode::fr_FR; } else if (hashCode == hi_IN_HASH) { return VocabularyLanguageCode::hi_IN; } else if (hashCode == it_IT_HASH) { return VocabularyLanguageCode::it_IT; } else if (hashCode == ja_JP_HASH) { return VocabularyLanguageCode::ja_JP; } else if (hashCode == ko_KR_HASH) { return VocabularyLanguageCode::ko_KR; } else if (hashCode == pt_BR_HASH) { return VocabularyLanguageCode::pt_BR; } else if (hashCode == pt_PT_HASH) { return VocabularyLanguageCode::pt_PT; } else if (hashCode == zh_CN_HASH) { return VocabularyLanguageCode::zh_CN; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<VocabularyLanguageCode>(hashCode); } return VocabularyLanguageCode::NOT_SET; } Aws::String GetNameForVocabularyLanguageCode(VocabularyLanguageCode enumValue) { switch(enumValue) { case VocabularyLanguageCode::ar_AE: return "ar-AE"; case VocabularyLanguageCode::de_CH: return "de-CH"; case VocabularyLanguageCode::de_DE: return "de-DE"; case VocabularyLanguageCode::en_AB: return "en-AB"; case VocabularyLanguageCode::en_AU: return "en-AU"; case VocabularyLanguageCode::en_GB: return "en-GB"; case VocabularyLanguageCode::en_IE: return "en-IE"; case VocabularyLanguageCode::en_IN: return "en-IN"; case VocabularyLanguageCode::en_US: return "en-US"; case VocabularyLanguageCode::en_WL: return "en-WL"; case VocabularyLanguageCode::es_ES: return "es-ES"; case VocabularyLanguageCode::es_US: return "es-US"; case VocabularyLanguageCode::fr_CA: return "fr-CA"; case VocabularyLanguageCode::fr_FR: return "fr-FR"; case VocabularyLanguageCode::hi_IN: return "hi-IN"; case VocabularyLanguageCode::it_IT: return "it-IT"; case VocabularyLanguageCode::ja_JP: return "ja-JP"; case VocabularyLanguageCode::ko_KR: return "ko-KR"; case VocabularyLanguageCode::pt_BR: return "pt-BR"; case VocabularyLanguageCode::pt_PT: return "pt-PT"; case VocabularyLanguageCode::zh_CN: return "zh-CN"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace VocabularyLanguageCodeMapper } // namespace Model } // namespace Connect } // namespace Aws
7,057
2,174
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation 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 "FTGlyphContainer.h" #include "FTGlyph.h" #include "FTFace.h" #include "FTCharmap.h" FTGlyphContainer::FTGlyphContainer( FTFace* f) : face(f), err(0) { glyphs.push_back( NULL); charMap = new FTCharmap( face); } FTGlyphContainer::~FTGlyphContainer() { GlyphVector::iterator glyphIterator; for( glyphIterator = glyphs.begin(); glyphIterator != glyphs.end(); ++glyphIterator) { delete *glyphIterator; } glyphs.clear(); delete charMap; } bool FTGlyphContainer::CharMap( FT_Encoding encoding) { bool result = charMap->CharMap( encoding); err = charMap->Error(); return result; } unsigned int FTGlyphContainer::FontIndex( const unsigned int characterCode) const { return charMap->FontIndex( characterCode); } void FTGlyphContainer::Add( FTGlyph* tempGlyph, const unsigned int characterCode) { charMap->InsertIndex( characterCode, glyphs.size()); glyphs.push_back( tempGlyph); } const FTGlyph* const FTGlyphContainer::Glyph( const unsigned int characterCode) const { signed int index = charMap->GlyphListIndex( characterCode); return glyphs[index]; } FTBBox FTGlyphContainer::BBox( const unsigned int characterCode) const { return glyphs[charMap->GlyphListIndex( characterCode)]->BBox(); } float FTGlyphContainer::Advance( const unsigned int characterCode, const unsigned int nextCharacterCode) { unsigned int left = charMap->FontIndex( characterCode); unsigned int right = charMap->FontIndex( nextCharacterCode); float width = face->KernAdvance( left, right).X(); width += glyphs[charMap->GlyphListIndex( characterCode)]->Advance().X(); return width; } FTPoint FTGlyphContainer::Render( const unsigned int characterCode, const unsigned int nextCharacterCode, FTPoint penPosition) { FTPoint kernAdvance, advance; unsigned int left = charMap->FontIndex( characterCode); unsigned int right = charMap->FontIndex( nextCharacterCode); kernAdvance = face->KernAdvance( left, right); if( !face->Error()) { advance = glyphs[charMap->GlyphListIndex( characterCode)]->Render( penPosition); } kernAdvance += advance; return kernAdvance; }
2,868
910
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #pragma once #include <cpu_resource.hpp> #include <device_map.hpp> #include <gpu_resource.hpp> #include <rmm/mr/device/device_memory_resource.hpp> #include <collectives/ib_comm.hpp> #include <collectives/all_reduce_comm.hpp> namespace HugeCTR { /** * @brief GPU resources container. * * A GPU resource container in one node. An instant includes: * GPU resource vector, thread pool for training, nccl communicators. */ class ResourceManager { int num_process_; int process_id_; DeviceMap device_map_; DeviceMap::Layout device_layout_; std::shared_ptr<CPUResource> cpu_resource_; std::vector<std::shared_ptr<GPUResource>> gpu_resources_; /**< GPU resource vector */ std::vector<std::vector<bool>> p2p_matrix_; std::vector<std::shared_ptr<rmm::mr::device_memory_resource>> base_cuda_mr_; std::vector<std::shared_ptr<rmm::mr::device_memory_resource>> memory_resource_; #ifdef ENABLE_MPI std::unique_ptr<IbComm> ib_comm_ = NULL; #endif std::shared_ptr<AllReduceInPlaceComm> ar_comm_ = NULL; void enable_all_peer_accesses(); public: ResourceManager(int num_process, int process_id, DeviceMap&& device_map, unsigned long long seed); static std::shared_ptr<ResourceManager> create( const std::vector<std::vector<int>>& visible_devices, unsigned long long seed, DeviceMap::Layout dist = DeviceMap::LOCAL_FIRST); ResourceManager(const ResourceManager&) = delete; ResourceManager& operator=(const ResourceManager&) = delete; int get_num_process() const { return num_process_; } int get_process_id() const { return process_id_; } int get_master_process_id() const { return 0; } bool is_master_process() const { return process_id_ == 0; } #ifdef ENABLE_MPI IbComm* get_ib_comm() const { return ib_comm_.get(); } void set_ready_to_transfer() { if (ib_comm_) ib_comm_->set_ready_to_transfer(); } #endif void set_ar_comm(AllReduceAlgo algo, bool use_mixed_precision); AllReduceInPlaceComm* get_ar_comm() const { return ar_comm_.get(); } DeviceMap::Layout get_device_layout() const { return device_map_.get_device_layout(); } const std::shared_ptr<CPUResource>& get_local_cpu() const { return cpu_resource_; } const std::shared_ptr<GPUResource>& get_local_gpu(size_t local_gpu_id) const { return gpu_resources_[local_gpu_id]; } const std::vector<int>& get_local_gpu_device_id_list() const { return device_map_.get_device_list(); } size_t get_local_gpu_count() const { return device_map_.get_device_list().size(); } size_t get_global_gpu_count() const { return device_map_.size(); } int get_process_id_from_gpu_global_id(size_t global_gpu_id) const { return device_map_.get_pid(global_gpu_id); } size_t get_gpu_local_id_from_global_id(size_t global_gpu_id) const { // sequential GPU indices return device_map_.get_local_id(global_gpu_id); } size_t get_gpu_global_id_from_local_id(size_t local_gpu_id) const { // sequential GPU indices return device_map_.get_global_id(local_gpu_id); } bool p2p_enabled(int src_dev, int dst_dev) const; bool all_p2p_enabled() const; const std::shared_ptr<rmm::mr::device_memory_resource>& get_device_rmm_device_memory_resource( int local_gpu_id) const { auto dev_list = device_map_.get_device_list(); auto it = std::find(dev_list.begin(), dev_list.end(), local_gpu_id); auto index = std::distance(dev_list.begin(), it); return memory_resource_[index]; } }; } // namespace HugeCTR
4,065
1,405
/**************************************************************************** // Usagi Engine, Copyright © Vitei, Inc. 2013 ****************************************************************************/ #include "Engine/Common/Common.h" #include "Engine/PostFX/PostFXSys.h" #include "Engine/Graphics/Device/GFXDevice.h" #include "Engine/Resource/ResourceMgr.h" #include "Engine/Graphics/StandardVertDecl.h" #include "Engine/Scene/SceneConstantSets.h" #include "Engine/Graphics/Device/GFXContext.h" #include "Engine/Layout/Global2D.h" #include "BlitImage.h" namespace usg { static const DescriptorDeclaration g_descriptorDecl[] = { DESCRIPTOR_ELEMENT(0, DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, SHADER_FLAG_PIXEL), DESCRIPTOR_END() }; BlitImage::BlitImage() { } BlitImage::~BlitImage() { } void BlitImage::Init(GFXDevice* pDevice, ResourceMgr* pResource, const RenderPassHndl& pass) { PipelineStateDecl pipelineDecl; pipelineDecl.inputBindings[0].Init(usg::GetVertexDeclaration(usg::VT_POSITION)); pipelineDecl.uInputBindingCount = 1; pipelineDecl.ePrimType = PT_TRIANGLES; pipelineDecl.pEffect = pResource->GetEffect(pDevice, "PostProcess.Copy"); pipelineDecl.alphaState.SetColor0Only(); usg::DescriptorSetLayoutHndl matDescriptors = pDevice->GetDescriptorSetLayout(g_descriptorDecl); SamplerDecl pointDecl(SF_LINEAR, SC_CLAMP); m_sampler = pDevice->GetSampler(pointDecl); pipelineDecl.layout.descriptorSets[0] = pDevice->GetDescriptorSetLayout(g_sGlobalDescriptors2D ); pipelineDecl.layout.descriptorSets[1] = matDescriptors; pipelineDecl.layout.uDescriptorSetCount = 2; pipelineDecl.rasterizerState.eCullFace = CULL_FACE_NONE; m_material.Init(pDevice, pDevice->GetPipelineState(pass, pipelineDecl), matDescriptors); // Shared vertex data PositionVertex verts[4] = { { -1.f, 1.f, 0.5f }, // 0 - TL { 1.f, 1.f, 0.5f }, // 1 - TR { -1.f, -1.f, 0.5f }, // 2 - BL { 1.f, -1.f, 0.5f }, // 3 - BR }; uint16 iIndices[6] = { 2, 1, 0, 2, 3, 1, }; m_fullScreenVB.Init(pDevice, verts, sizeof(PositionVertex), 4, "FullScreenVB"); m_fullScreenIB.Init(pDevice, iIndices, 6, PT_TRIANGLES); } void BlitImage::CleanUp(GFXDevice* pDevice) { m_fullScreenIB.CleanUp(pDevice); m_fullScreenVB.CleanUp(pDevice); m_material.Cleanup(pDevice); } void BlitImage::ChangeRenderPass(GFXDevice* pDevice, const RenderPassHndl& pass) { PipelineStateDecl decl; RenderPassHndl hndlTmp; pDevice->GetPipelineDeclaration(m_material.GetPipelineStateHndl(), decl, hndlTmp); m_material.SetPipelineState(pDevice->GetPipelineState(pass, decl)); } void BlitImage::SetSourceTexture(GFXDevice* pDevice, const TextureHndl& tex) { m_material.SetTexture(0, tex, m_sampler); m_material.UpdateDescriptors(pDevice); } bool BlitImage::Draw(GFXContext* pContext) { pContext->BeginGPUTag("BlitImage", Color::Green); m_material.Apply(pContext); pContext->SetVertexBuffer(&m_fullScreenVB); pContext->DrawIndexed(&m_fullScreenIB); pContext->EndGPUTag(); return true; } }
3,008
1,208
//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // 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. //***************************************************************************** #pragma once #include "ngraph/op/constant.hpp" #include "ngraph/op/parameter_vector.hpp" #include "ngraph/shape.hpp" #include "ngraph/type/element_type.hpp" #include <onnx/onnx.pb.h> #include "node.hpp" #include "tensor.hpp" namespace ngraph { namespace onnx_import { namespace error { namespace value_info { struct unspecified_element_type : ngraph_error { unspecified_element_type() : ngraph_error{"value info has no element type specified"} { } }; struct unsupported_element_type : ngraph_error { explicit unsupported_element_type(onnx::TensorProto_DataType type) : ngraph_error{"unsupported value info element type: " + onnx::TensorProto_DataType_Name(type)} { } }; } } class ValueInfo { public: ValueInfo(ValueInfo&&) = default; ValueInfo(const ValueInfo&) = default; ValueInfo() = delete; explicit ValueInfo(const onnx::ValueInfoProto& value_info_proto) : m_value_info_proto{&value_info_proto} { if (value_info_proto.type().has_tensor_type()) { for (const auto& dim : value_info_proto.type().tensor_type().shape().dim()) { m_shape.emplace_back(static_cast<Shape::value_type>(dim.dim_value())); } } } ValueInfo& operator=(const ValueInfo&) = delete; ValueInfo& operator=(ValueInfo&&) = delete; const std::string& get_name() const { return m_value_info_proto->name(); } const Shape& get_shape() const { return m_shape; } const element::Type& get_element_type() const { if (!m_value_info_proto->type().tensor_type().has_elem_type()) { throw error::value_info::unspecified_element_type{}; } switch (m_value_info_proto->type().tensor_type().elem_type()) { case onnx::TensorProto_DataType::TensorProto_DataType_BOOL: return element::boolean; case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT: case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT16: return element::f32; case onnx::TensorProto_DataType::TensorProto_DataType_DOUBLE: return element::f64; case onnx::TensorProto_DataType::TensorProto_DataType_INT8: return element::i8; case onnx::TensorProto_DataType::TensorProto_DataType_INT16: return element::i16; case onnx::TensorProto_DataType::TensorProto_DataType_INT32: return element::i32; case onnx::TensorProto_DataType::TensorProto_DataType_INT64: return element::i64; case onnx::TensorProto_DataType::TensorProto_DataType_UINT8: return element::u8; case onnx::TensorProto_DataType::TensorProto_DataType_UINT16: return element::u16; case onnx::TensorProto_DataType::TensorProto_DataType_UINT32: return element::u32; case onnx::TensorProto_DataType::TensorProto_DataType_UINT64: return element::u64; default: throw error::value_info::unsupported_element_type{ m_value_info_proto->type().tensor_type().elem_type()}; } } std::shared_ptr<ngraph::Node> get_ng_node(op::ParameterVector& parameters, const std::map<std::string, Tensor>& initializers) const { const auto it = initializers.find(get_name()); if (it != std::end(initializers)) { return get_ng_constant(it->second); } else { parameters.push_back(get_ng_parameter()); return parameters.back(); } } protected: std::shared_ptr<op::Parameter> get_ng_parameter() const { return std::make_shared<op::Parameter>(get_element_type(), get_shape()); } std::shared_ptr<op::Constant> get_ng_constant(const Tensor& tensor) const { switch (m_value_info_proto->type().tensor_type().elem_type()) { case onnx::TensorProto_DataType::TensorProto_DataType_BOOL: return make_ng_constant<bool>(element::boolean, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT: case onnx::TensorProto_DataType::TensorProto_DataType_FLOAT16: return make_ng_constant<float>(element::f32, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_DOUBLE: return make_ng_constant<double>(element::f64, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_INT8: return make_ng_constant<int8_t>(element::i8, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_INT16: return make_ng_constant<int16_t>(element::i16, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_INT32: return make_ng_constant<int32_t>(element::i32, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_INT64: return make_ng_constant<int64_t>(element::i64, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_UINT8: return make_ng_constant<uint8_t>(element::u8, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_UINT16: return make_ng_constant<uint16_t>(element::u16, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_UINT32: return make_ng_constant<uint32_t>(element::u32, tensor); case onnx::TensorProto_DataType::TensorProto_DataType_UINT64: return make_ng_constant<uint64_t>(element::u64, tensor); default: throw error::value_info::unsupported_element_type{ m_value_info_proto->type().tensor_type().elem_type()}; } } template <typename T> std::shared_ptr<op::Constant> make_ng_constant(const element::Type& type, const Tensor& tensor) const { return std::make_shared<op::Constant>(type, m_shape, tensor.get_data<T>()); } private: const onnx::ValueInfoProto* m_value_info_proto; Shape m_shape; }; inline std::ostream& operator<<(std::ostream& outs, const ValueInfo& info) { return (outs << "<ValueInfo: " << info.get_name() << ">"); } } // namespace onnx_import } // namespace ngraph
8,112
2,281
// // Warning: don't edit - generated by generate_ecu_code.pl processing ../dev/lim_i1.json: LIM 14: Charging interface module // This generated code makes it easier to process CANBUS messages from the LIM ecu in a BMW i3 // case I3_PID_LIM_STATUS_CALCVN: { // 0x2541 if (datalen < 20) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_STATUS_CALCVN", 20); break; } unsigned long STAT_CVN_WERT = (RXBUF_UINT32(16)); // Read out CVN (here the CVN must be output as in mode $ 09 (PID $ 06)) / CVN auslesen (hier muss die CVN wie // bei Mode $09 (PID $06) ausgegeben werden) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%lu%s\n", "LIM", "STATUS_CALCVN", "STAT_CVN_WERT", STAT_CVN_WERT, "\"HEX\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_LADESTECKDOSE_TEMPERATUR: { // 0xDB0F if (datalen < 2) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADESTECKDOSE_TEMPERATUR", 2); break; } float STAT_LADESTECKDOSE_TEMP_WERT = (RXBUF_UINT(0)/10.0f-40.0); // Temperature of the DC charging connection in ° C (China) / Temperatur der DC-Ladeanschluss in °C (China) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "LIM", "LADESTECKDOSE_TEMPERATUR", "STAT_LADESTECKDOSE_TEMP_WERT", STAT_LADESTECKDOSE_TEMP_WERT, "\"°C\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_LADEBEREITSCHAFT_LIM: { // 0xDEF2 if (datalen < 1) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADEBEREITSCHAFT_LIM", 1); break; } unsigned char STAT_LADEBEREITSCHAFT_LIM = (RXBUF_UCHAR(0)); // Ready to charge (HW line), (1 = yes, 0 = no) sent from LIM to SLE / Ladebereitschaft (HW-Leitung), (1 = ja, 0 // = nein) vom LIM an SLE gesendet ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADEBEREITSCHAFT_LIM", "STAT_LADEBEREITSCHAFT_LIM", STAT_LADEBEREITSCHAFT_LIM, "\"0/1\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_PROXIMITY: { // 0xDEF5 if (datalen < 2) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_PROXIMITY", 2); break; } unsigned char STAT_STECKER_NR = (RXBUF_UCHAR(0)); // Condition of the plug / Zustand des Steckers ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PROXIMITY", "STAT_STECKER_NR", STAT_STECKER_NR, "\"0-n\""); unsigned char STAT_STROMTRAGFAEHIGKEIT_WERT = (RXBUF_UCHAR(1)); // Current carrying capacity of the connected cable / Stromtragfähigkeit des angeschlossenen Kabels ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PROXIMITY", "STAT_STROMTRAGFAEHIGKEIT_WERT", STAT_STROMTRAGFAEHIGKEIT_WERT, "\"A\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_PILOTSIGNAL: { // 0xDEF6 if (datalen < 7) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_PILOTSIGNAL", 7); break; } unsigned char STAT_PILOT_AKTIV = (RXBUF_UCHAR(0)); // State of the pilot signal (0 = not active, 1 = active) / Zustand des Pilotsignals (0 = nicht aktiv, 1 = aktiv) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_AKTIV", STAT_PILOT_AKTIV, "\"0/1\""); unsigned char STAT_PILOT_PWM_DUTYCYCLE_WERT = (RXBUF_UCHAR(1)); // Pulse duty factor PWM pilot signal / Tastverhältnis PWM Pilotsignal ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_PWM_DUTYCYCLE_WERT", STAT_PILOT_PWM_DUTYCYCLE_WERT, "\"%\""); unsigned char STAT_PILOT_CURRENT_WERT = (RXBUF_UCHAR(2)); // Current value calculated from the pilot signal / Errechneter Stromwert aus Pilotsignal ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_CURRENT_WERT", STAT_PILOT_CURRENT_WERT, "\"A\""); unsigned char STAT_PILOT_LADEBEREIT = (RXBUF_UCHAR(3)); // Vehicle ready to charge state (0 = not ready to charge, 1 = ready to charge) / Zustand Ladebereitschaft // Fahrzeug (0 = nicht ladebereit, 1 = ladebereit) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_LADEBEREIT", STAT_PILOT_LADEBEREIT, "\"0/1\""); unsigned short STAT_PILOT_FREQUENZ_WERT = (RXBUF_UINT(4)); // Frequency of the pilot signal / Frequenz des Pilotsignals ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_FREQUENZ_WERT", STAT_PILOT_FREQUENZ_WERT, "\"Hz\""); float STAT_PILOT_PEGEL_WERT = (RXBUF_UCHAR(6)/10.0f); // Pilot signal level / Pegel des Pilotsignals ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%.4f%s\n", "LIM", "PILOTSIGNAL", "STAT_PILOT_PEGEL_WERT", STAT_PILOT_PEGEL_WERT, "\"V\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_LADESCHNITTSTELLE_DC_TEPCO: { // 0xDEF7 if (datalen < 4) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_LADESCHNITTSTELLE_DC_TEPCO", 4); break; } unsigned char STAT_CHARGE_CONTROL_1 = (RXBUF_UCHAR(0)); // Charge control status 1 line (0 = not active, 1 = active) / Zustand Charge control 1 Leitung (0 = nicht aktiv, // 1 = aktiv) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_CONTROL_1", STAT_CHARGE_CONTROL_1, "\"0/1\""); unsigned char STAT_CHARGE_CONTROL_2 = (RXBUF_UCHAR(1)); // Charge control status 2 line (0 = not active, 1 = active) / Zustand Charge control 2 Leitung (0 = nicht aktiv, // 1 = aktiv) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_CONTROL_2", STAT_CHARGE_CONTROL_2, "\"0/1\""); unsigned char STAT_CHARGE_PERMISSION = (RXBUF_UCHAR(2)); // Charge permission line status (0 = not active, 1 = active) / Zustand Charge Permission Leitung (0 = nicht // aktiv, 1 = aktiv) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_CHARGE_PERMISSION", STAT_CHARGE_PERMISSION, "\"0/1\""); unsigned char STAT_LADESTECKER = (RXBUF_UCHAR(3)); // State of charging plug (0 = not plugged in, 1 = plugged in) / Zustand Ladestecker (0 = nicht gesteckt, 1 = // gesteckt) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "LADESCHNITTSTELLE_DC_TEPCO", "STAT_LADESTECKER", STAT_LADESTECKER, "\"0/1\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_DC_SCHUETZ_SCHALTER: { // 0xDEF8 if (datalen < 1) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_SCHUETZ_SCHALTER", 1); break; } unsigned char STAT_DC_SCHUETZ_SCHALTER = (RXBUF_UCHAR(0)); // Contactor switch status (DC charging) / Status Schützschalter (DC-Laden) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_SCHUETZ_SCHALTER", "STAT_DC_SCHUETZ_SCHALTER", STAT_DC_SCHUETZ_SCHALTER, "\"0-n\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_DC_SCHUETZ_SPANNUNG_EINGANG: { // 0xDEF9 if (datalen < 3) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_SCHUETZ_SPANNUNG_EINGANG", 3); break; } unsigned short STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT = (RXBUF_UINT(0)); // Voltage at the input of the relay box (contactors) for DC charging / Spannung am Eingang der Relaisbox // (Schaltschütze) für DC-Laden ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%u%s\n", "LIM", "DC_SCHUETZ_SPANNUNG_EINGANG", "STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT", STAT_DC_SCHUETZ_SPANNUNG_EINGANG_WERT, "\"V\""); unsigned char STAT_DC_SCHUETZ_SPANNUNG_NEGATIV = (RXBUF_UCHAR(2)); // Detection of a negative voltage (0 = no or positive voltage / 1 = negative voltage) / Erkennung einer // negativen Spannung (0 = keine oder positive Spannung / 1 = negative Spannung) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_SCHUETZ_SPANNUNG_EINGANG", "STAT_DC_SCHUETZ_SPANNUNG_NEGATIV", STAT_DC_SCHUETZ_SPANNUNG_NEGATIV, "\"0/1\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; } case I3_PID_LIM_DC_PINABDECKUNG_COMBO: { // 0xDEFA if (datalen < 1) { ESP_LOGW(TAG, "Received %d bytes for %s, expected %d", datalen, "I3_PID_LIM_DC_PINABDECKUNG_COMBO", 1); break; } unsigned char STAT_DC_PINABDECKUNG = (RXBUF_UCHAR(0)); // State of the DC pin cover for combo socket (0 = closed, 1 = open) / Zustand der DC Pinabdeckung bei // Combo-Steckdose (0 = geschlossen, 1 = geöffnet) ESP_LOGD(TAG, "From ECU %s, pid %s: got %s=%x%s\n", "LIM", "DC_PINABDECKUNG_COMBO", "STAT_DC_PINABDECKUNG", STAT_DC_PINABDECKUNG, "\"0/1\""); // ========== Add your processing here ========== hexdump(rxbuf, type, pid); break; }
9,794
4,207
#include "core.h" #include "wbcompeldlight.h" #include "wbcompeldtransform.h" #include "wbevent.h" #include "eldritchworld.h" #include "idatastream.h" #include "configmanager.h" WBCompEldLight::WBCompEldLight() : m_Radius(0.0f), m_Color(), m_HasAddedLight(false), m_LightLocation(), m_DeferAddLight(false) {} WBCompEldLight::~WBCompEldLight() { RemoveLight(); } /*virtual*/ void WBCompEldLight::InitializeFromDefinition( const SimpleString& DefinitionName) { Super::InitializeFromDefinition(DefinitionName); MAKEHASH(DefinitionName); STATICHASH(Radius); m_Radius = ConfigManager::GetInheritedFloat(sRadius, 0.0f, sDefinitionName); STATICHASH(ColorR); m_Color.r = ConfigManager::GetInheritedFloat(sColorR, 0.0f, sDefinitionName); STATICHASH(ColorG); m_Color.g = ConfigManager::GetInheritedFloat(sColorG, 0.0f, sDefinitionName); STATICHASH(ColorB); m_Color.b = ConfigManager::GetInheritedFloat(sColorB, 0.0f, sDefinitionName); m_Color.a = 1.0f; STATICHASH(DeferAddLight); m_DeferAddLight = ConfigManager::GetInheritedBool(sDeferAddLight, false, sDefinitionName); } /*virtual*/ void WBCompEldLight::HandleEvent(const WBEvent& Event) { XTRACE_FUNCTION; Super::HandleEvent(Event); STATIC_HASHED_STRING(OnMoved); STATIC_HASHED_STRING(OnDestroyed); STATIC_HASHED_STRING(AddLight); STATIC_HASHED_STRING(RemoveLight); const HashedString EventName = Event.GetEventName(); if (EventName == sOnMoved) { if (m_DeferAddLight) { // Do nothing } else { AddLight(); } } else if (EventName == sAddLight) { AddLight(); } else if (EventName == sOnDestroyed || EventName == sRemoveLight) { RemoveLight(); } } void WBCompEldLight::AddLight() { // I don't currently want to support dynamic light-emitting entities. // So this event handles the first time a static entity's location is set. // But if it moves again, that's a problem! if (m_HasAddedLight) { return; } WBCompEldTransform* pTransform = GetEntity()->GetTransformComponent<WBCompEldTransform>(); DEVASSERT(pTransform); m_LightLocation = pTransform->GetLocation(); m_HasAddedLight = GetWorld()->AddLightAt(m_LightLocation, m_Radius, m_Color); } void WBCompEldLight::RemoveLight() { if (m_HasAddedLight) { m_HasAddedLight = false; if (GetWorld()) { GetWorld()->RemoveLightAt(m_LightLocation); } } } #define VERSION_EMPTY 0 #define VERSION_LIGHT 1 #define VERSION_CURRENT 1 uint WBCompEldLight::GetSerializationSize() { uint Size = 0; Size += 4; // Version Size += sizeof(bool); // m_HasAddedLight Size += sizeof(Vector); // m_LightLocation return Size; } void WBCompEldLight::Save(const IDataStream& Stream) { Stream.WriteUInt32(VERSION_CURRENT); Stream.WriteBool(m_HasAddedLight); #ifdef __amigaos4__ Vector tmp(m_LightLocation); littleBigEndian(&tmp.x); littleBigEndian(&tmp.y); littleBigEndian(&tmp.z); Stream.Write(sizeof(Vector), &tmp); #else Stream.Write(sizeof(Vector), &m_LightLocation); #endif } void WBCompEldLight::Load(const IDataStream& Stream) { XTRACE_FUNCTION; const uint Version = Stream.ReadUInt32(); if (Version >= VERSION_LIGHT) { m_HasAddedLight = Stream.ReadBool(); Stream.Read(sizeof(Vector), &m_LightLocation); #ifdef __amigaos4__ littleBigEndian(&m_LightLocation.x); littleBigEndian(&m_LightLocation.y); littleBigEndian(&m_LightLocation.z); #endif } }
3,494
1,299
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. // #include "CoreMinimal.h" #include "SteamVRPrivate.h" #if STEAMVR_SUPPORTED_PLATFORMS #include "SteamVRHMD.h" #include "RendererPrivate.h" #include "ScenePrivate.h" #include "PostProcess/PostProcessHMD.h" #include "PipelineStateCache.h" #include "ClearQuad.h" #include "DefaultSpectatorScreenController.h" #if PLATFORM_LINUX #include "VulkanRHIPrivate.h" #include "ScreenRendering.h" #include "VulkanPendingState.h" #include "VulkanContext.h" #endif void FSteamVRHMD::CreateSpectatorScreenController() { SpectatorScreenController = MakeUnique<FDefaultSpectatorScreenController>(this); } FIntRect FSteamVRHMD::GetFullFlatEyeRect_RenderThread(FTexture2DRHIRef EyeTexture) const { static FVector2D SrcNormRectMin(0.05f, 0.2f); static FVector2D SrcNormRectMax(0.45f, 0.8f); return FIntRect(EyeTexture->GetSizeX() * SrcNormRectMin.X, EyeTexture->GetSizeY() * SrcNormRectMin.Y, EyeTexture->GetSizeX() * SrcNormRectMax.X, EyeTexture->GetSizeY() * SrcNormRectMax.Y); } void FSteamVRHMD::CopyTexture_RenderThread(FRHICommandListImmediate& RHICmdList, FTexture2DRHIParamRef SrcTexture, FIntRect SrcRect, FTexture2DRHIParamRef DstTexture, FIntRect DstRect, bool bClearBlack) const { check(IsInRenderingThread()); const uint32 ViewportWidth = DstRect.Width(); const uint32 ViewportHeight = DstRect.Height(); const FIntPoint TargetSize(ViewportWidth, ViewportHeight); const float SrcTextureWidth = SrcTexture->GetSizeX(); const float SrcTextureHeight = SrcTexture->GetSizeY(); float U = 0.f, V = 0.f, USize = 1.f, VSize = 1.f; if (!SrcRect.IsEmpty()) { U = SrcRect.Min.X / SrcTextureWidth; V = SrcRect.Min.Y / SrcTextureHeight; USize = SrcRect.Width() / SrcTextureWidth; VSize = SrcRect.Height() / SrcTextureHeight; } SetRenderTarget(RHICmdList, DstTexture, FTextureRHIRef()); if (bClearBlack) { const FIntRect ClearRect(0, 0, DstTexture->GetSizeX(), DstTexture->GetSizeY()); RHICmdList.SetViewport(ClearRect.Min.X, ClearRect.Min.Y, 0, ClearRect.Max.X, ClearRect.Max.Y, 1.0f); DrawClearQuad(RHICmdList, FLinearColor::Black); } RHICmdList.SetViewport(DstRect.Min.X, DstRect.Min.Y, 0, DstRect.Max.X, DstRect.Max.Y, 1.0f); FGraphicsPipelineStateInitializer GraphicsPSOInit; RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit); GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI(); GraphicsPSOInit.RasterizerState = TStaticRasterizerState<>::GetRHI(); GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI(); GraphicsPSOInit.PrimitiveType = PT_TriangleList; const auto FeatureLevel = GMaxRHIFeatureLevel; auto ShaderMap = GetGlobalShaderMap(FeatureLevel); TShaderMapRef<FScreenVS> VertexShader(ShaderMap); TShaderMapRef<FScreenPS> PixelShader(ShaderMap); GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = RendererModule->GetFilterVertexDeclaration().VertexDeclarationRHI; GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader); GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader); SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit); const bool bSameSize = DstRect.Size() == SrcRect.Size(); if (bSameSize) { PixelShader->SetParameters(RHICmdList, TStaticSamplerState<SF_Point>::GetRHI(), SrcTexture); } else { PixelShader->SetParameters(RHICmdList, TStaticSamplerState<SF_Bilinear>::GetRHI(), SrcTexture); } RendererModule->DrawRectangle( RHICmdList, 0, 0, ViewportWidth, ViewportHeight, U, V, USize, VSize, TargetSize, FIntPoint(1, 1), *VertexShader, EDRF_Default); } #endif // STEAMVR_SUPPORTED_PLATFORMS
3,670
1,479
//Compile-time Flags //#define MAC_COMPILE 0 //#define LINUX_COMPILE 1 #define MEMORY_LOGGING 0 #define DEBUG 1 #include "main.h" int main() { //INITIALIZATION- Failures here cause a hard exit //Start Ruby ruby_setup_environment(); //VALUE rb_update_func = rb_intern("ruby_update"); //Initialize State & Debug Memory Manager Memory_Info mem_info = {0}; Global_State = &mem_info; State* state = (State*)walloc(sizeof(State)); //Load global strings String_DB _string_db; state->Strings = &_string_db; load_strings(state->Strings, "english"); wfree_string_db(state->Strings); //Initialize game input state->Input = (Game_Input*)walloc(sizeof(Game_Input)); clear_input(state->Input); //Load global settings file load_settings(state); state->IsRunning = true; //Set this to false to exit after one frame state->IsPaused = true; //Pause will be toggled when our window gains focus //DEBUG: Initialize rand() //TODO: remove this time_t t; srand((unsigned) time(&t)); //Initialize screen struct and buffer for taking screenshots state->Screen = (Texture*)walloc(sizeof(Texture)); state->Screen->asset_path = str_lit("Flamerokz"); state->Screen->width = state->Settings.horizontal_resolution; state->Screen->height = state->Settings.vertical_resolution; state->Screen->bytes_per_pixel = 3; state->Screen->pitch = state->Screen->width * state->Screen->bytes_per_pixel; state->Screen->buffer_size = state->Screen->pitch * state->Screen->height; state->Screen->buffer = (uint8_t*)walloc(state->Screen->buffer_size); //Initialize SDL and OpenGL SDL_Event event; int error = SDL_Init(SDL_INIT_VIDEO); if(error != 0) { message_log("SDL Init Error, Code", error); return 0; } SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); //Use OpenGL 3.1 SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 ); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //TODO: implement fullscreen SDL_Window* window = SDL_CreateWindow( state->Screen->asset_path, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, state->Screen->width, state->Screen->height, SDL_WINDOW_OPENGL); if(window == NULL) { message_log("Couldn't initialize-", "SDL OpenGL window"); return 0; } state->Window = window; SDL_GLContext context = SDL_GL_CreateContext( window ); if(context == NULL) { message_log("Couldn't get-", "OpenGL Context for window"); return 0; } if(state->Settings.vsync) { if(SDL_GL_SetSwapInterval(1) != 0) { //late-swap tearing if the vsync call fails SDL_GL_SetSwapInterval(-1); } } const uint8_t* SDL_KeyState = SDL_GetKeyboardState(NULL); //GLEW glewExperimental = GL_TRUE; if(glewInit() != GLEW_OK) { message_log("Couldn't initialize-", "GLEW"); return 0; } if(!GLEW_VERSION_2_1) { message_log("OpenGL 2.1 not supported by GLEW", ""); return 0; } //Set up simple OpenGL environment for rendering glPixelStorei(GL_PACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); //glFrontFace(GL_CCW); //Default is CCW, counter-clockwise //glDepthRange(1.0, -1.0); //change the handedness of the z axis glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //GAME INIT- Failures here may cause a proper smooth exit when necessary //Construct Camera state->Camera = (Scene_Camera*)walloc(sizeof(Scene_Camera)); state->Camera->physics = (Physics_Object*)walloc(sizeof(Physics_Object)); load_physics(state->Camera->physics); state->Camera->projection = glm::perspective(glm::radians(45.0f), (float)state->Screen->width/state->Screen->height, 0.1f, 100.0f); //Construct screen-space camera for HUD elements Scene_Camera screen_camera; screen_camera.physics = (Physics_Object*)walloc(sizeof(Physics_Object)); load_physics(screen_camera.physics); //TODO: figure out how to make this in semi-normalized coords that //can be somewhat resolution-independent screen_camera.projection = glm::ortho(0.0f, (float)state->Screen->width, 0.0f, (float)state->Screen->height); //Load Objects state->Debug_Cube = (Object*)walloc(sizeof(Object)); load_object(state->Debug_Cube, "cube", "blank", "blank_nm", "blank_spec", "shader"); state->Debug_Sphere = (Object*)walloc(sizeof(Object)); load_object(state->Debug_Sphere, "sphere", "blank", "blank_nm", "blank_spec", "flat_shaded"); state->Player = (Object*)walloc(sizeof(Object)); load_object(state->Player, "wedge", "cheese", "blank_nm_512", "cheese_spec", "shader"); state->Player->model->color = rgb_to_vector(0xE7, 0xE0, 0x8B); state->Player->physics->position = glm::vec3(0.0f, -1.0f, 0.0f); glm::vec3 light_direction = glm::vec3(0.0f, -1.0f, -1.0f); normalize(&light_direction); //TODO: break this out into level loading code state->ObjectCount = 3; state->Objects = (Object*)walloc(sizeof(Object)*state->ObjectCount); load_object(&state->Objects[0], "cube", "blank", "blank_nm", "blank_spec", "flat"); state->Objects[0].physics->position = glm::vec3(-10.5f, 0.0f, 0.0f); state->Objects[0].physics->rotation_vector = glm::vec3(1.0f, 1.0f, 0.0f); state->Objects[0].light_direction = light_direction; state->Objects[0].model->color = rgb_to_vector(0xE3, 0x1F, 0x1F); load_object(&state->Objects[1], "african_head", "african_head", "african_head", "african_head", "flat_shaded"); state->Objects[1].physics->position = glm::vec3(10.5f, 0.0f, 0.0f); state->Objects[1].physics->rotation_vector = glm::vec3(0.0f, 1.0f, 0.0f); state->Objects[1].light_direction = light_direction; state->Objects[1].model->color = rgb_to_vector(0xE3, 0x78, 0x1F); state->Objects[1].model->scale = glm::vec3(5.0f, 5.0f, 5.0f); load_object(&state->Objects[2], "cone", "blank", "blank_nm", "blank_spec", "flat_shaded"); state->Objects[2].physics->position = glm::vec3(-15.5f, 0.0f, 0.0f); state->Objects[2].physics->rotation_vector = glm::vec3(0.0f, 0.0f, 1.0f); state->Objects[2].light_direction = light_direction; state->Objects[2].model->color = rgb_to_vector(0x19, 0xB5, 0x19); state->Level = (Game_Level*)walloc(sizeof(Game_Level)); load_level(state->Level, "test_level"); //octree_print(&state->Level->octree->root); Font test_font; UChar* test_text = UChar_convert("#testing, unicode, 微研"); load_font(&test_font, "DroidSans"); //MAIN LOOP- Failures here may cause a proper smooth exit when necessary message_log("Starting update loop."); //TODO: figure out how to start my clock without eating the first frame state->TimeDifference = 0; state->LastUpdateTime = 0; state->PauseStartTime = 0; int passed_frames = 0; while(state->IsRunning) { update_time(state); //Process keydown events while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_WINDOWEVENT: if(event.window.event == SDL_WINDOWEVENT_SHOWN) { SDL_SetRelativeMouseMode(SDL_TRUE); //eat first input to avoid movement jitter SDL_GetRelativeMouseState(NULL, NULL); toggle_pause(state); } else if(event.window.event == SDL_WINDOWEVENT_HIDDEN) { SDL_SetRelativeMouseMode(SDL_FALSE); toggle_pause(state); } break; case SDL_KEYDOWN: handle_keyboard(state, event); break; case SDL_QUIT: state->IsRunning = false; break; } } if(state->IsPaused) { continue; } poll_input(state, SDL_KeyState); //TODO: is there a better way to control our framerate? if( state->DeltaTimeMS > 30 ) { process_input(state); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //TODO: unified camera system //first person camera #if 0 state->Camera->direction = glm::normalize( glm::vec3(0.0f, 0.0f, -1.0f) * state->Camera->physics->quaternion); state->Camera->view = glm::lookAt(state->Camera->physics->position, state->Camera->direction + state->Camera->physics->position, glm::vec3(0.0f, 1.0f, 0.0f)); state->Camera->physics->quaternion = glm::quat_cast(state->Camera->view); #endif //3rd-person camera #if 1 state->Camera->physics->position = state->Player->physics->position + (glm::vec3(0.0f, 6.0f, 6.0f) * state->Camera->physics->quaternion); state->Camera->view = glm::lookAt(state->Camera->physics->position, state->Player->physics->position, glm::vec3(0.0f, 1.0f, 0.0f)); #endif //draw dynamic objects for(int i = 0; i < state->ObjectCount; i++) { //state->Objects[i].physics->angular_velocity = 30.0f; //update_physics_object(state->Objects[i].physics, state->DeltaTimeS); gl_draw_object(state->Camera, &state->Objects[i]); } //draw level gl_draw_object(state->Camera, state->Level->geometry); //octree_debug_draw(state->Level->octree, state); //do player movement relative to the camera state->Player->physics->quaternion = state->Camera->physics->quaternion; state->Player->physics->time_remaining = state->DeltaTimeS; physics_process_movement(state->Player->physics); //TODO: make our collision detection not require this sanity check if(state->Player->physics->moved) { for(int reps = 0; reps < 25; reps ++) { if(!process_collision(state->Level, state->Player->physics)) { break; } } } //face model in direction of movement physics_face_movement_direction(state->Player); gl_draw_object(state->Camera, state->Player); //draw bounding box #if 1 state->Debug_Sphere->physics->position = state->Player->physics->position; state->Debug_Sphere->model->scale = state->Player->physics->radii; //state->Debug_Sphere->model->rotation = state->Player->model->rotation; gl_toggle_wireframe(true); gl_draw_object(state->Camera, state->Debug_Sphere); gl_toggle_wireframe(false); #endif //draw test text //TODO: make this an FPS counter test_font.quad->physics->position = glm::vec3(0.0f, 8.0f, 0.0f); gl_draw_text(&screen_camera, &test_font, test_text, 32.0f); SDL_GL_SwapWindow(window); state->LastUpdateTime = state->GameTime; state->FrameCounter += 1; //Spit out debug info if(state->FrameCounter > 100) { float fps = (float)state->FrameCounter; fps /= (state->WallTime - state->LastFPSUpdateTime); message_log("FPS-", fps*1000); fps = (float)passed_frames; fps /= (state->WallTime - state->LastFPSUpdateTime); message_log("Loops spent idling per second-", fps*1000); message_log("Memory in use-", mem_info.MemoryAllocated - mem_info.MemoryFreed); passed_frames = 0; state->FrameCounter = 0; state->LastFPSUpdateTime = state->WallTime; } clear_input(state->Input); } else { passed_frames++; } } take_screenshot(state); wfree_font(&test_font); wfree_camera(&screen_camera); wfree(test_text); wfree_state(state); wfree(state); ruby_cleanup(0); printf("Leaked- %lu Bytes", mem_info.MemoryAllocated - mem_info.MemoryFreed); SDL_Quit(); return 0; }
12,586
4,227
#include "Interfaces.h" #include "Memory.h" Memory::Memory() noexcept { present = findPattern<>("gameoverlayrenderer", "\xFF\x15????\x8B\xF8\x85\xDB", 2); reset = findPattern<>("gameoverlayrenderer", "\xC7\x45?????\xFF\x15????\x8B\xF8", 9); clientMode = **reinterpret_cast<ClientMode***>((*reinterpret_cast<uintptr_t**>(interfaces.client))[10] + 5); input = *reinterpret_cast<Input**>((*reinterpret_cast<uintptr_t**>(interfaces.client))[16] + 1); globalVars = **reinterpret_cast<GlobalVars***>((*reinterpret_cast<uintptr_t**>(interfaces.client))[11] + 10); glowObjectManager = *findPattern<GlowObjectManager**>("client_panorama", "\x0F\x11\x05????\x83\xC8\x01", 3); disablePostProcessing = *findPattern<bool**>("client_panorama", "\x83\xEC\x4C\x80\x3D", 5); loadSky = findPattern<decltype(loadSky)>("engine", "\x55\x8B\xEC\x81\xEC????\x56\x57\x8B\xF9\xC7\x45"); setClanTag = findPattern<decltype(setClanTag)>("engine", "\x53\x56\x57\x8B\xDA\x8B\xF9\xFF\x15"); lineGoesThroughSmoke = findPattern<decltype(lineGoesThroughSmoke)>("client_panorama", "\x55\x8B\xEC\x83\xEC\x08\x8B\x15????\x0F\x57\xC0"); smokeCount = *(reinterpret_cast<int**>(lineGoesThroughSmoke) + 2); cameraThink = findPattern<>("client_panorama", "\x85\xC0\x75\x30\x38\x86"); acceptMatch = findPattern<decltype(acceptMatch)>("client_panorama", "\x55\x8B\xEC\x83\xE4\xF8\x8B\x4D\x08\xBA????\xE8????\x85\xC0\x75\x12"); getSequenceActivity = findPattern<decltype(getSequenceActivity)>("client_panorama", "\x55\x8B\xEC\x53\x8B\x5D\x08\x56\x8B\xF1\x83"); }
1,575
767
//============================================================================ #include "Javelin/Tools/jasm/CodeSegmentSource.h" //============================================================================ using namespace Javelin::Assembler; //============================================================================ CodeSegmentSource::CodeSegmentSource(const CodeSegmentData &aData, int aIndent) : data(aData), indent(aIndent) { } int CodeSegmentSource::ReadByte() { if(index >= data.size()) return EOF; const std::string& s = data[index].line; if(offset >= s.size()) { offset = 0; ++index; return '\n'; } return (uint8_t) s[offset++]; } int CodeSegmentSource::PeekByte() { if(index >= data.size()) return EOF; const std::string& s = data[index].line; if(offset >= s.size()) return '\n'; return (uint8_t) s[offset]; } void CodeSegmentSource::SkipByte() { if(index >= data.size()) return; const std::string& s = data[index].line; if(offset >= s.size()) { offset = 0; ++index; } else { ++offset; } } //============================================================================ int CodeSegmentSource::GetCurrentLineNumber() const { if(data.size() == 0) return 0; if(index >= data.size()) return data[index-1].lineNumber; return data[index].lineNumber; } const std::string CodeSegmentSource::GetPreviousLine() const { if(data.size() == 0) return ""; if(index == 0) return data[0].line; return data[index-1].line; } const std::string CodeSegmentSource::GetCurrentLine() const { if(data.size() == 0) return ""; if(index >= data.size()) return data[index-1].line; return data[index].line; } int CodeSegmentSource::GetCurrentFileIndex() const { if(data.size() == 0) return 0; if(index >= data.size()) return data[index-1].fileIndex; return data[index].fileIndex; } bool CodeSegmentSource::GetCurrentLineIsPreprocessor() const { if(data.size() == 0) return false; if(index >= data.size()) return data[index-1].isPreprocessor; return data[index].isPreprocessor; } //============================================================================
2,112
705
#include "D3D11RHI.h" #include "D3D11Shader.h" D3D11RHI::~D3D11RHI() { D3D11RHI::Instance()->_Device->Release(); D3D11RHI::Instance()->_Context->Release();; D3D11RHI::Instance()->_SwapChain->Release(); D3D11RHI::Instance()->_BackBufferRTV->Release(); D3D11RHI::Instance()->_RasterizerStateSolid->Release(); D3D11RHI::Instance()->_SamplerState->Release(); D3D11RHI::Instance()->_DepthStencilView->Release();; } bool D3D11RHI::Initialize(HWND hwnd, unsigned int width, unsigned int height) { D3D11RHI::Instance()->_Width = width; D3D11RHI::Instance()->_Height = height; D3D11RHI::Instance()->_FeatureLevel = D3D_FEATURE_LEVEL_11_1; UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) //createDeviceFlags |= D3D11_DEBUG; #endif if (FAILED(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE::D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, &D3D11RHI::Instance()->_FeatureLevel, 1, D3D11_SDK_VERSION, &D3D11RHI::Instance()->_Device, nullptr, &D3D11RHI::Instance()->_Context))) { return false; } IDXGIFactory* factory = nullptr; if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory))) { return false; } const unsigned int RenderTargetWidth = width; const unsigned int RenderTargetHeight = height; DXGI_SWAP_CHAIN_DESC scd; ZeroMemory(&scd, sizeof(scd)); scd.BufferCount = 1; scd.BufferDesc.Width = RenderTargetWidth; scd.BufferDesc.Height = RenderTargetHeight; scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scd.BufferDesc.RefreshRate.Numerator = 60; scd.BufferDesc.RefreshRate.Denominator = 1; scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; scd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.OutputWindow = (HWND)hwnd; scd.SampleDesc.Count = 1; scd.SampleDesc.Quality = 0; scd.Windowed = true; scd.Flags = 0; if (FAILED(factory->CreateSwapChain(D3D11RHI::Instance()->_Device, &scd, &D3D11RHI::Instance()->_SwapChain))) { return false; } ID3D11Texture2D* backbuffer = nullptr; D3D11RHI::SwapChain()->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backbuffer)); D3D11RHI::Device()->CreateRenderTargetView(backbuffer, NULL, &D3D11RHI::Instance()->_BackBufferRTV); backbuffer->Release(); D3D11_TEXTURE2D_DESC db; ZeroMemory(&db, sizeof(db)); db.Width = RenderTargetWidth; db.Height = RenderTargetHeight; db.MipLevels = 1; db.ArraySize = 1; db.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; db.SampleDesc.Count = 1; db.SampleDesc.Quality = 0; db.Usage = D3D11_USAGE_DEFAULT; db.BindFlags = D3D11_BIND_DEPTH_STENCIL; db.CPUAccessFlags = 0; db.MiscFlags = 0; ID3D11Texture2D* depthstencilbuffer = nullptr; D3D11RHI::Device()->CreateTexture2D(&db, NULL, &depthstencilbuffer); D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc)); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = true; depthStencilDesc.StencilReadMask = 0xFF; depthStencilDesc.StencilWriteMask = 0xFF; depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; D3D11RHI::Device()->CreateDepthStencilState(&depthStencilDesc, &D3D11RHI::Instance()->_DepthStencilState); D3D11RHI::Context()->OMSetDepthStencilState(D3D11RHI::Instance()->_DepthStencilState, 1); D3D11_DEPTH_STENCIL_VIEW_DESC dsvd; ZeroMemory(&dsvd, sizeof(dsvd)); dsvd.Format = db.Format; dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; dsvd.Texture2D.MipSlice = 0; D3D11RHI::Device()->CreateDepthStencilView(depthstencilbuffer, &dsvd, &D3D11RHI::Instance()->_DepthStencilView); depthstencilbuffer->Release(); D3D11RHI::Context()->OMSetRenderTargets(1, &D3D11RHI::Instance()->_BackBufferRTV, D3D11RHI::DepthStencilView()); D3D11_RASTERIZER_DESC rd; ZeroMemory(&rd, sizeof(D3D11_RASTERIZER_DESC)); rd.AntialiasedLineEnable = false; rd.CullMode = D3D11_CULL_BACK; rd.DepthBias = 0; rd.DepthBiasClamp = 0.0f; rd.DepthClipEnable = true; rd.FillMode = D3D11_FILL_SOLID; rd.FrontCounterClockwise = false; rd.MultisampleEnable = false; rd.ScissorEnable = false; rd.SlopeScaledDepthBias = 0.0f; D3D11RHI::Device()->CreateRasterizerState(&rd, &D3D11RHI::Instance()->_RasterizerStateSolid); D3D11RHI::Context()->RSSetState(D3D11RHI::Instance()->_RasterizerStateSolid); D3D11_SAMPLER_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sd.ComparisonFunc = D3D11_COMPARISON_NEVER; sd.MinLOD = 0; sd.MaxLOD = D3D11_FLOAT32_MAX; if (FAILED(D3D11RHI::Device()->CreateSamplerState(&sd, &D3D11RHI::Instance()->_SamplerState))) { return false; } D3D11_VIEWPORT viewport; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; viewport.Width = static_cast<float>(RenderTargetWidth); viewport.Height = static_cast<float>(RenderTargetHeight); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; D3D11RHI::Context()->RSSetViewports(1, &viewport); D3D11RHI::Instance()->_DeferredBuffer = std::make_shared<D3D11DeferredBuffer>(); D3D11RHI::Instance()->_DeferredBuffer->Initialize(D3D11RHI::Device(), RenderTargetWidth, RenderTargetHeight); D3D11RHI::Instance()->_OrthoRect = std::make_shared<D3D11OrthoRect>(); D3D11RHI::Instance()->_OrthoRect->Initialize(D3D11RHI::Device(), RenderTargetWidth, RenderTargetHeight); D3D11RHI::Instance()->_Light = std::make_shared<D3D11Light>(); D3D11RHI::Instance()->_Light->Initialize(D3D11RHI::Device(), hwnd); D3D11RHI::Instance()->_OrthoMatrix = XMMatrixOrthographicLH(static_cast<float>(D3D11RHI::Instance()->_Width), static_cast<float>(D3D11RHI::Instance()->_Height), 0.f, 1000.f); return true; } void D3D11RHI::InitializeImGui(HWND hwnd, unsigned int width, unsigned int height) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); //ImGuiIO& io = ImGui::GetIO(); (void)io; ImGui::StyleColorsDark(); ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(D3D11RHI::Device(), D3D11RHI::Context()); } void D3D11RHI::StandbyDeferred(void) { float clear_color_with_alpha[4] = { 0.f, 0.f, 0.f, 0.f }; D3D11RHI::DeferredBuffer()->SetRenderTargets(D3D11RHI::Context()); D3D11RHI::DeferredBuffer()->ClearRenderTargets(D3D11RHI::Context(), clear_color_with_alpha); } void D3D11RHI::Draw(void) { float clear_color_with_alpha[4] = { 0.f, 0.f, 0.f, 0.f }; D3D11RHI::Context()->OMSetRenderTargets(1, &D3D11RHI::Instance()->_BackBufferRTV, D3D11RHI::DepthStencilView()); D3D11RHI::Context()->ClearRenderTargetView(D3D11RHI::BackBuffer(), clear_color_with_alpha); D3D11RHI::Context()->ClearDepthStencilView(D3D11RHI::DepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0); D3D11RHI::Context()->OMSetDepthStencilState(D3D11RHI::DepthStencilState(), 0); D3D11RHI::Instance()->_OrthoRect->Render(D3D11RHI::Context()); D3D11RHI::Instance()->_Light->Render( D3D11RHI::Context(), 6, XMMatrixIdentity(), XMMatrixIdentity(), D3D11RHI::Instance()->_OrthoMatrix, D3D11RHI::DeferredBuffer()->GetShaderResourceView(0), D3D11RHI::DeferredBuffer()->GetShaderResourceView(1), XMFLOAT3(-1.f, -1.f, 1.f)); } void D3D11RHI::BeginImGui(void) { ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); } void D3D11RHI::EndImGui(void) { ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); } void D3D11RHI::Present(void) { D3D11RHI::SwapChain()->Present(1, 0); } ID3D11Device* D3D11RHI::Device() { return D3D11RHI::Instance()->_Device; } ID3D11DeviceContext* D3D11RHI::Context() { return D3D11RHI::Instance()->_Context; } IDXGISwapChain* D3D11RHI::SwapChain() { return D3D11RHI::Instance()->_SwapChain; } ID3D11RenderTargetView* D3D11RHI::BackBuffer() { return D3D11RHI::Instance()->_BackBufferRTV; } ID3D11DepthStencilView* D3D11RHI::DepthStencilView() { return D3D11RHI::Instance()->_DepthStencilView; } ID3D11SamplerState* D3D11RHI::Sampler() { return D3D11RHI::Instance()->_SamplerState; } ID3D11DepthStencilState* D3D11RHI::DepthStencilState() { return D3D11RHI::Instance()->_DepthStencilState; } // //ID3D11Buffer * D3D11RHI::CreateBuffer(const D3D11_BUFFER_DESC* desc, const D3D11_SUBRESOURCE_DATA* data) //{ // ID3D11Buffer* buffer = nullptr; // Device()->CreateBuffer(desc, data, &buffer); // return buffer; //} // //ID3D11VertexShader * D3D11RHI::CreateVertexShader(ID3DBlob * blob) //{ // ID3D11VertexShader* shader = nullptr; // Device()->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &shader); // return shader; //} // //ID3D11PixelShader * D3D11RHI::CreatePixelShader(ID3DBlob * blob) //{ // ID3D11PixelShader* shader = nullptr; // Device()->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, &shader); // return shader; //} // //ID3D11InputLayout * D3D11RHI::CreateInputLayout(ID3DBlob * blob, D3D11_INPUT_ELEMENT_DESC * desc, unsigned int desc_size) //{ // ID3D11InputLayout* layout = nullptr; // Device()->CreateInputLayout(desc, desc_size, blob->GetBufferPointer(), blob->GetBufferSize(), &layout); // return layout; //} // //void D3D11RHI::BindVertexBuffer(ID3D11Buffer* buffer, unsigned int size, unsigned int offset) //{ // D3D11RHI::Context()->IASetVertexBuffers(0, 1, &buffer, &size, &offset); // //} // //void D3D11RHI::BindIndexBuffer(ID3D11Buffer* buffer) //{ // D3D11RHI::Context()->IASetIndexBuffer(buffer, DXGI_FORMAT_R32_UINT, 0); //} std::shared_ptr<D3D11DeferredBuffer> D3D11RHI::DeferredBuffer(void) { return D3D11RHI::Instance()->_DeferredBuffer; } void D3D11RHI::GetViewportSize(unsigned int& width, unsigned int& height) { width = D3D11RHI::Instance()->_Width; height = D3D11RHI::Instance()->_Height; }
10,317
4,701
/* * libnbt++ - A library for the Minecraft Named Binary Tag format. * Copyright (C) 2013, 2015 ljfa-ag * * This file is part of libnbt++. * * libnbt++ is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * libnbt++ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with libnbt++. If not, see <http://www.gnu.org/licenses/>. */ #include "tag_list.h" #include "nbt_tags.h" #include "io/stream_reader.h" #include "io/stream_writer.h" #include <istream> namespace nbt { tag_list::tag_list(std::initializer_list<int8_t> il) { init<tag_byte>(il); } tag_list::tag_list(std::initializer_list<int16_t> il) { init<tag_short>(il); } tag_list::tag_list(std::initializer_list<int32_t> il) { init<tag_int>(il); } tag_list::tag_list(std::initializer_list<int64_t> il) { init<tag_long>(il); } tag_list::tag_list(std::initializer_list<float> il) { init<tag_float>(il); } tag_list::tag_list(std::initializer_list<double> il) { init<tag_double>(il); } tag_list::tag_list(std::initializer_list<std::string> il) { init<tag_string>(il); } tag_list::tag_list(std::initializer_list<tag_byte_array> il) { init<tag_byte_array>(il); } tag_list::tag_list(std::initializer_list<tag_list> il) { init<tag_list>(il); } tag_list::tag_list(std::initializer_list<tag_compound> il) { init<tag_compound>(il); } tag_list::tag_list(std::initializer_list<tag_int_array> il) { init<tag_int_array>(il); } tag_list::tag_list(std::initializer_list<tag_long_array> il) { init<tag_long_array>(il); } tag_list::tag_list(std::initializer_list<value> init) { if(init.size() == 0) el_type_ = tag_type::Null; else { el_type_ = init.begin()->get_type(); for(const value& val: init) { if(!val || val.get_type() != el_type_) throw std::invalid_argument("The values are not all the same type"); } tags.assign(init.begin(), init.end()); } } value& tag_list::at(size_t i) { return tags.at(i); } const value& tag_list::at(size_t i) const { return tags.at(i); } void tag_list::set(size_t i, value&& val) { if(val.get_type() != el_type_) throw std::invalid_argument("The tag type does not match the list's content type"); tags.at(i) = std::move(val); } void tag_list::push_back(value_initializer&& val) { if(!val) //don't allow null values throw std::invalid_argument("The value must not be null"); if(el_type_ == tag_type::Null) //set content type if undetermined el_type_ = val.get_type(); else if(el_type_ != val.get_type()) throw std::invalid_argument("The tag type does not match the list's content type"); tags.push_back(std::move(val)); } void tag_list::reset(tag_type type) { clear(); el_type_ = type; } void tag_list::read_payload(io::stream_reader& reader) { tag_type lt = reader.read_type(true); int32_t length; reader.read_num(length); if(length < 0) reader.get_istr().setstate(std::ios::failbit); if(!reader.get_istr()) throw io::input_error("Error reading length of tag_list"); if(lt != tag_type::End) { reset(lt); tags.reserve(length); for(int32_t i = 0; i < length; ++i) tags.emplace_back(reader.read_payload(lt)); } else { //In case of tag_end, ignore the length and leave the type undetermined reset(tag_type::Null); } } void tag_list::write_payload(io::stream_writer& writer) const { if(size() > io::stream_writer::max_array_len) { writer.get_ostr().setstate(std::ios::failbit); throw std::length_error("List is too large for NBT"); } writer.write_type(el_type_ != tag_type::Null ? el_type_ : tag_type::End); writer.write_num(static_cast<int32_t>(size())); for(const auto& val: tags) { //check if the value is of the correct type if(val.get_type() != el_type_) { writer.get_ostr().setstate(std::ios::failbit); throw std::logic_error("The tags in the list do not all match the content type"); } writer.write_payload(val); } } bool operator==(const tag_list& lhs, const tag_list& rhs) { return lhs.el_type_ == rhs.el_type_ && lhs.tags == rhs.tags; } bool operator!=(const tag_list& lhs, const tag_list& rhs) { return !(lhs == rhs); } }
4,886
1,730
#include <iostream> #include <vector> #define ll int64_t #define endl "\n" using namespace std; void solve(){ int n; cin >> n; vector<int> vec1, vec2; for (int i = 0; i < n; i++){ string str; cin >> str; vec1.push_back(str[str.size() - 1] - '0'); } for (int i = 0; i < n; i++){ string str; cin >> str; vec2.push_back(str[str.size() - 1] - '0'); } if (vec1[n - 1] == 1 || vec1[n - 1] == 2){ cout << "NO" << endl; return; } for (int i = 0; i < n; i++){ if ((vec1[i] == 1 || vec1[i] == 2) && (vec2[i] == 3 || vec2[i] == 4)) continue; else if ((vec2[i] == 1 || vec2[i] == 2) && (vec1[i] == 3 || vec1[i] == 4)) continue; else{ cout << "NO" << endl; return; } } cout << "YES" << endl; } int main(){ ios::sync_with_stdio(false); cin.tie(0); //IO int t; cin >> t; while (t--){ solve(); } return 0; }
1,030
425
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Topper Trading Workbench // // Copyright (C) 2018 Hat Boy Software, Inc. // // @author Matthew Alan Gray - <mgray@hatboysoftware.com> //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #pragma once #include "Entity.hpp" //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace Topper { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ class RootEntity : public Entity { /// @name Types /// @{ public: /// @} /// @name I_Cleanable implementation /// @{ public: void setDirty() const override; /// @} /// @name Entity implementation /// @{ public: const std::string& getType() const override; const I_Entity& getRoot() const; const Helmet::Workbench::I_Model& getParentModel() const override; bool isVisible() override; /// @} /// @name RootEntity implementation /// @{ public: /// @} /// @name 'Structors /// @{ public: RootEntity(Helmet::Workbench::I_Model& _parent, const std::string& _name, const std::string& _entityInfo); virtual ~RootEntity(); /// @} /// @name Member Variables /// @{ private: static const std::string sm_type; Helmet::Workbench::I_Model& m_parent; /// @} }; // class RootEntity //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace Topper //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
1,617
849
#define BOOST_TEST_MODULE "result_type_test" #include <boost/test/included/unit_test.hpp> #include <toml/result.hpp> #include <iostream> #include <iomanip> using namespace toml; using namespace detail; BOOST_AUTO_TEST_CASE(test_construction) { { result<int, double> r(ok(42)); BOOST_CHECK(r); BOOST_CHECK(r.is_ok()); BOOST_CHECK(!r.is_err()); } { result<int, double> r(err(3.14)); BOOST_CHECK(!r); BOOST_CHECK(!r.is_ok()); BOOST_CHECK(r.is_err()); } { result<int, double> r = ok(42); BOOST_CHECK(r); BOOST_CHECK(r.is_ok()); BOOST_CHECK(!r.is_err()); } { result<int, double> r = err(3.14); BOOST_CHECK(!r); BOOST_CHECK(!r.is_ok()); BOOST_CHECK(r.is_err()); } } BOOST_AUTO_TEST_CASE(test_unwrap) { { result<int, double> r(ok(42)); BOOST_CHECK_EQUAL(r.unwrap(), 42); BOOST_CHECK_EQUAL(r.ok_or(54), 42); BOOST_CHECK_EQUAL(r.err_or(2.71), 2.71); } { result<int, double> r(err(3.14)); BOOST_CHECK_EQUAL(r.unwrap_err(), 3.14); BOOST_CHECK_EQUAL(r.ok_or(54), 54); BOOST_CHECK_EQUAL(r.err_or(2.71), 3.14); } }
1,250
550
//Modified by Nishka Dasgupta, Akash Shah #include <iostream> #include "Network/BtChannel.h" #include "Network/BtEndpoint.h" //#include "../MPCHonestMajority/MPSI_Party.h" using namespace std; #include "Common/Defines.h" using namespace osuCrypto; #include "OtBinMain.h" #include "bitPosition.h" #include <numeric> #include "Common/Log.h" //int miraclTestMain(); void usage(const char* argv0) { std::cout << "Error! Please use:" << std::endl; std::cout << "\t 1. For unit test: " << argv0 << " -u" << std::endl; std::cout << "\t 2. For simulation (5 parties <=> 5 terminals): " << std::endl;; std::cout << "\t\t each terminal: " << argv0 << " -n 5 -t 2 -m 12 -p [pIdx]" << std::endl; } int main(int argc, char** argv) { /*char **circuitArgv; std::vector<uint64_t> bins; MPSI_Party<ZpMersenneLongElement> mpsi(1, circuitArgv, bins, 4096); mpsi.readMPSIInputs(bins, 4096); mpsi.runMPSI();*/ //myCuckooTest_stash(); //Table_Based_Random_Test(); //OPPRF2_EmptrySet_Test_Main(); //OPPRFn_EmptrySet_Test_Main(); //Transpose_Test(); //OPPRF3_EmptrySet_Test_Main(); //OPPRFnt_EmptrySet_Test_Main(); //OPPRFnt_EmptrySet_Test_Main(); //OPPRFn_Aug_EmptrySet_Test_Impl(); //OPPRFnt_EmptrySet_Test_Main(); //OPPRF2_EmptrySet_Test_Main(); //return 0; u64 trials = 1; u64 pSetSize = 5, psiSecParam = 40, bitSize = 128; u64 nParties, tParties, opt_basedOPPRF, setSize, isAug; u64 roundOPPRF; char * timingsfile = "runtime.txt"; switch (argc) { case 2: //unit test if (argv[1][0] == '-' && argv[1][1] == 'u') OPPRFnt_EmptrySet_Test_Main(); break; case 7: //2PSI if (argv[1][0] == '-' && argv[1][1] == 'n') nParties = atoi(argv[2]); else { usage(argv[0]); return 0; } if (argv[3][0] == '-' && argv[3][1] == 'm') setSize = 1 << atoi(argv[4]); else { usage(argv[0]); return 0; } if (argv[5][0] == '-' && argv[5][1] == 'p') { u64 pIdx = atoi(argv[6]); if (nParties == 2) party2(pIdx, setSize); else { usage(argv[0]); return 0; } } else { usage(argv[0]); return 0; } break; case 11: //nPSI or optimized 3PSI cout << "11\n"; if (argv[1][0] == '-' && argv[1][1] == 'n') nParties = atoi(argv[2]); else { usage(argv[0]); return 0; } if (argv[3][0] == '-' && argv[3][1] == 'r' && nParties == 3) { roundOPPRF = atoi(argv[4]); tParties = 2; } else if (argv[3][0] == '-' && argv[3][1] == 't') tParties = atoi(argv[4]); else if (argv[3][0] == '-' && argv[3][1] == 'a') opt_basedOPPRF = atoi(argv[4]); else { usage(argv[0]); return 0; } if (argv[5][0] == '-' && argv[5][1] == 'm') setSize = 1 << atoi(argv[6]); else { usage(argv[0]); return 0; } if (argv[7][0] == '-' && argv[7][1] == 'p') { u64 pIdx = atoi(argv[8]); if (roundOPPRF == 1 && nParties == 3) { //cout << nParties << " " << roundOPPRF << " " << setSize << " " << pIdx << "\n"; party3(pIdx, setSize, trials); } else if (argv[3][1] == 't') { //cout << nParties << " " << tParties << " " << setSize << " " << pIdx << "\n"; if (argv[9][0] == '-' && argv[9][1] == 'F') { timingsfile = argv[10]; } tparty(pIdx, nParties, tParties, setSize, trials, timingsfile); } else if (argv[3][1] == 'a') { aug_party(pIdx, nParties, setSize, opt_basedOPPRF, trials); } } else { usage(argv[0]); return 0; } break; } return 0; }
3,432
1,773
/* * Copyright 2001-2008, Axel Dörfler, axeld@pinc-software.de * This file may be used under the terms of the MIT License. */ //! Transaction and logging #include "Journal.h" #include "Inode.h" #include <Drivers.h> #include <util/kernel_cpp.h> struct run_array { int32 count; int32 max_runs; block_run runs[0]; int32 CountRuns() const { return BFS_ENDIAN_TO_HOST_INT32(count); } int32 MaxRuns() const { return BFS_ENDIAN_TO_HOST_INT32(max_runs); } const block_run &RunAt(int32 i) const { return runs[i]; } static int32 MaxRuns(int32 blockSize) { return (blockSize - sizeof(run_array)) / sizeof(block_run); } }; class LogEntry : public DoublyLinkedListLinkImpl<LogEntry> { public: LogEntry(Journal *journal, uint32 logStart); ~LogEntry(); status_t InitCheck() const { return fArray != NULL ? B_OK : B_NO_MEMORY; } uint32 Start() const { return fStart; } uint32 Length() const { return fLength; } Journal *GetJournal() { return fJournal; } bool InsertBlock(off_t blockNumber); bool NotifyBlocks(int32 count); run_array *Array() const { return fArray; } int32 CountRuns() const { return fArray->CountRuns(); } int32 MaxRuns() const { return fArray->MaxRuns() - 1; } // the -1 is an off-by-one error in Be's BFS implementation const block_run &RunAt(int32 i) const { return fArray->RunAt(i); } private: Journal *fJournal; uint32 fStart; uint32 fLength; uint32 fCachedBlocks; run_array *fArray; }; // #pragma mark - LogEntry::LogEntry(Journal *journal, uint32 start) : fJournal(journal), fStart(start), fLength(1), fCachedBlocks(0) { int32 blockSize = fJournal->GetVolume()->BlockSize(); fArray = (run_array *)malloc(blockSize); if (fArray == NULL) return; memset(fArray, 0, blockSize); fArray->max_runs = HOST_ENDIAN_TO_BFS_INT32(run_array::MaxRuns(blockSize)); } LogEntry::~LogEntry() { free(fArray); } /** Adds the specified block into the array. */ bool LogEntry::InsertBlock(off_t blockNumber) { // Be's BFS log replay routine can only deal with block_runs of size 1 // A pity, isn't it? Too sad we have to be compatible. if (CountRuns() >= MaxRuns()) return false; block_run run = fJournal->GetVolume()->ToBlockRun(blockNumber); fArray->runs[CountRuns()] = run; fArray->count = HOST_ENDIAN_TO_BFS_INT32(CountRuns() + 1); fLength++; fCachedBlocks++; return true; } bool LogEntry::NotifyBlocks(int32 count) { fCachedBlocks -= count; return fCachedBlocks == 0; } // #pragma mark - Journal::Journal(Volume *volume) : fVolume(volume), fLock("bfs journal"), fOwner(NULL), fArray(volume->BlockSize()), fLogSize(volume->Log().Length()), fMaxTransactionSize(fLogSize / 4 - 5), fUsed(0), fTransactionsInEntry(0) { if (fMaxTransactionSize > fLogSize / 2) fMaxTransactionSize = fLogSize / 2 - 5; } Journal::~Journal() { FlushLogAndBlocks(); } status_t Journal::InitCheck() { if (fVolume->LogStart() != fVolume->LogEnd()) { if (fVolume->SuperBlock().flags != SUPER_BLOCK_DISK_DIRTY) FATAL(("log_start and log_end differ, but disk is marked clean - trying to replay log...\n")); return ReplayLog(); } return B_OK; } status_t Journal::_CheckRunArray(const run_array *array) { int32 maxRuns = run_array::MaxRuns(fVolume->BlockSize()); if (array->MaxRuns() != maxRuns || array->CountRuns() > maxRuns || array->CountRuns() <= 0) { FATAL(("Log entry has broken header!\n")); return B_ERROR; } for (int32 i = 0; i < array->CountRuns(); i++) { if (fVolume->ValidateBlockRun(array->RunAt(i)) != B_OK) return B_ERROR; } PRINT(("Log entry has %ld entries (%Ld)\n", array->CountRuns())); return B_OK; } /** Replays an entry in the log. * \a _start points to the entry in the log, and will be bumped to the next * one if replaying succeeded. */ status_t Journal::_ReplayRunArray(int32 *_start) { PRINT(("ReplayRunArray(start = %ld)\n", *_start)); off_t logOffset = fVolume->ToBlock(fVolume->Log()); off_t blockNumber = *_start % fLogSize; int32 blockSize = fVolume->BlockSize(); int32 count = 1; CachedBlock cachedArray(fVolume); const run_array *array = (const run_array *)cachedArray.SetTo(logOffset + blockNumber); if (array == NULL) return B_IO_ERROR; if (_CheckRunArray(array) < B_OK) return B_BAD_DATA; blockNumber = (blockNumber + 1) % fLogSize; CachedBlock cached(fVolume); for (int32 index = 0; index < array->CountRuns(); index++) { const block_run &run = array->RunAt(index); PRINT(("replay block run %lu:%u:%u in log at %Ld!\n", run.AllocationGroup(), run.Start(), run.Length(), blockNumber)); off_t offset = fVolume->ToOffset(run); for (int32 i = 0; i < run.Length(); i++) { const uint8 *data = cached.SetTo(logOffset + blockNumber); if (data == NULL) RETURN_ERROR(B_IO_ERROR); ssize_t written = write_pos(fVolume->Device(), offset + (i * blockSize), data, blockSize); if (written != blockSize) RETURN_ERROR(B_IO_ERROR); blockNumber = (blockNumber + 1) % fLogSize; count++; } } *_start += count; return B_OK; } /** Replays all log entries - this will put the disk into a * consistent and clean state, if it was not correctly unmounted * before. * This method is called by Journal::InitCheck() if the log start * and end pointer don't match. */ status_t Journal::ReplayLog() { INFORM(("Replay log, disk was not correctly unmounted...\n")); int32 start = fVolume->LogStart(); int32 lastStart = -1; while (true) { // stop if the log is completely flushed if (start == fVolume->LogEnd()) break; if (start == lastStart) { // strange, flushing the log hasn't changed the log_start pointer return B_ERROR; } lastStart = start; status_t status = _ReplayRunArray(&start); if (status < B_OK) { FATAL(("replaying log entry from %ld failed: %s\n", start, strerror(status))); return B_ERROR; } start = start % fLogSize; } PRINT(("replaying worked fine!\n")); fVolume->SuperBlock().log_start = HOST_ENDIAN_TO_BFS_INT64(fVolume->LogEnd()); fVolume->LogStart() = fVolume->LogEnd(); fVolume->SuperBlock().flags = HOST_ENDIAN_TO_BFS_INT32(SUPER_BLOCK_DISK_CLEAN); return fVolume->WriteSuperBlock(); } /** This is a callback function that is called by the cache, whenever * a block is flushed to disk that was updated as part of a transaction. * This is necessary to keep track of completed transactions, to be * able to update the log start pointer. */ void Journal::blockNotify(off_t blockNumber, size_t numBlocks, void *arg) { LogEntry *logEntry = (LogEntry *)arg; if (!logEntry->NotifyBlocks(numBlocks)) { // nothing to do yet... return; } Journal *journal = logEntry->GetJournal(); disk_super_block &superBlock = journal->fVolume->SuperBlock(); bool update = false; // Set log_start pointer if possible... journal->fEntriesLock.Lock(); if (logEntry == journal->fEntries.First()) { LogEntry *next = journal->fEntries.GetNext(logEntry); if (next != NULL) { int32 length = next->Start() - logEntry->Start(); superBlock.log_start = HOST_ENDIAN_TO_BFS_INT64((superBlock.LogStart() + length) % journal->fLogSize); } else superBlock.log_start = HOST_ENDIAN_TO_BFS_INT64(journal->fVolume->LogEnd()); update = true; } journal->fUsed -= logEntry->Length(); journal->fEntries.Remove(logEntry); journal->fEntriesLock.Unlock(); free(logEntry); // update the superblock, and change the disk's state, if necessary if (update) { journal->fVolume->LogStart() = superBlock.log_start; if (superBlock.log_start == superBlock.log_end) superBlock.flags = SUPER_BLOCK_DISK_CLEAN; status_t status = journal->fVolume->WriteSuperBlock(); if (status != B_OK) FATAL(("blockNotify: could not write back superblock: %s\n", strerror(status))); } } status_t Journal::WriteLogEntry() { fTransactionsInEntry = 0; fHasChangedBlocks = false; sorted_array *array = fArray.Array(); if (array == NULL || array->count == 0) return B_OK; // Make sure there is enough space in the log. // If that fails for whatever reason, panic! force_cache_flush(fVolume->Device(), false); int32 tries = fLogSize / 2 + 1; while (TransactionSize() > FreeLogBlocks() && tries-- > 0) force_cache_flush(fVolume->Device(), true); if (tries <= 0) { fVolume->Panic(); return B_BAD_DATA; } int32 blockShift = fVolume->BlockShift(); off_t logOffset = fVolume->ToBlock(fVolume->Log()) << blockShift; off_t logStart = fVolume->LogEnd(); off_t logPosition = logStart % fLogSize; // Create log entries for the transaction LogEntry *logEntry = NULL, *firstEntry = NULL, *lastAdded = NULL; for (int32 i = 0; i < array->CountItems(); i++) { retry: if (logEntry == NULL) { logEntry = new LogEntry(this, logStart); if (logEntry == NULL) return B_NO_MEMORY; if (logEntry->InitCheck() != B_OK) { delete logEntry; return B_NO_MEMORY; } if (firstEntry == NULL) firstEntry = logEntry; logStart++; } if (!logEntry->InsertBlock(array->ValueAt(i))) { // log entry is full - start a new one fEntriesLock.Lock(); fEntries.Add(logEntry); fEntriesLock.Unlock(); lastAdded = logEntry; logEntry = NULL; goto retry; } logStart++; } if (firstEntry == NULL) return B_OK; if (logEntry != lastAdded) { fEntriesLock.Lock(); fEntries.Add(logEntry); fEntriesLock.Unlock(); } // Write log entries to disk CachedBlock cached(fVolume); fEntriesLock.Lock(); for (logEntry = firstEntry; logEntry != NULL; logEntry = fEntries.GetNext(logEntry)) { // first write the log entry array write_pos(fVolume->Device(), logOffset + (logPosition << blockShift), logEntry->Array(), fVolume->BlockSize()); logPosition = (logPosition + 1) % fLogSize; for (int32 i = 0; i < logEntry->CountRuns(); i++) { uint8 *block = cached.SetTo(logEntry->RunAt(i)); if (block == NULL) return B_IO_ERROR; // write blocks write_pos(fVolume->Device(), logOffset + (logPosition << blockShift), block, fVolume->BlockSize()); logPosition = (logPosition + 1) % fLogSize; } } fEntriesLock.Unlock(); fUsed += array->CountItems(); // Update the log end pointer in the superblock fVolume->SuperBlock().flags = HOST_ENDIAN_TO_BFS_INT32(SUPER_BLOCK_DISK_DIRTY); fVolume->SuperBlock().log_end = HOST_ENDIAN_TO_BFS_INT64(logPosition); fVolume->LogEnd() = logPosition; status_t status = fVolume->WriteSuperBlock(); // We need to flush the drives own cache here to ensure // disk consistency. // If that call fails, we can't do anything about it anyway ioctl(fVolume->Device(), B_FLUSH_DRIVE_CACHE); fEntriesLock.Lock(); logStart = firstEntry->Start(); for (logEntry = firstEntry; logEntry != NULL; logEntry = fEntries.GetNext(logEntry)) { // Note: this only works this way as we only have block_runs of length 1 // We're reusing the fArray array, as we don't need it anymore, and // it's guaranteed to be large enough for us, too for (int32 i = 0; i < logEntry->CountRuns(); i++) { array->values[i] = fVolume->ToBlock(logEntry->RunAt(i)); } set_blocks_info(fVolume->Device(), &array->values[0], logEntry->CountRuns(), blockNotify, logEntry); } fEntriesLock.Unlock(); fArray.MakeEmpty(); // If the log goes to the next round (the log is written as a // circular buffer), all blocks will be flushed out which is // possible because we don't have any locked blocks at this // point. if (logPosition < logStart) fVolume->FlushDevice(); return status; } status_t Journal::FlushLogAndBlocks() { status_t status = Lock((Transaction *)this); if (status != B_OK) return status; // write the current log entry to disk if (TransactionSize() != 0) { status = WriteLogEntry(); if (status < B_OK) FATAL(("writing current log entry failed: %s\n", strerror(status))); } status = fVolume->FlushDevice(); Unlock((Transaction *)this, true); return status; } status_t Journal::Lock(Transaction *owner) { if (owner == fOwner) return B_OK; status_t status = fLock.Lock(); if (status == B_OK) fOwner = owner; // if the last transaction is older than 2 secs, start a new one if (fTransactionsInEntry != 0 && system_time() - fTimestamp > 2000000L) WriteLogEntry(); return B_OK; } void Journal::Unlock(Transaction *owner, bool success) { if (owner != fOwner) return; TransactionDone(success); fTimestamp = system_time(); fOwner = NULL; fLock.Unlock(); } /** If there is a current transaction that the current thread has * started, this function will give you access to it. */ Transaction * Journal::CurrentTransaction() { if (fLock.LockWithTimeout(0) != B_OK) return NULL; Transaction *owner = fOwner; fLock.Unlock(); return owner; } status_t Journal::TransactionDone(bool success) { if (!success && fTransactionsInEntry == 0) { // we can safely abort the transaction sorted_array *array = fArray.Array(); if (array != NULL) { // release the lock for all blocks in the array (we don't need // to be notified when they are actually written to disk) for (int32 i = 0; i < array->CountItems(); i++) release_block(fVolume->Device(), array->ValueAt(i)); } return B_OK; } // Up to a maximum size, we will just batch several // transactions together to improve speed if (TransactionSize() < fMaxTransactionSize) { fTransactionsInEntry++; fHasChangedBlocks = false; return B_OK; } return WriteLogEntry(); } status_t Journal::LogBlocks(off_t blockNumber, const uint8 *buffer, size_t numBlocks) { // ToDo: that's for now - we should change the log file size here if (TransactionSize() + numBlocks + 1 > fLogSize) return B_DEVICE_FULL; fHasChangedBlocks = true; int32 blockSize = fVolume->BlockSize(); for (;numBlocks-- > 0; blockNumber++, buffer += blockSize) { if (fArray.Find(blockNumber) >= 0) { // The block is already in the log, so just update its data // Note, this is only necessary if this method is called with a buffer // different from the cached block buffer - which is unlikely but // we'll make sure this way (costs one cache lookup, though). status_t status = cached_write(fVolume->Device(), blockNumber, buffer, 1, blockSize); if (status < B_OK) return status; continue; } // Insert the block into the transaction's array, and write the changes // back into the locked cache buffer fArray.Insert(blockNumber); status_t status = cached_write_locked(fVolume->Device(), blockNumber, buffer, 1, blockSize); if (status < B_OK) return status; } // If necessary, flush the log, so that we have enough space for this transaction if (TransactionSize() > FreeLogBlocks()) force_cache_flush(fVolume->Device(), true); return B_OK; } // #pragma mark - status_t Transaction::Start(Volume *volume, off_t refBlock) { // has it already been started? if (fJournal != NULL) return B_OK; fJournal = volume->GetJournal(refBlock); if (fJournal != NULL && fJournal->Lock(this) == B_OK) return B_OK; fJournal = NULL; return B_ERROR; }
15,007
5,763
/********************************************************************** Audacity: A Digital Audio Editor @file TransportUtilities.cpp @brief implements some UI related to starting and stopping play and record Paul Licameli split from TransportMenus.cpp **********************************************************************/ #include "TransportUtilities.h" #include <thread> #include "AudioIO.h" #include "commands/CommandContext.h" #include "Project.h" #include "ProjectAudioIO.h" #include "ProjectAudioManager.h" #include "ViewInfo.h" #include "toolbars/ControlToolBar.h" #include "widgets/ProgressDialog.h" void TransportUtilities::PlayCurrentRegionAndWait( const CommandContext &context, bool newDefault, bool cutpreview) { auto &project = context.project; auto &projectAudioManager = ProjectAudioManager::Get(project); const auto &playRegion = ViewInfo::Get(project).playRegion; double t0 = playRegion.GetStart(); double t1 = playRegion.GetEnd(); projectAudioManager.PlayCurrentRegion(newDefault, cutpreview); if (project.mBatchMode > 0 && t0 != t1 && !newDefault) { wxYieldIfNeeded(); /* i18n-hint: This title appears on a dialog that indicates the progress in doing something.*/ ProgressDialog progress(XO("Progress"), XO("Playing"), pdlgHideCancelButton); auto gAudioIO = AudioIO::Get(); while (projectAudioManager.Playing()) { ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0); if (result != ProgressResult::Success) { projectAudioManager.Stop(); if (result != ProgressResult::Stopped) { context.Error(wxT("Playing interrupted")); } break; } using namespace std::chrono; std::this_thread::sleep_for(100ms); wxYieldIfNeeded(); } projectAudioManager.Stop(); wxYieldIfNeeded(); } } void TransportUtilities::PlayPlayRegionAndWait( const CommandContext &context, const SelectedRegion &selectedRegion, const AudioIOStartStreamOptions &options, PlayMode mode) { auto &project = context.project; auto &projectAudioManager = ProjectAudioManager::Get(project); double t0 = selectedRegion.t0(); double t1 = selectedRegion.t1(); projectAudioManager.PlayPlayRegion(selectedRegion, options, mode); if (project.mBatchMode > 0) { wxYieldIfNeeded(); /* i18n-hint: This title appears on a dialog that indicates the progress in doing something.*/ ProgressDialog progress(XO("Progress"), XO("Playing"), pdlgHideCancelButton); auto gAudioIO = AudioIO::Get(); while (projectAudioManager.Playing()) { ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0); if (result != ProgressResult::Success) { projectAudioManager.Stop(); if (result != ProgressResult::Stopped) { context.Error(wxT("Playing interrupted")); } break; } using namespace std::chrono; std::this_thread::sleep_for(100ms); wxYieldIfNeeded(); } projectAudioManager.Stop(); wxYieldIfNeeded(); } } void TransportUtilities::RecordAndWait( const CommandContext &context, bool altAppearance) { auto &project = context.project; auto &projectAudioManager = ProjectAudioManager::Get(project); const auto &selectedRegion = ViewInfo::Get(project).selectedRegion; double t0 = selectedRegion.t0(); double t1 = selectedRegion.t1(); projectAudioManager.OnRecord(altAppearance); if (project.mBatchMode > 0 && t1 != t0) { wxYieldIfNeeded(); /* i18n-hint: This title appears on a dialog that indicates the progress in doing something.*/ ProgressDialog progress(XO("Progress"), XO("Recording"), pdlgHideCancelButton); auto gAudioIO = AudioIO::Get(); while (projectAudioManager.Recording()) { ProgressResult result = progress.Update(gAudioIO->GetStreamTime() - t0, t1 - t0); if (result != ProgressResult::Success) { projectAudioManager.Stop(); if (result != ProgressResult::Stopped) { context.Error(wxT("Recording interrupted")); } break; } using namespace std::chrono; std::this_thread::sleep_for(100ms); wxYieldIfNeeded(); } projectAudioManager.Stop(); wxYieldIfNeeded(); } } // Returns true if this project was stopped, otherwise false. // (it may though have stopped another project playing) bool TransportUtilities::DoStopPlaying(const CommandContext &context) { auto &project = context.project; auto &projectAudioManager = ProjectAudioManager::Get(project); auto gAudioIO = AudioIOBase::Get(); auto &toolbar = ControlToolBar::Get(project); auto token = ProjectAudioIO::Get(project).GetAudioIOToken(); //If this project is playing, stop playing, make sure everything is unpaused. if (gAudioIO->IsStreamActive(token)) { toolbar.SetStop(); //Pushes stop down projectAudioManager.Stop(); // Playing project was stopped. All done. return true; } // This project isn't playing. // If some other project is playing, stop playing it if (gAudioIO->IsStreamActive()) { //find out which project we need; auto start = AllProjects{}.begin(), finish = AllProjects{}.end(), iter = std::find_if(start, finish, [&](const AllProjects::value_type &ptr) { return gAudioIO->IsStreamActive( ProjectAudioIO::Get(*ptr).GetAudioIOToken()); }); //stop playing the other project if (iter != finish) { auto otherProject = *iter; auto &otherToolbar = ControlToolBar::Get(*otherProject); auto &otherProjectAudioManager = ProjectAudioManager::Get(*otherProject); otherToolbar.SetStop(); //Pushes stop down otherProjectAudioManager.Stop(); } } return false; } void TransportUtilities::DoStartPlaying( const CommandContext &context, bool newDefault) { auto &project = context.project; auto &projectAudioManager = ProjectAudioManager::Get(project); auto gAudioIO = AudioIOBase::Get(); //play the front project if (!gAudioIO->IsBusy()) { //Otherwise, start playing (assuming audio I/O isn't busy) // Will automatically set mLastPlayMode PlayCurrentRegionAndWait(context, newDefault); } }
6,553
1,832
#pragma once #include <Messages/BasicMessage.hpp> struct CodeModelResponse : public BasicMessage { struct IncludePath { std::string path; }; struct FileGroup { std::string compileFlags; std::vector<std::string> defines; std::vector<IncludePath> includePaths; bool isGenerated; std::string language; std::vector<std::string> sources; }; struct Target { std::vector<std::string> artifacts; std::string buildDirectory; std::vector<FileGroup> fileGroups; std::string fullName; std::string linkerLanguage; std::string name; std::string sourceDirectory; std::string type; }; struct Project { std::string buildDirectory; std::string name; std::string sourceDirectory; std::vector<Target> targets; }; struct Configuration { std::string name; std::vector<Project> projects; }; std::vector<Configuration> configurations; static void deserialize(const nlohmann::json& json, BasicMessage& msg); }; namespace { Messages::Registrator<ComputeResponse> CodeModelResponseRegistrator( "reply", "codemodel", Messages::Type::CodeModelResponse, nullptr, &CodeModelResponse::deserialize ); }
1,367
380
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/metrics_constants_util_win.h" #include "chrome/installer/util/browser_distribution.h" namespace { // Returns the registry path for this product with |suffix| appended to it. // |suffix| is expected to provide the separator. base::string16 GetSuffixedRegistryPath(const wchar_t* suffix) { BrowserDistribution* chrome_distribution = BrowserDistribution::GetDistribution(); DCHECK(chrome_distribution); DCHECK_EQ(BrowserDistribution::CHROME_BROWSER, chrome_distribution->GetType()); DCHECK_EQ(L'\\', *suffix); DCHECK_NE(L'\\', chrome_distribution->GetRegistryPath().back()); return chrome_distribution->GetRegistryPath() + suffix; } } // namespace namespace chrome { base::string16 GetBrowserExitCodesRegistryPath() { return GetSuffixedRegistryPath(L"\\BrowserExitCodes"); } } // namespace chrome
1,027
322
#ifndef __SPARSESA_IMP_H__ #define __SPARSESA_IMP_H__ #undef _OPENMP #ifdef _OPENMP #include <omp.h> #endif // Implementation of some sparseSA functions namespace mummer { namespace sparseSA_imp { #ifndef _OPENMP template<typename Map, typename Seq, typename Vec> void computeLCP(Map& LCP, const Seq& S, const Vec& SA, const Vec& ISA, const long N, const long K) { long h = 0; for(long i = 0; i < N / K; ++i) { const long m = ISA[i]; if(m > 0) { const long bj = SA[m-1]; const long bi = i * K; while(bi + h < N && bj + h < N && S[bi + h] == S[bj + h]) ++h; LCP.set(m, h); //LCP[m] = h; } else { LCP.set(m, 0); // LCP[m]=0; } h = std::max(0L, h - K); } LCP.init(); } #else // _OPENMP template<typename Map, typename Seq, typename Vec> void computeLCP(Map& LCP, const Seq& S, const Vec& SA, const Vec& ISA, const long N, const long K) { // const long chunk = std::min((long)10000000, (long)(N / omp_get_num_threads())); std::vector<typename Map::item_vector> Ms; #pragma omp parallel { long h = 0; typename Map::item_vector tM; // M array for this thread #pragma omp for schedule(static) for(long i = 0; i < N / K; ++i) { const long m = ISA[i]; if(m > 0) { const long bj = SA[m-1]; const long bi = i * K; while(bi + h < N && bj + h < N && S[bi + h] == S[bj + h]) ++h; LCP.set(m, h, tM); //LCP[m] = h; } else { LCP.set(m, 0); // LCP[m]=0; } h = std::max(0L, h - K); } std::sort(tM.begin(), tM.end(), Map::first_comp); #pragma omp critical Ms.push_back(std::move(tM)); } LCP.init_merge(Ms); } #endif // _OPENMP } // namespace sparseSA_imp } // namespace mummer #endif /* __SPARSESA_IMP_H__ */
1,789
761
/****************************************** Copyright (c) 2016, Mate Soos 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 "comphandler.h" #include "compfinder.h" #include "varreplacer.h" #include "solver.h" #include "varupdatehelper.h" #include "watchalgos.h" #include "clauseallocator.h" #include "clausecleaner.h" #include <iostream> #include <cassert> #include <iomanip> #include "cryptominisat5/cryptominisat.h" #include "sqlstats.h" using namespace CMSat; using std::make_pair; using std::cout; using std::endl; //#define VERBOSE_DEBUG CompHandler::CompHandler(Solver* _solver) : solver(_solver) , compFinder(NULL) { } CompHandler::~CompHandler() { if (compFinder != NULL) { delete compFinder; } } void CompHandler::new_var(const uint32_t orig_outer) { if (orig_outer == std::numeric_limits<uint32_t>::max()) { savedState.push_back(l_Undef); } assert(savedState.size() == solver->nVarsOuter()); } void CompHandler::new_vars(size_t n) { savedState.insert(savedState.end(), n, l_Undef); assert(savedState.size() == solver->nVarsOuter()); } void CompHandler::save_on_var_memory() { } size_t CompHandler::mem_used() const { size_t mem = 0; mem += savedState.capacity()*sizeof(lbool); mem += useless.capacity()*sizeof(uint32_t); mem += smallsolver_to_bigsolver.capacity()*sizeof(uint32_t); mem += bigsolver_to_smallsolver.capacity()*sizeof(uint32_t); return mem; } void CompHandler::createRenumbering(const vector<uint32_t>& vars) { smallsolver_to_bigsolver.resize(vars.size()); bigsolver_to_smallsolver.resize(solver->nVars()); for(size_t i = 0, size = vars.size() ; i < size ; ++i ) { bigsolver_to_smallsolver[vars[i]] = i; smallsolver_to_bigsolver[i] = vars[i]; } } bool CompHandler::assumpsInsideComponent(const vector<uint32_t>& vars) { for(uint32_t var: vars) { if (solver->var_inside_assumptions(var)) { return true; } } return false; } vector<pair<uint32_t, uint32_t> > CompHandler::get_component_sizes() const { vector<pair<uint32_t, uint32_t> > sizes; map<uint32_t, vector<uint32_t> > reverseTable = compFinder->getReverseTable(); for (map<uint32_t, vector<uint32_t> >::iterator it = reverseTable.begin() ; it != reverseTable.end() ; ++it ) { sizes.push_back(make_pair( it->first //Comp number , (uint32_t)it->second.size() //Size of the table )); } //Sort according to smallest size first std::sort(sizes.begin(), sizes.end(), sort_pred()); assert(sizes.size() > 1); return sizes; } bool CompHandler::handle() { assert(solver->conf.independent_vars == NULL && "Cannot handle components when indep vars is set"); assert(solver->okay()); double myTime = cpuTime(); delete compFinder; compFinder = new CompFinder(solver); compFinder->find_components(); if (compFinder->getTimedOut()) { delete compFinder; compFinder = NULL; return solver->okay(); } const uint32_t num_comps = compFinder->getNumComps(); //If there is only one big comp, we can't do anything if (num_comps <= 1) { if (solver->conf.verbosity >= 3) { cout << "c [comp] Only one component, not handling it separately" << endl; } delete compFinder; compFinder = NULL; return solver->okay(); } solver->xorclauses.clear(); #ifdef USE_GAUSS solver->clearEnGaussMatrixes(); #endif map<uint32_t, vector<uint32_t> > reverseTable = compFinder->getReverseTable(); assert(num_comps == compFinder->getReverseTable().size()); vector<pair<uint32_t, uint32_t> > sizes = get_component_sizes(); size_t num_comps_solved = 0; size_t vars_solved = 0; for (uint32_t it = 0; it < sizes.size()-1; ++it) { const uint32_t comp = sizes[it].first; vector<uint32_t>& vars = reverseTable[comp]; const bool ok = try_to_solve_component(it, comp, vars, num_comps); if (!ok) { break; } num_comps_solved++; vars_solved += vars.size(); } if (!solver->okay()) { delete compFinder; compFinder = NULL; return solver->okay(); } const double time_used = cpuTime() - myTime; if (solver->conf.verbosity >= 1) { cout << "c [comp] Coming back to original instance, solved " << num_comps_solved << " component(s), " << vars_solved << " vars" << solver->conf.print_times(time_used) << endl; } if (solver->sqlStats) { solver->sqlStats->time_passed_min( solver , "comphandler" , time_used ); } check_local_vardata_sanity(); delete compFinder; compFinder = NULL; return solver->okay(); } bool CompHandler::try_to_solve_component( const uint32_t comp_at , const uint32_t comp , const vector<uint32_t>& vars_orig , const size_t num_comps ) { for(const uint32_t var: vars_orig) { assert(solver->value(var) == l_Undef); } if (vars_orig.size() > 100ULL*1000ULL* solver->conf.var_and_mem_out_mult ) { //There too many variables -- don't create a sub-solver //I'm afraid that we will memory-out return true; } //Components with assumptions should not be removed if (assumpsInsideComponent(vars_orig)) return true; return solve_component(comp_at, comp, vars_orig, num_comps); } bool CompHandler::solve_component( const uint32_t comp_at , const uint32_t comp , const vector<uint32_t>& vars_orig , const size_t num_comps ) { assert(!solver->drat->enabled()); vector<uint32_t> vars(vars_orig); components_solved++; //Sort and renumber std::sort(vars.begin(), vars.end()); createRenumbering(vars); if (solver->conf.verbosity && num_comps < 20) { cout << "c [comp] Solving component " << comp_at << " num vars: " << vars.size() << " =======================================" << endl; } //Set up new solver SolverConf conf = configureNewSolver(vars.size()); SATSolver newSolver( (void*)&conf , solver->get_must_interrupt_inter_asap_ptr() ); moveVariablesBetweenSolvers(&newSolver, vars, comp); //Move clauses over moveClausesImplicit(&newSolver, comp, vars); moveClausesLong(solver->longIrredCls, &newSolver, comp); for(auto& lredcls: solver->longRedCls) { moveClausesLong(lredcls, &newSolver, comp); } const lbool status = newSolver.solve(); //Out of time if (status == l_Undef) { if (solver->conf.verbosity) { cout << "c [comp] subcomponent returned l_Undef -- timeout or interrupt." << endl; } readdRemovedClauses(); return false; } if (status == l_False) { solver->ok = false; if (solver->conf.verbosity) { cout << "c [comp] The component is UNSAT -> problem is UNSAT" << endl; } return false; } check_solution_is_unassigned_in_main_solver(&newSolver, vars); save_solution_to_savedstate(&newSolver, vars, comp); move_decision_level_zero_vars_here(&newSolver); if (solver->conf.verbosity && num_comps < 20) { cout << "c [comp] component " << comp_at << " =======================================" << endl; } return true; } void CompHandler::check_local_vardata_sanity() { //Checking that all variables that are not in the remaining comp have //correct 'removed' flags, and none have been assigned size_t num_vars_removed_check = 0; for (uint32_t outerVar = 0; outerVar < solver->nVarsOuter(); ++outerVar) { const uint32_t interVar = solver->map_outer_to_inter(outerVar); if (savedState[outerVar] != l_Undef) { assert(solver->varData[interVar].removed == Removed::decomposed); assert(solver->value(interVar) == l_Undef || solver->varData[interVar].level == 0); } if (solver->varData[interVar].removed == Removed::decomposed) { num_vars_removed_check++; } } assert(num_vars_removed == num_vars_removed_check); } void CompHandler::check_solution_is_unassigned_in_main_solver( const SATSolver* newSolver , const vector<uint32_t>& vars ) { for (size_t i = 0; i < vars.size(); ++i) { uint32_t var = vars[i]; if (newSolver->get_model()[upd_bigsolver_to_smallsolver(var)] != l_Undef) { assert(solver->value(var) == l_Undef); } } } void CompHandler::save_solution_to_savedstate( const SATSolver* newSolver , const vector<uint32_t>& vars , const uint32_t comp ) { assert(savedState.size() == solver->nVarsOuter()); for (size_t i = 0; i < vars.size(); ++i) { uint32_t var = vars[i]; uint32_t outerVar = solver->map_inter_to_outer(var); if (newSolver->get_model()[upd_bigsolver_to_smallsolver(var)] != l_Undef) { assert(savedState[outerVar] == l_Undef); assert(compFinder->getVarComp(var) == comp); savedState[outerVar] = newSolver->get_model()[upd_bigsolver_to_smallsolver(var)]; } } } void CompHandler::move_decision_level_zero_vars_here( const SATSolver* newSolver ) { const vector<Lit> zero_assigned = newSolver->get_zero_assigned_lits(); for (Lit lit: zero_assigned) { assert(lit.var() < newSolver->nVars()); assert(lit.var() < smallsolver_to_bigsolver.size()); lit = Lit(smallsolver_to_bigsolver[lit.var()], lit.sign()); assert(solver->value(lit) == l_Undef); assert(solver->varData[lit.var()].removed == Removed::decomposed); solver->varData[lit.var()].removed = Removed::none; solver->set_decision_var(lit.var()); num_vars_removed--; const uint32_t outer = solver->map_inter_to_outer(lit.var()); savedState[outer] = l_Undef; solver->enqueue(lit); //These vars are not meant to be in the orig solver //so they cannot cause UNSAT solver->ok = (solver->propagate<false>().isNULL()); assert(solver->ok); } } SolverConf CompHandler::configureNewSolver( const size_t numVars ) const { SolverConf conf(solver->conf); conf.origSeed = solver->mtrand.randInt(); conf.independent_vars = NULL; if (numVars < 60) { conf.do_simplify_problem = false; conf.doStamp = false; conf.doCache = false; conf.doProbe = false; conf.otfHyperbin = false; conf.verbosity = std::min(solver->conf.verbosity, 0); } //Otherwise issues are: // * variable elimination assumes some of these variables are set // (in orig instance) // // * every var replaced with var replacement would need to be set anyway // // Let's not complicate all of this. conf.greedy_undef = false; //To small, don't clogger up the screen if (numVars < 20 && solver->conf.verbosity < 3) { conf.verbosity = 0; } //Don't recurse conf.doCompHandler = false; return conf; } /** @brief Moves the variables to the new solver This implies making the right variables decision in the new solver, and making it non-decision in the old solver. */ void CompHandler::moveVariablesBetweenSolvers( SATSolver* newSolver , const vector<uint32_t>& vars , const uint32_t comp ) { for(const uint32_t var: vars) { newSolver->new_var(); assert(compFinder->getVarComp(var) == comp); assert(solver->value(var) == l_Undef); assert(solver->varData[var].removed == Removed::none); solver->varData[var].removed = Removed::decomposed; num_vars_removed++; } } void CompHandler::moveClausesLong( vector<ClOffset>& cs , SATSolver* newSolver , const uint32_t comp ) { vector<Lit> tmp; vector<ClOffset>::iterator i, j, end; for (i = j = cs.begin(), end = cs.end() ; i != end ; ++i ) { Clause& cl = *solver->cl_alloc.ptr(*i); //Irred, different comp if (!cl.red()) { if (compFinder->getVarComp(cl[0].var()) != comp) { //different comp, move along *j++ = *i; continue; } } if (cl.red()) { //Check which comp(s) it belongs to bool thisComp = false; bool otherComp = false; for (Lit* l = cl.begin(), *end2 = cl.end(); l != end2; ++l) { if (compFinder->getVarComp(l->var()) == comp) thisComp = true; if (compFinder->getVarComp(l->var()) != comp) otherComp = true; } //In both comps, remove it if (thisComp && otherComp) { solver->detachClause(cl); solver->cl_alloc.clauseFree(&cl); continue; } //In one comp, but not this one if (!thisComp) { //different comp, move along *j++ = *i; continue; } assert(thisComp && !otherComp); } //Let's move it to the other solver! #ifdef VERBOSE_DEBUG cout << "clause in this comp:" << cl << endl; #endif //Create temporary space 'tmp' and copy to backup tmp.resize(cl.size()); for (size_t i2 = 0; i2 < cl.size(); ++i2) { tmp[i2] = upd_bigsolver_to_smallsolver(cl[i2]); } //Add 'tmp' to the new solver if (cl.red()) { #ifdef STATS_NEEDED cl.stats.introduced_at_conflict = 0; #endif //newSolver->addRedClause(tmp, cl.stats); } else { saveClause(cl); newSolver->add_clause(tmp); } //Remove from here solver->detachClause(cl); solver->cl_alloc.clauseFree(&cl); } cs.resize(cs.size() - (i-j)); } void CompHandler::remove_bin_except_for_lit1(const Lit lit, const Lit lit2) { removeWBin(solver->watches, lit2, lit, true); //Update stats solver->binTri.redBins--; } void CompHandler::move_binary_clause( SATSolver* newSolver , const uint32_t comp , Watched *i , const Lit lit ) { const Lit lit2 = i->lit2(); //Unless redundant, cannot be in 2 comps at once assert((compFinder->getVarComp(lit.var()) == comp && compFinder->getVarComp(lit2.var()) == comp ) || i->red() ); //If it's redundant and the lits are in different comps, remove it. if (compFinder->getVarComp(lit.var()) != comp || compFinder->getVarComp(lit2.var()) != comp ) { //Can only be redundant, otherwise it would be in the same //component assert(i->red()); //The way we go through this, it's definitely going to be //lit2 that's in the other component assert(compFinder->getVarComp(lit2.var()) != comp); remove_bin_except_for_lit1(lit, lit2); return; } //don't add the same clause twice if (lit < lit2) { //Add clause tmp_lits = {upd_bigsolver_to_smallsolver(lit), upd_bigsolver_to_smallsolver(lit2)}; assert(compFinder->getVarComp(lit.var()) == comp); assert(compFinder->getVarComp(lit2.var()) == comp); //Add new clause if (i->red()) { //newSolver->addRedClause(tmp_lits); numRemovedHalfRed++; } else { //Save backup saveClause(vector<Lit>{lit, lit2}); newSolver->add_clause(tmp_lits); numRemovedHalfIrred++; } } else { //Just remove, already added above if (i->red()) { numRemovedHalfRed++; } else { numRemovedHalfIrred++; } } } void CompHandler::moveClausesImplicit( SATSolver* newSolver , const uint32_t comp , const vector<uint32_t>& vars ) { numRemovedHalfIrred = 0; numRemovedHalfRed = 0; for(const uint32_t var: vars) { for(unsigned sign = 0; sign < 2; ++sign) { const Lit lit = Lit(var, sign); watch_subarray ws = solver->watches[lit]; //If empty, nothing to to, skip if (ws.empty()) { continue; } Watched *i = ws.begin(); Watched *j = i; for (Watched *end2 = ws.end() ; i != end2 ; ++i ) { //At least one variable inside comp if (i->isBin() && (compFinder->getVarComp(lit.var()) == comp || compFinder->getVarComp(i->lit2().var()) == comp ) ) { move_binary_clause(newSolver, comp, i, lit); continue; } *j++ = *i; } ws.shrink_(i-j); }} assert(numRemovedHalfIrred % 2 == 0); solver->binTri.irredBins -= numRemovedHalfIrred/2; assert(numRemovedHalfRed % 2 == 0); solver->binTri.redBins -= numRemovedHalfRed/2; } void CompHandler::addSavedState(vector<lbool>& solution) { //Enqueue them. They may need to be extended, so enqueue is needed //manipulating "model" may not be good enough assert(savedState.size() == solver->nVarsOuter()); assert(solution.size() == solver->nVarsOuter()); for (size_t var = 0; var < savedState.size(); ++var) { if (savedState[var] != l_Undef) { const uint32_t interVar = solver->map_outer_to_inter(var); assert(solver->varData[interVar].removed == Removed::decomposed); const lbool val = savedState[var]; assert(solution[var] == l_Undef); solution[var] = val; //cout << "Solution to var " << var + 1 << " has been added: " << val << endl; solver->varData[interVar].polarity = (val == l_True); } } } template<class T> void CompHandler::saveClause(const T& lits) { //Update variable number to 'outer' number. This means we will not have //to update the variables every time the internal variable numbering changes for (const Lit lit : lits ) { removedClauses.lits.push_back( solver->map_inter_to_outer(lit) ); } removedClauses.sizes.push_back(lits.size()); } void CompHandler::readdRemovedClauses() { assert(solver->okay()); double myTime = cpuTime(); //Avoid recursion, clear 'removed' status for(size_t outer = 0; outer < solver->nVarsOuter(); ++outer) { const uint32_t inter = solver->map_outer_to_inter(outer); VarData& dat = solver->varData[inter]; if (dat.removed == Removed::decomposed) { dat.removed = Removed::none; num_vars_removed--; } } //Clear saved state for(lbool& val: savedState) { val = l_Undef; } vector<Lit> tmp; size_t at = 0; for (uint32_t sz: removedClauses.sizes) { //addClause() needs *outer* literals, so just do that tmp.clear(); for(size_t i = at; i < at + sz; ++i) { tmp.push_back(removedClauses.lits[i]); } if (solver->conf.verbosity >= 6) { cout << "c [comp] Adding back component clause " << tmp << endl; } //Add the clause to the system solver->addClause(tmp); assert(solver->okay()); //Move 'at' along at += sz; } //The variables have been added back thanks to addClause() //-> set them decision for(size_t outer = 0; outer < solver->nVarsOuter(); ++outer) { const uint32_t inter = solver->map_outer_to_inter(outer); VarData& dat = solver->varData[inter]; if (dat.removed == Removed::none && solver->value(inter) == l_Undef ) { solver->set_decision_var(inter); } } //Explain what we just did const double time_used = cpuTime() - myTime; if (solver->conf.verbosity) { cout << "c [comp] re-added components. Lits: " << removedClauses.lits.size() << " cls:" << removedClauses.sizes.size() << solver->conf.print_times(time_used) << endl; } if (solver->sqlStats) { solver->sqlStats->time_passed_min( solver , "comp re-adding" , time_used ); } //Clear added data removedClauses.lits.clear(); removedClauses.sizes.clear(); } uint32_t CompHandler::dump_removed_clauses(std::ostream* outfile) const { if (outfile == NULL) return removedClauses.sizes.size(); uint32_t num_cls = 0; vector<Lit> tmp; size_t at = 0; for (uint32_t size :removedClauses.sizes) { tmp.clear(); for(size_t i = at; i < at + size; ++i) { tmp.push_back(removedClauses.lits[i]); } std::sort(tmp.begin(), tmp.end()); *outfile << tmp << " 0" << endl; num_cls ++; //Move 'at' along at += size; } return num_cls; }
22,336
7,604
// Copyright (c) 2016 Nuxi, https://nuxi.nl/ // // SPDX-License-Identifier: BSD-2-Clause #include <libintl.h> #include <locale.h> #include "gtest/gtest.h" TEST(dcgettext, example) { ASSERT_STREQ("Hello", dcgettext("appname", "Hello", LC_MESSAGES)); }
256
122
/******************************************************************************** * File Name: * version.hpp * * Description: * Drone Controller Version * * 2021 | Brandon Braun | brandonbraun653@gmail.com *******************************************************************************/ #pragma once #ifndef DC_VERSION_HPP #define DC_VERSION_HPP /* STL Includes */ #include <string_view> namespace DC { /** * CHANGELOG; * * v0.1.0: Initial version * v0.2.0: Core hardware working, including basic networking. */ static constexpr std::string_view version = "0.2.0"; } // namespace DC #endif /* !DC_VERSION_HPP */
658
205
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: SAX2XMLFilter.hpp 527149 2007-04-10 14:56:39Z amassari $ */ #if !defined(XERCESC_INCLUDE_GUARD_SAX2XMLFILTER_HPP) #define XERCESC_INCLUDE_GUARD_SAX2XMLFILTER_HPP #include <xercesc/sax2/SAX2XMLReader.hpp> XERCES_CPP_NAMESPACE_BEGIN class SAX2_EXPORT SAX2XMLFilter : public SAX2XMLReader { public: // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- /** @name Constructors and Destructor */ //@{ /** The default constructor */ SAX2XMLFilter() { } /** The destructor */ virtual ~SAX2XMLFilter() { } //@} //----------------------------------------------------------------------- // The XMLFilter interface //----------------------------------------------------------------------- /** @name Implementation of SAX 2.0 XMLFilter interface's. */ //@{ /** * This method returns the parent XMLReader object. * * @return A pointer to the parent XMLReader object. */ virtual SAX2XMLReader* getParent() const = 0 ; /** * Sets the parent XMLReader object; parse requests will be forwarded to this * object, and callback notifications coming from it will be postprocessed * * @param parent The new XMLReader parent. * @see SAX2XMLReader#SAX2XMLReader */ virtual void setParent(SAX2XMLReader* parent) = 0; //@} private : /* The copy constructor, you cannot call this directly */ SAX2XMLFilter(const SAX2XMLFilter&); /* The assignment operator, you cannot call this directly */ SAX2XMLFilter& operator=(const SAX2XMLFilter&); }; XERCES_CPP_NAMESPACE_END #endif
2,577
765
/* * fixture_string.cpp * * Created on: 01.02.2015 * Author: mike_gresens */ #include "fixture_string.hpp" namespace json { namespace fixture { const fixture_base::entry_t fixture_string::_empty = { string_t(), "\"\"" }; const fixture_base::entry_t fixture_string::_simple = { string_t("foo"), "\"foo\"" }; const fixture_base::entry_t fixture_string::_space = { string_t(" foo bar "), "\" foo bar \"" }; const fixture_base::entry_t fixture_string::_quote = { string_t("\"foo\"bar\""), "\"\\\"foo\\\"bar\\\"\"" }; const fixture_base::entry_t fixture_string::_backslash = { string_t("\\foo\\bar\\"), "\"\\\\foo\\\\bar\\\\\"" }; const fixture_base::entry_t fixture_string::_slash = { string_t("/foo/bar/"), "\"\\/foo\\/bar\\/\"" }; const fixture_base::entry_t fixture_string::_backspace = { string_t("\bfoo\bbar\b"), "\"\\bfoo\\bbar\\b\"" }; const fixture_base::entry_t fixture_string::_formfeed = { string_t("\ffoo\fbar\f"), "\"\\ffoo\\fbar\\f\"" }; const fixture_base::entry_t fixture_string::_newline = { string_t("\nfoo\nbar\n"), "\"\\nfoo\\nbar\\n\"" }; const fixture_base::entry_t fixture_string::_return = { string_t("\rfoo\rbar\r"), "\"\\rfoo\\rbar\\r\"" }; const fixture_base::entry_t fixture_string::_tab = { string_t("\tfoo\tbar\t"), "\"\\tfoo\\tbar\\t\"" }; const fixture_base::entry_t fixture_string::_unicode = { string_t("\u1234foo\u5555bar\u9876"), "\"\\u1234foo\\u5555bar\\u9876\"" }; const string_t fixture_string::_invalid1 = { "\"\\ufoo\"" }; const string_t fixture_string::_invalid2 = { "\"\\u12\"" }; const string_t fixture_string::_invalid3 = { "\"\n\"" }; const string_t fixture_string::_invalid4 = { "\\" }; const string_t fixture_string::_invalid5 = { "\"foo" }; } }
1,750
815
//Language: GNU C++ #include <iostream> #include <vector> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <stack> #include <bitset> #include <algorithm> #include <map> #include <fstream> #define pb push_back #define MP make_pair #define FOR(a,b) for((a)=0 ; (a)<(b) ; (a)++) typedef long long ll; using namespace std; vector<int> table[3001]; vector<int> V; int N; bool used[3001]; bool cycle[3001]; int dis[3001]; int cur[3001]; void dfs(int from , int s, int depth){ int i,j; for(i=0;i<table[s].size();i++){ int to = table[s][i]; if(to == from)continue; if(used[to]){ for(j=0;j<depth;j++){ if(cur[j]==to){ for(;j<depth;j++) cycle[cur[j]]=1; break; } } }else{ used[to] = 1; cur[depth] = to; dfs(s,to,depth+1); } } } void bfs(){ int i,j,k; queue< pair<int,int> > Q; for(i=1;i<=N;i++){ if(cycle[i])Q.push(MP(i,0)); } while(!Q.empty()){ int s= Q.front().first; int d = Q.front().second; if(dis[s]==0)d = 0; for(i=0;i<table[s].size();i++){ int to =table[s][i]; if(dis[to] > d + 1){ dis[to] = d+1; Q.push(MP(to,d+1)); } } Q.pop(); } return ; } int main(){ int i,j,k,M,P,l,m,n; cin >> N; int t1,t2; for(i=0;i<N;i++){ cin >> t1>>t2; table[t1].pb(t2); table[t2].pb(t1); } cur[0] = 1; used[1] = 1; dfs(0,1,1); for(i=1;i<=N;i++) if(cycle[i]){ V.pb(i); dis[i] = 0; }else dis[i]=100000; bfs(); for(i=1;i<N;i++){ cout<<dis[i]<<" "; } cout<<dis[N]<<endl; }
1,954
830
// // Quantum Script Extension Shell // // Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com> // Created by Grigore Stefan <g_stefan@yahoo.com> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #ifndef QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_HPP #define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_HPP #define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_ABCD 2,1,0,19 #define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR "2.1.0" #define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR_BUILD "19" #define QUANTUM_SCRIPT_EXTENSION_SHELL_VERSION_STR_DATETIME "2021-08-09 17:38:06" #ifndef XYO_RC #ifndef QUANTUM_SCRIPT_EXTENSION_SHELL__EXPORT_HPP #include "quantum-script-extension-shell--export.hpp" #endif namespace Quantum { namespace Script { namespace Extension { namespace Shell { namespace Version { QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *version(); QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *build(); QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *versionWithBuild(); QUANTUM_SCRIPT_EXTENSION_SHELL_EXPORT const char *datetime(); }; }; }; }; }; #endif #endif
1,227
543
/* Copyright 2018 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 "tensorflow/lite/experimental/microfrontend/lib/window.h" #include "tensorflow/lite/experimental/microfrontend/lib/window_util.h" #include "tensorflow/lite/micro/testing/micro_test.h" namespace { const int kSampleRate = 1000; const int kWindowSamples = 25; const int kStepSamples = 10; const int16_t kFakeAudioData[] = { 0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768, 0, 32767, 0, -32768 }; // Test window function behaviors using default config values. class WindowTestConfig { public: WindowTestConfig() { config_.size_ms = 25; config_.step_size_ms = 10; } struct WindowConfig config_; }; } // namespace TF_LITE_MICRO_TESTS_BEGIN TF_LITE_MICRO_TEST(WindowState_CheckCoefficients) { WindowTestConfig config; struct WindowState state; TF_LITE_MICRO_EXPECT( WindowPopulateState(&config.config_, &state, kSampleRate)); const int16_t expected[] = { 16, 144, 391, 743, 1176, 1664, 2177, 2681, 3145, 3541, 3843, 4032, 4096, 4032, 3843, 3541, 3145, 2681, 2177, 1664, 1176, 743, 391, 144, 16 }; TF_LITE_MICRO_EXPECT_EQ(state.size, sizeof(expected) / sizeof(expected[0])); int i; for (i = 0; i < state.size; ++i) { TF_LITE_MICRO_EXPECT_EQ(state.coefficients[i], expected[i]); } WindowFreeStateContents(&state); } TF_LITE_MICRO_TEST(WindowState_CheckResidualInput) { WindowTestConfig config; struct WindowState state; TF_LITE_MICRO_EXPECT( WindowPopulateState(&config.config_, &state, kSampleRate)); size_t num_samples_read; TF_LITE_MICRO_EXPECT(WindowProcessSamples( &state, kFakeAudioData, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read)); int i; for (i = kStepSamples; i < kWindowSamples; ++i) { TF_LITE_MICRO_EXPECT_EQ(state.input[i - kStepSamples], kFakeAudioData[i]); } WindowFreeStateContents(&state); } TF_LITE_MICRO_TEST(WindowState_CheckOutputValues) { WindowTestConfig config; struct WindowState state; TF_LITE_MICRO_EXPECT( WindowPopulateState(&config.config_, &state, kSampleRate)); size_t num_samples_read; TF_LITE_MICRO_EXPECT(WindowProcessSamples( &state, kFakeAudioData, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read)); const int16_t expected[] = { 0, 1151, 0, -5944, 0, 13311, 0, -21448, 0, 28327, 0, -32256, 0, 32255, 0, -28328, 0, 21447, 0, -13312, 0, 5943, 0, -1152, 0 }; TF_LITE_MICRO_EXPECT_EQ(state.size, sizeof(expected) / sizeof(expected[0])); int i; for (i = 0; i < state.size; ++i) { TF_LITE_MICRO_EXPECT_EQ(state.output[i], expected[i]); } WindowFreeStateContents(&state); } TF_LITE_MICRO_TEST(WindowState_CheckMaxAbsValue) { WindowTestConfig config; struct WindowState state; TF_LITE_MICRO_EXPECT( WindowPopulateState(&config.config_, &state, kSampleRate)); size_t num_samples_read; TF_LITE_MICRO_EXPECT(WindowProcessSamples( &state, kFakeAudioData, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read)); TF_LITE_MICRO_EXPECT_EQ(state.max_abs_output_value, 32256); WindowFreeStateContents(&state); } TF_LITE_MICRO_TEST(WindowState_CheckConsecutiveWindow) { WindowTestConfig config; struct WindowState state; TF_LITE_MICRO_EXPECT( WindowPopulateState(&config.config_, &state, kSampleRate)); size_t num_samples_read; TF_LITE_MICRO_EXPECT(WindowProcessSamples( &state, kFakeAudioData, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read)); TF_LITE_MICRO_EXPECT(WindowProcessSamples( &state, kFakeAudioData + kWindowSamples, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) - kWindowSamples, &num_samples_read)); const int16_t expected[] = { 0, -1152, 0, 5943, 0, -13312, 0, 21447, 0, -28328, 0, 32255, 0, -32256, 0, 28327, 0, -21448, 0, 13311, 0, -5944, 0, 1151, 0 }; TF_LITE_MICRO_EXPECT_EQ(state.size, sizeof(expected) / sizeof(expected[0])); int i; for (i = 0; i < state.size; ++i) { TF_LITE_MICRO_EXPECT_EQ(state.output[i], expected[i]); } WindowFreeStateContents(&state); } TF_LITE_MICRO_TEST(WindowState_CheckNotEnoughSamples) { WindowTestConfig config; struct WindowState state; TF_LITE_MICRO_EXPECT( WindowPopulateState(&config.config_, &state, kSampleRate)); size_t num_samples_read; TF_LITE_MICRO_EXPECT(WindowProcessSamples( &state, kFakeAudioData, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]), &num_samples_read)); TF_LITE_MICRO_EXPECT(WindowProcessSamples( &state, kFakeAudioData + kWindowSamples, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) - kWindowSamples, &num_samples_read)); TF_LITE_MICRO_EXPECT_EQ( false, WindowProcessSamples( &state, kFakeAudioData + kWindowSamples + kStepSamples, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) - kWindowSamples - kStepSamples, &num_samples_read)); TF_LITE_MICRO_EXPECT_EQ( state.input_used, sizeof(kFakeAudioData) / sizeof(kFakeAudioData[0]) - 2 * kStepSamples); WindowFreeStateContents(&state); } TF_LITE_MICRO_TESTS_END
6,252
2,563
// Chapter 4 Exercises #include <iostream> #include <string> #include <vector> #include <algorithm> #include <cctype> using namespace std; int main() { cout << "\tChapter43 Exercises\n\n"; // Question 1 vector<string> gameList; vector<string>::iterator myIterator; vector<string>::const_iterator iter; cout << "Question 1\n"; cout << "Favorite Games List:\n\n"; cout << "Action Options:\n"; cout << "'List' - list all game titles\n"; cout << "'Add' - add a game title\n"; cout << "'Remove' - remove a game title\n"; cout << "'Quit' - quit the program\n"; string action; string gameTitle; // main loop while (action != "QUIT") { cout << "\nAction: "; cin >> action; if (action == "LIST") { cout << "\nFavorite Game:\n"; for (iter = gameList.begin(); iter != gameList.end(); ++iter) { cout << *iter << endl; } } else if (action == "ADD") { cout << "\nAdd Game: "; cin >> gameTitle; gameList.push_back(gameTitle); cout << "\nFavorite Game:\n"; for (iter = gameList.begin(); iter < gameList.end(); ++iter) { cout << *iter << endl; } } else if (action == "REMOVE") { cout << "\nRemove Game: "; cin >> gameTitle; myIterator = find(gameList.begin(), gameList.end(), gameTitle); if (myIterator != gameList.end()) { gameList.erase(myIterator); cout << "\nFavorite Game:\n"; for (iter = gameList.begin(); iter < gameList.end(); ++iter) { cout << *iter << endl; } } else { cout << "\nGame title not found. Try Again."; } } } // Question 2 cout << "Question 2\n\n"; vector<int> scores(5,0); vector<int>::iterator myIter2; vector<int>::const_iterator iter2; // increment each score for (myIter2 = scores.begin(); myIter2 != scores.end(); ++myIter2) { (*myIter2)++; } cout << "Scores:\n"; for (iter2 = scores.begin(); iter2 != scores.end(); ++iter2) { cout << *iter2 << endl; } return 0; }
2,046
849
#include "pch.h" #include "buffer.h" #include "renderer/opengl/opengl_vertex_array.h" #include "renderer/renderer.h" namespace Maki { VertexArray* VertexArray::create() { switch(Renderer::get_renderer_impl()) { case Renderer::Implementation::none: MAKI_RAISE_CRITICAL("Renderer::Implementation::none is not supported."); return nullptr; case Renderer::Implementation::opengl: return new OpenGLVertexArray(); default: MAKI_RAISE_CRITICAL("The requested renderer implementation is not supported."); return nullptr; } } } // namespace Maki
602
193
// Массивы.cpp: главный файл проекта. #include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; int main() { float a[10]; float proiz = 1.0; int i, n, k = 0; cout << "Vvedite elementi massiva cherez enter:" << endl; for (i = 0; i < 10; i++) { cin >> a[i]; } for (i = 0; i < 10; i++) { cout << a[i] << " "; } cout << "\nVvedite chislo N:" << endl; cin >> n; for (i = 0; i < 10; i++) { if (a[i] > n) { k++; proiz *= a[i]; }; } cout << "Proizvedenie elementov massiva = " << proiz << endl; cout << "Kol-vo elementov bolshih chisla = " << k << endl; getch(); return 0; }
653
312
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include <boost/test/unit_test.hpp> #include "Common/boost-taef.h" #include "TStoreTestBase.h" #define ALLOC_TAG 'ssTP' namespace TStoreTests { class StoreTransactionTest : public TStoreTestBase<LONG64, KBuffer::SPtr, LongComparer, TestStateSerializer<LONG64>, KBufferSerializer> { public: StoreTransactionTest() { Setup(1); Store->EnableSweep = false; } ~StoreTransactionTest() { Cleanup(); } KBuffer::SPtr CreateBuffer(__in LONG64 size, __in byte fillValue=0xb6) { CODING_ERROR_ASSERT(size >= 0); KBuffer::SPtr bufferSPtr = nullptr; NTSTATUS status = KBuffer::Create(static_cast<ULONG>(size), bufferSPtr, GetAllocator()); CODING_ERROR_ASSERT(NT_SUCCESS(status)); byte* buffer = static_cast<byte *>(bufferSPtr->GetBuffer()); memset(buffer, fillValue, static_cast<ULONG>(size)); return bufferSPtr; } ktl::Awaitable<void> AbortTxnInBackground(WriteTransaction<LONG64, KBuffer::SPtr> & txn) { co_await CorHelper::ThreadPoolThread(GetAllocator().GetKtlSystem().DefaultSystemThreadPool()); txn.StoreTransactionSPtr->Unlock(); } ktl::Awaitable<void> VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition() { long key1 = 17; long key2 = 18; KBuffer::SPtr value = CreateBuffer(4); { auto txn = CreateWriteTransaction(); co_await Store->AddAsync(*txn->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None); co_await Store->AddAsync(*txn->StoreTransactionSPtr, key2, value, DefaultTimeout, CancellationToken::None); co_await txn->CommitAsync(); } auto txn1 = CreateWriteTransaction(); co_await Store->ConditionalUpdateAsync(*txn1->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None); auto abortTask = AbortTxnInBackground(*txn1); try { co_await Store->ConditionalUpdateAsync(*txn1->StoreTransactionSPtr, key2, value, DefaultTimeout, CancellationToken::None); } catch (ktl::Exception const & e) { CODING_ERROR_ASSERT(e.GetStatus() == SF_STATUS_TRANSACTION_ABORTED); } co_await abortTask; // Dispose txn txn1 = nullptr; // If the abort of txn above does not do a proper cleanup, get on lock key2 will see a timeout exception { KeyValuePair<LONG64, KBuffer::SPtr> kvp; auto txn = CreateWriteTransaction(); txn->StoreTransactionSPtr->ReadIsolationLevel = StoreTransactionReadIsolationLevel::ReadRepeatable; co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, key1, DefaultTimeout, kvp, CancellationToken::None); co_await Store->ConditionalGetAsync(*txn->StoreTransactionSPtr, key2, DefaultTimeout, kvp, CancellationToken::None); co_await txn->CommitAsync(); } } ktl::Awaitable<void> VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition() { long key1 = 17; long key2 = 18; KBuffer::SPtr value = CreateBuffer(4); { auto txn = CreateWriteTransaction(); co_await Store->AddAsync(*txn->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None); co_await Store->AddAsync(*txn->StoreTransactionSPtr, key2, value, DefaultTimeout, CancellationToken::None); co_await txn->CommitAsync(); } auto txn1 = CreateWriteTransaction(); auto updateTask = Store->ConditionalUpdateAsync(*txn1->StoreTransactionSPtr, key1, value, DefaultTimeout, CancellationToken::None); auto abortTask = AbortTxnInBackground(*txn1); try { await updateTask; } catch (ktl::Exception const & e) { CODING_ERROR_ASSERT(e.GetStatus() == SF_STATUS_TRANSACTION_ABORTED); } await abortTask; // Dispose txn txn1 = nullptr; // If the abort of txn above does not do a proper cleanup, prime lock will timeout co_await Store->LockManagerSPtr->AcquirePrimeLockAsync(LockMode::Exclusive, Common::TimeSpan::FromSeconds(1)); Store->LockManagerSPtr->ReleasePrimeLock(LockMode::Exclusive); } #pragma region test functions public: ktl::Awaitable<void> VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test() { co_await VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition(); co_return; } ktl::Awaitable<void> VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test() { co_await VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquisition(); co_return; } #pragma endregion }; BOOST_FIXTURE_TEST_SUITE(StoreTransactionTestSuite, StoreTransactionTest) BOOST_AUTO_TEST_CASE(VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion) { SyncAwait(VerifyKeyLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test()); } BOOST_AUTO_TEST_CASE(VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion) { SyncAwait(VerifyPrimeLockIsReleasedIfTxnIsAbortedBeforeLockAcquistion_Test()); } BOOST_AUTO_TEST_SUITE_END() }
6,038
1,744
/** ****************************************************************************** * This file is part of the TouchGFX 4.13.0 distribution. * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef DISPLAYTRANSFORMATION_HPP #define DISPLAYTRANSFORMATION_HPP #include <touchgfx/hal/Types.hpp> namespace touchgfx { /** * @class DisplayTransformation DisplayTransformation.hpp touchgfx/transforms/DisplayTransformation.hpp * * @brief Defines transformations from display space to frame buffer space. * * Defines transformations from display space to frame buffer space. The display might * be (considered) in portrait mode from 0,0 to 272,480, while the actual frame buffer * is from 0,0 to 480,272. This class handles the transformations. */ class DisplayTransformation { public: /** * @fn static void DisplayTransformation::transformDisplayToFrameBuffer(int16_t& x, int16_t& y); * * @brief Transform x,y from display to frame buffer coordinates. * * Transform x,y from display to frame buffer coordinates. * * @param [in,out] x the x part to translate. * @param [in,out] y the y part to translate. */ static void transformDisplayToFrameBuffer(int16_t& x, int16_t& y); /** * @fn static void DisplayTransformation::transformDisplayToFrameBuffer(float& x, float& y); * * @brief Transform x,y from display to frame buffer coordinates. * * Transform x,y from display to frame buffer coordinates. * * @param [in,out] x the x part to translate. * @param [in,out] y the y part to translate. */ static void transformDisplayToFrameBuffer(float& x, float& y); /** * @fn static void DisplayTransformation::transformFrameBufferToDisplay(int16_t& x, int16_t& y); * * @brief Transform x,y from frame buffer to display coordinates. * * Transform x,y from frame buffer to display coordinates. * * @param [in,out] x the x part to translate. * @param [in,out] y the y part to translate. */ static void transformFrameBufferToDisplay(int16_t& x, int16_t& y); /** * @fn static void DisplayTransformation::transformDisplayToFrameBuffer(int16_t& x, int16_t& y, const Rect& in); * * @brief Transform x,y from coordinates relative to the in rect to frame buffer coordinates. * * Transform x,y from coordinates relative to the in rect to frame buffer * coordinates. * * @param [in,out] x the x part to translate. * @param [in,out] y the y part to translate. * @param in the rectangle defining the coordinate space. */ static void transformDisplayToFrameBuffer(int16_t& x, int16_t& y, const Rect& in); /** * @fn static void DisplayTransformation::transformDisplayToFrameBuffer(float& x, float& y, const Rect& in); * * @brief Transform x,y from coordinates relative to the in rect to frame buffer coordinates. * * Transform x,y from coordinates relative to the in rect to frame buffer * coordinates. * * @param [in,out] x the x part to translate. * @param [in,out] y the y part to translate. * @param in the rectangle defining the coordinate space. */ static void transformDisplayToFrameBuffer(float& x, float& y, const Rect& in); /** * @fn static void DisplayTransformation::transformDisplayToFrameBuffer(Rect& r); * * @brief Transform rectangle from display to frame buffer coordinates. * * Transform rectangle from display to frame buffer coordinates. * * @param [in,out] r the rectangle to translate. */ static void transformDisplayToFrameBuffer(Rect& r); /** * @fn static void DisplayTransformation::transformFrameBufferToDisplay(Rect& r); * * @brief Transform rectangle from frame buffer to display coordinates. * * Transform rectangle from frame buffer to display coordinates. * * @param [in,out] r the rectangle to translate. */ static void transformFrameBufferToDisplay(Rect& r); /** * @fn static void DisplayTransformation::transformDisplayToFrameBuffer(Rect& r, const Rect& in); * * @brief Transform rectangle r from coordinates relative to the in rect to frame buffer * coordinates. * * Transform rectangle r from coordinates relative to the in rect to frame buffer * coordinates. * * @param [in,out] r the rectangle to translate. * @param in the rectangle defining the coordinate space. */ static void transformDisplayToFrameBuffer(Rect& r, const Rect& in); }; } // namespace touchgfx #endif // DISPLAYTRANSFORMATION_HPP
5,215
1,474
#ifndef ZIPPER_ITERATOR_HPP #define ZIPPER_ITERATOR_HPP #include <tuple> #include <optional> namespace ecs::containers { template<class ...T> class zipper; } namespace ecs::iterators { /** * @brief This class defines an iterator instantiated by the zipper class. it's intended to be used in a range based * loop or a simple for. * @tparam Containers This variadic template refers to the types to bind the iterator. */ template<class ...Containers> class zipper_iterator { template<class Container> using iterator_t = typename Container::iterator; template<class Container> using it_reference_t = decltype(std::declval<typename iterator_t<Container>::reference>().value()); public: using value_type = std::tuple<it_reference_t<Containers>...>; using reference = value_type &; using pointer = void; using difference_type = std::size_t; using iterator_category = std::input_iterator_tag; using iterator_tuple = std::tuple<iterator_t<Containers>...>; friend ecs::containers::zipper<Containers ...>; zipper_iterator(zipper_iterator const &z) noexcept : _max(z._max), _idx(z._idx), _current(z._current) {} const zipper_iterator &operator++() //TODO fix this magic { if (_max == 0) return (*this); if (_idx == _max - 1) { _incrAll(_seq); _idx++; } else if (_idx < _max - 1) do { _incrAll(_seq); _idx += 1; } while (!_allSet(_seq) && _idx < _max - 1); if (_idx == _max - 1 && !_allSet(_seq)) { _incrAll(_seq); _idx++; } return (*this); } zipper_iterator operator++(int) { zipper_iterator<Containers...> old = *this; operator++(); return (old); } value_type operator*() { return (_toValue(_seq)); } value_type operator->() { return (_toValue(_seq)); } friend inline bool operator==(zipper_iterator const &lhs, zipper_iterator const &rhs) { return ((lhs._max - lhs._idx) == (rhs._max - rhs._idx)); } friend inline bool operator!=(zipper_iterator const &lhs, zipper_iterator const &rhs) { return ((lhs._max - lhs._idx) != (rhs._max - rhs._idx)); } private: iterator_tuple _current; std::size_t _max; std::size_t _idx{}; static constexpr std::index_sequence_for<Containers ...> _seq{}; template<size_t ... Is> void _incrAll(std::index_sequence<Is ...>) { ((++std::get<Is>(_current)), ...); } template<size_t ... Is> [[nodiscard]] bool _allSet(std::index_sequence<Is ...>) { return (((*std::get<Is>(_current)) != std::nullopt) && ...); } template<size_t ... Is> [[nodiscard]] value_type _toValue(std::index_sequence<Is ...>) { return std::tie(std::get<Is>(_current)->value()...); } zipper_iterator(iterator_tuple const &it_tuple, std::size_t max) : _current(it_tuple), _max(max) { if (_max > 0 && !_allSet(_seq)) this->operator++(); } }; } #endif //ZIPPER_ITERATOR_HPP
3,919
1,111
#include "simulate_bayer_mosaic.h" void simulate_bayer_mosaic( const std::vector<unsigned char> & rgb, const int & width, const int & height, std::vector<unsigned char> & bayer) { bayer.resize(width*height); //////////////////////////////////////////////////////////////////////////// // Add your code here if (width == 0 || height == 0) { throw("Image must have proper dimentions"); } /** * Idea: Start in the upper left corner (green) and since it is an alternating * square pattern, we can use even/odd indices to determine the color */ int green_blue, red_green; int pxl_idx = 0; for (int row = 0; row < height; row++) { if (row % 2 == 0) { // Then we are on an even row, so we alternate g, b, g, b, ... green_blue = 0; for (int col = 0; col < width; col++) { if (green_blue++ % 2 == 0) { // Then we are on a green square bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 1]; } else { // Then we are on a blue square bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 2]; } } } else { // Then we are on an odd row, so we alternate r, g, r, g, ... red_green = 0; for (int col = 0; col < width; col++) { if (red_green++ % 2 == 0) { // Then we are on a red square bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 0]; } else { // Then we are on a green square bayer[pxl_idx++] = rgb[(row * width + col) * 3 + 1]; } } } } /** * NOTE: When we are indexing a pixel here (i.e. green = rgb[(row * width + col) * 3 + 1];) * (row * width + col) is the index of the pixel we want, then we multiply by * 3 since we know we are indexing a 3-channel pixel, then we add 1 to get the * green subpixel in this case. This is different than the way we indexed * in rgb_to_gray.cpp */ //////////////////////////////////////////////////////////////////////////// }
1,989
676
// // Created by aydoganmusa on 22.11.18. // #include <libgba-sprite-engine/sprites/sprite.h> #include <libgba-sprite-engine/sprites/sprite_builder.h> #include <libgba-sprite-engine/gba_engine.h> #include "fighting_scene.h" #include "goku_spritedata.h" #include "yamcha_spritedata.h" #include "lifebar_spritedata.h" #include "energybar_spritedata.h" #include "wave_spritedata.h" #include "shared.h" #include "tournament.h" #include "attack0.h" #include "attack1.h" #include "victory.h" #include "blast_fullpower.h" std::vector<Sprite *> FightingScene::sprites() { std::vector<Sprite *> sprites; sprites.push_back(goku_object->getSpriteWaveGoku()); sprites.push_back(goku_object->getSpriteGoku()); sprites.push_back(yamcha_object->getSpriteYamcha()); sprites.push_back(goku_object->getSpriteLifebarGoku()); sprites.push_back(yamcha_object->getSpriteLifebarYamcha()); sprites.push_back(goku_object->getSpriteEnergybarGoku()); sprites.push_back(yamcha_object->getSpriteEnergybarYamcha()); return {sprites}; } std::vector<Background *> FightingScene::backgrounds() { return {bg.get()}; } void FightingScene::load() { foregroundPalette = std::unique_ptr<ForegroundPaletteManager>( new ForegroundPaletteManager(sharedPal, sizeof(sharedPal))); backgroundPalette = std::unique_ptr<BackgroundPaletteManager>( new BackgroundPaletteManager(tournamentPal, sizeof(tournamentPal))); SpriteBuilder<Sprite> Builder; goku = Builder .withData(gokuTiles, sizeof(gokuTiles)) .withSize(SIZE_32_32) .withAnimated(6, 3) .withLocation(16, GBA_SCREEN_HEIGHT / 2 + 32) .withinBounds() .buildPtr(); goku->animateToFrame(0); goku->stopAnimating(); yamcha = Builder .withData(yamchaTiles, sizeof(yamchaTiles)) .withSize(SIZE_32_32) .withAnimated(2, 3) .withLocation(GBA_SCREEN_WIDTH - 32, GBA_SCREEN_HEIGHT / 2 + 32) .withinBounds() .buildPtr(); yamcha->animateToFrame(1); yamcha->stopAnimating(); lifebar_yamcha = Builder .withData(lifebarTiles, sizeof(lifebarTiles)) .withSize(SIZE_32_8) .withAnimated(4, 3) .withLocation(GBA_SCREEN_WIDTH - 36, 12) .withinBounds() .buildPtr(); lifebar_yamcha->animateToFrame(0); lifebar_yamcha->stopAnimating(); lifebar_goku = Builder .withData(lifebarTiles, sizeof(lifebarTiles)) .withSize(SIZE_32_8) .withAnimated(4, 3) .withLocation(4, 12) .withinBounds() .buildPtr(); lifebar_goku->animateToFrame(0); lifebar_goku->stopAnimating(); energybar_goku = Builder .withData(energybarTiles, sizeof(energybarTiles)) .withSize(SIZE_32_8) .withAnimated(4, 3) .withLocation(4, 20) .withinBounds() .buildPtr(); energybar_goku->animateToFrame(0); energybar_goku->stopAnimating(); energybar_yamcha = Builder .withData(energybarTiles, sizeof(energybarTiles)) .withSize(SIZE_32_8) .withAnimated(4, 3) .withLocation(GBA_SCREEN_WIDTH - 36, 20) .withinBounds() .buildPtr(); energybar_yamcha->animateToFrame(0); energybar_yamcha->stopAnimating(); wave = Builder .withData(waveTiles, sizeof(waveTiles)) .withSize(SIZE_64_32) .withLocation(-64, -32) .withinBounds() .buildPtr(); bg = std::unique_ptr<Background>( new Background(0, tournamentTiles, sizeof(tournamentTiles), tournamentMap, sizeof(tournamentMap))); bg.get()->useMapScreenBlock(20); yamcha_object = std::unique_ptr<Yamcha>( new Yamcha(std::move(yamcha), std::move(lifebar_yamcha), std::move(energybar_yamcha))); goku_object = std::unique_ptr<Goku>( new Goku(std::move(goku), std::move(lifebar_goku), std::move(wave), std::move(energybar_goku))); } void FightingScene::tick(u16 keys) { if (gameEnd) { if (keys & KEY_START) { goku_object->resetGoku(); yamcha_object->resetYamcha(); engine->enqueueSound(victory_sound, sizeof(victory_sound), 15700); gameEnd = false; } } else { goku_object->tick(); yamcha_object->tick(); if (keys & KEY_LEFT) { if (!(goku_object->getMoveLeft())) { goku_object->setMoveLeft(true); } } else if (keys & KEY_RIGHT) { if (!(goku_object->getMoveRight())) { goku_object->setMoveRight(true); } } else if (keys & KEY_A) { if (!(goku_object->getHit())) { goku_object->setHit(true); engine->enqueueSound(attack0_sound, sizeof(attack0_sound), 15768); } else { if (goku_object->getSpriteGoku()->collidesWith(*(yamcha_object->getSpriteYamcha()))) { yamcha_object->gotHurt(); } } } else if (keys & KEY_B) { if (!(goku_object->getKick())) { goku_object->setKick(true); engine->enqueueSound(attack1_sound, sizeof(attack1_sound), 15768); } else { if (goku_object->getSpriteGoku()->collidesWith(*(yamcha_object->getSpriteYamcha()))) { yamcha_object->gotHurt(); } } } else if (keys & KEY_UP) { if (goku_object->getSpriteWaveGoku()->collidesWith(*(yamcha_object->getSpriteYamcha()))) { yamcha_object->gotHurt(); } if (goku_object->getSpecialAttack()) { engine->enqueueSound(blast_fullpower, sizeof(blast_fullpower), 15768); goku_object->setChargeSpecialAttack(false); } else { goku_object->setChargeSpecialAttack(true); } } else if (yamcha_object->isdood() || goku_object->getDood()) { gameEnd = true; return; } else { goku_object->setMoveLeft(false); goku_object->setMoveRight(false); goku_object->setHit(false); goku_object->setKick(false); goku_object->setChargeSpecialAttack(false); goku_object->setSpecialAttack(false); yamcha_object->notGotHurt(); } } }
6,540
2,268
/* Vector math for libostd. * * This file is part of libostd. See COPYING.md for futher information. */ #ifndef OSTD_VECMATH_HH #define OSTD_VECMATH_HH #include <cstddef> namespace ostd { template<typename T> struct vec2 { union { struct { T x, y; }; T value[2]; }; vec2(): x(0), y(0) {} vec2(vec2 const &v): x(v.x), y(v.y) {} vec2(T v): x(v), y(v) {} vec2(T x, T y): x(x), y(y) {} T &operator[](std::size_t idx) { return value[idx]; } T operator[](std::size_t idx) const { return value[idx]; } vec2 &add(T v) { x += v; y += v; return *this; } vec2 &add(vec2 const &o) { x += o.x; y += o.y; return *this; } vec2 &sub(T v) { x -= v; y -= v; return *this; } vec2 &sub(vec2 const &o) { x -= o.x; y -= o.y; return *this; } vec2 &mul(T v) { x *= v; y *= v; return *this; } vec2 &mul(vec2 const &o) { x *= o.x; y *= o.y; return *this; } vec2 &div(T v) { x /= v; y /= v; return *this; } vec2 &div(vec2 const &o) { x /= o.x; y /= o.y; return *this; } vec2 &neg() { x = -x; y = -y; return *this; } bool is_zero() const { return (x == 0) && (y == 0); } T dot(vec2<T> const &o) const { return (x * o.x) + (y * o.y); } }; template<typename T> inline bool operator==(vec2<T> const &a, vec2<T> const &b) { return (a.x == b.x) && (a.y == b.y); } template<typename T> inline bool operator!=(vec2<T> const &a, vec2<T> const &b) { return (a.x != b.x) || (a.y != b.y); } template<typename T> inline vec2<T> operator+(vec2<T> const &a, vec2<T> const &b) { return vec2<T>(a).add(b); } template<typename T> inline vec2<T> operator+(vec2<T> const &a, T b) { return vec2<T>(a).add(b); } template<typename T> inline vec2<T> operator-(vec2<T> const &a, vec2<T> const &b) { return vec2<T>(a).sub(b); } template<typename T> inline vec2<T> operator-(vec2<T> const &a, T b) { return vec2<T>(a).sub(b); } template<typename T> inline vec2<T> operator*(vec2<T> const &a, vec2<T> const &b) { return vec2<T>(a).mul(b); } template<typename T> inline vec2<T> operator*(vec2<T> const &a, T b) { return vec2<T>(a).mul(b); } template<typename T> inline vec2<T> operator/(vec2<T> const &a, vec2<T> const &b) { return vec2<T>(a).div(b); } template<typename T> inline vec2<T> operator/(vec2<T> const &a, T b) { return vec2<T>(a).div(b); } template<typename T> inline vec2<T> operator-(vec2<T> const &a) { return vec2<T>(a).neg(); } using vec2f = vec2<float>; using vec2d = vec2<double>; using vec2b = vec2<unsigned char>; using vec2i = vec2<int>; template<typename T> struct vec3 { union { struct { T x, y, z; }; struct { T r, g, b; }; T value[3]; }; vec3(): x(0), y(0), z(0) {} vec3(vec3 const &v): x(v.x), y(v.y), z(v.z) {} vec3(T v): x(v), y(v), z(v) {} vec3(T x, T y, T z): x(x), y(y), z(z) {} T &operator[](std::size_t idx) { return value[idx]; } T operator[](std::size_t idx) const { return value[idx]; } vec3 &add(T v) { x += v; y += v; z += v; return *this; } vec3 &add(vec3 const &o) { x += o.x; y += o.y; z += o.z; return *this; } vec3 &sub(T v) { x -= v; y -= v; z -= v; return *this; } vec3 &sub(vec3 const &o) { x -= o.x; y -= o.y; z -= o.z; return *this; } vec3 &mul(T v) { x *= v; y *= v; z *= v; return *this; } vec3 &mul(vec3 const &o) { x *= o.x; y *= o.y; z *= o.z; return *this; } vec3 &div(T v) { x /= v; y /= v; z /= v; return *this; } vec3 &div(vec3 const &o) { x /= o.x; y /= o.y; z /= o.z; return *this; } vec3 &neg() { x = -x; y = -y; z = -z; return *this; } bool is_zero() const { return (x == 0) && (y == 0) && (z == 0); } T dot(vec3<T> const &o) const { return (x * o.x) + (y * o.y) + (z * o.z); } }; template<typename T> inline bool operator==(vec3<T> const &a, vec3<T> const &b) { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z); } template<typename T> inline bool operator!=(vec3<T> const &a, vec3<T> const &b) { return (a.x != b.x) || (a.y != b.y) || (a.z != b.z); } template<typename T> inline vec3<T> operator+(vec3<T> const &a, vec3<T> const &b) { return vec3<T>(a).add(b); } template<typename T> inline vec3<T> operator+(vec3<T> const &a, T b) { return vec3<T>(a).add(b); } template<typename T> inline vec3<T> operator-(vec3<T> const &a, vec3<T> const &b) { return vec3<T>(a).sub(b); } template<typename T> inline vec3<T> operator-(vec3<T> const &a, T b) { return vec3<T>(a).sub(b); } template<typename T> inline vec3<T> operator*(vec3<T> const &a, vec3<T> const &b) { return vec3<T>(a).mul(b); } template<typename T> inline vec3<T> operator*(vec3<T> const &a, T b) { return vec3<T>(a).mul(b); } template<typename T> inline vec3<T> operator/(vec3<T> const &a, vec3<T> const &b) { return vec3<T>(a).div(b); } template<typename T> inline vec3<T> operator/(vec3<T> const &a, T b) { return vec3<T>(a).div(b); } template<typename T> inline vec3<T> operator-(vec3<T> const &a) { return vec3<T>(a).neg(); } using vec3f = vec3<float>; using vec3d = vec3<double>; using vec3b = vec3<unsigned char>; using vec3i = vec3<int>; template<typename T> struct vec4 { union { struct { T x, y, z, w; }; struct { T r, g, b, a; }; T value[4]; }; vec4(): x(0), y(0), z(0), w(0) {} vec4(vec4 const &v): x(v.x), y(v.y), z(v.z), w(v.w) {} vec4(T v): x(v), y(v), z(v), w(v) {} vec4(T x, T y, T z, T w): x(x), y(y), z(z), w(w) {} T &operator[](std::size_t idx) { return value[idx]; } T operator[](std::size_t idx) const { return value[idx]; } vec4 &add(T v) { x += v; y += v; z += v; w += v; return *this; } vec4 &add(vec4 const &o) { x += o.x; y += o.y; z += o.z; w += o.w; return *this; } vec4 &sub(T v) { x -= v; y -= v; z -= v; w -= v; return *this; } vec4 &sub(vec4 const &o) { x -= o.x; y -= o.y; z -= o.z; w -= o.w; return *this; } vec4 &mul(T v) { x *= v; y *= v; z *= v; w *= v; return *this; } vec4 &mul(vec4 const &o) { x *= o.x; y *= o.y; z *= o.z; w *= o.w; return *this; } vec4 &div(T v) { x /= v; y /= v; z /= v; w /= v; return *this; } vec4 &div(vec4 const &o) { x /= o.x; y /= o.y; z /= o.z; w /= o.w; return *this; } vec4 &neg() { x = -x; y = -y; z = -z; w = -w; return *this; } bool is_zero() const { return (x == 0) && (y == 0) && (z == 0) && (w == 0); } T dot(vec4<T> const &o) const { return (x * o.x) + (y * o.y) + (z * o.z) + (w * o.w); } }; template<typename T> inline bool operator==(vec4<T> const &a, vec4<T> const &b) { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w); } template<typename T> inline bool operator!=(vec4<T> const &a, vec4<T> const &b) { return (a.x != b.x) || (a.y != b.y) || (a.z != b.z) || (a.w != b.w); } template<typename T> inline vec4<T> operator+(vec4<T> const &a, vec4<T> const &b) { return vec4<T>(a).add(b); } template<typename T> inline vec4<T> operator+(vec4<T> const &a, T b) { return vec4<T>(a).add(b); } template<typename T> inline vec4<T> operator-(vec4<T> const &a, vec4<T> const &b) { return vec4<T>(a).sub(b); } template<typename T> inline vec4<T> operator-(vec4<T> const &a, T b) { return vec4<T>(a).sub(b); } template<typename T> inline vec4<T> operator*(vec4<T> const &a, vec4<T> const &b) { return vec4<T>(a).mul(b); } template<typename T> inline vec4<T> operator*(vec4<T> const &a, T b) { return vec4<T>(a).mul(b); } template<typename T> inline vec4<T> operator/(vec4<T> const &a, vec4<T> const &b) { return vec4<T>(a).div(b); } template<typename T> inline vec4<T> operator/(vec4<T> const &a, T b) { return vec4<T>(a).div(b); } template<typename T> inline vec4<T> operator-(vec4<T> const &a) { return vec4<T>(a).neg(); } using vec4f = vec4<float>; using vec4d = vec4<double>; using vec4b = vec4<unsigned char>; using vec4i = vec4<int>; } /* namespace ostd */ #endif
8,556
3,794
#ifndef __GDRIVE_REQUEST_HPP__ #define __GDRIVE_REQUEST_HPP__ #include "gdrive/config.hpp" #include "common/all.hpp" #include <string> #include <map> #include <vector> #include <curl/curl.h> namespace GDRIVE { enum RequestMethod { RM_GET, RM_POST, RM_PUT, RM_DELETE, RM_PATCH }; enum EncodeMethod { EM_URL, EM_JSON, }; typedef std::map<std::string, std::string> RequestHeader; typedef std::map<std::string, std::string> RequestQuery; typedef size_t (*ReadFunction) (void*, size_t, size_t, void*); class HttpResponse; class HttpRequest; class MemoryString { public: MemoryString(const char* str, int size) :_str(str), _size(size), _pos(0) {} static size_t read(void* ptr, size_t size, size_t nmemb, void* userp) { MemoryString* self = (MemoryString*)userp; if (self->_size - self->_pos == 0) return 0; int length = self->_size - self->_pos > size * nmemb ? size * nmemb : self->_size - self->_pos; memcpy(ptr, self->_str + self->_pos, length); self->_pos += length; return length; } private: const char* _str; int _size; int _pos; }; class HttpResponse { CLASS_MAKE_LOGGER public: HttpResponse() { _header_map.clear(); } static size_t curl_write_callback(void* content, size_t size, size_t nmemb, void* userp); inline std::string content() const { return _content; }; inline std::string header() const { return _header; }; inline void clear() { _content = ""; _header = ""; _header_map.clear(); } inline int status() const { return _status; } inline void set_status(int status) { _status = status;} std::string get_header(std::string field); void _parse_header(); private: std::string _content; std::string _header; int _status; std::map<std::string, std::string> _header_map; friend class HttpRequest; }; class HttpRequest { CLASS_MAKE_LOGGER public: HttpRequest(std::string uri, RequestMethod method); HttpRequest(std::string uri, RequestMethod method, RequestHeader& header, std::string body); void add_header(RequestHeader &header); void add_header(std::string key, std::string value); void add_query(RequestQuery& query); void add_query(std::string key, std::string value); inline void clear_header() { _header.clear();} inline void clear_query() { _query.clear(); } void clear(); void set_uri(std::string uri); HttpResponse& request(); inline HttpResponse& response() { return _resp;} ~HttpRequest(); protected: std::string _uri; RequestMethod _method; RequestHeader _header; RequestQuery _query; std::string _body; HttpResponse _resp; CURL *_handle; ReadFunction _read_hook; void* _read_context; void _init_curl_handle(); curl_slist* _build_header(); }; } #endif
3,080
950
#include <modelo/include/RelacionesFecha.h> using namespace visualizador::modelo::relaciones; using namespace visualizador::modelo; using namespace visualizador; RelacionesFecha::RelacionesFecha(herramientas::utiles::ID* id_fecha) : IRelaciones(id_fecha, aplicacion::ConfiguracionAplicacion::prefijoRelacionesFecha()), IRelacionConPeriodos(new RelacionConGrupo()) { } RelacionesFecha::~RelacionesFecha() { } // GETTERS // getters de IAlmacenable std::string RelacionesFecha::getValorAlmacenable() { this->armarJson(); return this->getJson()->jsonString(); } // SETTERS // METODOS // metodos de IAlmacenable void RelacionesFecha::parsearValorAlmacenable(std::string valor_almacenable) { herramientas::utiles::Json * json_almacenable = new herramientas::utiles::Json(valor_almacenable); this->setJson(json_almacenable); this->parsearJson(); } std::string RelacionesFecha::prefijoGrupo() { return aplicacion::ConfiguracionAplicacion::prefijoRelacionesFecha(); } unsigned long long int RelacionesFecha::hashcode() { return this->getRelacionConPeriodos()->hashcode(); } // metodos de IContieneJson bool RelacionesFecha::armarJson() { herramientas::utiles::Json * relaciones_fecha = new herramientas::utiles::Json(); relaciones_fecha->agregarAtributoArray("ids_periodos", this->getRelacionConPeriodos()->getIdsGrupoComoUint()); this->getJson()->reset(); this->getJson()->agregarAtributoJson("relaciones_fecha", relaciones_fecha); delete relaciones_fecha; return true; } bool RelacionesFecha::parsearJson() { herramientas::utiles::Json * json_relaciones_fecha = this->getJson()->getAtributoValorJson("relaciones_fecha"); std::vector<unsigned long long int> ids_periodos = json_relaciones_fecha->getAtributoArrayUint("ids_periodos"); for (std::vector<unsigned long long int>::iterator it = ids_periodos.begin(); it != ids_periodos.end(); it++) { this->getRelacionConPeriodos()->agregarRelacion(*it); } delete json_relaciones_fecha; return true; } IRelaciones * RelacionesFecha::clonar() { RelacionesFecha * clon = new RelacionesFecha(this->getId()->copia()); std::vector<herramientas::utiles::ID*> ids_periodos = this->getRelacionConPeriodos()->getIdsGrupo(); for (std::vector<herramientas::utiles::ID*>::iterator it = ids_periodos.begin(); it != ids_periodos.end(); it++) { clon->agregarRelacionConPeriodo(*it); } return clon; }
2,579
921
#ifndef GCD_HPP #define GCD_HPP namespace TADSF { constexpr int gcd(int a, int b) { if (a > b) { a ^= b ^= a ^= b; // constexpr alternative to std::swap(a, b) } while (b%a) { b %= a; a ^= b ^= a ^= b; } return a; } constexpr int ctpow(int base, int exp) { int acc = 1; while(exp) { if (exp%2) { acc *= base; } exp >>= 1; base <<= 1; } return acc; } } #endif
467
201
#pragma once #include "element/box.hpp" #include "element/button.hpp" #include "element/flow.hpp" #include "element/frame.hpp" #include "element/image.hpp" #include "element/label.hpp" #include "element/mouse_action.hpp" #include "element/multiplex.hpp" #include "element/widget.hpp"
285
99
#ifndef METAL_MAP_ERASE_KEY_HPP #define METAL_MAP_ERASE_KEY_HPP #include "../config.hpp" #include "../list/erase.hpp" #include "../map/order.hpp" namespace metal { /// \ingroup map /// /// ### Description /// Removes the entry associated with some key in a \map. /// /// ### Usage /// For any \map `m` and \value `k` /// \code /// using result = metal::erase_key<m, k>; /// \endcode /// /// \returns: \map /// \semantics: /// If `m` associates keys `k_1, ..., k, ..., k_n` to values /// `v_1, ..., v, ..., v_n`, then /// \code /// using result = metal::map< /// metal::pair<k_1, v_1>, ..., metal::pair<k_n, v_n> /// >; /// \endcode /// /// ### Example /// \snippet map.cpp erase_key /// /// ### See Also /// \see map, has_key, at_key, insert_key template<typename seq, typename key> using erase_key = metal::erase<seq, metal::order<seq, key>>; } #endif
1,016
376
#include "data.hh" #include "notify-icon-object.hh" #include <map> #include <mutex> #include <optional> static std::mutex env_datas_mutex; // Must be map<>, not unordered_map<>, for the // guarantee that insert and delete do not invalidate // other elements. static std::map<napi_env, EnvData> env_datas; EnvData* get_env_data(napi_env env) { std::lock_guard lock{env_datas_mutex}; if (auto it = env_datas.find(env); it != env_datas.end()) { return &it->second; } return nullptr; } napi_status EnvData::add_icon(int32_t id, napi_value value, NotifyIconObject* object) { // std::lock_guard icons_lock{icons_mutex}; if (icons.empty()) { NAPI_RETURN_IF_NOT_OK(icon_message_loop.init(this)); } NapiRef ref; NAPI_RETURN_IF_NOT_OK(ref.create(env, value)); auto insert = icons.insert({id, {ref.ref, object->notify_icon.id.callback_id, object->notify_icon.id.guid}}); // If the insert succeeded, don't unref if (insert.second) { ref.release(); } return napi_ok; } using UserCallParam = std::function<LRESULT(HWND, WPARAM)>; bool EnvData::remove_icon(int32_t id) { { // std::lock_guard icons_lock{icons_mutex}; if (auto it = icons.find(id); it == icons.end()) { return false; } else { icons.erase(it); if (icons.empty()) { icon_message_loop.quit(); // ::PostMessageW(msg_hwnd, WM_USER_QUIT, 0, 0); } } } // msg_thread.join(); return true; } void EnvData::notify_select(int32_t icon_id, NotifySelectArgs args) { icon_message_loop.run_on_env_thread.blocking([=](napi_env env, napi_value) { NAPI_FATAL_IF(this->env != env); napi_ref ref; { // std::lock_guard icons_lock{env_data->icons_mutex}; if (auto it = icons.find(icon_id); it != icons.end()) { ref = it->second.ref; } else { return; } } napi_value value; NAPI_THROW_RETURN_VOID_IF_NOT_OK( env, napi_get_reference_value(env, ref, &value)); NotifyIconObject* object; NAPI_THROW_RETURN_VOID_IF_NOT_OK(env, napi_get_value(env, value, &object)); napi_value event; NAPI_THROW_RETURN_VOID_IF_NOT_OK( env, napi_create_object(env, &event, { {"target", value}, {"rightButton", args.right_button}, {"mouseX", args.mouse_x}, {"mouseY", args.mouse_y}, })); object->select_callback(value, {event}); }); } template <typename Fn> napi_status napi_add_env_cleanup_hook(napi_env env, Fn fn) { auto fn_ptr = std::make_unique<Fn>(std::move(fn)); NAPI_RETURN_IF_NOT_OK(napi_add_env_cleanup_hook( env, [](void* ptr) { (*static_cast<Fn*>(ptr))(); }, fn_ptr.get())); fn_ptr.release(); return napi_ok; } std::tuple<napi_status, EnvData*> create_env_data(napi_env env) { // Lock for the whole method just so we know we'll get // a consistent EnvData. std::lock_guard lock{env_datas_mutex}; auto data = &env_datas[env]; data->env = env; if (auto status = data->icon_message_loop.run_on_env_thread.create(env); status != napi_ok) { return {status, nullptr}; } if (auto status = napi_add_env_cleanup_hook(env, [=] { std::lock_guard lock{env_datas_mutex}; // This will also fire all the required // destructors. env_datas.erase(env); }); status != napi_ok) { return {status, nullptr}; } return {napi_ok, data}; } EnvData::~EnvData() { for (auto& pair : icons) { delete_notify_icon( {icon_message_loop.hwnd, pair.second.id, pair.second.guid}); } }
3,994
1,401
#include "range.h" #include "server/range_server.h" #include "watch.h" #include "monitor/statistics.h" namespace sharkstore { namespace dataserver { namespace range { Status Range::GetAndResp( watch::WatcherPtr pWatcher, const watchpb::WatchCreateRequest& req, const std::string &dbKey, const bool &prefix, int64_t &version, watchpb::DsWatchResponse *dsResp) { version = 0; Status ret; if(prefix) { //use iterator std::string dbKeyEnd{""}; dbKeyEnd.assign(dbKey); if (0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) { //to do set error message FLOG_ERROR("GetAndResp:NextComparableBytes error."); return Status(Status::kUnknown); } std::string hashKey(""); WatchUtil::GetHashKey(pWatcher, prefix, meta_.GetTableID(), &hashKey); auto watcherServer = context_->WatchServer(); auto ws = watcherServer->GetWatcherSet_(hashKey); auto result = ws->loadFromDb(store_.get(), watchpb::PUT, dbKey, dbKeyEnd, version, meta_.GetTableID(), dsResp); if (result.first <= 0) { delete dsResp; dsResp = nullptr; } } else { auto resp = dsResp->mutable_resp(); resp->set_watchid(pWatcher->GetWatcherId()); resp->set_code(static_cast<int>(ret.code())); auto evt = resp->add_events(); std::string dbValue(""); ret = store_->Get(dbKey, &dbValue); if (ret.ok()) { evt->set_type(watchpb::PUT); int64_t dbVersion(0); std::string userValue(""); std::string ext(""); watch::Watcher::DecodeValue(&dbVersion, &userValue, &ext, dbValue); auto userKv = new watchpb::WatchKeyValue; for(auto userKey : req.kv().key()) { userKv->add_key(userKey); } userKv->set_value(userValue); userKv->set_version(dbVersion); userKv->set_tableid(meta_.GetTableID()); version = dbVersion; RANGE_LOG_INFO("GetAndResp ok, db_version: [%" PRIu64 "]", dbVersion); } else { evt->set_type(watchpb::DELETE); RANGE_LOG_INFO("GetAndResp code_: %s key:%s", ret.ToString().c_str(), EncodeToHexString(dbKey).c_str()); } } return ret; } void Range::WatchGet(common::ProtoMessage *msg, watchpb::DsWatchRequest &req) { errorpb::Error *err = nullptr; auto btime = get_micro_second(); context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time); auto ds_resp = new watchpb::DsWatchResponse; auto header = ds_resp->mutable_header(); std::string dbKey{""}; std::string dbValue{""}; int64_t dbVersion{0}; auto prefix = req.req().prefix(); auto tmpKv = req.req().kv(); RANGE_LOG_DEBUG("WatchGet begin msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id); do { if (!VerifyLeader(err)) { break; } if( Status::kOk != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchGet, meta_.Get(), tmpKv, dbKey, dbValue, err) ) { break; } FLOG_DEBUG("range[%" PRIu64 " %s-%s] WatchGet key:%s", id_, EncodeToHexString(meta_.GetStartKey()).c_str(), EncodeToHexString(meta_.GetEndKey()).c_str(), EncodeToHexString(dbKey).c_str()); auto epoch = req.header().range_epoch(); bool in_range = KeyInRange(dbKey); bool is_equal = EpochIsEqual(epoch); if (!in_range) { if (is_equal) { err = KeyNotInRange(dbKey); break; } } } while (false); //int16_t watchFlag{0}; if (err != nullptr) { RANGE_LOG_WARN("WatchGet error: %s", err->message().c_str()); common::SetResponseHeader(req.header(), header, err); context_->SocketSession()->Send(msg, ds_resp); return; } //add watch if client version is not equal to ds side auto clientVersion = req.req().startversion(); //to do add watch auto watch_server = context_->WatchServer(); std::vector<watch::WatcherKey*> keys; for (auto i = 0; i < tmpKv.key_size(); i++) { keys.push_back(new watch::WatcherKey(tmpKv.key(i))); } watch::WatchType watchType = watch::WATCH_KEY; if(prefix) { watchType = watch::WATCH_PREFIX; } //int64_t expireTime = (req.req().longpull() > 0)?getticks() + req.req().longpull():msg->expire_time; int64_t expireTime = (req.req().longpull() > 0)?get_micro_second() + req.req().longpull()*1000:msg->expire_time*1000; auto w_ptr = std::make_shared<watch::Watcher>(watchType, meta_.GetTableID(), keys, clientVersion, expireTime, msg); watch::WatchCode wcode; if(prefix) { //to do load data from memory //std::string dbKeyEnd(""); //dbKeyEnd.assign(dbKey); // if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) { // //to do set error message // FLOG_ERROR("NextComparableBytes error."); // return; // } auto hashKey = w_ptr->GetKeys(); std::string encode_key(""); w_ptr->EncodeKey(&encode_key, w_ptr->GetTableId(), w_ptr->GetKeys()); std::vector<watch::CEventBufferValue> vecUpdKeys; auto retPair = eventBuffer->loadFromBuffer(encode_key, clientVersion, vecUpdKeys); int32_t memCnt(retPair.first); auto verScope = retPair.second; RANGE_LOG_DEBUG("loadFromBuffer key:%s hit count[%" PRId32 "] version scope:%" PRId32 "---%" PRId32 " client_version:%" PRId64 , EncodeToHexString(encode_key).c_str(), memCnt, verScope.first, verScope.second, clientVersion); if(memCnt > 0) { auto resp = ds_resp->mutable_resp(); resp->set_code(Status::kOk); resp->set_scope(watchpb::RESPONSE_PART); for (auto j = 0; j < memCnt; j++) { auto evt = resp->add_events(); for (decltype(vecUpdKeys[j].key().size()) k = 0; k < vecUpdKeys[j].key().size(); k++) { evt->mutable_kv()->add_key(vecUpdKeys[j].key(k)); } evt->mutable_kv()->set_value(vecUpdKeys[j].value()); evt->mutable_kv()->set_version(vecUpdKeys[j].version()); evt->set_type(vecUpdKeys[j].type()); } w_ptr->Send(ds_resp); return; } else { w_ptr->setBufferFlag(memCnt); wcode = watch_server->AddPrefixWatcher(w_ptr, store_.get()); } } else { wcode = watch_server->AddKeyWatcher(w_ptr, store_.get()); } if(watch::WATCH_OK == wcode) { return; } else if(watch::WATCH_WATCHER_NOT_NEED == wcode) { auto btime = get_micro_second(); //to do get from db again GetAndResp(w_ptr, req.req(), dbKey, prefix, dbVersion, ds_resp); context_->Statistics()->PushTime(monitor::HistogramType::kQWait, get_micro_second() - btime); w_ptr->Send(ds_resp); } else { RANGE_LOG_ERROR("add watcher exception(%d).", static_cast<int>(wcode)); return; } return; } void Range::PureGet(common::ProtoMessage *msg, watchpb::DsKvWatchGetMultiRequest &req) { errorpb::Error *err = nullptr; auto btime = get_micro_second(); context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time); auto ds_resp = new watchpb::DsKvWatchGetMultiResponse; auto header = ds_resp->mutable_header(); //encode key and value std::string dbKey{""}; std::string dbKeyEnd{""}; std::string dbValue(""); //int64_t version{0}; int64_t minVersion(0); int64_t maxVersion(0); auto prefix = req.prefix(); RANGE_LOG_DEBUG("PureGet beginmsgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id); do { if (!VerifyLeader(err)) { break; } auto &key = req.kv().key(); if (key.empty()) { RANGE_LOG_WARN("PureGet error: key empty"); err = KeyNotInRange("EmptyKey"); break; } //encode key if( 0 != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchGet, meta_.Get(), req.kv(), dbKey, dbValue, err)) { break; } RANGE_LOG_INFO("PureGet key before:%s after:%s", key[0].c_str(), EncodeToHexString(dbKey).c_str()); auto epoch = req.header().range_epoch(); bool in_range = KeyInRange(dbKey); bool is_equal = EpochIsEqual(epoch); if (!in_range) { if (is_equal) { err = KeyNotInRange(dbKey); break; } } auto resp = ds_resp; auto btime = get_micro_second(); storage::Iterator *it = nullptr; Status::Code code = Status::kOk; if (prefix) { dbKeyEnd.assign(dbKey); if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) { //to do set error message break; } RANGE_LOG_DEBUG("PureGet key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str()); //need to encode and decode std::shared_ptr<storage::Iterator> iterator(store_->NewIterator(dbKey, dbKeyEnd)); uint32_t count{0}; for (int i = 0; iterator->Valid() ; ++i) { count++; auto kv = resp->add_kvs(); auto tmpDbKey = iterator.get()->key(); auto tmpDbValue = iterator.get()->value(); if(Status::kOk != WatchEncodeAndDecode::DecodeKv(funcpb::kFuncPureGet, meta_.GetTableID(), kv, tmpDbKey, tmpDbValue, err)) { //break; continue; } //to judge version after decoding value and spliting version from value if (minVersion > kv->version()) { minVersion = kv->version(); } if(maxVersion < kv->version()) { maxVersion = kv->version(); } iterator->Next(); } RANGE_LOG_DEBUG("PureGet ok:%d ", count); code = Status::kOk; } else { auto ret = store_->Get(dbKey, &dbValue); if(ret.ok()) { //to do decode value version RANGE_LOG_DEBUG("PureGet: dbKey:%s dbValue:%s ", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbValue).c_str()); auto kv = resp->add_kvs(); /* int64_t dbVersion(0); std::string userValue(""); std::string extend(""); watch::Watcher::DecodeValue(&dbVersion, &userValue, &extend, dbValue); */ if (Status::kOk != WatchEncodeAndDecode::DecodeKv(funcpb::kFuncPureGet, meta_.GetTableID(), kv, dbKey, dbValue, err)) { RANGE_LOG_WARN("DecodeKv fail. dbvalue:%s err:%s", EncodeToHexString(dbValue).c_str(), err->message().c_str()); //break; } } RANGE_LOG_DEBUG("PureGet code:%d msg:%s ", ret.code(), ret.ToString().data()); code = ret.code(); } context_->Statistics()->PushTime(monitor::HistogramType::kQWait, get_micro_second() - btime); resp->set_code(static_cast<int32_t>(code)); } while (false); if (err != nullptr) { RANGE_LOG_WARN("PureGet error: %s", err->message().c_str()); } common::SetResponseHeader(req.header(), header, err); context_->SocketSession()->Send(msg, ds_resp); } void Range::WatchPut(common::ProtoMessage *msg, watchpb::DsKvWatchPutRequest &req) { errorpb::Error *err = nullptr; std::string dbKey{""}; //auto dbValue{std::make_shared<std::string>("")}; //auto extPtr{std::make_shared<std::string>("")}; auto btime = get_micro_second(); context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time); RANGE_LOG_DEBUG("WatchPut begin msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id); if (!CheckWriteable()) { auto resp = new watchpb::DsKvWatchPutResponse; resp->mutable_resp()->set_code(Status::kNoLeftSpace); return SendError(msg, req.header(), resp, nullptr); } do { if (!VerifyLeader(err)) { break; } auto kv = req.mutable_req()->mutable_kv(); if (kv->key().empty()) { RANGE_LOG_WARN("WatchPut error: key empty"); err = KeyNotInRange("-"); break; } RANGE_LOG_DEBUG("WatchPut key:%s value:%s", kv->key(0).c_str(), kv->value().c_str()); /* //to do move to apply encode key if( 0 != version_seq_->nextId(&version)) { if (err == nullptr) { err = new errorpb::Error; } err->set_message(version_seq_->getErrMsg()); break; } kv->set_version(version); FLOG_DEBUG("range[%" PRIu64 "] WatchPut key-version[%" PRIu64 "]", meta_.id(), version); if( Status::kOk != WatchCode::EncodeKv(funcpb::kFuncWatchPut, meta_, *kv, *dbKey, *dbValue, err) ) { break; }*/ std::vector<std::string*> vecUserKeys; for ( auto i = 0 ; i < kv->key_size(); i++) { vecUserKeys.emplace_back(kv->mutable_key(i)); } watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), vecUserKeys); auto epoch = req.header().range_epoch(); bool in_range = KeyInRange(dbKey); bool is_equal = EpochIsEqual(epoch); if (!in_range) { if (is_equal) { err = KeyNotInRange(dbKey); } else { err = StaleEpochError(epoch); } break; } /* //increase key version kv->set_version(version); kv->clear_key(); kv->add_key(*dbKey); kv->set_value(*dbValue); */ //raft propagate at first, propagate KV after encodding if (!WatchPutSubmit(msg, req)) { err = RaftFailError(); } } while (false); if (err != nullptr) { RANGE_LOG_WARN("WatchPut error: %s", err->message().c_str()); auto resp = new watchpb::DsKvWatchPutResponse; return SendError(msg, req.header(), resp, err); } } void Range::WatchDel(common::ProtoMessage *msg, watchpb::DsKvWatchDeleteRequest &req) { errorpb::Error *err = nullptr; std::string dbKey{""}; //auto dbValue = std::make_shared<std::string>(); //auto extPtr = std::make_shared<std::string>(); auto btime = get_micro_second(); context_->Statistics()->PushTime(monitor::HistogramType::kQWait, btime - msg->begin_time); RANGE_LOG_DEBUG("WatchDel begin, msgid: %" PRId64 " session_id: %" PRId64, msg->header.msg_id, msg->session_id); if (!CheckWriteable()) { auto resp = new watchpb::DsKvWatchDeleteResponse; resp->mutable_resp()->set_code(Status::kNoLeftSpace); return SendError(msg, req.header(), resp, nullptr); } do { if (!VerifyLeader(err)) { break; } auto kv = req.mutable_req()->mutable_kv(); if (kv->key_size() < 1) { RANGE_LOG_WARN("WatchDel error due to key is empty"); err = KeyNotInRange("EmptyKey"); break; } /* if(Status::kOk != WatchCode::EncodeKv(funcpb::kFuncWatchDel, meta_, *kv, *dbKey, *dbValue, err)) { break; }*/ /*std::vector<std::string*> vecUserKeys; for(auto itKey : kv->key()) { vecUserKeys.emplace_back(&itKey); }*/ std::vector<std::string*> vecUserKeys; for ( auto i = 0 ; i < kv->key_size(); i++) { vecUserKeys.emplace_back(kv->mutable_key(i)); } watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), vecUserKeys); auto epoch = req.header().range_epoch(); bool in_range = KeyInRange(dbKey); bool is_equal = EpochIsEqual(epoch); if (!in_range) { if (is_equal) { err = KeyNotInRange(dbKey); } else { err = StaleEpochError(epoch); } break; } /* //set encoding value to request kv->clear_key(); kv->add_key(*dbKey); kv->set_value(*dbValue); */ /*to do move to apply //to do consume version and will reply to client int64_t version{0}; if( 0 != version_seq_->nextId(&version)) { if (err == nullptr) { err = new errorpb::Error; } err->set_message(version_seq_->getErrMsg()); break; } kv->set_version(version); */ if (!WatchDeleteSubmit(msg, req)) { err = RaftFailError(); } } while (false); if (err != nullptr) { RANGE_LOG_WARN("WatchDel error: %s", err->message().c_str()); auto resp = new watchpb::DsKvWatchDeleteResponse; return SendError(msg, req.header(), resp, err); } } bool Range::WatchPutSubmit(common::ProtoMessage *msg, watchpb::DsKvWatchPutRequest &req) { auto &kv = req.req().kv(); if (is_leader_ && kv.key_size() > 0 ) { auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) { cmd.set_cmd_type(raft_cmdpb::CmdType::KvWatchPut); cmd.set_allocated_kv_watch_put_req(req.release_req()); }); return ret.ok() ? true : false; } return false; } bool Range::WatchDeleteSubmit(common::ProtoMessage *msg, watchpb::DsKvWatchDeleteRequest &req) { auto &kv = req.req().kv(); if (is_leader_ && kv.key_size() > 0 ) { auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) { cmd.set_cmd_type(raft_cmdpb::CmdType::KvWatchDel); cmd.set_allocated_kv_watch_del_req(req.release_req()); }); return ret.ok() ? true : false; } return false; } Status Range::ApplyWatchPut(const raft_cmdpb::Command &cmd, uint64_t raftIdx) { Status ret; errorpb::Error *err = nullptr; //RANGE_LOG_DEBUG("ApplyWatchPut begin"); auto &req = cmd.kv_watch_put_req(); auto btime = get_micro_second(); watchpb::WatchKeyValue notifyKv; notifyKv.CopyFrom(req.kv()); static int64_t version{0}; version = raftIdx; //for test if (0) { static std::atomic<int64_t> test_version = {0}; test_version += 1; //////////////////////////////////////////////////////////// version = test_version; apply_index_=version; /////////////////////////////////////////////////////////// } notifyKv.set_version(version); RANGE_LOG_DEBUG("ApplyWatchPut new version[%" PRIu64 "]", version); int64_t beginTime(getticks()); std::string dbKey{""}; std::string dbValue{""}; if( Status::kOk != WatchEncodeAndDecode::EncodeKv(funcpb::kFuncWatchPut, meta_.Get(), notifyKv, dbKey, dbValue, err) ) { //to do // SendError() FLOG_WARN("EncodeKv failed, key:%s ", notifyKv.key(0).c_str()); ; } notifyKv.clear_key(); notifyKv.add_key(dbKey); notifyKv.set_value(dbValue); RANGE_LOG_DEBUG("ApplyWatchPut dbkey:%s dbvalue:%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbValue).c_str()); do { if (!KeyInRange(dbKey, err)) { FLOG_WARN("Apply WatchPut failed, key:%s not in range.", dbKey.data()); ret = std::move(Status(Status::kInvalidArgument, "key not in range", "")); break; } //save to db auto btime = get_micro_second(); ret = store_->Put(dbKey, dbValue); context_->Statistics()->PushTime(monitor::HistogramType::kQWait, get_micro_second() - btime); if (!ret.ok()) { FLOG_ERROR("ApplyWatchPut failed, code:%d, msg:%s", ret.code(), ret.ToString().data()); break; } /*if(req.kv().key_size() > 1) { //to do decode group key,ignore single key auto value = std::make_shared<watch::CEventBufferValue>(notifyKv, watchpb::PUT); if(value->key_size()) { FLOG_DEBUG(">>>key is valid."); } if (!eventBuffer->enQueue(dbKey, value.get())) { FLOG_ERROR("load delete event kv to buffer error."); } } */ if (cmd.cmd_id().node_id() == node_id_) { auto len = static_cast<uint64_t>(req.kv().ByteSizeLong()); CheckSplit(len); } } while (false); if (cmd.cmd_id().node_id() == node_id_) { auto resp = new watchpb::DsKvWatchPutResponse; resp->mutable_resp()->set_code(ret.code()); ReplySubmit(cmd, resp, err, btime); //notify watcher std::string errMsg(""); int32_t retCnt = WatchNotify(watchpb::PUT, req.kv(), version, errMsg); if (retCnt < 0) { FLOG_ERROR("WatchNotify-put failed, ret:%d, msg:%s", retCnt, errMsg.c_str()); } else { FLOG_DEBUG("WatchNotify-put success, count:%d, msg:%s", retCnt, errMsg.c_str()); } } else if (err != nullptr) { delete err; return ret; } int64_t endTime(getticks()); FLOG_DEBUG("ApplyWatchPut key[%s], take time:%" PRId64 " ms", EncodeToHexString(dbKey).c_str(), endTime - beginTime); return ret; } Status Range::ApplyWatchDel(const raft_cmdpb::Command &cmd, uint64_t raftIdx) { Status ret; errorpb::Error *err = nullptr; // RANGE_LOG_DEBUG("ApplyWatchDel begin"); auto &req = cmd.kv_watch_del_req(); auto btime = get_micro_second(); watchpb::WatchKeyValue notifyKv; notifyKv.CopyFrom(req.kv()); auto prefix = req.prefix(); uint64_t version{0}; //version = getNextVersion(err); version = raftIdx; //for test if (0) { static std::atomic<int64_t> test_version = {1}; test_version += 1; //////////////////////////////////////////////////////////// version = test_version; apply_index_=version; /////////////////////////////////////////////////////////// } notifyKv.set_version(version); RANGE_LOG_DEBUG("ApplyWatchDel new-version[%" PRIu64 "]", version); std::string dbKey{""}; std::string dbValue{""}; std::vector<std::string*> userKeys; for(auto i = 0; i < req.kv().key_size(); i++) { userKeys.push_back(std::move(new std::string(req.kv().key(i)))); } watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), userKeys); for(auto it:userKeys) { delete it; } if(!req.kv().value().empty()) { std::string extend(""); watch::Watcher::EncodeValue(&dbValue, version, &req.kv().value(), &extend); } std::vector<std::string> delKeys; if (!KeyInRange(dbKey, err)) { FLOG_WARN("ApplyWatchDel failed, key:%s not in range.", dbKey.data()); } if (err != nullptr) { delete err; return ret; } if(prefix) { std::string dbKeyEnd(dbKey); if (0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) { //to do set error message FLOG_ERROR("NextComparableBytes error, skip key:%s", EncodeToHexString(dbKey).c_str()); return Status(Status::kUnknown); } RANGE_LOG_DEBUG("ApplyWatchDel key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str()); std::shared_ptr<storage::Iterator> iterator(store_->NewIterator(dbKey, dbKeyEnd)); for (int i = 0; iterator->Valid(); ++i) { delKeys.push_back(std::move(iterator->key())); iterator->Next(); } std::string first_key(""); std::string last_key(""); int64_t keySize = delKeys.size(); if (delKeys.size() > 0) { first_key = delKeys[0]; last_key = delKeys[delKeys.size() - 1]; } RANGE_LOG_DEBUG("BatchDelete afftected_keys:%" PRId64 " first_key:%s last_key:%s", keySize, EncodeToHexString(first_key).c_str(), EncodeToHexString(last_key).c_str()); } else { delKeys.push_back(dbKey); } // ret = store_->BatchDelete(delKeys); // if (!ret.ok()) { // FLOG_ERROR("BatchDelete failed, code:%d, msg:%s , key:%s", ret.code(), // ret.ToString().c_str(), EncodeToHexString(dbKey).c_str()); // break; // } auto keySize(delKeys.size()); int64_t idx(0); std::vector<std::string*> vecKeys; for(auto it : delKeys) { idx++; FLOG_DEBUG("execute delte...[%" PRId64 "/%" PRIu64 "]", idx, keySize); auto btime = get_micro_second(); ret = store_->Delete(it); context_->Statistics()->PushTime(monitor::HistogramType::kQWait, get_micro_second() - btime); if (cmd.cmd_id().node_id() == node_id_ && delKeys[keySize-1] == it) { //FLOG_DEBUG("Delete:%s del key:%s---last key:%s", ret.ToString().c_str(), EncodeToHexString(it).c_str(), EncodeToHexString(delKeys[keySize-1]).c_str()); auto resp = new watchpb::DsKvWatchDeleteResponse; resp->mutable_resp()->set_code(ret.code()); ReplySubmit(cmd, resp, err, btime); } else if (err != nullptr) { delete err; continue; } if (!ret.ok()) { FLOG_ERROR("ApplyWatchDel failed, code:%d, msg:%s , key:%s", ret.code(), ret.ToString().c_str(), EncodeToHexString(dbKey).c_str()); continue; } FLOG_DEBUG("store->Delete->ret.code:%s", ret.ToString().c_str()); if (cmd.cmd_id().node_id() == node_id_) { notifyKv.clear_key(); vecKeys.clear(); watch::Watcher::DecodeKey(vecKeys, it); for (auto key:vecKeys) { notifyKv.add_key(*key); } for (auto key:vecKeys) { delete key; } //notify watcher int32_t retCnt(0); std::string errMsg(""); retCnt = WatchNotify(watchpb::DELETE, notifyKv, version, errMsg, prefix); if (retCnt < 0) { FLOG_ERROR("WatchNotify-del failed, ret:%d, msg:%s", retCnt, errMsg.c_str()); } else { FLOG_DEBUG("WatchNotify-del success, watch_count:%d, msg:%s", retCnt, errMsg.c_str()); } } } if(prefix && cmd.cmd_id().node_id() == node_id_ && keySize == 0) { auto resp = new watchpb::DsKvWatchDeleteResponse; //Delete没有失败,统一返回ok ret = Status(Status::kOk); resp->mutable_resp()->set_code(ret.code()); ReplySubmit(cmd, resp, err, btime); } return ret; } int32_t Range::WatchNotify(const watchpb::EventType evtType, const watchpb::WatchKeyValue& kv, const int64_t &version, std::string &errMsg, bool prefix) { if(kv.key_size() == 0) { errMsg.assign("WatchNotify--key is empty."); return -1; } std::vector<watch::WatcherPtr> vecNotifyWatcher; std::vector<watch::WatcherPtr> vecPrefixNotifyWatcher; //continue to get prefix key std::vector<std::string *> decodeKeys; std::string hashKey(""); std::string dbKey(""); bool hasPrefix(prefix); if(!hasPrefix && kv.key_size() > 1) { hasPrefix = true; } for(auto it : kv.key()) { decodeKeys.emplace_back(std::move(new std::string(it))); //only push the first key break; } watch::Watcher::EncodeKey(&hashKey, meta_.GetTableID(), decodeKeys); if(hasPrefix) { int16_t tmpCnt{0}; for(auto it : kv.key()) { ++tmpCnt; if(tmpCnt == 1) continue; //to do skip the first element decodeKeys.emplace_back(std::move(new std::string(it))); } watch::Watcher::EncodeKey(&dbKey, meta_.GetTableID(), decodeKeys); } else { dbKey = hashKey; } for(auto it : decodeKeys) { delete it; } FLOG_DEBUG("WatchNotify haskkey:%s key:%s version:%" PRId64, EncodeToHexString(hashKey).c_str(), EncodeToHexString(dbKey).c_str(), version); if(hasPrefix) { auto value = std::make_shared<watch::CEventBufferValue>(kv, evtType, version); if (!eventBuffer->enQueue(hashKey, value.get())) { FLOG_ERROR("load delete event kv to buffer error."); } } auto dbValue = kv.value(); int64_t currDbVersion{version}; auto watch_server = context_->WatchServer(); watch_server->GetKeyWatchers(evtType, vecNotifyWatcher, hashKey, dbKey, currDbVersion); //start to send user kv to client int32_t watchCnt = vecNotifyWatcher.size(); FLOG_DEBUG("single key notify:%" PRId32 " key:%s", watchCnt, EncodeToHexString(dbKey).c_str()); for(auto i = 0; i < watchCnt; i++) { auto dsResp = new watchpb::DsWatchResponse; auto resp = dsResp->mutable_resp(); auto evt = resp->add_events(); evt->set_allocated_kv(new watchpb::WatchKeyValue(kv)); evt->mutable_kv()->set_version(currDbVersion); evt->set_type(evtType); SendNotify(vecNotifyWatcher[i], dsResp); } if(hasPrefix) { //watch_server->GetPrefixWatchers(evtType, vecPrefixNotifyWatcher, hashKey, dbKey, currDbVersion); watch_server->GetPrefixWatchers(evtType, vecPrefixNotifyWatcher, hashKey, hashKey, currDbVersion); watchCnt = vecPrefixNotifyWatcher.size(); FLOG_DEBUG("prefix key notify:%" PRId32 " key:%s", watchCnt, EncodeToHexString(dbKey).c_str()); for( auto i = 0; i < watchCnt; i++) { int64_t startVersion(vecPrefixNotifyWatcher[i]->getKeyVersion()); auto dsResp = new watchpb::DsWatchResponse; std::vector<watch::CEventBufferValue> vecUpdKeys; vecUpdKeys.clear(); auto retPair = eventBuffer->loadFromBuffer(hashKey, startVersion, vecUpdKeys); int32_t memCnt(retPair.first); auto verScope = retPair.second; RANGE_LOG_DEBUG("loadFromBuffer key:%s hit count[%" PRId32 "] version scope:%" PRId32 "---%" PRId32 " client_version:%" PRId64 , EncodeToHexString(hashKey).c_str(), memCnt, verScope.first, verScope.second, startVersion); if (0 == memCnt) { FLOG_ERROR("doudbt no changing, notify %d/%" PRId32 " key:%s", i+1, watchCnt, EncodeToHexString(dbKey).c_str()); delete dsResp; dsResp = nullptr; } else if (memCnt > 0) { FLOG_DEBUG("notify %d/%" PRId32 " loadFromBuffer key:%s hit count:%" PRId32, i+1, watchCnt, EncodeToHexString(dbKey).c_str(), memCnt); auto resp = dsResp->mutable_resp(); resp->set_code(Status::kOk); resp->set_scope(watchpb::RESPONSE_PART); for (auto j = 0; j < memCnt; j++) { auto evt = resp->add_events(); for (decltype(vecUpdKeys[j].key().size()) k = 0; k < vecUpdKeys[j].key().size(); k++) { evt->mutable_kv()->add_key(vecUpdKeys[j].key(k)); } evt->mutable_kv()->set_value(vecUpdKeys[j].value()); evt->mutable_kv()->set_version(vecUpdKeys[j].version()); evt->set_type(vecUpdKeys[j].type()); } } else { //get all from db FLOG_INFO("overlimit version in memory,get from db now. notify %d/%" PRId32 " key:%s version:%" PRId64, i+1, watchCnt, EncodeToHexString(dbKey).c_str(), startVersion); //use iterator std::string dbKeyEnd{""}; dbKeyEnd.assign(dbKey); if( 0 != WatchEncodeAndDecode::NextComparableBytes(dbKey.data(), dbKey.length(), dbKeyEnd)) { //to do set error message FLOG_ERROR("NextComparableBytes error."); return -1; } //RANGE_LOG_DEBUG("WatchNotify key scope %s---%s", EncodeToHexString(dbKey).c_str(), EncodeToHexString(dbKeyEnd).c_str()); auto watcherServer = context_->WatchServer(); auto ws = watcherServer->GetWatcherSet_(hashKey); auto result = ws->loadFromDb(store_.get(), evtType, dbKey, dbKeyEnd, startVersion, meta_.GetTableID(), dsResp); if(result.first <= 0) { delete dsResp; dsResp = nullptr; } //scopeFlag = 1; FLOG_DEBUG("notify %d/%" PRId32 " load from db, db-count:%" PRId32 " key:%s ", i+1, watchCnt, result.first, EncodeToHexString(dbKey).c_str()); } if (hasPrefix && watchCnt > 0 && dsResp != nullptr) { SendNotify(vecPrefixNotifyWatcher[i], dsResp, true); } } } return watchCnt; } int32_t Range::SendNotify( watch::WatcherPtr w, watchpb::DsWatchResponse *ds_resp, bool prefix) { auto watch_server = context_->WatchServer(); auto resp = ds_resp->mutable_resp(); auto w_id = w->GetWatcherId(); resp->set_watchid(w_id); w->Send(ds_resp); //delete watch watch::WatchCode del_ret = watch::WATCH_OK; if (!prefix && w->GetType() == watch::WATCH_KEY) { del_ret = watch_server->DelKeyWatcher(w); if (del_ret) { RANGE_LOG_WARN(" DelKeyWatcher error, watch_id[%" PRId64 "]", w_id); } else { RANGE_LOG_WARN(" DelKeyWatcher execute end. watch_id:%" PRIu64, w_id); } } if (prefix && w->GetType() == watch::WATCH_KEY) { del_ret = watch_server->DelPrefixWatcher(w); if (del_ret) { RANGE_LOG_WARN(" DelPrefixWatcher error, watch_id[%" PRId64 "]", w_id); } else { RANGE_LOG_WARN(" DelPrefixWatcher execute end. watch_id:%" PRIu64, w_id); } } return del_ret; } } // namespace range } // namespace dataserver } // namespace sharkstore
35,300
11,499
//////////////////////////////////////////////////////////////////////////////// // impl-matchers.h // // Copyright (C) Codeplay Software Limited. // // 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. // //////////////////////////////////////////////////////////////////////////////// #ifndef IMPL_MATCHERS_H #define IMPL_MATCHERS_H #include <CL/opencl.h> #include <iostream> #include <nlohmann/json.hpp> #include <set> #include <string> #include <tuple> #include <utility> #include <vector> // This macro expands to the boilerplate of all the comparison operators // The operator< must be defined first by the programmer. Any other // operators are defined relatively to the operator< #define SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS(type) \ friend inline bool operator>(const type& lhs, const type& rhs) { \ return rhs < lhs; \ } \ friend inline bool operator==(const type& lhs, const type& rhs) { \ return !(lhs < rhs) && !(rhs < lhs); \ } \ friend inline bool operator!=(const type& lhs, const type& rhs) { \ return !(lhs == rhs); \ } \ friend inline bool operator<=(const type& lhs, const type& rhs) { \ return !(rhs < lhs); \ } \ friend inline bool operator>=(const type& lhs, const type& rhs) { \ return !(lhs < rhs); \ } namespace sycl_info { struct using_target_matcher { // The layout we want to model/print //-------------------------------------- // Platform name: name // Platform vendor: vendor // device1: // device_name: name // device_vendor: vendor // supported_drivers: 1.2, 1.3, etc // device2: // device_name: name // device_vendor: vendor // supported_drivers: 1.2, 1.3, etc // ... // ... // deviceN: // Platform Name: nameN // ... //-------------------------------------- /// @brief A device consists of a name, a vendor and /// a vector of the supported drivers /// struct device { std::string name; std::string vendor; /// @brief This is necessarry as this struct will be stored in /// an std::set. Marking this mutable is important, because /// it allows us to modify this field without rebalancing /// the tree. Essentially, this field is ignored in the /// comparison function used by the data structure /// mutable std::vector<std::string> drivers; /// @brief The container of this is an std::set which requires /// strict weak ordering /// @see Strict weak ordering https://en.wikipedia.org/wiki/Weak_ordering /// @see std::set container requirements /// https://en.cppreference.com/w/cpp/container/set /// friend inline bool operator<(const device& lhs, const device& rhs) { return std::tie(lhs.name, lhs.vendor) < std::tie(rhs.name, rhs.vendor); } /// define the rest of the comparisson operators SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS(device) }; /// @brief A platform consists of a name, a vendor and /// a set of supported devices. Name and vendor, /// struct platform { std::string name; std::string vendor; /// @brief This is necessarry as this struct will be stored in /// an std::set. Marking this mutable is important, because /// it allows us to modify this field without rebalancing /// the tree. Essentially, this field is ignored in the /// comparison function used by the data structure /// mutable std::set<device> devices; /// @brief The container of this is an std::set which requires /// strict weak ordering /// @see Strict weak ordering https://en.wikipedia.org/wiki/Weak_ordering /// @see std::set container requirements /// https://en.cppreference.com/w/cpp/container/set /// friend inline bool operator<(const platform& lhs, const platform& rhs) { return std::tie(lhs.name, lhs.vendor) < std::tie(rhs.name, rhs.vendor); } /// define the rest of the comparisson operators SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS(platform); }; /// The type that we print using print_type = std::set<platform>; /// @brief Helper function the converts a json file to the internal /// representation print_type /// @param syclinfo json /// @return a print_type from the nlohmann::json /// static print_type from_json(const nlohmann::json& syclImp); /// @brief Finds the common platforms/devices between a sycl /// implementation and the system's available platforms/devices /// @param A syclinfo file, the current available hardware, /// that is, the systems platforms and devices retrieved /// with the target_selector /// @return a print_type with the matched results /// static print_type match(const nlohmann::json& syclImpJson, const print_type& currentHardware); }; /// @brief Helper function that converts a vector of platform ids and /// and device ids into their respective string names /// using_target_matcher::print_type to_print_type( const std::vector<std::pair<cl_platform_id, cl_device_id>>& devices); /// @brief Pretty print function for the --using command line option /// @param A result of type print_type retrieved by the match() /// function and an ostream to print to /// void dump_picked_impl(const using_target_matcher::print_type& devices, std::ostream& out) noexcept; /// @brief Retrieves the implementation index for a given input string /// @param The user input string and the available implementations /// @return A pair of bool and int, representing whether an implementation was /// found, and if so the index of that implemetnation /// std::pair<bool, int> retrieve_index_for_impl( const std::string& chosenImpl, const std::vector<nlohmann::json>& impls) noexcept; /// @brief Matches the --impl index with the available implementations /// @param The --impl index, a vector of the syclinfo implementations /// to match /// using_target_matcher::print_type match_picked_impl( const unsigned int index, const std::vector<nlohmann::json>& impls, const bool displayAll); /// @brief Picks a sycl-info implementation and displays it /// @param The --using-target index, a vector of the syclinfo /// implementations and an ostream to print to /// void print_picked_impl(const unsigned int index, const std::vector<nlohmann::json>& impls, const bool displayAll, std::ostream& out); /// @brief Structure for platform/device pair to represent the --config option /// struct config { std::string platform; std::string device; }; /// @brief Gets the config from an implementation and an index /// @return The config specified by the index /// config get_config(const unsigned int index, const std::vector<nlohmann::json>& impls, const std::pair<int, int> configIndex, const bool displayAll); /// @brief prints the config /// void print_config(const unsigned int index, const std::vector<nlohmann::json>& impls, const std::pair<int, int> configIndex, const std::string& target, const bool displayAll, std::ostream& out); /// @brief Checks if the user specified option config_ is a valid index /// @return True if config_ is a valid index, false otherwise bool is_config_index_valid(const using_target_matcher::print_type& impls, const std::pair<int, int> configIndex) noexcept; /// @brief Structure for platform/device pair to represent the backend /// information of a specified --impl struct backend_info { std::string backend; std::string deviceFlags; }; /// @brief Returns the backend specified by the option --target /// @param An iterator to the syclinfo file and the value of --target option /// backend_info get_backend_from_target( nlohmann::json::const_iterator foundElement, const std::string& target); /// @brief Returns the default backend for a target (first in the list by /// default) /// @param An iterator to the syclinfo file /// backend_info get_default_backend( const nlohmann::json::const_iterator foundElement); /// @brief Helper function that matches an implementation file with the /// --config. Optinally, it filters by --target. /// @return The backend specified by config filtered by the optional target /// backend_info match_config_with_impls(const config& conf, const nlohmann::json& impl, const std::string& target); /// @brief Dumps the backend information specified by --config to a stream // void dump_config(const backend_info& info, std::ostream& out) noexcept; /// @brief Enum that represents the name of a field in the json file. /// enum class selections { supported_configurations, plat_name, plat_vendor, dev_name, dev_flags, dev_vendor, supported_backend_targets, backend, supported_drivers }; /// @brief Generic template that will be fully specialized for each value in /// in the enum selections. The unspecialized base template is left undefined. /// All in all, a field in the enum selections maps to a string value /// representing the name of the respective field in the json file. /// template <selections T> struct select; /// @brief Specialization for selections::supported_configurations /// template <> struct select<selections::supported_configurations> { static constexpr const char* value = "supported_configurations"; }; /// @brief Specialization for selections::plat_name /// template <> struct select<selections::plat_name> { static constexpr const char* value = "platform_name"; }; /// @brief Specialization for selections::plat_vendor /// template <> struct select<selections::plat_vendor> { static constexpr const char* value = "platform_vendor"; }; /// @brief Specialization for selections::device_name /// template <> struct select<selections::dev_name> { static constexpr const char* value = "device_name"; }; /// @brief Specialization for selections::device_flags /// template <> struct select<selections::dev_flags> { static constexpr const char* value = "device_flags"; }; /// @brief Specialization for selections::device_vendor /// template <> struct select<selections::dev_vendor> { static constexpr const char* value = "device_vendor"; }; /// @brief Specialization for selections::supported_backend_targets /// template <> struct select<selections::supported_backend_targets> { static constexpr const char* value = "supported_backend_targets"; }; /// @brief Specialization for selections::backend_target /// template <> struct select<selections::backend> { static constexpr const char* value = "backend_target"; }; /// @brief Specialization for selections::supported_drivers /// template <> struct select<selections::supported_drivers> { static constexpr const char* value = "supported_drivers"; }; } // namespace sycl_info #undef SYCL_INFO_IMPL_MATCHERS_DEFINE_COMPARISON_OPERATORS #endif
11,993
3,310
#include "Map.hpp" #include <fstream> #include <cfloat> // FLT_MAX #include <iostream> // FLT_MAX #include <memory> #include "Rando.hpp" #include "RoadTile.hpp" namespace ts { Map::Map() : grid_(120) { } void Map::clearMap() { cars_.clear(); light_networks_.clear(); building_handlers_.clear(); current_network_id_ = 0; current_building_id_ = 0; grid_.init(); } void Map::initDay() { for(unsigned int i = 0; i < grid_.getTotalTileCount(); ++i) { if(grid_.getTile(i)->getCategory() == TileCategory::RoadCategory) { grid_.getTile(i)->getNode()->resetCounter(); } } for (auto it = building_handlers_.begin(); it != building_handlers_.end(); ++it) { it->second->initDay(); } } void Map::update(const sf::Time &game_time, float delta_time) { // Move cars, and other things which are dependent on time //cars, humans, trafficlights if (!simulating_) return; for (auto ita = building_handlers_.begin(); ita != building_handlers_.end(); ++ita) { if (ita->second->update(game_time)) { Rando r(building_handlers_.size()); int index = r.uniroll() - 1; int i = 0; const Tile *dest_tile; for (auto itb = building_handlers_.begin(); itb != building_handlers_.end(); ++itb) { if (index == i) { dest_tile = itb->second->getClosestRoad(); break; } i++; } auto spawn_tile = ita->second->getClosestRoad(); if(dest_tile && spawn_tile) addCar(spawn_tile, dest_tile); } } for (auto &car : cars_) car->update(game_time, delta_time, cars_, light_networks_); removeFinishedCars(); for (auto ita = light_networks_.begin(); ita != light_networks_.end(); ++ita) ita->second->update(delta_time); } void Map::addCar(const Tile *spawn_pos, const Tile *dest) { cars_.push_back(std::make_unique<Car>(Car(spawn_pos->getNode(), dest->getNode(), sf::Vector2f(50, 100)))); } unsigned int Map::addBuilding(BuildingTile *building) { auto closest_road_node = closestRoadNode(building->getCenter()); if (closest_road_node) building_handlers_.insert({current_building_id_, std::make_unique<BuildingHandler>(building, grid_.getTile(closest_road_node->getPos()), current_building_id_)}); else building_handlers_.insert({current_building_id_, std::make_unique<BuildingHandler>(building, nullptr, current_building_id_)}); current_building_id_++; return current_building_id_ - 1; } void Map::updateClosestRoads() { for (auto it = building_handlers_.begin(); it != building_handlers_.end(); ++it) { auto closest_road_node = closestRoadNode(it->second->getBuildingTile()->getCenter()); if(closest_road_node) it->second->setClosestRoad(grid_.getTile(closest_road_node->getPos())); } } void Map::addLight(TrafficLight *light, unsigned int handler_id) { if (light_networks_.find(handler_id) == light_networks_.end()) { if (handler_id < UINT_MAX) { light_networks_.insert({handler_id, std::make_unique<TrafficLightNetwork>(handler_id)}); } else light_networks_.insert({0, std::make_unique<TrafficLightNetwork>(0)}); } if (light_networks_.find(handler_id) != light_networks_.end()) light_networks_.at(handler_id)->addLight(light); else light_networks_.at(current_network_id_)->addLight(light); } void Map::newLightNetwork(TrafficLight *light) { current_network_id_++; light_networks_.insert({current_network_id_, std::make_unique<TrafficLightNetwork>(current_network_id_)}); if (light) { light_networks_.at(light->getHandlerId())->removeLight(light, light->getPos()); light->setHandlerId(current_network_id_); light_networks_.at(current_network_id_)->addLight(light); } } void Map::removeBuilding(unsigned int id) { building_handlers_.erase(id); } void Map::removeLight(TrafficLight *light) { light_networks_.at(light->getHandlerId())->removeLight(light, light->getPos()); } void Map::removeFinishedCars() { cars_.erase(std::remove_if(cars_.begin(), cars_.end(), [](const auto &car) -> bool { return car->isFinished(); }), cars_.end()); } std::shared_ptr<Node> Map::closestRoadNode(const sf::Vector2f &pos) { std::shared_ptr<Node> closest = nullptr; float closest_distance = FLT_MAX; for (unsigned int i = 0; i < grid_.getTotalTileCount(); ++i) { if (grid_.getTile(i)->getCategory() == TileCategory::RoadCategory) { auto road_tile = static_cast<RoadTile *>(grid_.getTile(i)); if (road_tile->getType() == RoadType::StraightRoadType) { float dist = VectorMath::Distance(pos, grid_.getTile(i)->getCenter()); if (closest_distance > dist) { closest_distance = dist; closest = grid_.getTile(i)->getNode(); } } } } return closest; } void Map::setSimulating(bool val) { if (simulating_ == val) return; simulating_ = val; cars_.clear(); } void Map::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(grid_, states); if (simulating_) { for (const auto &car : cars_) target.draw(*car, states); } else { for (auto ita = light_networks_.begin(); ita != light_networks_.end(); ++ita) target.draw(*ita->second, states); } } } // namespace ts
5,747
1,890
#include "AudioPluginUtil.h" namespace Multiband { enum Param { P_MasterGain, P_LowFreq, P_HighFreq, P_LowGain, P_MidGain, P_HighGain, P_LowAttack, P_MidAttack, P_HighAttack, P_LowRelease, P_MidRelease, P_HighRelease, P_LowThreshold, P_MidThreshold, P_HighThreshold, P_LowRatio, P_MidRatio, P_HighRatio, P_LowKnee, P_MidKnee, P_HighKnee, P_FilterOrder, P_UseLogScale, P_ShowSpectrum, P_SpectrumDecay, P_NUM }; struct CompressorChannel { float env; float atk; float rel; float thr; float ratio; float knee; float reduction; float exp1; float exp2; float GetTimeConstant(float accuracy, float numSamples) { /* Derivation of time constant from transition length specified as numSamples and desired accuracy within which target is reached: y(n) = y(n-1) + [x(n) - y(n-1)] * alpha y(0) = 1, x(n) = 0 => y(1) = 1 + [0 - 1] * alpha = 1-alpha y(2) = 1-alpha + [0 - (1-alpha)] * alpha = (1-alpha)*(1-alpha) = (1-alpha)^2 y(3) = (1-alpha)^2 + [0 - (1-alpha)^2] * alpha = (1-alpha) * (1-alpha)^2 = (1-alpha)^3 ... y(n) = (1-alpha)^n = 1-accuracy => 1-alpha = (1-accuracy)^(1/n) alpha = 1 - (1-accuracy)^(1/n) */ if (numSamples <= 0.0f) return 1.0f; return 1.0f - powf(1.0f - accuracy, 1.0f / numSamples); } void Setup(float _atk, float _rel, float _thr, float _ratio, float _knee) { thr = _thr; ratio = _ratio; knee = _knee; float g = 0.05f * ((1.0f / ratio) - 1.0f); exp1 = powf(10.0f, g * 0.25f / ((knee > 0.0f) ? knee : 1.0f)); exp2 = powf(10.0f, g); atk = GetTimeConstant(0.99f, atk); rel = GetTimeConstant(0.99f, rel); } inline float Process(float input) { float g = 1.0f; float s = FastClip(input * input, 1.0e-11f, 100.0f); float timeConst = (s > env) ? atk : rel; env += (s - env) * timeConst + 1.0e-16f; // add small constant to always positive number to avoid denormal numbers float sideChainLevel = 10.0f * log10f(env); // multiply by 10 (not 20) because duckEnvelope is RMS float t = sideChainLevel - thr; if (fabsf(t) < knee) { t += knee; g = powf(exp1, t * t); } else if (t > 0.0f) g = powf(exp2, t); reduction = g; return input * g; } }; const int MAXORDER = 4; struct EffectData { struct Data { float p[P_NUM]; BiquadFilter bandsplit[8][MAXORDER][4]; BiquadFilter previewBandsplit[4]; CompressorChannel band[3][8]; Random random; FFTAnalyzer analyzer; }; union { Data data; unsigned char pad[(sizeof(Data) + 15) & ~15]; // This entire structure must be a multiple of 16 bytes (and and instance 16 byte aligned) for PS3 SPU DMA requirements }; }; int InternalRegisterEffectDefinition(UnityAudioEffectDefinition& definition) { static const char* bandname[] = { "Low", "Mid", "High" }; int numparams = P_NUM; definition.paramdefs = new UnityAudioParameterDefinition[numparams]; RegisterParameter(definition, "MasterGain", "dB", -100.0f, 100.0f, 0.0f, 1.0f, 1.0f, P_MasterGain, "Overall gain"); RegisterParameter(definition, "LowFreq", "Hz", 0.01f, 24000.0f, 800.0f, 1.0f, 3.0f, P_LowFreq, "Low/Mid cross-over frequency"); RegisterParameter(definition, "HighFreq", "Hz", 0.01f, 24000.0f, 5000.0f, 1.0f, 3.0f, P_HighFreq, "Mid/High cross-over frequency"); for (int i = 0; i < 3; i++) RegisterParameter(definition, tmpstr(0, "%sGain", bandname[i]), "dB", -100.0f, 100.0f, 0.0f, 1.0f, 1.0f, P_LowGain + i, tmpstr(1, "%s band gain in dB", bandname[i])); for (int i = 0; i < 3; i++) RegisterParameter(definition, tmpstr(0, "%sAttackTime", bandname[i]), "ms", 0.0f, 10.0f, 0.1f, 1000.0f, 4.0f, P_LowAttack + i, tmpstr(1, "%s band attack time in seconds", bandname[i])); for (int i = 0; i < 3; i++) RegisterParameter(definition, tmpstr(0, "%sReleaseTime", bandname[i]), "ms", 0.0f, 10.0f, 0.5f, 1000.0f, 4.0f, P_LowRelease + i, tmpstr(1, "%s band release time in seconds", bandname[i])); for (int i = 0; i < 3; i++) RegisterParameter(definition, tmpstr(0, "%sThreshold", bandname[i]), "dB", -50.0f, 0.0f, -10.0f, 1.0f, 1.0f, P_LowThreshold + i, tmpstr(1, "%s band compression level threshold time in dB", bandname[i])); for (int i = 0; i < 3; i++) RegisterParameter(definition, tmpstr(0, "%sRatio", bandname[i]), "%", 1.0f, 30.0f, 1.0f, 100.0f, 1.0f, P_LowRatio + i, tmpstr(1, "%s band compression ratio time in percent", bandname[i])); for (int i = 0; i < 3; i++) RegisterParameter(definition, tmpstr(0, "%sKnee", bandname[i]), "dB", 0.0f, 40.0f, 10.0f, 1.0f, 1.0f, P_LowKnee + i, tmpstr(1, "%s band compression curve knee range in dB", bandname[i])); RegisterParameter(definition, "FilterOrder", "", 1.0f, (float)MAXORDER, 1.0f, 1.0f, 1.0f, P_FilterOrder, "Filter order of cross-over filters"); RegisterParameter(definition, "UseLogScale", "", 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, P_UseLogScale, "Use logarithmic scale for plotting the filter curve frequency response and input/output spectra"); RegisterParameter(definition, "ShowSpectrum", "", 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, P_ShowSpectrum, "Overlay input spectrum (green) and output spectrum (red)"); RegisterParameter(definition, "SpectrumDecay", "dB/s", -50.0f, 0.0f, -10.0f, 1.0f, 1.0f, P_SpectrumDecay, "Hold time for overlaid spectra"); return numparams; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK CreateCallback(UnityAudioEffectState* state) { EffectData* effectdata = new EffectData; memset(effectdata, 0, sizeof(EffectData)); effectdata->data.analyzer.spectrumSize = 4096; InitParametersFromDefinitions(InternalRegisterEffectDefinition, effectdata->data.p); state->effectdata = effectdata; return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ReleaseCallback(UnityAudioEffectState* state) { EffectData::Data* data = &state->GetEffectData<EffectData>()->data; data->analyzer.Cleanup(); delete data; return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK SetFloatParameterCallback(UnityAudioEffectState* state, int index, float value) { EffectData::Data* data = &state->GetEffectData<EffectData>()->data; if (index >= P_NUM) return UNITY_AUDIODSP_ERR_UNSUPPORTED; data->p[index] = value; return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK GetFloatParameterCallback(UnityAudioEffectState* state, int index, float* value, char *valuestr) { EffectData::Data* data = &state->GetEffectData<EffectData>()->data; if (value != NULL) *value = data->p[index]; if (valuestr != NULL) valuestr[0] = 0; return UNITY_AUDIODSP_OK; } static void SetupFilterCoeffs(EffectData::Data* data, int samplerate, BiquadFilter* filter0, BiquadFilter* filter1, BiquadFilter* filter2, BiquadFilter* filter3) { const float qfactor = 0.707f; filter0->SetupLowpass(data->p[P_LowFreq], samplerate, qfactor); filter1->SetupHighpass(data->p[P_LowFreq], samplerate, qfactor); filter2->SetupLowpass(data->p[P_HighFreq], samplerate, qfactor); filter3->SetupHighpass(data->p[P_HighFreq], samplerate, qfactor); } int UNITY_AUDIODSP_CALLBACK GetFloatBufferCallback(UnityAudioEffectState* state, const char* name, float* buffer, int numsamples) { EffectData::Data* data = &state->GetEffectData<EffectData>()->data; if (strcmp(name, "InputSpec") == 0) data->analyzer.ReadBuffer(buffer, numsamples, true); else if (strcmp(name, "OutputSpec") == 0) data->analyzer.ReadBuffer(buffer, numsamples, false); else if (strcmp(name, "LiveData") == 0) { buffer[0] = data->band[0][0].reduction; buffer[1] = data->band[1][0].reduction; buffer[2] = data->band[2][0].reduction; buffer[3] = data->band[0][0].env; buffer[4] = data->band[1][0].env; buffer[5] = data->band[2][0].env; } else if (strcmp(name, "Coeffs") == 0) { SetupFilterCoeffs(data, state->samplerate, &data->previewBandsplit[0], &data->previewBandsplit[1], &data->previewBandsplit[2], &data->previewBandsplit[3]); data->previewBandsplit[0].StoreCoeffs(buffer); data->previewBandsplit[1].StoreCoeffs(buffer); data->previewBandsplit[2].StoreCoeffs(buffer); data->previewBandsplit[3].StoreCoeffs(buffer); } else memset(buffer, 0, sizeof(float) * numsamples); return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ProcessCallback(UnityAudioEffectState* state, float* inbuffer, float* outbuffer, unsigned int length, int inchannels, int outchannels) { EffectData::Data* data = &state->GetEffectData<EffectData>()->data; const float sr = (float)state->samplerate; float specDecay = powf(10.0f, 0.05f * data->p[P_SpectrumDecay] * length / sr); bool calcSpectrum = (data->p[P_ShowSpectrum] >= 0.5f); if (calcSpectrum) data->analyzer.AnalyzeInput(inbuffer, inchannels, length, specDecay); for (int i = 0; i < inchannels; i++) { data->band[0][i].Setup(data->p[P_LowAttack] * sr, data->p[P_LowRelease] * sr, data->p[P_LowThreshold], data->p[P_LowRatio], data->p[P_LowKnee]); data->band[1][i].Setup(data->p[P_MidAttack] * sr, data->p[P_MidRelease] * sr, data->p[P_MidThreshold], data->p[P_MidRatio], data->p[P_MidKnee]); data->band[2][i].Setup(data->p[P_HighAttack], data->p[P_HighRelease], data->p[P_HighThreshold], data->p[P_HighRatio], data->p[P_HighKnee]); for (int k = 0; k < MAXORDER; k++) SetupFilterCoeffs(data, state->samplerate, &data->bandsplit[i][k][0], &data->bandsplit[i][k][1], &data->bandsplit[i][k][2], &data->bandsplit[i][k][3]); } const float lowGainLin = powf(10.0f, (data->p[P_LowGain] + data->p[P_MasterGain]) * 0.05f); const float midGainLin = powf(10.0f, (data->p[P_MidGain] + data->p[P_MasterGain]) * 0.05f); const float highGainLin = powf(10.0f, (data->p[P_HighGain] + data->p[P_MasterGain]) * 0.05f); const int order = (int)data->p[P_FilterOrder]; for (unsigned int n = 0; n < length; n++) { for (int i = 0; i < outchannels; i++) { float killdenormal = (float)(data->random.Get() & 255) * 1.0e-9f; float input = inbuffer[n * inchannels + i] + killdenormal; float lpf = input, bpf = input, hpf = input; for (int k = 0; k < order; k++) { lpf = data->bandsplit[i][k][0].Process(lpf); bpf = data->bandsplit[i][k][1].Process(bpf); } for (int k = 0; k < order; k++) { bpf = data->bandsplit[i][k][2].Process(bpf); hpf = data->bandsplit[i][k][3].Process(hpf); } outbuffer[n * outchannels + i] = data->band[0]->Process(lpf) * lowGainLin + data->band[1]->Process(bpf) * midGainLin + data->band[2]->Process(hpf) * highGainLin; } } if (calcSpectrum) data->analyzer.AnalyzeOutput(outbuffer, outchannels, length, specDecay); return UNITY_AUDIODSP_OK; } }
12,371
4,577
// // Created by Nicolas Cuenca on 11/25/2020. // #include "PlayerLinkedList.h" #include <iostream> PlayerLinkedList::PlayerLinkedList(Player *first) { this->first = first; this->currentPlayer = first; } Player *PlayerLinkedList::getFirst() const { return first; } Player *PlayerLinkedList::getCurrentPlayer() const { return currentPlayer; } void PlayerLinkedList::setCurrentPlayer(Player *currentPlayer) { PlayerLinkedList::currentPlayer = currentPlayer; } void PlayerLinkedList::reverseList() { Player *prev = first; Player *temp; Player *curr = first->getNextPlayer(); bool visited = false; while(!visited || prev != first){ temp = curr->getNextPlayer(); curr->setNextPlayer(prev); prev = curr; curr = temp; visited = true; } } void PlayerLinkedList::deletePlayers() { Player *curr = first; Player *next; int count = 0; bool visited = false; while(curr != first || !visited ){ count++; curr = curr->getNextPlayer(); visited = true; } int delete_until = 0; while(delete_until < count){ std::cout << curr->getId() << std::endl; next = curr->getNextPlayer(); delete curr; curr = next; delete_until++; } first = nullptr; currentPlayer = nullptr; }
1,409
435
/** * Copyright 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 "src/runtime/kernel/arm/nnacl/fp32/deconv.h" void PackDeConvWeightFp32(const float *weight, float *dst, int input_channel, int output_channel, int plane) { /* ichwoc(nhwc) -> oc4 * h * w * incUP4 * 4 */ int ic_up4 = UP_ROUND(input_channel, C4NUM); for (int oc = 0; oc < output_channel; oc++) { int oc4div = oc / C4NUM; int oc4mod = oc % C4NUM; for (int ic = 0; ic < input_channel; ic++) { for (int hw = 0; hw < plane; hw++) { int src_index = ic * plane * output_channel + hw * output_channel + oc; int dst_index = oc4div * ic_up4 * plane * C4NUM + hw * ic_up4 * C4NUM + ic * C4NUM + oc4mod; dst[dst_index] = weight[src_index]; } } } return; } int DeConvFp32(const float *input, const float *weight, float *output, float *tmp_buffer, StrassenMatMulParameter matmul_param) { return StrassenMatmul(input, weight, output, &matmul_param, FP32_STRASSEN_MAX_RECURSION, 0, tmp_buffer); } int DeConvPostFp32C8x8(const float *src, float *tmp, const float *bias, float *dst, int output_channel, ConvParameter *conv_param) { /* row8x8-major(ih*iw x oc*kh*kw) -> row8-major(oh*ow x oc) */ size_t input_plane = conv_param->input_w_ * conv_param->input_h_; size_t kernel_plane = conv_param->kernel_w_ * conv_param->kernel_h_; size_t output_plane = conv_param->output_w_ * conv_param->output_h_; int oc8 = UP_DIV(output_channel, C8NUM); int in_plane8 = UP_ROUND(input_plane, C8NUM); for (int c = 0; c < oc8; c++) { float *dst_ptr = tmp + c * output_plane * C8NUM; const float *src_ptr = src + c * in_plane8 * kernel_plane * C8NUM; memset(dst_ptr, 0, output_plane * C8NUM * sizeof(int32_t)); for (int ih = 0; ih < conv_param->input_h_; ih++) { for (int iw = 0; iw < conv_param->input_w_; iw++) { int oh = ih * conv_param->stride_h_ - conv_param->pad_h_; int ow = iw * conv_param->stride_w_ - conv_param->pad_w_; int kh_start = MSMAX(0, UP_DIV(-oh, conv_param->dilation_h_)); int kh_end = MSMIN(conv_param->kernel_h_, UP_DIV(conv_param->output_h_ - oh, conv_param->dilation_h_)); int kw_start = MSMAX(0, UP_DIV(-ow, conv_param->dilation_w_)); int kw_end = MSMIN(conv_param->kernel_w_, UP_DIV(conv_param->output_w_ - ow, conv_param->dilation_w_)); for (int kh = kh_start; kh < kh_end; kh++) { for (int kw = kw_start; kw < kw_end; kw++) { int src_index = ih * conv_param->input_w_ * C8NUM + iw * C8NUM + kh * in_plane8 * conv_param->kernel_w_ * C8NUM + kw * in_plane8 * C8NUM; int dst_index = oh * conv_param->output_w_ * C8NUM + ow * C8NUM + kh * conv_param->dilation_h_ * conv_param->output_w_ * C8NUM + kw * conv_param->dilation_w_ * C8NUM; for (int i = 0; i < C8NUM; i++) { dst_ptr[dst_index + i] += src_ptr[src_index + i]; } } /*kw*/ } /*kh*/ } /*iw*/ } /*ih*/ } /*oc8*/ PostConvFuncFp32C8(tmp, dst, bias, output_channel, output_plane, conv_param->output_channel_, conv_param->is_relu_, conv_param->is_relu6_); return NNACL_OK; } int DeConvPostFp32C4(const float *src, float *tmp_c4, float *dst, const float *bias, int output_channel, int input_plane, int kernel_plane, int output_plane, ConvParameter *conv_param) { int oc4 = UP_DIV(output_channel, C4NUM); for (int c = 0; c < oc4; c++) { float *dst_ptr = tmp_c4 + c * output_plane * C4NUM; const float *src_ptr = src + c * input_plane * kernel_plane * C4NUM; memset(dst_ptr, 0, output_plane * C4NUM * sizeof(float)); for (int ih = 0; ih < conv_param->input_h_; ih++) { for (int iw = 0; iw < conv_param->input_w_; iw++) { int oh = ih * conv_param->stride_h_ - conv_param->pad_h_; int ow = iw * conv_param->stride_w_ - conv_param->pad_w_; int kh_start = MSMAX(0, UP_DIV(-oh, conv_param->dilation_h_)); int kh_end = MSMIN(conv_param->kernel_h_, UP_DIV(conv_param->output_h_ - oh, conv_param->dilation_h_)); int kw_start = MSMAX(0, UP_DIV(-ow, conv_param->dilation_w_)); int kw_end = MSMIN(conv_param->kernel_w_, UP_DIV(conv_param->output_w_ - ow, conv_param->dilation_w_)); for (int kh = kh_start; kh < kh_end; kh++) { for (int kw = kw_start; kw < kw_end; kw++) { int src_index = ih * conv_param->input_w_ * C4NUM + iw * C4NUM + kh * input_plane * conv_param->kernel_w_ * C4NUM + kw * input_plane * C4NUM; int dst_index = oh * conv_param->output_w_ * C4NUM + ow * C4NUM + kh * conv_param->dilation_h_ * conv_param->output_w_ * C4NUM + kw * conv_param->dilation_w_ * C4NUM; for (int i = 0; i < C4NUM; i++) { dst_ptr[dst_index + i] += src_ptr[src_index + i]; } } /*kw*/ } /*kh*/ } /*iw*/ } /*ih*/ } /*oc4*/ PostConvFuncFp32C4(tmp_c4, dst, bias, output_channel, output_plane, conv_param->output_channel_, conv_param->is_relu_, conv_param->is_relu6_); return NNACL_OK; }
5,894
2,207
#include "simulation/ElementCommon.h" int Element_RFRG_update(UPDATE_FUNC_ARGS); void Element::Element_RFGL() { Identifier = "DEFAULT_PT_RFGL"; Name = "RFGL"; Colour = PIXPACK(0x84C2CF); MenuVisible = 0; MenuSection = SC_LIQUID; Enabled = 1; Advection = 0.6f; AirDrag = 0.01f * CFDS; AirLoss = 0.98f; Loss = 0.95f; Collision = 0.0f; Gravity = 0.1f; Diffusion = 0.00f; HotAir = 0.000f * CFDS; Falldown = 2; Flammable = 0; Explosive = 0; Meltable = 0; Hardness = 20; Weight = 10; HeatConduct = 3; Description = "Liquid refrigerant."; Properties = TYPE_LIQUID|PROP_DEADLY; LowPressure = 2; LowPressureTransition = PT_RFRG; HighPressure = IPH; HighPressureTransition = NT; LowTemperature = ITL; LowTemperatureTransition = NT; HighTemperature = ITH; HighTemperatureTransition = NT; Update = &Element_RFRG_update; }
851
431
/*! * \file * \brief Plik nagłówkowy klasy DaneSymulacji. */ #ifndef DANE_HH #define DANE_HH #include <iostream> #include <fstream> #include <string> #include <vector> #include <QVector> #include <QString> #include <QDebug> #include <QFile> #include <iostream> #include <fstream> #include <string> using namespace std; /*! * \brief Klasa odpowiedzialna za kontrolę trybu symulacji. * * Klasa DaneSymulacji przechowuje informacje konieczne do poprawnego działania trybu symulacyjnego. */ class DaneSymulacji { public: /*! * \brief Konstruktor klasy DaneSymulacji. */ DaneSymulacji(); /*! * \brief Pole typu double przechowujące aktualny czas symulacji. */ double _aktualnyCzas; /*! * \brief Wektor typu double przechowujący wartości symulacji. */ vector<double> _wartosci; /*! * \brief Wektor typu double przechowujący czasy odpowiadające wartościom. */ vector<double> _czas; /*! * \brief Metoda wczytująca dane do symulacji z pliku. * \param[in] plik - łańcuch określający nazwę pliku z danymi * \return Nic nie jest zwracane. * * Metoda pobiera jako argument samą nazwę pliku i szuka go w folderze data wewnątrz katalogu projektu. */ void wczytajDane(string plik); /*! * \brief Pole typu string przechowujące kompletną ścieżkę do pliku z danymi. */ string _plikSymulacji; }; #endif
1,312
520
#pragma once #include <asio.hpp> #include "http_handler.hpp" #include <memory> #include <functional> #include <string> #include "uuid.hpp" #include <unordered_map> #include "string_view.hpp" #include "utils.hpp" #include <memory> #include "md5.hpp" #include <queue> #include <random> #include <list> #include "message_handler.hpp" #include "any.hpp" namespace xfinal { struct frame_info { frame_info() = default; bool eof; int opcode; int mask; std::uint64_t payload_length; unsigned char mask_key[4]; }; class websockets; class websocket; template<typename T> void close_ws(websocket& ws); inline void close_ws_with_notification(websocket& ws); class websocket_event final { friend class websockets; public: websocket_event() = default; public: template<typename Function, typename...Args> websocket_event& on(std::string const& event_name, Function&& function, Args&& ...args) { event_call_back_.insert(std::make_pair(event_name, on_help<(sizeof...(Args))>(0, std::forward<Function>(function), std::forward<Args>(args)...))); return *this; } void trigger(std::string const& event_name, websocket& ws) { auto it = event_call_back_.find(event_name); if (it != event_call_back_.end()) { (it->second)(ws); } } private: template<std::size_t N, typename Function, typename...Args, typename U = typename std::enable_if<std::is_same<number_content<N>, number_content<0>>::value>::type> auto on_help(int, Function && function, Args && ...args)->decltype(std::bind(std::forward<Function>(function), std::placeholders::_1)) { return std::bind(std::forward<Function>(function), std::placeholders::_1); } template<std::size_t N, typename Function, typename...Args, typename U = typename std::enable_if<!std::is_same<number_content<N>, number_content<0>>::value>::type> auto on_help(long, Function && function, Args && ...args)->decltype(std::bind(std::forward<Function>(function), std::forward<Args>(args)..., std::placeholders::_1)) { return std::bind(std::forward<Function>(function), std::forward<Args>(args)..., std::placeholders::_1); } private: std::unordered_map<std::string, std::function<void(websocket&)>> event_call_back_; }; class websocket_event_map { friend class websockets; friend class websocket; public: void trigger(const std::string& url, std::string const& event_name, websocket& ws) {//只是读 多线程没有问题 auto it = events_.find(url); if (it != events_.end()) { it->second.trigger(event_name, ws); } else { close_ws<void>(ws); } } void add(nonstd::string_view uuid,std::weak_ptr<websocket> weak) { std::unique_lock<std::mutex> lock(map_mutex_); websockets_.insert(std::make_pair(uuid, weak.lock())); } void remove(nonstd::string_view uuid) { std::unique_lock<std::mutex> lock(map_mutex_); auto it = websockets_.find(uuid); if (it != websockets_.end()) { websockets_.erase(it); } } ~websocket_event_map() { map_mutex_.lock(); auto copy_sockets = websockets_; map_mutex_.unlock(); for (auto&& wsocket : copy_sockets) { close_ws_with_notification(*wsocket.second); } } private: std::mutex map_mutex_; std::unordered_map<std::string, websocket_event> events_; std::unordered_map<nonstd::string_view, std::shared_ptr<websocket>> websockets_; }; struct send_message { std::shared_ptr<websocket> websocket_; std::shared_ptr<std::queue<std::shared_ptr<std::string>>> message_queue; std::shared_ptr<std::function<void(bool, std::error_code)>> write_callback; }; inline void send_to_hub(send_message const&); class websocket final :public std::enable_shared_from_this<websocket> { friend class websocket_hub; friend class connection; template<typename T> friend void close_ws(websocket& ws); public: websocket(websocket_event_map& web, std::string const& url) :websocket_event_manager(web), socket_uid_(uuids::uuid_system_generator{}().to_short_str()), url_(url){ } public: std::string const& uuid() { return socket_uid_; } bool is_open() { return socket_is_open_; } asio::ip::tcp::socket& socket() { return *socket_; } std::map<std::string, std::string> key_params () const noexcept { return decode_url_params_; } private: void move_socket(std::unique_ptr<asio::ip::tcp::socket>&& socket) { socket_ = std::move(socket); socket = nullptr; socket_is_open_ = true; auto& io = static_cast<asio::io_service&>(socket_->get_executor().context()); wait_read_timer_ = std::move(std::unique_ptr<asio::steady_timer>(new asio::steady_timer(io))); wait_write_timer_ = std::move(std::unique_ptr<asio::steady_timer>(new asio::steady_timer(io))); websocket_event_manager.trigger(url_, "open", *this); start_read(); } private: void start_read() { read_pos_ = 0; std::memset(frame, 0, sizeof(frame)); std::memset(&frame_info_, 0, sizeof(frame_info_)); auto handler = this->shared_from_this(); start_read_timeout(); //开始开启空连接超时 从当前时间算起 socket_->async_read_some(asio::buffer(&frame[read_pos_], 2), [handler,this](std::error_code const& ec, std::size_t read_size) { if (ec) { handler->close(); return; } cancel_read_time(); handler->frame_parser(); }); } public: nonstd::string_view messages() const { return message_; } unsigned char message_code() const { return message_opcode; } public: //void write(std::string const& message, unsigned char opcode) { // auto message_size = message.size(); // auto offset = 0; // if (message_size < 126) { // unsigned char frame_head = 128; // frame_head = frame_head | opcode; // unsigned char c2 = 0; // c2 = c2 | ((unsigned char)message_size); // std::string a_frame; // a_frame.push_back(frame_head); // a_frame.push_back(c2); // a_frame.append(message); // write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame)))); // } // else if (message_size >= 126) { // auto counts = message_size / frame_data_size_; // if ((message_size % frame_data_size_) != 0) { // counts++; // } // std::size_t read_pos = 0; // for (std::size_t i = 0; i < counts; ++i) { // std::int64_t left_size = std::int64_t(message_size) - std::int64_t(frame_data_size_); // unsigned short write_data_size = (unsigned short)frame_data_size_; // unsigned char frame_head = 0; // std::string a_frame; // if (left_size <= 0) { // frame_head = 128; // write_data_size = (unsigned short)message_size; // //frame_head = frame_head | opcode; // } // if (i == 0) { // frame_head = frame_head | opcode; // } // a_frame.push_back(frame_head); // unsigned char c2 = 0; // if (write_data_size >= 126) { // unsigned char tmp_c = 126; // c2 = c2 | tmp_c; // a_frame.push_back(c2); // auto data_length = l_to_netendian(write_data_size); // a_frame.append(data_length); // } // else if (write_data_size < 126) { // unsigned char tmp_c = (unsigned char)write_data_size; // c2 = c2 | tmp_c; // a_frame.push_back(c2); // } // a_frame.append(std::string(&message[read_pos], write_data_size)); // read_pos += write_data_size; // message_size = (std::size_t)left_size; // write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame)))); // } // } // write_frame(); //} void write(std::string const& message, unsigned char opcode, std::function<void(bool, std::error_code)> const& call_back) { auto message_size = message.size(); if (message_size == 0) { return; } auto offset = 0; //std::shared_ptr<std::string> write_data(new std::string()); std::shared_ptr<std::queue<std::shared_ptr<std::string>>> write_queue{ new std::queue<std::shared_ptr<std::string>> {} }; if (message_size < 126) { unsigned char frame_head = 128; frame_head = frame_head | opcode; unsigned char c2 = 0; c2 = c2 | ((unsigned char)message_size); std::shared_ptr<std::string> a_frame{new std::string()}; a_frame->push_back(frame_head); a_frame->push_back(c2); a_frame->append(message); write_queue->emplace(a_frame); //write_data->append(a_frame); /*write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame))));*/ } else if (message_size >= 126) { auto counts = message_size / frame_data_size_; if ((message_size % frame_data_size_) != 0) { counts++; } std::size_t read_pos = 0; for (std::size_t i = 0; i < counts; ++i) { std::int64_t left_size = std::int64_t(message_size) - std::int64_t(frame_data_size_); unsigned short write_data_size = (unsigned short)frame_data_size_; unsigned char frame_head = 0; std::shared_ptr<std::string> a_frame{ new std::string() }; if (left_size <= 0) { frame_head = 128; write_data_size = (unsigned short)message_size; //frame_head = frame_head | opcode; } if (i == 0) { frame_head = frame_head | opcode; } a_frame->push_back(frame_head); unsigned char c2 = 0; if (write_data_size >= 126) { unsigned char tmp_c = 126; c2 = c2 | tmp_c; a_frame->push_back(c2); auto data_length = l_to_netendian(write_data_size); a_frame->append(data_length); } else if (write_data_size < 126) { unsigned char tmp_c = (unsigned char)write_data_size; c2 = c2 | tmp_c; a_frame->push_back(c2); } a_frame->append(std::string(&message[read_pos], write_data_size)); read_pos += write_data_size; message_size = (std::size_t)left_size; write_queue->emplace(a_frame); //write_frame_queue_.emplace(std::unique_ptr<std::string>(new std::string(std::move(a_frame)))); //write_data->append(a_frame); } } /*write_frame();*/ send_message send_msg = { this->shared_from_this() ,write_queue,std::shared_ptr<std::function<void(bool,std::error_code)>>(new std::function<void(bool,std::error_code)>{call_back}) }; send_to_hub(send_msg); } public: void write_string(std::string const& message,std::function<void(bool,std::error_code)> const& call_back = nullptr) { write(message, 1, call_back); } void write_binary(std::string const& message, std::function<void(bool, std::error_code)> const& call_back = nullptr) { write(message, 2, call_back); } template<typename T> void set_user_data(std::string const& key,std::shared_ptr<T> const& value){ user_data_.emplace(key, value); } template<typename T> T get_user_data(std::string const& key) { auto it = user_data_.find(key); if (it != user_data_.end()) { return nonstd::any_cast<T>(it->second); } return nullptr;//error } private: //void write_frame() { // if (write_frame_queue_.empty()) { // return; // } // while (!write_frame_queue_.empty()) { // reset_time(); // auto frame = std::move(write_frame_queue_.front()); // write_frame_queue_.pop(); // asio::const_buffer buffers(frame->data(), frame->size()); // std::error_code ingore_ec; // asio::write(*socket_, buffers, ingore_ec); // if (ingore_ec) { // auto clear = std::queue<std::unique_ptr<std::string>>{}; // write_frame_queue_.swap(clear); // break; // } // } // // asio::async_write(*socket_,buffers, [frame = std::move(frame),handler = this->shared_from_this()](std::error_code const& ec,std::size_t size) { // // if (ec) { // // return; // // } // // handler->write_frame(); // // }); //} public: void start_read_timeout() { wait_read_timer_->expires_from_now(std::chrono::seconds(wait_read_time_)); auto handler = this->shared_from_this(); wait_read_timer_->async_wait([handler,this](std::error_code const& ec) { if (ec) { return; } std::stringstream ss; ss << "websocket id: "<< socket_uid_<< " read no data during " << wait_read_time_ << " seconds"; utils::messageCenter::get().trigger_message(ss.str()); handler->close(); }); } void cancel_read_time() { std::error_code ignore; wait_read_timer_->cancel(ignore); } void start_write_timeout() { wait_write_timer_->expires_from_now(std::chrono::seconds(wait_write_time_)); auto handler = this->shared_from_this(); wait_write_timer_->async_wait([handler,this](std::error_code const& ec) { if (ec) { return; } std::stringstream ss; ss << "websocket id: " << socket_uid_ << " couldn't write data during " << wait_write_time_ << " seconds"; utils::messageCenter::get().trigger_message(ss.str()); handler->close(); }); } void cancel_write_time() { std::error_code ignore; wait_write_timer_->cancel(ignore); } void ping() { //ping_pong_timer_->expires_from_now(std::chrono::seconds(ping_pong_time_)); //ping_pong_timer_->async_wait([handler = this->shared_from_this()](std::error_code const& ec) { // if (ec) { // return; // } // handler->write("", 9); // handler->reset_time(); // handler->ping(); //}); } private: void frame_parser() { read_pos_ += 2; unsigned char c = frame[0]; frame_info_.eof = c >> 7; frame_info_.opcode = c & 15; if (frame_info_.opcode) { message_opcode = (unsigned char)frame_info_.opcode; } if (frame_info_.opcode == 8) { //关闭连接 close(); return; } if (frame_info_.opcode == 9) { //ping write("", 10,nullptr); //回应客户端心跳 return; } if (frame_info_.opcode == 10) { //pong cancel_read_time(); return; } unsigned char c2 = frame[1]; frame_info_.mask = c2 >> 7; if (frame_info_.mask != 1) { //mask 必须是1 close(); return; } c2 = c2 & 127; if (c2 < 126) { //数据的长度为当前值 frame_info_.payload_length = c2; handle_payload_length(0); } else if (c2 == 126) { //后续2个字节 unsigned auto handler = this->shared_from_this(); start_read_timeout(); asio::async_read(*socket_, asio::buffer(&frame[read_pos_], 2), [handler,this](std::error_code const& ec, std::size_t read_size) { if (ec) { handler->close(); return; } cancel_read_time(); handler->handle_payload_length(2); }); } else if (c2 == 127) { //后续8个字节 unsigned auto handler = this->shared_from_this(); start_read_timeout(); asio::async_read(*socket_, asio::buffer(&frame[read_pos_], 8), [handler,this](std::error_code const& ec, std::size_t read_size) { if (ec) { handler->close(); return; } cancel_read_time(); handler->handle_payload_length(8); }); } } void handle_payload_length(std::size_t read_size) { //if length >126 if (read_size == 2) { unsigned short tmp = 0; netendian_to_l(tmp, &(frame[read_pos_])); frame_info_.payload_length = tmp; } else if (read_size == 8) { std::uint64_t tmp = 0; netendian_to_l(tmp, &(frame[read_pos_])); frame_info_.payload_length = tmp; } if (frame_info_.mask == 1) { //应该必须等于1 auto handler = this->shared_from_this(); start_read_timeout(); asio::async_read(*socket_, asio::buffer(&frame_info_.mask_key[0], 4), [handler,this](std::error_code const& ec, std::size_t read_size) { if (ec) { handler->close(); return; } cancel_read_time(); handler->read_data(); }); } } void read_data() { if (frame_info_.payload_length == 0) { //没有数据需要读取 if (frame_info_.eof) { message_ = std::string(); buffers_.resize(0); data_current_pos_ = 0; //数据帧都处理完整 回调 websocket_event_manager.trigger(url_, "message", *this); } start_read(); return; } expand_buffer(frame_info_.payload_length); auto handler = this->shared_from_this(); start_read_timeout(); asio::async_read(*socket_, asio::buffer(&buffers_[data_current_pos_], (std::size_t)frame_info_.payload_length), [handler,this](std::error_code const& ec, std::size_t read_size) { if (ec) { handler->close(); return; } cancel_read_time(); handler->set_current_pos(read_size); handler->decode_data(read_size); }); } void decode_data(std::size_t use_size) { unsigned char* iter = &(buffers_[data_current_pos_ - use_size]); for (std::size_t i = 0; i < use_size; ++i) { auto j = i % 4; auto mask_key = frame_info_.mask_key[j]; *iter = (*iter) ^ mask_key; ++iter; } if (frame_info_.eof) { message_ = std::string(buffers_.begin(), buffers_.begin() + data_current_pos_); buffers_.resize(0); data_current_pos_ = 0; //数据帧都处理完整 回调 websocket_event_manager.trigger(url_, "message", *this); } start_read(); } void set_current_pos(std::size_t size) { data_current_pos_ += size; } std::size_t left_buffer_size() { return buffers_.size() - data_current_pos_; } void expand_buffer(std::uint64_t need_size) { auto left_size = left_buffer_size(); if (need_size > left_buffer_size()) { auto total_size = buffers_.size() + (need_size - left_size); buffers_.resize((std::size_t)total_size); } } public: void set_check_alive_time(std::time_t seconds) { wait_read_time_ = seconds; } void set_frame_data_size(std::size_t size) { frame_data_size_ = size; } void set_check_write_alive_time(std::time_t seconds) { wait_write_time_ = seconds; } public: void close() { if (socket_is_open_) { std::error_code ec; socket_->shutdown(asio::ip::tcp::socket::shutdown_both, ec); std::error_code ec0; socket_->close(ec0); socket_is_open_ = false; is_writing_ = false; cancel_read_time(); cancel_write_time(); //ping_pong_timer_->cancel(); websocket_event_manager.trigger(url_, "close", *this); //关闭事件 websocket_event_manager.remove(nonstd::string_view(socket_uid_.data(), socket_uid_.size())); } } void shutdown() { null_close(); } private: void null_close() { //无路由的空连接需要关闭 std::error_code ec; socket_->shutdown(asio::ip::tcp::socket::shutdown_both, ec); std::error_code ec0; socket_->close(ec0); socket_is_open_ = false; is_writing_ = false; cancel_read_time(); cancel_write_time(); //ping_pong_timer_->cancel(); websocket_event_manager.remove(nonstd::string_view(socket_uid_.data(), socket_uid_.size())); } private: std::unique_ptr<asio::ip::tcp::socket> socket_; websocket_event_map& websocket_event_manager; std::string socket_uid_; std::vector<unsigned char> buffers_; unsigned char frame[10] = {0}; frame_info frame_info_; std::size_t read_pos_ = 0; std::size_t data_current_pos_ = 0; std::string message_; std::string const url_; //std::queue<std::unique_ptr<std::string>> write_frame_queue_; std::size_t frame_data_size_ = 65535;//256 //std::time_t ping_pong_time_ = 30 * 60 * 60; std::time_t wait_read_time_ = 30 * 60; std::time_t wait_write_time_ = 30 * 60; std::unique_ptr<asio::steady_timer> wait_read_timer_; std::unique_ptr<asio::steady_timer> wait_write_timer_; //std::unique_ptr<asio::steady_timer> ping_pong_timer_; unsigned char message_opcode = 0; std::atomic_bool socket_is_open_{ false }; std::atomic_bool is_writing_{ false }; std::map<std::string, nonstd::any> user_data_; std::map<std::string, std::string> decode_url_params_; }; class websocket_hub { friend class http_router; public: static websocket_hub& get() { static websocket_hub instance; return instance; } public: void add(send_message const& message) { std::unique_lock<std::mutex> lock(list_mutex_); message_list_.emplace_back(message); lock.unlock(); condtion_.notify_all(); } private: void write_ok(std::shared_ptr<websocket> const& websocket) const { websocket->is_writing_ = false; } void close_socket(std::shared_ptr<websocket> const& websocket) const { websocket->close(); } private: void write_frame(std::shared_ptr<websocket> const& websocket, std::shared_ptr<std::queue<std::shared_ptr<std::string>>> const& frame_queue, std::shared_ptr<std::function<void(bool, std::error_code)>> const& call_back) const { if (frame_queue->empty() || !websocket->is_open()) { write_ok(websocket); if (call_back != nullptr && *call_back != nullptr) { (*call_back)(true, std::error_code{}); } return; } auto a_frame = frame_queue->front(); frame_queue->pop(); auto buff = asio::buffer(a_frame->data(), a_frame->size()); websocket->start_write_timeout(); asio::async_write(*websocket->socket_, buff, [websocket, a_frame, frame_queue, this, call_back](std::error_code const& ec, std::size_t size) { websocket->cancel_write_time(); if (ec) { close_socket(websocket); if (call_back != nullptr && *call_back != nullptr) { (*call_back)(false, ec); } return; } write_frame(websocket, frame_queue, call_back); }); } private: void send() { while (true) { std::unique_lock<std::mutex> lock(list_mutex_); condtion_.wait(lock, [this]() { return message_list_.empty() == false; }); if (end_thread_ == true) { return; } auto one = message_list_.front(); message_list_.pop_front(); auto websocket = one.websocket_; auto message = one.message_queue; auto write_callback = one.write_callback; if (websocket->socket_is_open_ == true && websocket->is_writing_ == false) { websocket->is_writing_ = true; write_frame(websocket, message, write_callback); } else if (websocket->socket_is_open_ == true && websocket->is_writing_ == true) { message_list_.push_back(one); } } } private: websocket_hub() = default; private: std::mutex list_mutex_; std::condition_variable condtion_; std::list<send_message> message_list_; std::atomic_bool end_thread_{ false }; }; inline void send_to_hub(send_message const& message) { websocket_hub::get().add(message); } template<typename T> void close_ws(websocket& ws) { ws.null_close(); } void close_ws_with_notification(websocket& ws) { ws.close(); } class websockets final :private nocopyable { friend class connection; public: using event_reg_func = std::function<void(websocket&)>; public: std::shared_ptr<websocket> start_webscoket(std::string const& url) { //有多线程竞争 auto ws = std::make_shared<websocket>(websocket_event_map_, url); ws->set_check_alive_time(websocket_check_read_alive_time_); ws->set_check_write_alive_time(websocket_check_write_time_); ws->set_frame_data_size(frame_data_size_); auto& uuid = ws->uuid(); websocket_event_map_.add(nonstd::string_view{ uuid.data(),uuid.size() }, ws); return ws; } void add_event(std::string const& url, websocket_event const& websocket_event_) {//注册事件 没有多线程竞争 websocket_event_map_.events_.insert(std::make_pair(url, websocket_event_)); } public: void set_check_read_alive_time(std::time_t seconds) { if (seconds <= 0) { return; } websocket_check_read_alive_time_ = seconds; } std::time_t get_check_read_alive_time() { return websocket_check_read_alive_time_; } void set_check_write_alive_time(std::time_t seconds) { if (seconds <= 0) { return; } websocket_check_write_time_ = seconds; } std::time_t get_check_write_alive_time() { return websocket_check_write_time_; } void set_frame_data_size(std::size_t size) { if (size <= 0) { return; } frame_data_size_ = size; } std::size_t get_frame_data_size() { return frame_data_size_; } private: bool is_websocket(request& req) { using namespace nonstd::string_view_literals; if (req.method() != "GET"_sv) { return false; } auto connection = req.header("connection"); if (connection.empty() && to_lower(view2str(connection)) != "upgrade") { return false; } auto upgrade = req.header("upgrade"); if (upgrade.empty() && to_lower(view2str(upgrade)) != "websocket") { return false; } auto sec_webSocket_key = req.header("Sec-WebSocket-Key"); if (sec_webSocket_key.empty()) { return false; } auto sec_websocket_version = req.header("Sec-WebSocket-Version"); if (sec_websocket_version.empty()) { return false; } sec_webSocket_key_ = sec_webSocket_key; sec_websocket_version_ = sec_websocket_version; return true; } void update_to_websocket(response& res) { res.add_header("Connection", "Upgrade"); res.add_header("Upgrade", "websocket"); auto str = view2str(sec_webSocket_key_) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; auto result = to_base64(to_sha1(str)); res.add_header("Sec-WebSocket-Accept", result); res.add_header("Sec-WebSocket-Version", view2str(sec_websocket_version_)); res.write_state(http_status::switching_protocols); } private: nonstd::string_view sec_webSocket_key_; nonstd::string_view sec_websocket_version_; websocket_event_map websocket_event_map_; std::time_t websocket_check_read_alive_time_ = 30*60; std::time_t websocket_check_write_time_ = 30 * 60; std::size_t frame_data_size_ = 65535; }; }
25,018
10,932
/* The MIT License Copyright (c) 2021, Prominence AI, Inc. 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 "catch.hpp" #include "Dsl.h" #include <glib/gstdio.h> #include <gtypes.h> #include "DslSoupServerMgr.h" using namespace DSL; SCENARIO( "A Signaling Transceiver is created correctly", "[SoupServerMgr]" ) { GIVEN( "Attribute for a new Client Reciever" ) { WHEN( "The Signaling Transceiver is created" ) { std::unique_ptr<SignalingTransceiver> pSignalingTransceiver= std::unique_ptr<SignalingTransceiver>(new SignalingTransceiver()); THEN( "All attributes are setup correctly" ) { REQUIRE( pSignalingTransceiver->GetConnection() == NULL); } } } } SCENARIO( "A Soup Server Manager can listen on and disconnect from a specific port number", "[SoupServerMgr]" ) { GIVEN( "A the Soup Server manager" ) { uint initialPortNumber(99); REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false ); REQUIRE( initialPortNumber == 0 ); WHEN( "The Soup Server Manager starts listening on a specified port" ) { uint newPortNumber(DSL_WEBSOCKET_SERVER_DEFAULT_WEBSOCKET_PORT); uint retPortNumber(0); REQUIRE( SoupServerMgr::GetMgr()->StartListening(newPortNumber) == true ); REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&retPortNumber) == true ); REQUIRE( retPortNumber == newPortNumber ); // Second call to start when already listening must fail REQUIRE( SoupServerMgr::GetMgr()->StartListening(newPortNumber) == false ); THEN( "The Soup Server Manager can stop listening successfully." ) { REQUIRE( SoupServerMgr::GetMgr()->StopListening() == true ); // Second call with the same Signaling Transceiver must fail REQUIRE( SoupServerMgr::GetMgr()->StopListening() == false ); REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false ); REQUIRE( initialPortNumber == 0 ); } } } } SCENARIO( "A Soup Server Manager can add and listen for a new URI", "[SoupServerMgr]" ) { GIVEN( "A the Soup Server manager" ) { uint initialPortNumber(99); REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false ); REQUIRE( initialPortNumber == 0 ); WHEN( "A new URI is added to the Soup Server Manager" ) { std::string newPath("/ws/new_path"); REQUIRE( SoupServerMgr::GetMgr()->AddPath(newPath.c_str()) == true ); THEN( "The Soup Server Manager starts and stops listening correctly." ) { uint newPortNumber(DSL_WEBSOCKET_SERVER_DEFAULT_WEBSOCKET_PORT); uint retPortNumber(0); REQUIRE( SoupServerMgr::GetMgr()->StartListening(newPortNumber) == true ); REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&retPortNumber) == true ); REQUIRE( retPortNumber == newPortNumber ); REQUIRE( SoupServerMgr::GetMgr()->StopListening() == true ); REQUIRE( SoupServerMgr::GetMgr()->GetListeningState(&initialPortNumber) == false ); REQUIRE( initialPortNumber == 0 ); } } } } SCENARIO( "A Signaling Transceiver can be added and removed ", "[SoupServerMgr]" ) { GIVEN( "A new Client Reciever" ) { std::unique_ptr<SignalingTransceiver> pSignalingTransceiver= std::unique_ptr<SignalingTransceiver>(new SignalingTransceiver()); WHEN( "The Signaling Transceiver is added the Soup Server Manager" ) { // First call initializes the singlton, if not called already REQUIRE( SoupServerMgr::GetMgr()->AddSignalingTransceiver(pSignalingTransceiver.get()) == true); // Second call with the same Signaling Transceiver must fail REQUIRE( SoupServerMgr::GetMgr()->AddSignalingTransceiver(pSignalingTransceiver.get()) == false); THEN( "The same Signaling Transceiver can be removed" ) { REQUIRE( SoupServerMgr::GetMgr()->RemoveSignalingTransceiver(pSignalingTransceiver.get()) == true); // Second call with the same Signaling Transceiver must fail REQUIRE( SoupServerMgr::GetMgr()->RemoveSignalingTransceiver(pSignalingTransceiver.get()) == false); } } } } SCENARIO( "A Connection event after removing the only client is handled correctly", "[SoupServerMgr]" ) { GIVEN( "A new Client Reciever" ) { std::unique_ptr<SignalingTransceiver> pSignalingTransceiver= std::unique_ptr<SignalingTransceiver>(new SignalingTransceiver()); std::string pathString("ws"); WHEN( "The Signaling Transceiver is added the Soup Server Manager" ) { // First call initializes the singlton REQUIRE( SoupServerMgr::GetMgr()->AddSignalingTransceiver(pSignalingTransceiver.get()) == true); // Remove the client reciever leaving the Soup Server without a client. REQUIRE( SoupServerMgr::GetMgr()->RemoveSignalingTransceiver(pSignalingTransceiver.get()) == true); THEN( "When a new connection is simulated" ) { SoupWebsocketConnection connection; SoupServerMgr::GetMgr()->HandleOpen(&connection, pathString.c_str()); } } } } static void websocket_server_client_listener_1(const wchar_t* path, void* client_data) { std::cout << "Websocket client listener 1\n"; } static void websocket_server_client_listener_2(const wchar_t* path, void* client_data) { std::cout << "Websocket client listener 2\n"; } SCENARIO( "A Websocket client listener can be added and removed from the Soup Server Manger", "[SoupServerMgr]" ) { GIVEN( "The Soup Server Manger" ) { WHEN( "The client listener is added to the Soup Server Manager" ) { // First call initializes the singlton, if not called previously by other test cases. REQUIRE( SoupServerMgr::GetMgr()->AddClientListener( websocket_server_client_listener_1, NULL) == true ); // Second call with the same Signaling Transceiver must fail REQUIRE( SoupServerMgr::GetMgr()->AddClientListener( websocket_server_client_listener_1, NULL) == false ); THEN( "The same Signaling Transceiver can be removed" ) { REQUIRE( SoupServerMgr::GetMgr()->RemoveClientListener( websocket_server_client_listener_1) == true ); // Second call with the same Signaling Transceiver must fail REQUIRE( SoupServerMgr::GetMgr()->RemoveClientListener( websocket_server_client_listener_1) == false ); } } } } SCENARIO( "A Connection event results in the Soup Server client listener to be called", "[SoupServerMgr]" ) { GIVEN( "A new Client Reciever" ) { std::string pathString("ws"); // First call initializes the singlton, if not called previously by other test cases. REQUIRE( SoupServerMgr::GetMgr()->AddClientListener( websocket_server_client_listener_1, NULL) == true ); REQUIRE( SoupServerMgr::GetMgr()->AddClientListener( websocket_server_client_listener_2, NULL) == true ); WHEN( "When a new socket open event occurrs" ) { SoupWebsocketConnection connection; SoupServerMgr::GetMgr()->HandleOpen(&connection, pathString.c_str()); THEN( "Both client listners are called " ) { // Note: requires visual confirmation of console statements } } } }
8,990
2,669
int iN, aW, N/*hA*/ ,AK8, Vi0 , QCmew, bs,iio1,El , A3 , bZV , BTJ61W ,cAgH2,uL , VWN,lsQZ/*K4*/ , nKtYm,/*7R9d*/ HRZ ,tBMY, ohG , cgGKP,xbFv, BBi , gR ,//j9l Ek, OD1 ,S6A//Ma , tvG,Gy, b , tylWc ,/*g*/ wby,gUK,BMc , r3,zHKSm ,jL ,Jivf , Zcr ,ehp ,LG, Ue,fly;void f_f0()//vtg {int n5kter ; volatile int UuR , fc4IA, vSA , HGn , // dTr , IQ5, taB ;{volatile int J,FPq, Q , b9qB , OC , Bu/*a*/;if /*A*/( true ) fly= Bu + J + FPq/*Yyad*/+ Q + b9qB+OC ;else { int D3//N8i ; volatile int dBTo// ,Xf0 ,SaN , Dw;return ;//W { {{} { } }} {volatile int I, Ry; {} iN = Ry + I ;/*c*/}for (int /*y*/ i=1; i< 1 ;++i ){volatile int CP2 , BX,Zpg,VgFCPuF, eT //Udf ,XJNti; /*eR6*/aW=XJNti //G + CP2 +BX ;for(int i=1 ; i<2 ;++i )N = Zpg+ VgFCPuF +eT ; } D3= Dw + dBTo + Xf0 +SaN;/*5*/{{ return ; }}}; if /*iAd*/(true){ volatile int Xs ,T, P9la ,O ;if( true) for(int i=1 ; i< 3;++i)/*t*/{int PAi;volatile int QHf6,P5x, qF;PAi= qF+// QHf6+ P5x //J ;{volatile int cUVO,qM; AK8=/*N0P*/ qM + cUVO ;}for (int i=1;i<4;++i) return ; { } } else{ volatile int fjlLC /*pI*/, TX ; Vi0=TX +fjlLC//DAUF ; }; {{ }}QCmew =O +Xs + T +P9la;}else {int s; volatile int df, V , Lwiv ,CBu ; s=CBu + df + V +Lwiv ;for (int i=1 ; //YZ i< 5;++i)/*1*/return//YK ;{int o7 ; volatile int K //Kg , jX;; o7 = /*RGu*/jX + K ; } } }n5kter=taB +UuR +fc4IA + vSA +HGn+dTr+IQ5 ; return ; for (int i=1; i<6 ;++i )for (int i=1;i< //ci 7 ;++i ){ volatile int JO1f,IXqn6, Lu ,oRMf, BYJG;; if//Q4G ( true )return ; else bs =BYJG+ JO1f//cw + IXqn6+ Lu+oRMf ; { { { { }{}}};//231S } return ;{ for (int i=1 ;i< 8 ;++i) return ; { {//GS ; } } {return ;; { { }}} {/**/;return/*x*/ ; } }{int i8O;volatile int CCFF,ft6S9,fDzsV//x ,uaPIH; return//ZA ; return ; i8O =uaPIH +CCFF + ft6S9//j //Xq +fDzsV ; } } /*0aG*/ return ;}void f_f1 (){volatile int Wzx , erI5J ,bCD , LX/*J*/ ,C , u, Mu ; { { volatile int /*n*/ U8GU , gj , h,uC ; ;iio1= uC+ U8GU+gj+ h ; { { };for (int i=1;i<9 ;++i ) { } } } ; return ;} for(int i=1 /*dwW76*/;i< 10 ;++i ) { int/*Y*/ D7 ;//29P volatile int Do , DVd , TB,/*fBpR*/// /*VF*/ VJB, cxtax ,deh , VT//M3 ,B , Qq80 ; if( true) if(true ) D7 =Qq80 + Do + DVd +TB + VJB ; else{volatile int hBr, Ry2 , hmC3 ,M ;/*X*/{return ;}El=M + hBr+/*h7pI*/Ry2 + hmC3; //5jxQ {{{}}for(int i=1 ; i<11 ;++i ){ { }} } ; }else A3 /*S*/= cxtax+ deh+ VT/**//*Ao*/+ B ; { { return ; { ;}{ { };{//Csa } }} { ;//j } }return/**/ ;/*Hzi*/ if ( true) /*4O*/return ; else { return ; return ;{{ { }/**/}{/*8bX*/for(int i=1/*K1*/ ;i< 12;++i) for (int i=1 ; i<13 ;++i)return ; } { } }return ;}} for(int i=1 ; i< 14 ;++i ) { int tL ; volatile int//Yys NvW ,a/**/ , iIPf , VY ,p ,//dkiH Oc ;/*FZRx*/ { volatile int/*1L*/ IhM , wcEy ,A3a , gjjl ; ; bZV = gjjl+ IhM+ wcEy + A3a ; { int xeolf;volatile int Y ,DdPJDs,cfl//w ,PvoQG/*yU*/; {};return ;xeolf= PvoQG+ Y+ DdPJDs //D8P + cfl ; } } tL/*U*/=Oc /*tR*/+NvW +a + iIPf+ //6y16 VY+p;if/*N5CI*/(/*s2gki*/true ) { int rS ; volatile int fi4,RGBPw8, re18 , cxD ;rS = cxD + fi4 + RGBPw8+ re18;{ return//xlF ;}} else{ /*iBU4HzeB*/{for (int i=1;/*r5j*/i< 15 ;++i) {}{}}for(int i=1; i<16 ;++i//NFzwR ) { {volatile int cr ; for (int i=1; i< 17 ;++i )//qfW /*2I*/{ } BTJ61W=cr ; } ;{ { } } }{ { /*xTS*/{ }if( true );else{ //rjg } }} }{ volatile int lI,iRj ,Qr ,/*8D*/ VctV ;{int IE1IB ; volatile int eurp,j, gx3, u5O7B ;/*e*/ for(int i=1 ;i< 18 ;++i )if( true) cAgH2= u5O7B+ eurp; else//7 { }//Jo if( true //h2tyM )IE1IB= j+gx3 ;else if (true/*9*/)for (int i=1 ; i< 19;++i ) { }/*UYP*/ else{ { //aU }for (int i=1 ; i<20;++i ) ; } {/*g*/{//Hh }}} for(int i=1 ;i<21 ;++i)/*ao*/if (true/*SN*/ )uL = VctV/*UaJc*/ + lI +iRj+Qr ;else{ { { for (int i=1 ;/*T*//*i*/i<22 ;++i ) ;}} }//T }} {;{{{ { }} } ; } { int ln123 ;volatile int//q oaq0 ,KX ,ORYNf,W ; for(int i=1; i< 23 /*qW7*/;++i ) {int vo ;volatile int n ,FIFGT2;for //Amt (int i=1; i<24 ;++i){}//RYo vo = FIFGT2//h +n ;}ln123 =W+ oaq0+//w7 KX+ ORYNf ;} {return ; ;//q }{/*wzy6*/ {int TU; volatile int g2,//Lf1q BE ,//H qiH,j4,je8n ;for (int i=1;//BUy i< 25 ;++i //GT ) { }// TU= je8n+ g2 + BE +qiH + /*PrLU*/ j4 ; }return ;{{ volatile int/*qR1*/ DK ;VWN = DK; }} if( true){ { for (int i=1 ; i<26 ;++i ) { volatile int kO ;lsQZ=kO ;return ;} }} else{if( true ) { }else//Yh { }//WN2u {}}//g ; } } nKtYm=Mu +Wzx+erI5J +bCD +LX+C+u ;{int WGbb; volatile int VRFK,WS ,//t xc ,GFx, Dtcq ;WGbb//YIz //fZ =//B Dtcq +VRFK// +WS//Qh + xc+GFx ; return ;/*E3t*/ return ; { volatile int RrX,//iQt LIqLnz, Yf ; for(int i=1; i< 27 ;++i)HRZ =Yf+ RrX +LIqLnz ;;if( true)for(int i=1 ; i< 28;++i) { return ; return ; }else ;} { /*uj5*/ { return ;} {volatile int A , c5/*m*/;if( true) if ( true ){ {}} else tBMY=c5 + A /*E*/ ;else{ }for (int i=1 ; i< 29;++i/*vk*/) ;/*r*/ ;}; }{ int Pd; volatile int //JZ M5bGt ,kDR18U, /*fGp*/ kVH , /*Vl*/ TG , yla, eAZ;{ { ;} { int g38 ;volatile int mLYH ,z9B ; ;for(int i=1; i<30;++i ) if( true//ID )/*f4Wr*/if ( true) {} else for (int i=1;i<31 ;++i ) g38= z9B//6 // + mLYH/*5n*/ ; else// { }}{ {}{} }}if (true ) Pd=eAZ+ M5bGt+ kDR18U ; else ohG =kVH + TG + yla ;} } return ; return ; }void f_f2() {int ggsq ;//IPv volatile int iW8 , fC , lF9 ,//HZ ZgT ,ACJ , lt3lf// ,id , spd, BaV4 , Gk ,//62eyaw gOp, U, ibD ; /*0cC*/if (true /*U7*/) ; else ;cgGKP =ibD + iW8 + fC+ lF9+ZgT + ACJ;ggsq = lt3lf+//kF id + spd /*W*/+ BaV4 + Gk +gOp +U ;; {{int wV3A ; volatile int v ,tw , Qv1Gj,N6u0 ,//p4prhZ WyD/*g*//*XYc*/; wV3A=WyD +v +tw +//BAux2 Qv1Gj + N6u0 ;{volatile int IxZX , JPtW,/**/mo ; xbFv = mo +IxZX+ JPtW ; for (int i=1 ; //Y24 i<32 ;++i ) { }if(true) return ; else for(int i=1;i< 33 ;++i) {}} { {}} } { ; {/*GQR*/ return ; /*E8qy*/ } }{ volatile int /**/ Xq /*6gq7*/ ,cG,S , tHty; BBi=/*bxDQ*///rRPPt tHty +Xq+ cG +S ;;for//Rg2nZ (int i=1;i<34;++i ){ ; { } { {} }}} }return/*MXq*/ ; } int main() { {volatile int uI , eC ,Up,K0R2 ,//UWUM EPCm//u8p ;{ volatile int WThA , bBC ,X21 ;for (int //ec i=1 ; i< 35 ;++i )/*Q8b*//*c*/if (true) {/*dv*/int CFl;volatile int Hl ,/**/ wDq ; CFl//XK5 = wDq/*n*/ + Hl; }else{ { } { int Njh ;volatile int l3W ; for(int i=1 ; i<36/*dSj*/;++i ) if(true ){ {}for (int i=1 ; i< 37 ;++i )/*rV*/{ }}//N else for (int i=1 ; i< //wG 38 ;++i ){}Njh= l3W ;return 1459539307; }} if (true)//zd { {{ }{ ; }}} else gR = X21 + WThA+bBC ; ; }if ( true/**/) { return 450129796 ; { int iJGW4 ;volatile int EIi , CELl , cH3t, ebh ,mHL,//S lgbJF ; for (int i=1 ; i<39 ;++i)Ek= lgbJF +/*qD*/EIi+ CELl; iJGW4 =cH3t +ebh +mHL/**/;}{ volatile int Ekwc , q; {{} return//WUCIv 77365647; //fCo } OD1=q+//8 Ekwc; }{/*IGp*/{ ; }} if //ROoq (/*7*/ true )for (int i=1 ;//2 i< 40//6cY ;++i ) return 966886858 ; else return 61553154 ;{{{ }{ return 254619342 ;}}}for(int i=1; i< 41/*PK1Hs*/;++i ) ;} else{ int h5di/*Ti*/;volatile int ka//FF ,Zc8R /*68PHtN*/,XGro; {volatile int GJ2,tbnaB//Bf ; S6A= tbnaB+ /*gVNJv*/GJ2 ;//Ko if(true/*pGa6*//*W*/ ); else{return 1301871030 ; } } /*ZVe*/for (int /*7O*/i=1;i< 42 ;++i//v )if(true/*CKR*/ ) if(true )h5di=XGro +/*o*/ka +Zc8R ; else return 501854691 ;else /*BaNt*/{for // (int /*S*/i=1;i< 43;++i ){if ( true) return //cq 834040775/*94OMC*/; else{ {}} { { if( true){} else { }} }/*dTu*/ } { ; ; }//F }; /*X*/} tvG =EPCm+ uI+ eC +Up + /*Q*/K0R2;; }return 493153421 ; { { {/*oIE*/{ if(true){ } else //pmx { }/*OfV*/ //2W }{ ; } } //t for//Pfe (int i=1 ;i<44/*M*/;++i ) { volatile int qC2 ,X7, jYR , sm ,F9VH/*Tp*/ ;Gy = F9VH+qC2 ; { { } ; } b = X7+jYR+ sm/*YqhC*/;/*qV*/} { { {} } { }} ; } /*Im*/{{volatile int tws, Uf,PrHRv;{{}/*g*/} ; tylWc=PrHRv + tws +/*Gycm*/Uf; } { ; if(true )//D48 { int QB;//Aw volatile int eL3, Xp; return 1486057255; {// } { } return 724636532 ; QB =Xp + eL3; } else { volatile int dp/*LW*/ , GjQWFe/*Qp*/ ;wby= GjQWFe+dp ; }}return 1870620381 ; } if (true){ for (int i=1 ;i<45 ;++i ) //h ;{ {/*TD*/ {return 307491052 ;/*SoA*/} } { } } for (int i=1 ;i<46;++i ) { { } { volatile int d ,FW ; gUK =FW + d ; { int OJD; volatile int c ; ; if (true ){} else for(int i=1 ; i< 47 ;++i//cAs ) OJD =c ;}}}if(true)if ( true ) {int keT ;volatile int uJ, //9e hw,x,xm ; {{} } { ;//JwS {{}; } }for(int //L i=1 ; i<48 ;++i)/*S*/keT=xm+/*jt*/ uJ+hw +x ; {volatile int Czf//9CtW , //J PQJ ; BMc=PQJ + Czf ; }}else { volatile int nC5 , l ,UXFnU ; if (true) {int xNS;volatile int q3 , tlG, DRX;xNS = DRX +q3 +tlG/*2V*/ ; } else {; }r3 //dL = UXFnU +nC5+ l ; }else for (int i=1 ;i< 49 ;++i ){{ } {volatile int vDrLW,Ag//T , Lmf ;zHKSm=Lmf +vDrLW +Ag ; }}}//6A else { for /*3r8*/(int i=1/*d*/;i< 50;++i ) { for (int i=1 ; i< 51 ;++i );} return 26605759 ;{if/**/ ( true ){ int D6S ;volatile int s2J, Nd; D6S = Nd+ s2J ;/*eRQ4*/} else { {}} {} /*QSFr*/{/*pf*/{ }//OSkg /*V3H*/}}} } {int irM6 ; volatile int QO , vLi3 ,TwH, w, dMZ7o/*mN0*/; { {//KvK int// WL ; volatile int tAl,cT, bTy; {{} return 1839056157;} { /**/}WL = bTy +tAl +cT ;}for(int i=1 ; i<52 ;++i ) { {} //eI {for(int i=1 ; i< 53 ;++i){ for(int /*D*/i=1 ; i< 54 ;++i) {} } for (int /*bR*/i=1 ; i<55;++i //9y /**/) {} }} { //N3j if( true) {}/*JT*/ else{ } return 699596162 ;{ volatile int //Ot qTjy/**/,S9v ,FsT , lh; jL = lh +qTjy ; if (true){/*vZ*/} else for (int i=1 ; i< 56;++i ) Jivf//g3qjW =S9v + FsT ; }{ {}{ }} }}; irM6 = dMZ7o + QO+ vLi3+TwH+ w ; } {int R ;/*63*/volatile int Z ,/*z8*/ b9G,wR0 , kV, Gg9O ; /**/if( /*UaN*/ true) {volatile int jpR /**/ ,CqK, PMxc,/*ncX*/ Ow ; { { {for (int i=1; i< 57 ;++i){ } }} { if( true) {} else {} }} Zcr=Ow + jpR + CqK + PMxc ; } else for (int i=1;i<58;++i )R //a = Gg9O +Z + b9G + wR0 //ZYO +kV ; {{ ;} //c0 for(int i=1;i< 59 ;++i ) { for (int /*DS*/i=1 ; i< //m 60 ;++i ); ;//MM }}// for(int i=1 ;i< 61/**/;++i ); { if ( true)for//G6 (int i=1; i< 62;++i /*Vt*/) {{int aP7 ;volatile int yXuqh ,fg3; { } ; { {} }aP7 = fg3+yXuqh; }{if/*cddz*/ ( true); else for //M6vE (int i=1 ;i< 63;++i ){{ }} } }else //I { volatile int upr ,vx, n7w /*PfXG*/ , eve,r ;if(true )if ( //V true ) {{} } else ehp= r+ upr + vx ; else LG = n7w+eve ;{}} if ( true)/*2mtV*/{ { return 1669666163 ; //ZSt } } else { volatile int ZO, SLUs ;/*asJ*/ // if ( true )Ue //vB =SLUs+ ZO; else if (true//uI ); else ;}};if (true) {for(int i=1 ;i< 64 ;++i) {return 231352685 //2 ;//rj0sm }//q { {/*4*/ } }}else return 1008721898 ; } }
11,145
7,725
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 <iostream> #include "itkCropImageFilter.h" #include "itkSimpleFilterWatcher.h" #include "itkTestingMacros.h" int itkCropImageFilterTest( int, char* [] ) { // Define the dimension of the images constexpr unsigned int ImageDimension = 2; // Declare the pixel types of the images using PixelType = short; // Declare the types of the images using ImageType = itk::Image< PixelType, ImageDimension >; ImageType::Pointer inputImage = ImageType::New(); // Fill in the image ImageType::IndexType index = {{0, 0}}; ImageType::SizeType size = {{8, 12}}; ImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); inputImage->SetLargestPossibleRegion( region ); inputImage->SetBufferedRegion( region ); inputImage->Allocate(); itk::ImageRegionIterator< ImageType > iterator( inputImage, region ); short i = 0; for(; !iterator.IsAtEnd(); ++iterator, ++i) { iterator.Set( i ); } // Create the filter itk::CropImageFilter< ImageType, ImageType >::Pointer cropFilter = itk::CropImageFilter< ImageType, ImageType >::New(); EXERCISE_BASIC_OBJECT_METHODS( cropFilter, CropImageFilter, ExtractImageFilter ); itk::SimpleFilterWatcher watcher( cropFilter ); cropFilter->SetInput( inputImage ); ImageType::RegionType requestedRegion; ImageType::SizeType extractSize = {{8, 12}}; extractSize[0] = 1; extractSize[1] = 1; cropFilter->SetBoundaryCropSize( extractSize ); cropFilter->SetUpperBoundaryCropSize( extractSize ); TEST_SET_GET_VALUE( extractSize, cropFilter->GetUpperBoundaryCropSize() ); cropFilter->SetLowerBoundaryCropSize( extractSize ); TEST_SET_GET_VALUE( extractSize, cropFilter->GetLowerBoundaryCropSize() ); cropFilter->UpdateLargestPossibleRegion(); requestedRegion = cropFilter->GetOutput()->GetRequestedRegion(); if( cropFilter->GetOutput()->GetLargestPossibleRegion().GetSize()[0] != 6 || cropFilter->GetOutput()->GetLargestPossibleRegion().GetSize()[1] != 10 ) { return EXIT_FAILURE; } if( cropFilter->GetOutput()->GetLargestPossibleRegion().GetIndex()[0] != 1 || cropFilter->GetOutput()->GetLargestPossibleRegion().GetIndex()[1] != 1 ) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
3,054
987
// See LICENSE_CELLO file for license and copyright information /// @file control_refresh.cpp /// @author James Bordner (jobordner@ucsd.edu) /// @date 2013-04-26 /// @brief Charm-related functions associated with refreshing ghost zones /// @ingroup Control #include "simulation.hpp" #include "mesh.hpp" #include "control.hpp" #include "charm_simulation.hpp" #include "charm_mesh.hpp" // #define DEBUG_REFRESH #ifdef DEBUG_REFRESH # define TRACE_REFRESH(msg,REFRESH) \ printf ("%d %s:%d %s TRACE_REFRESH %s type %d\n",CkMyPe(), \ __FILE__,__LINE__,name().c_str(),msg,REFRESH->sync_type()); \ fflush(stdout); #else # define TRACE_REFRESH(msg,REFRESH) /* NOTHING */ #endif //---------------------------------------------------------------------- void Block::refresh_begin_() { Refresh * refresh = this->refresh(); TRACE_REFRESH("refresh_begin_()",refresh); check_leaf_(); check_delete_(); cello::simulation()->set_phase(phase_refresh); ERROR("refresh_begin_()", "refresh_begin_ called with NEW_REFRESH"); } //---------------------------------------------------------------------- void Block::refresh_continue() { // Refresh if Refresh object exists and have data Refresh * refresh = this->refresh(); TRACE_REFRESH("refresh_continue_()",refresh); if ( refresh && refresh->is_active() ) { // count self int count = 1; // send Field face data if (refresh->any_fields()) { count += refresh_load_field_faces_ (refresh); } // send Particle face data if (refresh->any_particles()){ count += refresh_load_particle_faces_ (refresh); } // wait for all messages to arrive (including this one) // before continuing to p_refresh_exit() ERROR("refresh_continue_()", "refresh_continue_ called with NEW_REFRESH"); } else { refresh_exit_(); } } //---------------------------------------------------------------------- void Block::p_refresh_store (MsgRefresh * msg) { performance_start_(perf_refresh_store); msg->update(data()); delete msg; Refresh * refresh = this->refresh(); TRACE_REFRESH("p_refresh_store()",refresh); ERROR("p_refresh_store()", "p_refresh_store() called with NEW_REFRESH"); performance_stop_(perf_refresh_store); performance_start_(perf_refresh_store_sync); } //---------------------------------------------------------------------- int Block::refresh_load_field_faces_ (Refresh *refresh) { int count = 0; const int min_face_rank = refresh->min_face_rank(); const int neighbor_type = refresh->neighbor_type(); if (neighbor_type == neighbor_leaf || neighbor_type == neighbor_tree) { // Loop over neighbor leaf Blocks (not necessarily same level) const int min_level = cello::config()->mesh_min_level; ItNeighbor it_neighbor = this->it_neighbor(min_face_rank,index_, neighbor_type,min_level,refresh->root_level()); int if3[3]; while (it_neighbor.next(if3)) { Index index_neighbor = it_neighbor.index(); int ic3[3]; it_neighbor.child(ic3); const int level = this->level(); const int level_face = it_neighbor.face_level(); const int refresh_type = (level_face == level - 1) ? refresh_coarse : (level_face == level) ? refresh_same : (level_face == level + 1) ? refresh_fine : refresh_unknown; refresh_load_field_face_ (refresh_type,index_neighbor,if3,ic3); ++count; } } else if (neighbor_type == neighbor_level) { // Loop over neighbor Blocks in same level (not necessarily leaves) ItFace it_face = this->it_face(min_face_rank,index_); int if3[3]; while (it_face.next(if3)) { // count all faces if not a leaf, else don't count if face level // is less than this block's level if ( ! is_leaf() || face_level(if3) >= level()) { Index index_face = it_face.index(); int ic3[3] = {0,0,0}; refresh_load_field_face_ (refresh_same,index_face,if3,ic3); ++count; } } } return count; } //---------------------------------------------------------------------- void Block::refresh_load_field_face_ ( int refresh_type, Index index_neighbor, int if3[3], int ic3[3]) { // TRACE_REFRESH("refresh_load_field_face()"); // REFRESH FIELDS // ... coarse neighbor requires child index of self in parent if (refresh_type == refresh_coarse) { index_.child(index_.level(),ic3,ic3+1,ic3+2); } // ... copy field ghosts to array using FieldFace object bool lg3[3] = {false,false,false}; Refresh * refresh = this->refresh(); FieldFace * field_face = create_face (if3, ic3, lg3, refresh_type, refresh,false); #ifdef DEBUG_FIELD_FACE CkPrintf ("%d %s:%d DEBUG_FIELD_FACE creating %p\n",CkMyPe(),__FILE__,__LINE__,field_face); #endif DataMsg * data_msg = new DataMsg; data_msg -> set_field_face (field_face,true); data_msg -> set_field_data (data()->field_data(),false); MsgRefresh * msg = new MsgRefresh; msg->set_data_msg (data_msg); thisProxy[index_neighbor].p_refresh_store (msg); } //---------------------------------------------------------------------- int Block::refresh_load_particle_faces_ (Refresh * refresh) { // TRACE_REFRESH("refresh_load_particle_faces()"); const int rank = cello::rank(); const int npa = (rank == 1) ? 4 : ((rank == 2) ? 4*4 : 4*4*4); ParticleData ** particle_array = new ParticleData *[npa]; ParticleData ** particle_list = new ParticleData *[npa]; std::fill_n(particle_array,npa,nullptr); std::fill_n(particle_list ,npa,nullptr); Index * index_list = new Index[npa]; // Sort particles that have left the Block into 4x4x4 array // corresponding to neighbors int nl = particle_load_faces_ (npa,particle_list,particle_array, index_list, refresh); // Send particle data to neighbors particle_send_(nl,index_list,particle_list); delete [] particle_array; delete [] particle_list; delete [] index_list; return nl; } //---------------------------------------------------------------------- void Block::particle_send_ (int nl,Index index_list[], ParticleData * particle_list[]) { ParticleDescr * p_descr = cello::particle_descr(); for (int il=0; il<nl; il++) { Index index = index_list[il]; ParticleData * p_data = particle_list[il]; Particle particle_send (p_descr,p_data); if (p_data && p_data->num_particles(p_descr)>0) { DataMsg * data_msg = new DataMsg; data_msg ->set_particle_data(p_data,true); MsgRefresh * msg = new MsgRefresh; msg->set_data_msg (data_msg); thisProxy[index].p_refresh_store (msg); } else if (p_data) { MsgRefresh * msg = new MsgRefresh; thisProxy[index].p_refresh_store (msg); // assert ParticleData object exits but has no particles delete p_data; } } }
6,897
2,385
#include <cstdlib> #ifdef _YCSB_VERIBETRFS #include "Application.h" #endif #include "core_workload.h" #include "ycsbwrappers.h" #include "leakfinder.h" #include "MallocAccounting.h" #include "hdrhist.hpp" #ifdef _YCSB_ROCKS #include "rocksdb/db.h" #include "rocksdb/table.h" #include "rocksdb/filter_policy.h" #endif #ifdef _YCSB_KYOTO #include <kchashdb.h> #endif #ifdef _YCSB_BERKELEYDB #include <db_cxx.h> #include <dbstl_map.h> #endif #include <chrono> #include <iostream> using namespace std; using namespace chrono; template< class C, class D1, class D2 > void record_duration(HDRHist &hist, const time_point<C,D1> &begin, const time_point<C,D2> &end) { auto duration = duration_cast<nanoseconds>(end - begin); hist.add_value(duration.count()); } void print_summary(HDRHistQuantiles& summary, const string workload_name, const string op) { if (summary.samples() != 0) { cout << "--" << "\tlatency_ccdf\top\t" << "quantile" << "\t" << "upper_bound(ns)" << endl; for (auto summary_el = summary.next(); summary_el.has_value(); summary_el = summary.next()) { cout << workload_name << "\tlatency_summary\t" << op << "\t" << summary_el->quantile << "\t" << summary_el->upper_bound << endl; } } } void print_ccdf(HDRHistCcdf &ccdf, const string workload_name, const string op) { optional<CcdfElement> cur = ccdf.next(); while (cur.has_value()) { cout << workload_name << " latency_ccdf " << op << " " << cur->value << " " << cur->fraction << " " << cur->count << endl; cur = ccdf.next(); } } static const vector<pair<ycsbc::Operation, string>> YcsbOperations = { make_pair(ycsbc::READ, "read"), make_pair(ycsbc::UPDATE, "update"), make_pair(ycsbc::INSERT, "insert"), make_pair(ycsbc::SCAN, "scan"), make_pair(ycsbc::READMODIFYWRITE, "readmodifywrite"), }; template< class DB > class YcsbExecution { // Benchmark definition DB db; string name; ycsbc::CoreWorkload& workload; bool verbose; int record_count; int num_ops; milliseconds max_sync_interval; int max_sync_interval_ops; milliseconds progress_report_interval; // Benchmark results map<ycsbc::Operation, unique_ptr<HDRHist>> latency_hist; HDRHist load_insert_latency_hist; // for inserts during load phase HDRHist sync_latency_hist; // does not include sync at end of load phase milliseconds load_duration_ms; // includes time to sync at end milliseconds run_duration_ms; // includes time to sync at end public: YcsbExecution(DB db, string name, ycsbc::CoreWorkload& workload, int record_count, int num_ops, bool verbose, int max_sync_interval_ms = 0, int max_sync_interval_ops = 0, int progress_report_interval_ms = 1000) : db(db), name(name), workload(workload), record_count(record_count), num_ops(num_ops), verbose(verbose), max_sync_interval(max_sync_interval_ms), max_sync_interval_ops(max_sync_interval_ops), progress_report_interval(progress_report_interval_ms) { for (auto op : YcsbOperations) { latency_hist[op.first] = move(make_unique<HDRHist>()); } } inline void performRead() { malloc_accounting_set_scope("performRead setup"); ycsbcwrappers::TxRead txread = ycsbcwrappers::TransactionRead(workload); if (!workload.read_all_fields()) { cerr << db.name << " error: not reading all fields unsupported" << endl; exit(-1); } if (verbose) { cerr << db.name << " [op] READ " << txread.table << " " << txread.key << " { all fields }" << endl; } malloc_accounting_default_scope(); // TODO use the table name? db.query(txread.key); } inline void performInsert(bool load) { malloc_accounting_set_scope("performInsert setup"); ycsbcwrappers::TxInsert txinsert = ycsbcwrappers::TransactionInsert(workload, load); if (txinsert.values->size() != 1) { cerr << db.name << " error: only fieldcount=1 is supported" << endl; exit(-1); } const string& value = (*txinsert.values)[0].second; if (verbose) { cerr << db.name << " [op] INSERT " << txinsert.table << " " << txinsert.key << " " << value << endl; } malloc_accounting_default_scope(); // TODO use the table name? db.insert(txinsert.key, value); } inline void performUpdate() { malloc_accounting_set_scope("performUpdate setup"); ycsbcwrappers::TxUpdate txupdate = ycsbcwrappers::TransactionUpdate(workload); if (!workload.write_all_fields()) { cerr << db.name << " error: not writing all fields unsupported" << endl; exit(-1); } if (txupdate.values->size() != 1) { cerr << db.name << " error: only fieldcount=1 is supported" << endl; exit(-1); } const string& value = (*txupdate.values)[0].second; if (verbose) { cerr << db.name << " [op] UPDATE " << txupdate.table << " " << txupdate.key << " " << value << endl; } malloc_accounting_default_scope(); // TODO use the table name? db.update(txupdate.key, value); } inline void performReadModifyWrite() { malloc_accounting_set_scope("performReadModifyWrite setup"); ycsbcwrappers::TxUpdate txupdate = ycsbcwrappers::TransactionUpdate(workload); if (!workload.write_all_fields()) { cerr << db.name << " error: not writing all fields unsupported" << endl; exit(-1); } if (txupdate.values->size() != 1) { cerr << db.name << " error: only fieldcount=1 is supported" << endl; exit(-1); } const string& value = (*txupdate.values)[0].second; if (verbose) { cerr << db.name << " [op] READMODIFYWRITE " << txupdate.table << " " << txupdate.key << " " << value << endl; } malloc_accounting_default_scope(); // TODO use the table name? db.readmodifywrite(txupdate.key, value); } inline void performScan() { malloc_accounting_set_scope("performScan setup"); ycsbcwrappers::TxScan txscan = ycsbcwrappers::TransactionScan(workload); if (!workload.write_all_fields()) { cerr << db.name << " error: not writing all fields unsupported" << endl; exit(-1); } if (verbose) { cerr << db.name << " [op] SCAN " << txscan.table << " " << txscan.key << " " << txscan.scan_length << endl; } malloc_accounting_default_scope(); // TODO use the table name? db.scan(txscan.key, txscan.scan_length); } void Load() { cout << "[step] " << name << " load start (num ops: " << record_count << ")" << endl; auto clock_start = steady_clock::now(); auto clock_next_report = clock_start + progress_report_interval; auto clock_op_started = clock_start; auto clock_op_completed = clock_start; for (int i = 0; i < record_count; ++i) { clock_op_started = steady_clock::now(); performInsert(true /* load */); clock_op_completed = steady_clock::now(); record_duration(load_insert_latency_hist, clock_op_started, clock_op_completed); if (clock_next_report < clock_op_completed) { auto duration_ms = duration_cast<milliseconds>( clock_op_completed - clock_start).count(); cout << "[step] " << name << " load progress " << duration_ms << " ms " << i << " ops" << endl; malloc_accounting_status(); clock_next_report = clock_op_completed + progress_report_interval; } } auto duration_ms = duration_cast<milliseconds>(clock_op_completed - clock_start); cout << "[step] " << name << " load sync " << duration_ms.count() << " ms" << endl; db.sync(true); auto clock_end = steady_clock::now(); load_duration_ms = duration_cast<milliseconds>(clock_end - clock_start); cout << "[step] " << name << " load end " << load_duration_ms.count() << " ms" << endl; auto load_duration_ns = duration_cast<nanoseconds>(clock_end - clock_start); assert(load_duration_ns.count() != 0); double load_duration_s = duration_cast<nanoseconds>(clock_end - clock_start).count() / 1000000000.0; double throughput = record_count / load_duration_s; cout << "[step] " << name << " load throughput " << throughput << " ops/sec" << endl; auto load_insert_summary = load_insert_latency_hist.summary(); auto load_insert_ccdf = load_insert_latency_hist.ccdf(); print_summary(load_insert_summary, name, "load"); print_ccdf(load_insert_ccdf, name, "load"); } void Run() { malloc_accounting_set_scope("ycsbRun.setup"); malloc_accounting_default_scope(); auto clock_start = steady_clock::now(); auto next_sync = clock_start + max_sync_interval; auto next_display = clock_start + progress_report_interval; int next_sync_ops = 0 < max_sync_interval_ops ? max_sync_interval_ops : num_ops+1; bool have_done_insert_since_last_sync = false; #define HACK_EVICT_PERIODIC 0 #if HACK_EVICT_PERIODIC // An experiment that demonstrated that the heap was filling with small // junk ("heap Kessler syndrome"?): by evicting periodically, we freed // most of the small junk and kept the heap waste down. TODO okay to clean up. int evict_interval_ms = 100000; int next_evict_ms = evict_interval_ms; #endif // HACK_EVICT_PERIODIC #define HACK_PROBE_PERIODIC 1 #if HACK_PROBE_PERIODIC // An experiment to periodically study how the kv allocations are distributed int probe_interval_ms = 50000; int next_probe_ms = probe_interval_ms; #endif // HACK_PROBE_PERIODIC cout << "[step] " << name << " run start (num ops: " << num_ops << ", sync interval " << max_sync_interval.count() << " ms, sync ops " << max_sync_interval_ops << ")" << endl; for (int i = 0; i < num_ops; ++i) { auto next_operation = workload.NextOperation(); auto clock_op_started = steady_clock::now(); switch (next_operation) { case ycsbc::READ: performRead(); break; case ycsbc::UPDATE: performUpdate(); have_done_insert_since_last_sync = true; break; case ycsbc::INSERT: performInsert(false /* not load */); have_done_insert_since_last_sync = true; break; case ycsbc::SCAN: performScan(); break; case ycsbc::READMODIFYWRITE: performReadModifyWrite(); have_done_insert_since_last_sync = true; break; default: cerr << "error: invalid NextOperation" << endl; exit(-1); } auto clock_op_completed = steady_clock::now(); record_duration(*latency_hist[next_operation], clock_op_started, clock_op_completed); if (next_display <= clock_op_completed) { malloc_accounting_display("periodic"); auto elapsed_ms = duration_cast<milliseconds>(clock_op_completed - clock_start); cout << "[step] " << name << " run progress " << elapsed_ms.count() << " ms " << i << " ops" << endl; next_display += progress_report_interval; } if (have_done_insert_since_last_sync && ((0 < max_sync_interval.count() && next_sync < clock_op_completed) || next_sync_ops <= i)) { auto sync_started = steady_clock::now(); milliseconds elapsed_ms = duration_cast<milliseconds>(sync_started - clock_start); cout << "[step] " << name << " run sync start " << elapsed_ms.count() << " ms " << i << " ops" << endl; db.sync(false); auto sync_completed = steady_clock::now(); elapsed_ms = duration_cast<milliseconds>(sync_completed - clock_start); cout << "[step] " << name << " run sync end " << elapsed_ms.count() << " ms " << i << " ops" << endl; record_duration(sync_latency_hist, sync_started, sync_completed); have_done_insert_since_last_sync = false; next_sync = sync_completed + max_sync_interval; next_sync_ops = i + max_sync_interval_ops; malloc_accounting_status(); #ifdef _YCSB_VERIBETRFS #ifdef LOG_QUERY_STATS cout << "=========================================" << endl; benchmark_dump(); benchmark_clear(); cout << "=========================================" << endl; #endif #endif fflush(stdout); } } if (have_done_insert_since_last_sync) { auto sync_started = steady_clock::now(); milliseconds elapsed_ms = duration_cast<milliseconds>(sync_started - clock_start); cout << "[step] " << name << " sync start " << elapsed_ms.count() << " ms " << num_ops << " ops" << endl; db.sync(true); auto sync_completed = steady_clock::now(); elapsed_ms = duration_cast<milliseconds>(sync_completed - clock_start); cout << "[step] " << name << " sync end " << elapsed_ms.count() << " ms " << num_ops << " ops" << endl; record_duration(sync_latency_hist, sync_started, sync_completed); have_done_insert_since_last_sync = false; next_sync = sync_completed + max_sync_interval; next_sync_ops = num_ops + max_sync_interval_ops; } auto clock_end = steady_clock::now(); run_duration_ms = duration_cast<milliseconds>(clock_end - clock_start); double run_duration_s = duration_cast<nanoseconds>(clock_end - clock_start).count() / 1000000000.0; double throughput = num_ops / run_duration_s; cout << "[step] " << name << " run throughput " << throughput << " ops/sec" << endl; malloc_accounting_set_scope("ycsbRun.summary"); { for (auto op : YcsbOperations) { auto op_summary = latency_hist[op.first]->summary(); auto op_ccdf = latency_hist[op.first]->ccdf(); print_summary(op_summary, name, op.second); print_ccdf(op_ccdf, name, op.second); } auto sync_summary = sync_latency_hist.summary(); auto sync_ccdf = sync_latency_hist.ccdf(); print_summary(sync_summary, name, "sync"); print_ccdf(sync_ccdf, name, "sync"); } malloc_accounting_default_scope(); } void LoadAndRun() { Load(); Run(); malloc_accounting_display("after experiment before teardown"); } }; #ifdef _YCSB_VERIBETRFS class VeribetrkvFacade { protected: Application& app; public: static const string name; VeribetrkvFacade(Application& app) : app(app) { } inline void query(const string& key) { app.Query(key); } inline void insert(const string& key, const string& value) { app.Insert(key, value); } inline void update(const string& key, const string& value) { app.Insert(key, value); } inline void readmodifywrite(const string& key, const string& value) { update(key, value); } inline void scan(const string &key, int len) { app.Succ(ByteString(key), true, len); } inline void sync(bool fullSync) { app.Sync(fullSync); } inline void evictEverything() { app.EvictEverything(); } inline void CountAmassAllocations() { app.CountAmassAllocations(); printf("debug-accumulator finish\n"); } inline void cacheDebug() { //app.CacheDebug(); } }; const string VeribetrkvFacade::name = string("veribetrkv"); #endif #ifdef _YCSB_ROCKS class RocksdbFacade { protected: rocksdb::DB& db; public: static const string name; RocksdbFacade(rocksdb::DB& db) : db(db) { } inline void query(const string& key) { static struct rocksdb::ReadOptions roptions = rocksdb::ReadOptions(); string value; rocksdb::Status status = db.Get(roptions, rocksdb::Slice(key), &value); assert(status.ok() || status.IsNotFound()); // TODO is it expected we're querying non-existing keys? } inline void insert(const string& key, const string& value) { static struct rocksdb::WriteOptions woptions = rocksdb::WriteOptions(); woptions.disableWAL = true; rocksdb::Status status = db.Put(woptions, rocksdb::Slice(key), rocksdb::Slice(value)); assert(status.ok()); } inline void update(const string& key, const string& value) { static struct rocksdb::WriteOptions woptions = rocksdb::WriteOptions(); woptions.disableWAL = true; rocksdb::Status status = db.Put(woptions, rocksdb::Slice(key), rocksdb::Slice(value)); assert(status.ok()); } inline void readmodifywrite(const string& key, const string& value) { update(key, value); } inline void scan(const string &key, int len) { rocksdb::Iterator* it = db.NewIterator(rocksdb::ReadOptions()); int i = 0; for (it->Seek(key); i < len && it->Valid(); it->Next()) { i++; } delete it; } inline void sync(bool /*fullSync*/) { static struct rocksdb::FlushOptions foptions = rocksdb::FlushOptions(); rocksdb::Status status = db.Flush(foptions); assert(status.ok()); } inline void evictEverything() { } inline void CountAmassAllocations() { } }; const string RocksdbFacade::name = string("rocksdb"); #endif #ifdef _YCSB_KYOTO class KyotoFacade { protected: kyotocabinet::TreeDB &db; public: static const string name; KyotoFacade(kyotocabinet::TreeDB &db) : db(db) { } inline void query(const string& key) { string result; db.get(key, &result); } inline void insert(const string& key, const string& value) { if (!db.set(key, value)) { cout << "Insert failed" << endl; abort(); } } inline void update(const string& key, const string& value) { if (!db.set(key, value)) { cout << "Update failed" << endl; abort(); } } inline void readmodifywrite(const string& key, const string& value) { query(key); update(key, value); } inline void scan(const string &key, int len) { kyotocabinet::DB::Cursor *cursor = db.cursor(); assert(cursor); assert(cursor->jump(key)); int i = 0; while (i < len && cursor->step()) i++; delete cursor; } inline void sync(bool /*fullSync*/) { db.synchronize(); } inline void evictEverything() { } inline void CountAmassAllocations() { } }; const string KyotoFacade::name = string("kyotodb"); #endif #ifdef _YCSB_BERKELEYDB class BerkeleyDBFacade { protected: //DbEnv *env; Db* pdb; dbstl::db_map<string, string> *huge_map; public: static const string name; BerkeleyDBFacade(Db *_pdb) : pdb(_pdb) { huge_map = new dbstl::db_map<string, string>(pdb, NULL); } inline void query(const string& key) { string result; try { const auto &t = *huge_map; // Get a const reference so operator[] doesn't insert key if it doesn't exist. result = t[key]; } catch (DbException& e) { cerr << "DbException: " << e.what() << endl; abort(); } catch (std::exception& e) { cerr << e.what() << endl; abort(); } } inline void insert(const string& key, const string& value) { try { (*huge_map)[key] = value; } catch (DbException& e) { cerr << "DbException: " << e.what() << endl; abort(); } catch (std::exception& e) { cerr << e.what() << endl; abort(); } } inline void update(const string& key, const string& value) { insert(key, value); } inline void readmodifywrite(const string& key, const string& value) { query(key); update(key, value); } inline void scan(const string &key, int len) { int i = 0; auto iter = huge_map->begin(); // lower_bound() seems to be broken in berkeleydb while(i < len && iter != huge_map->end()) { ++iter; i++; } } inline void sync(bool /*fullSync*/) { pdb->sync(0); } inline void evictEverything() { } inline void CountAmassAllocations() { } }; const string BerkeleyDBFacade::name = string("berkeleydb"); #endif class NopFacade { public: static const string name; NopFacade() { } inline void query(const string& key) { asm volatile ("nop"); } inline void insert(const string& key, const string& value) { asm volatile ("nop"); } inline void update(const string& key, const string& value) { asm volatile ("nop"); } inline void readmodifywrite(const string& key, const string& value) { } inline void scan(const string &key, int len) { } inline void sync(bool /*fullSync*/) { asm volatile ("nop"); } inline void evictEverything() { asm volatile ("nop"); } inline void CountAmassAllocations() { asm volatile ("nop"); } inline void cacheDebug() { asm volatile ("nop"); } }; const string NopFacade::name = string("nop"); void dump_metadata(const char* workload_filename, const char* database_filename) { FILE* fp; char space[1000]; char* line; // This could output wrong info if we are not actually running in // the cgroup. // // fp = fopen("/sys/fs/cgroup/memory/VeribetrfsExp/memory.limit_in_bytes", "r"); // if (fp) { // line = fgets(space, sizeof(space), fp); // fclose(fp); // printf("metadata cgroups-memory.limit_in_bytes %s", line); // } printf("metadata workload_filename %s", workload_filename); fp = fopen(workload_filename, "r"); while (true) { char* line = fgets(space, sizeof(space), fp); if (line==NULL) { break; } printf("metadata workload %s", line); } fclose(fp); printf("metadata database_filename %s", database_filename); fflush(stdout); char cmdbuf[1000]; // yes, this is a security hole. In the measurement framework, // not the actual system. You can take the man out of K&R, as they say... snprintf(cmdbuf, sizeof(cmdbuf), "df --output=source %s | tail -1", database_filename); system(cmdbuf); fflush(stdout); } template< class DbFacade > void runOneWorkload(DbFacade db, string workload_filename, string database_filename, ycsbc::CoreWorkload &workload, bool load, bool do_nop, bool verbose) { utils::Properties props = ycsbcwrappers::props_from(workload_filename); auto properties_map = props.properties(); workload.Init(props, !load); int record_count = stoi(props[ycsbc::CoreWorkload::RECORD_COUNT_PROPERTY]); int num_ops = stoi(props[ycsbc::CoreWorkload::OPERATION_COUNT_PROPERTY]); int sync_interval_ms = 0; int sync_interval_ops = 0; string workload_name; if (properties_map.find("syncintervalms") != properties_map.end()) { sync_interval_ms= stoi(props["syncintervalms"]); } if (properties_map.find("syncintervalops") != properties_map.end()) { sync_interval_ops = stoi(props["syncintervalops"]); } if (properties_map.find("workloadname") != properties_map.end()) { workload_name = props["workloadname"]; } else { workload_name = workload_filename; } dump_metadata(workload_filename.c_str(), database_filename.c_str()); if (do_nop) { NopFacade nopdb; YcsbExecution ycsbExecution(nopdb, workload_name, workload, record_count, num_ops, verbose, sync_interval_ms, sync_interval_ops); if (load) ycsbExecution.Load(); else ycsbExecution.Run(); } else { YcsbExecution ycsbExecution(db, workload_name, workload, record_count, num_ops, verbose, sync_interval_ms, sync_interval_ops); if (load) ycsbExecution.Load(); else ycsbExecution.Run(); } } void pretendToDoLoadPhase(const string &workload_filename, ycsbc::CoreWorkload &workload) { utils::Properties props = ycsbcwrappers::props_from(workload_filename); auto properties_map = props.properties(); workload.Init(props, false); workload.AdvanceToEndOfLoad(); } void usage(int argc, char **argv) { cerr << "Usage: " << argv[0] << " "; #ifdef _YCSB_VERIBETRFS cout << "<veribetrkv.img> "; #endif #ifdef _YCSB_ROCKS cout << "<rocksdb-directory> "; #endif #ifdef _YCSB_BERKELEYDB cout << "<berkeley.db> "; #endif #ifdef _YCSB_KYOTO cout << "<kyoto.cbt> "; #endif cout << "[--nop] [--verbose] [--preloaded] "; #ifdef _YCSB_ROCKS cout << "[--filters] "; #endif cout << "<load-workload.spec> [run-workload1.spec...]" << endl; cout << " --nop: use a no-op database" << endl; cout << " --preloaded: don't format database. Database must have been loaded " << endl; cout << " with the given load workload." << endl; #ifdef _YCSB_ROCKS cout << " --filters: enable filters" << endl; #endif exit(-1); } int main(int argc, char* argv[]) { if (argc < 3) usage(argc, argv); bool do_nop = false; bool verbose = false; bool preloaded = false; #ifdef _YCSB_ROCKS bool use_filters = false; #endif std::string database_filename(argv[1]); int first_workload_filename; int i; for (i = 2; i < argc; i++) { if (string(argv[i]) == "--nop") { do_nop = true; } else if (string(argv[i]) == "--verbose") { verbose = true; } else if (string(argv[i]) == "--preloaded") { preloaded = true; #ifdef _YCSB_ROCKS } else if (string(argv[i]) == "--filters") { use_filters = true; #endif } else { break; } } first_workload_filename = i; // == veribetrkv == #ifdef _YCSB_VERIBETRFS if (!preloaded) Mkfs(database_filename); Application app(database_filename); VeribetrkvFacade db(app); #endif // == rocksdb == #ifdef _YCSB_ROCKS rocksdb::DB* rocks_db; rocksdb::Options options; if (!preloaded) options.create_if_missing = true; //options.error_if_exists = true; // FIXME this is probably not fair, especially when we implement off-thread compaction // disables background compaction _and_ flushing // https://github.com/facebook/rocksdb/blob/master/include/rocksdb/options.h#L531-L536 options.max_background_jobs = 0; // disabled - we let rocks use the page cache // options.use_direct_reads = true; // options.use_direct_io_for_flush_and_compaction = true; if (use_filters) { rocksdb::BlockBasedTableOptions table_options; table_options.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false)); options.table_factory.reset(rocksdb::NewBlockBasedTableFactory(table_options)); } rocksdb::Status status = rocksdb::DB::Open(options, database_filename, &rocks_db); assert(status.ok()); RocksdbFacade db(*rocks_db); #endif // == kyotodb == #ifdef _YCSB_KYOTO kyotocabinet::TreeDB tdb; bool success = tdb.open(database_filename, kyotocabinet::TreeDB::OWRITER | (preloaded ? 0 : kyotocabinet::TreeDB::OCREATE) | kyotocabinet::TreeDB::ONOLOCK); if (!success) abort(); KyotoFacade db(tdb); #endif // == berkeleydb == #ifdef _YCSB_BERKELEYDB Db* pdb; pdb = new Db(NULL, DB_CXX_NO_EXCEPTIONS); assert(pdb); if (pdb->open(NULL, database_filename.c_str(), NULL, DB_BTREE, preloaded ? 0 : DB_CREATE, 0)) { cerr << "Failed to open database " << database_filename << endl; abort(); } BerkeleyDBFacade db(pdb); #endif ycsbc::CoreWorkload workload_template; for (i = first_workload_filename; i < argc; i++) { if (preloaded && i == first_workload_filename) pretendToDoLoadPhase(argv[i], workload_template); else runOneWorkload(db, argv[i], database_filename, workload_template, i == first_workload_filename, do_nop, verbose); } #ifdef _YCSB_VERIBETRFS // No shutdown needed #endif #ifdef _YCSB_ROCKS // No shutdown needed #endif #ifdef _YCSB_KYOTO if (!tdb.close()) { cout << "Failed to close " << database_filename; abort(); } #endif #ifdef _YCSB_BERKELEYDB if (pdb != NULL) { if (pdb->close(0)) { cerr << "Failed to close database" << endl; abort(); } delete pdb; } #endif return 0; }
28,056
9,598
/*++ Copyright (c) 1998-1999 Microsoft Corporation Module Name: DTEvntSk.cpp Abstract: This module contains implementation of CPTEventSink. Author: vlade Nov 1999 --*/ #include "precomp.h" #pragma hdrstop // // a helper function that releases the resources allocated inside event info // HRESULT FreeEventInfo( MSP_EVENT_INFO * pEvent ) { LOG((MSP_TRACE, "FreeEventInfo - enter")); switch ( pEvent->Event ) { case ME_ADDRESS_EVENT: if (NULL != pEvent->MSP_ADDRESS_EVENT_INFO.pTerminal) { (pEvent->MSP_ADDRESS_EVENT_INFO.pTerminal)->Release(); } break; case ME_CALL_EVENT: if (NULL != pEvent->MSP_CALL_EVENT_INFO.pTerminal) { (pEvent->MSP_CALL_EVENT_INFO.pTerminal)->Release(); } if (NULL != pEvent->MSP_CALL_EVENT_INFO.pStream) { (pEvent->MSP_CALL_EVENT_INFO.pStream)->Release(); } break; case ME_TSP_DATA: break; case ME_PRIVATE_EVENT: if ( NULL != pEvent->MSP_PRIVATE_EVENT_INFO.pEvent ) { (pEvent->MSP_PRIVATE_EVENT_INFO.pEvent)->Release(); } break; case ME_FILE_TERMINAL_EVENT: if( NULL != pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal) { (pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal)->Release(); pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal = NULL; } if( NULL != pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack ) { (pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack)->Release(); pEvent->MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack = NULL; } break; case ME_ASR_TERMINAL_EVENT: if( NULL != pEvent->MSP_ASR_TERMINAL_EVENT_INFO.pASRTerminal) { (pEvent->MSP_ASR_TERMINAL_EVENT_INFO.pASRTerminal)->Release(); } break; case ME_TTS_TERMINAL_EVENT: if( NULL != pEvent->MSP_TTS_TERMINAL_EVENT_INFO.pTTSTerminal) { (pEvent->MSP_TTS_TERMINAL_EVENT_INFO.pTTSTerminal)->Release(); } break; case ME_TONE_TERMINAL_EVENT: if( NULL != pEvent->MSP_TONE_TERMINAL_EVENT_INFO.pToneTerminal) { (pEvent->MSP_TONE_TERMINAL_EVENT_INFO.pToneTerminal)->Release(); } break; default: break; } LOG((MSP_TRACE, "FreeEventInfo - finished")); return S_OK; } CPTEventSink::CPTEventSink() : m_pMSPStream(NULL) { LOG((MSP_TRACE, "CPTEventSink::CPTEventSink enter")); LOG((MSP_TRACE, "CPTEventSink::CPTEventSink exit")); } CPTEventSink::~CPTEventSink() { LOG((MSP_TRACE, "CPTEventSink::~CPTEventSink enter")); LOG((MSP_TRACE, "CPTEventSink::~CPTEventSink exit")); }; // --- ITPluggableTerminalEventSnk --- /*++ FireEvent Parameters: IN MSPEVENTITEM * pEventItem pointer to the structure that describes the event. all the pointers contained in the structure must be addreffed by the caller, and then released by the caller if FireEvent fails FireEvent makes a (shallow) copy of the structure, so the caller can delete the structure when the function returns Returns: S_OK - every thing was OK E_FAIL & other - something was wrong Description: This method is called by the dynamic terminals to signal a new event --*/ STDMETHODIMP CPTEventSink::FireEvent( IN const MSP_EVENT_INFO * pEventInfo ) { LOG((MSP_TRACE, "CPTEventSink::FireEvent enter")); // // make sure we got a good mspeventitem structure // if( MSPB_IsBadWritePtr( (void*)pEventInfo, sizeof( MSP_EVENT_INFO ))) { LOG((MSP_ERROR, "CPTEventSink::FireEvent -" "pEventItem is bad, returns E_POINTER")); return E_POINTER; } // // Create an MSPEVENTITEM // MSPEVENTITEM *pEventItem = AllocateEventItem(); if (NULL == pEventItem) { LOG((MSP_ERROR, "CPTEventSink::FireEvent -" "failed to create MSPEVENTITEM. returning E_OUTOFMEMORY ")); return E_OUTOFMEMORY; } // // make a shallow copy of the structure // pEventItem->MSPEventInfo = *pEventInfo; Lock(); HRESULT hr = E_FAIL; if (NULL != m_pMSPStream) { // // nicely ask stream to process our event // LOG((MSP_TRACE, "CPTEventSink::FireEvent - passing event [%p] to the stream", pEventItem)); AsyncEventStruct *pAsyncEvent = new AsyncEventStruct; if (NULL == pAsyncEvent) { LOG((MSP_ERROR, "CPTEventSink::FireEvent - failed to allocate memory for AsyncEventStruct")); hr = E_OUTOFMEMORY; } else { // // stuff the structure with the addref'fed stream on which the // event will be fired and the actual event to fire // ULONG ulRC = m_pMSPStream->AddRef(); if (1 == ulRC) { // // this is a workaround for a timing window: the stream could // be in its desctructor while we are doing the addref. this // condition is very-vary rare, as the timing window is very // narrow. // // the good thing is that stream destructor will not finish // while we are here, because it will try to get event sink's // critical section in its call to SetSinkStream() to set our // stream pointer to NULL. // // so if we detect that the refcount after our addref is 1, // that would mean that the stream is in (or is about to start // executing its desctructor). in which case we should do // nothing. // // cleanup and return a failure. // Unlock(); LOG((MSP_ERROR, "CPTEventSink::FireEvent - stream is going away")); delete pAsyncEvent; pAsyncEvent = NULL; FreeEventItem(pEventItem); pEventItem = NULL; return TAPI_E_INVALIDSTREAM; } pAsyncEvent->pMSPStream = m_pMSPStream; pAsyncEvent->pEventItem = pEventItem; // // now use thread pool api to schedule the event for future async // processing // BOOL bQueueSuccess = QueueUserWorkItem( CPTEventSink::FireEventCallBack, (void *)pAsyncEvent, WT_EXECUTEDEFAULT); if (!bQueueSuccess) { DWORD dwLastError = GetLastError(); LOG((MSP_ERROR, "CPTEventSink::FireEvent - QueueUserWorkItem failed. LastError = %ld", dwLastError)); // // undo the addref we did on the stream object. the event will // be freed later // m_pMSPStream->Release(); // // the event was not enqueued. delete now. // delete pAsyncEvent; pAsyncEvent = NULL; // // map the code and bail out // hr = HRESULT_FROM_WIN32(dwLastError); } else { // // log the event we have submitted, so we can match submission // with processing from the log // LOG((MSP_TRACE, "CPTEventSink::FireEvent - submitted event [%p]", pAsyncEvent)); hr = S_OK; } // async event structure submitted } // async event structure allocated } // msp stream exists else { hr = TAPI_E_INVALIDSTREAM; LOG((MSP_ERROR, "CPTEventSink::FireEvent - stream pointer is NULL")); } Unlock(); // // if we don't have a stream, or if the stream refused to process the // event, cleanup and return an error // if (FAILED(hr)) { LOG((MSP_ERROR, "CPTEventSink::FireEvent - call to HandleStreamEvent failed. hr = 0x%08x", hr)); FreeEventItem(pEventItem); return hr; } LOG((MSP_TRACE, "CPTEventSink::FireEvent - exit")); return S_OK; } ///////////////////////////////////////////////////////////////////////////// // // CPTEventSink::FireEventCallBack // // the callback function that is called by thread pool api to asyncronously to // process events fired by the terminals. // // the argument should point to the structure that contains the pointer to the // stream on which to fire the event and the pointer to the event to fire. // // the dll is guaranteed to not go away, since the structure passed in holds a // reference to the stream object on which to process the event // // static DWORD WINAPI CPTEventSink::FireEventCallBack(LPVOID lpParameter) { LOG((MSP_TRACE, "CPTEventSink::FireEventCallBack - enter. Argument [%p]", lpParameter)); AsyncEventStruct *pEventStruct = (AsyncEventStruct *)lpParameter; // // make sure the structure is valid // if (IsBadReadPtr(pEventStruct, sizeof(AsyncEventStruct))) { // // complain and exit. should not happen, unless there is a problem in // thread pool api or memory corruption // LOG((MSP_ERROR, "CPTEventSink::FireEventCallBack - Argument does not point to a valid AsyncEventStruct")); return FALSE; } BOOL bBadDataPassedIn = FALSE; // // the structure contains an addref'fed stream pointer. extract it and // make sure it is still valid // CMSPStream *pMSPStream = pEventStruct->pMSPStream; if (IsBadReadPtr(pMSPStream, sizeof(CMSPStream))) { // // should not happen, unless there is a problem in thread pool api or // memory corruption, or someone is over-releasing the stream object // LOG((MSP_ERROR, "CPTEventSink::FireEventCallBack - stream pointer is bad")); pMSPStream = NULL; bBadDataPassedIn = TRUE; } // // the structure contains the event that we are tryint to fire. // make sure the event we are about to fire is good. // MSPEVENTITEM *pEventItem = pEventStruct->pEventItem; if (IsBadReadPtr(pEventItem, sizeof(MSPEVENTITEM))) { // // should not happen, unless there is a problem in thread pool api or // memory corruption, or we didn't check success of allocation when we // created the event (which we did!) // LOG((MSP_ERROR, "CPTEventSink::FireEventCallBack - event is bad")); pEventItem = NULL; bBadDataPassedIn = TRUE; } // // bad stream or event structure? // if (bBadDataPassedIn) { // // release the event if it was good. // if ( NULL != pEventItem) { FreeEventItem(pEventItem); pEventItem = NULL; } // // release the stream if it was good. // if (NULL != pMSPStream) { pMSPStream->Release(); pMSPStream = NULL; } // // no need to keep the event structure itself, delete it // delete pEventStruct; pEventStruct = NULL; return FALSE; } // // we have both the stream and the event, fire the event on the stream // HRESULT hr = pMSPStream->HandleSinkEvent(pEventItem); // // if HandleSinkEvent succeeded, pEventItem will be released by whoever // will handle the event, otherwise we need to release eventitem here // if (FAILED(hr)) { LOG((MSP_ERROR, "CPTEventSink::FireEventCallBack - HandleSinkEvent not called or failed. hr = %lx", hr)); // // need to free all the resources held by event info // FreeEventInfo(&(pEventItem->MSPEventInfo)); FreeEventItem(pEventItem); pEventItem = NULL; } // // release the stream pointer that is a part of the structure -- // we don't want any reference leaks. // // // note that the dll may go away at this point (if we are holding the last // reference to the last object from the dll) // pMSPStream->Release(); pMSPStream = NULL; // // at this point we release the stream pointer and either submitted the // event or freed it. we no longer need the event structure. // delete pEventStruct; pEventStruct = NULL; LOG((MSP_(hr), "CPTEventSink::FireEventCallBack - exit. hr = %lx", hr)); return SUCCEEDED(hr); } /*++ SetSinkStream Parameters: CMSPStream *pStream the stream that will be processing our events, or NULL when no stream is available to process our events Returns: S_OK - Description: this method is called by the stream that is going to process our events when the stream is going away and is no longer available to process our messages, it will call SetSinkStream with NULL. --*/ HRESULT CPTEventSink::SetSinkStream( CMSPStream *pStream ) { LOG((MSP_TRACE, "CPTEventSink::SetSinkStream - enter")); Lock(); LOG((MSP_TRACE, "CPTEventSink::SetSinkStream - replacing sink stream [%p] with [%p]", m_pMSPStream, pStream)); // // we don't keep a reference to the stream -- the stream keeps a reference // to us. when the stream goes away, it will let us know. // m_pMSPStream = pStream; Unlock(); LOG((MSP_TRACE, "CPTEventSink::SetSinkStream - exit")); return S_OK; }
14,960
4,777
// bitset::test #include <iostream> // std::cout #include <string> // std::string #include <cstddef> // std::size_t #include <bitset> // std::bitset int main () { std::bitset<16> shit; std::bitset<16> bar (0xfa2); std::bitset<16> foo (std::string("0101111001")); std::cout << "shit: \t" << shit << '\n'; std::cout << "bar: \t" << bar << '\n'; std::cout << "f: \t" << foo << '\n'; std::cout << "flip f:\t" << foo.flip() << '\n'; std::cout << "test f:\t"; for (std::size_t i=0; i<foo.size(); ++i) std::cout << foo.test(foo.size() - 1 - i) << ' '; std::cout << std::endl; std::cout << "to_str:\t" << foo.to_string() << std::endl; std::cout << "to_ul:\t" << foo.to_ulong() << std::endl; std::cout << "to_ull:\t" << foo.to_ullong() << std::endl; std::cout << std::boolalpha; std::cout << "all: \t" << foo.all() << '\n'; std::cout << "any: \t" << foo.any() << '\n'; std::cout << "none: \t" << foo.none() << '\n'; std::cout << "ones: \t" << foo.count() << '\n'; std::cout << "zeros: \t" << (foo.size()-foo.count()) << '\n'; std::cout << "set: \t" << foo.set() << '\n'; std::cout << "reset: \t" << foo.reset() << '\n'; return 0; }
1,180
521
#include <id.h>
15
8
//------------------------------------------------------------------------------ // globallightentity.cc // (C) 2007 Radon Labs GmbH // (C) 2013-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "graphics/globallightentity.h" #include "lighting/shadowserver.h" #include "lighting/lightserver.h" namespace Graphics { __ImplementClass(Graphics::GlobalLightEntity, 'GLBE', Graphics::AbstractLightEntity); using namespace Math; using namespace Messaging; using namespace Lighting; //------------------------------------------------------------------------------ /** */ GlobalLightEntity::GlobalLightEntity() : backLightColor(0.0f, 0.0f, 0.0f, 0.0f), ambientLightColor(0.0f, 0.0f, 0.0f, 0.0f), lightDir(0.0f, 0.0f, -1.0f), backLightOffset(0.3) { this->SetLightType(LightType::Global); this->SetAlwaysVisible(true); } //------------------------------------------------------------------------------ /** */ ClipStatus::Type GlobalLightEntity::ComputeClipStatus(const Math::bbox& box) { // since we are essentially a directional light, everything is visible, // we depend on the visibility detection code in the Cell class to // only create light links for objects that are actually visible return ClipStatus::Inside; } //------------------------------------------------------------------------------ /** */ void GlobalLightEntity::OnTransformChanged() { AbstractLightEntity::OnTransformChanged(); // if the light transforms then all shadows must be updated this->castShadowsThisFrame = this->castShadows; // extract the light's direction from the transformation matrix this->lightDir = float4::normalize(this->transform.getrow2()); // calculate shadow transform by doing a simple lookat this->shadowTransform = matrix44::lookatrh(point(0,0,0), this->lightDir, vector::upvec()); // extend shadow casting frustum so that the global light resolves everything within the shadow casting range this->transform.set_xaxis(float4::normalize(this->transform.get_xaxis()) * 1000000.0f); this->transform.set_yaxis(float4::normalize(this->transform.get_yaxis()) * 1000000.0f); this->transform.set_zaxis(float4::normalize(this->transform.get_zaxis()) * 1000000.0f); } //------------------------------------------------------------------------------ /** */ void GlobalLightEntity::OnRenderDebug() { // TODO: render shadow frustum? } //------------------------------------------------------------------------------ /** Handle a message, override this method accordingly in subclasses! */ void GlobalLightEntity::HandleMessage(const Ptr<Message>& msg) { __Dispatch(GlobalLightEntity, this, msg); } } // namespace Graphics
2,801
799
#include "Main.h" #include "KDMAPI.h" #include "OmniMIDI.h" #include "Config.h" #include "Utils.h" #include "Platform.h" #include <inttypes.h> #include <fmt/locale.h> #include <fmt/format.h> // msvc complains about narrowing conversion with bin2c #pragma warning(push) #pragma warning(disable : 4838) #pragma warning(disable : 4309) #include "Shaders/notes_f.h" #include "Shaders/notes_v.h" #include "Shaders/notes_g.h" #pragma warning(pop) Renderer r; GlobalTime* gtime; Midi* midi; MidiTrack* trk; Vertex instanced_quad[] { { {0,1}, {0,1} }, { {1,1}, {1,1} }, { {1,0}, {1,0} }, { {0,0}, {0,0} }, }; uint32_t instanced_quad_indis[] = { 0, 1, 2, 2, 3, 0, }; void Main::run(int argc, wchar_t** argv) { std::wstring filename; if(argc < 2) { filename = Platform::OpenMIDIFileDialog(); if(filename.empty()) return; } else { filename = argv[1]; } auto config_path = Config::GetConfigPath(); Config::GetConfig().Load(config_path); InitializeKDMAPIStream(); SetConsoleOutputCP(65001); // utf-8 fmt::print("Loading {}\n", Utils::wstringToUtf8(Utils::GetFileName(filename))); #ifdef RELEASE try { std::cout << "RPC Enabled: " << Config::GetConfig().discord_rpc << std::endl; if(Config::GetConfig().discord_rpc) Utils::InitDiscord(); } catch(const std::exception& e) { std::cout << "RPC Enabled: 0 (Discord Not Installed)" << std::endl; Config::GetConfig().discord_rpc = false; } #else std::cout << "RPC Enabled: 0 (Chikara is compiled as debug)" << std::endl; #endif try { if(Config::GetConfig().loader_buffer < 0) { Config::GetConfig().loader_buffer = 0; Config::GetConfig().Save(); } } catch(const std::exception& e) { //Config didn't exist, expecting it to just be 10; } wchar_t* filename_temp = _wcsdup(filename.c_str()); midi = new Midi(filename_temp); r.note_event_buffer = midi->note_event_buffer; r.midi_renderer_time = &midi->renderer_time; r.note_stacks.resize(midi->track_count * 16); r.note_count = &midi->note_count; r.notes_played = &midi->notes_played; r.song_len = midi->song_len; r.marker = &midi->marker; r.colors = midi->colors; r.createColors(); midi->colors.clear(); //free up the colors array in color since we no longer need it // playback thread spawned in mainLoop to ensure it's synced with render //printf(file_name); midi->SpawnLoaderThread(); initWindow(filename); //Setup everything for the window initVulkan(); //Setup everything for Vulkan gt = new GlobalTime(Config::GetConfig().start_delay, midi->note_count, filename); gtime = gt; mainLoop(filename); //The main loop for the application cleanup(); //Cleanup everything because we closed the application free(filename_temp); } std::wstring midi_file_name; long long start_time; long long end_time; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) exit(1); if(key == GLFW_KEY_SPACE && action == GLFW_PRESS) { r.paused = !r.paused; r.paused ? gtime->pause() : gtime->resume(); } if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS && mods != GLFW_MOD_SHIFT) gtime->skipForward(1); if(key == GLFW_KEY_RIGHT && action == GLFW_PRESS && mods == GLFW_MOD_SHIFT) gtime->skipForward(5); } void Main::initWindow(std::wstring midi) { midi_file_name = midi; glfwInit(); //Init glfw glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); //Set the glfw api to GLFW_NO_API because we are using Vulkan glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); //Change the ability to resize the window if(Config::GetConfig().transparent) glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE); //Window Transparancy auto filename = Utils::wstringToUtf8(Utils::GetFileName(midi)); int count; int monitorX, monitorY; GLFWmonitor** monitors = glfwGetMonitors(&count); glfwGetMonitorPos(monitors[0], &monitorX, &monitorY); const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); if(Config::GetConfig().fullscreen) { r.window = glfwCreateWindow(mode->width, mode->height, std::string("Chikara | " + filename).c_str(), glfwGetPrimaryMonitor(), nullptr); //Now we create the window r.window_width = mode->width; r.window_height = mode->height; } else { r.window = glfwCreateWindow(default_width, default_height, std::string("Chikara | " + filename).c_str(), nullptr, nullptr); //Now we create the window glfwSetWindowPos(r.window, monitorX + (mode->width - default_width) / 2, monitorY + (mode->height - default_height) / 2); } glfwSetWindowUserPointer(r.window, &r); glfwSetFramebufferSizeCallback(r.window, r.framebufferResizeCallback); glfwSetKeyCallback(r.window, key_callback); } void Main::initVulkan() { r.createInstance(); //Create the Vulkan Instance r.setupDebugMessenger(); r.createSurface(); r.setupDevice(); //Pick the physical device r.createLogicalDevice(); //Create the logical device to use r.createSwapChain(); r.createImageViews(); r.createRenderPass(&r.note_render_pass, true, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); r.createRenderPass(&r.additional_note_render_pass, true, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); r.createDescriptorSetLayout(); r.createGraphicsPipeline(notes_v, notes_v_length, notes_f, notes_f_length, notes_g, notes_g_length, r.note_render_pass, &r.note_pipeline_layout, &r.note_pipeline); r.createRenderPass(&r.imgui_render_pass, false, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); r.createPipelineCache(); r.createCommandPool(&r.cmd_pool, 0); r.createCommandPool(&r.imgui_cmd_pool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); r.createDepthResources(); r.createFramebuffers(); r.createImGuiFramebuffers(); //r.createTextureImage(); //r.createTextureImageView(); //r.createTextureSampler(); //r.createVertexBuffer(instanced_quad, 4, r.note_vertex_buffer, r.note_vertex_buffer_mem); //r.createInstanceBuffer(sizeof(InstanceData) * MAX_NOTES, r.note_instance_buffer, r.note_instance_buffer_mem); //r.createIndexBuffer(instanced_quad_indis, 6, r.note_index_buffer, r.note_index_buffer_mem); r.createNoteDataBuffer(sizeof(NoteData) * MAX_NOTES, r.note_buffer, r.note_buffer_mem); r.createUniformBuffers(r.uniform_buffers, r.uniform_buffers_mem); r.createDescriptorPool(); r.createImGuiDescriptorPool(); r.createDescriptorSets(); r.createCommandBuffers(); r.createImGuiCommandBuffers(); r.createSyncObjects(); r.initImGui(); r.PrepareKeyboard(); } auto timer = std::chrono::steady_clock(); auto last_time = timer.now(); uint64_t frame_counter = 0; uint64_t fps = 0; void Main::mainLoop(std::wstring midi_name) { midi->SpawnPlaybackThread(gt, Config::GetConfig().start_delay); /* char buffer[256]; sprintf(buffer, "Note Count: %s", fmt::format(std::locale(""), "{:n}", midi->note_count)); */ #ifdef RELEASE if(Config::GetConfig().discord_rpc && midi) { auto rpc_text = fmt::format(std::locale(""), "Note Count: {:n}", midi->note_count); Utils::UpdatePresence(rpc_text.c_str(), "Playing: ", Utils::wstringToUtf8(Utils::GetFileName(midi_name))); } #endif while(!glfwWindowShouldClose(r.window)) { r.pre_time = Config::GetConfig().note_speed; //float time; //auto current_time = std::chrono::high_resolution_clock::now(); //time = std::chrono::duration<float, std::chrono::seconds::period>(current_time - start_time).count(); r.midi_renderer_time->store(gt->getTime() + r.pre_time); glfwPollEvents(); r.drawFrame(gt); } vkDeviceWaitIdle(r.device); TerminateKDMAPIStream(); } #pragma region Recreating the swap chain void Main::cleanupSwapChain() { vkDestroyImageView(r.device, r.depth_img_view, nullptr); vkDestroyImage(r.device, r.depth_img, nullptr); vkFreeMemory(r.device, r.depth_img_mem, nullptr); for(size_t i = 0; i < r.swap_chain_framebuffers.size(); i++) vkDestroyFramebuffer(r.device, r.swap_chain_framebuffers[i], nullptr); for(size_t i = 0; i < r.imgui_swap_chain_framebuffers.size(); i++) vkDestroyFramebuffer(r.device, r.imgui_swap_chain_framebuffers[i], nullptr); vkFreeCommandBuffers(r.device, r.cmd_pool, static_cast<uint32_t>(r.cmd_buffers.size()), r.cmd_buffers.data()); vkFreeCommandBuffers(r.device, r.imgui_cmd_pool, static_cast<uint32_t>(r.imgui_cmd_buffers.size()), r.imgui_cmd_buffers.data()); vkDestroyPipeline(r.device, r.note_pipeline, nullptr); vkDestroyPipelineLayout(r.device, r.note_pipeline_layout, nullptr); vkDestroyRenderPass(r.device, r.note_render_pass, nullptr); vkDestroyRenderPass(r.device, r.additional_note_render_pass, nullptr); vkDestroyRenderPass(r.device, r.imgui_render_pass, nullptr); for(size_t i = 0; i < r.swap_chain_img_views.size(); i++) { vkDestroyImageView(r.device, r.swap_chain_img_views[i], nullptr); } vkDestroySwapchainKHR(r.device, r.swap_chain, nullptr); for(size_t i = 0; i < r.swap_chain_imgs.size(); i++) { vkDestroyBuffer(r.device, r.uniform_buffers[i], nullptr); vkFreeMemory(r.device, r.uniform_buffers_mem[i], nullptr); } vkDestroyDescriptorPool(r.device, r.descriptor_pool, nullptr); vkDestroyDescriptorPool(r.device, r.imgui_descriptor_pool, nullptr); } void Main::recreateSwapChain() { int width = 0, height = 0; glfwGetFramebufferSize(r.window, &width, &height); while(width == 0 || height == 0) { glfwGetFramebufferSize(r.window, &width, &height); glfwWaitEvents(); } r.window_width = width; r.window_height = height; vkDeviceWaitIdle(r.device); r.destroyImGui(); cleanupSwapChain(); r.createSwapChain(); r.createImageViews(); r.createRenderPass(&r.note_render_pass, true, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); r.createRenderPass(&r.additional_note_render_pass, true, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); r.createGraphicsPipeline(notes_v, notes_v_length, notes_f, notes_f_length, notes_g, notes_g_length, r.note_render_pass, &r.note_pipeline_layout, &r.note_pipeline); r.createRenderPass(&r.imgui_render_pass, false, VK_ATTACHMENT_LOAD_OP_LOAD, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); r.createDepthResources(); r.createFramebuffers(); r.createImGuiFramebuffers(); r.createUniformBuffers(r.uniform_buffers, r.uniform_buffers_mem); r.createDescriptorPool(); r.createImGuiDescriptorPool(); r.createDescriptorSets(); r.createCommandBuffers(); r.createImGuiCommandBuffers(); r.initImGui(); r.PrepareKeyboard(); } #pragma endregion #pragma region Cleanup void Main::cleanup() { if(enable_validation_layers) { r.DestroyDebugUtilsMessengerEXT(r.inst, r.debug_msg, nullptr); } r.destroyImGui(); cleanupSwapChain(); //vkDestroySampler(r.device, r.tex_sampler, nullptr); vkDestroyImageView(r.device, r.tex_img_view, nullptr); vkDestroyImage(r.device, r.tex_img, nullptr); vkFreeMemory(r.device, r.tex_img_mem, nullptr); vkDestroyDescriptorSetLayout(r.device, r.descriptor_set_layout, nullptr); vkDestroyBuffer(r.device, r.note_buffer, nullptr); vkFreeMemory(r.device, r.note_buffer_mem, nullptr); for(size_t i = 0; i < max_frames_in_flight; i++) { vkDestroySemaphore(r.device, r.render_fin_semaphore[i], nullptr); vkDestroySemaphore(r.device, r.img_available_semaphore[i], nullptr); vkDestroyFence(r.device, r.in_flight_fences[i], nullptr); } vkDestroyCommandPool(r.device, r.cmd_pool, nullptr); vkDestroyCommandPool(r.device, r.imgui_cmd_pool, nullptr); vkDestroyPipelineCache(r.device, r.pipeline_cache, nullptr); vkDestroyDevice(r.device, nullptr); vkDestroySurfaceKHR(r.inst, r.surface, nullptr); vkDestroyInstance(r.inst, nullptr); glfwDestroyWindow(r.window); glfwTerminate(); //Now we terminate #ifdef RELEASE Utils::DestroyDiscord(); #endif } #pragma endregion int wmain(int argc, wchar_t** argv) { Main app; //Get the main class and call it app try { app.run(argc, argv); //Startup the application } catch(const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; //Something broke... } return EXIT_SUCCESS; }
12,795
5,035
/* Copyright (c) 2015 Convey Computer Corporation * * This file is part of the OpenHT toolset located at: * * https://github.com/TonyBrewer/OpenHT * * Use and distribution licensed under the BSD 3-clause license. * See the LICENSE file for the complete license text. */ // HtFile.cpp: implementation of the CHtFile class. // ////////////////////////////////////////////////////////////////////// #include "Htfe.h" #include "HtfeErrorMsg.h" #include "HtfeFile.h" #ifndef _MSC_VER #include <sys/types.h> #include <unistd.h> #define _lseek lseek #define _read read #define _unlink unlink #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CHtFile::CHtFile() { m_indentLevel = 0; m_bNewLine = false; m_bDoNotSplitLine = false; m_dstFp = 0; m_lineCol = 0; m_lineNum = 1; m_maxLineCol = 70; m_bLineBuffering = false; m_lineListIdx = 0; m_bVarInit = false; m_bInTask = false; } bool CHtFile::Open(const string &outputFileName, char *pMode) { m_fileName = outputFileName; m_dstFp = fopen(outputFileName.c_str(), pMode); int lastSlash = outputFileName.find_last_of("/\\"); if (lastSlash > 0) m_folder = outputFileName.substr(0,lastSlash); else m_folder = "."; return m_dstFp != 0; } void CHtFile::Close() { Assert(m_dstFp); fclose(m_dstFp); m_dstFp = 0; } void CHtFile::Delete() { if (m_dstFp) { fclose(m_dstFp); _unlink(m_fileName.c_str()); } m_dstFp = 0; } void CHtFile::Dup(int srcFd, int startOffset, int endOffset) { int origOffset = _lseek(srcFd, 0, SEEK_CUR); _lseek(srcFd, startOffset, SEEK_SET); char buffer[4096]; for (int offset = startOffset; offset < endOffset; ) { int readSize = endOffset - offset; if (readSize > 4096) readSize = 4096; int readBytes = _read(srcFd, buffer, readSize); if (readBytes <= 0) break; fwrite(buffer, 1, readBytes, m_dstFp); offset += readBytes; } _lseek(srcFd, origOffset, SEEK_SET); } void CHtFile::PrintVarInit(const char *format, ...) { int savedIndentLevel = GetIndentLevel(); SetIndentLevel(m_varInitIndentLevel); m_bVarInit = true; va_list marker; va_start(marker, format); /* Initialize variable arguments. */ Print_(format, marker); m_bVarInit = false; SetIndentLevel(savedIndentLevel); } int CHtFile::Print(const char *format, ...) { va_list marker; va_start(marker, format); /* Initialize variable arguments. */ return Print_(format, marker); } int CHtFile::Print_(const char *format, va_list marker) { if (m_indentLevel == -1) { int r = vfprintf(m_dstFp, format, marker); for (const char *pCh = format; *pCh; pCh += 1) if (*pCh == '\n') m_lineNum += 1; return r; } else { char buf[4096]; int r = vsprintf(buf, format, marker); // a newline in the input forces a new line in the output // the formated string can be split where a space exists or at the boundary bool bEol = false; char *pStrStart = buf; for (;;) { if (m_bNewLine) { int level = m_indentLevel; for (int i = 0; i < level; i += 1) Putc(' '); m_lineCol = m_indentLevel; m_bNewLine = false; } // find next string terminated by a ' ', '\t', '\n' or '\0' char *pStrEnd = pStrStart; if (pStrStart[0] == '/' && pStrStart[1] == '/') { // comments must be handled together to avoid wrapping to a newline while (*pStrEnd != '\n' && *pStrEnd != '\r' && *pStrEnd != '\0') pStrEnd++; } else { while (*pStrEnd != ' ' && *pStrEnd != '\t' && *pStrEnd != '\n' && *pStrEnd != '\r' && *pStrEnd != '\0') pStrEnd++; } m_bNewLine = *pStrEnd == '\n' || *pStrEnd == '\r'; bEol = *pStrEnd == '\0'; bool bSpace = *pStrEnd == ' '; bool bTab = *pStrEnd == '\t'; *pStrEnd = '\0'; // check if string can fit in current line int strLen = strlen(pStrStart); if (!m_bDoNotSplitLine && m_indentLevel < m_lineCol && m_lineCol + strLen > m_maxLineCol) { // string does not fit, start new line Putc('\n'); m_lineNum += 1; for (int i = 0; i < m_indentLevel+1; i += 1) Putc(' '); m_lineCol = m_indentLevel+1; } if (strLen > 0) Puts(pStrStart); m_lineCol += strLen; if (!m_bNewLine && bSpace) Putc(' '); if (!m_bNewLine && bTab) Putc('\t'); pStrStart = pStrEnd+1; if (m_bNewLine) { Putc('\n'); m_lineNum += 1; } while (!bEol && *pStrStart == '\n') { pStrStart += 1; Putc('\n'); m_lineNum += 1; } if (bEol || *pStrStart == '\0') { m_bDoNotSplitLine = false; return r; } } } } void CHtFile::Putc(char ch) { if (m_bVarInit) { m_varInitBuffer += ch; if (ch == '\n') { m_varInitLineList.push_back(m_varInitBuffer); m_varInitBuffer.clear(); } } else if (m_bLineBuffering) { m_lineBuffer += ch; if (ch == '\n') { m_lineList[m_lineListIdx].push_back(m_lineBuffer); m_lineBuffer.clear(); } } else fputc(ch, m_dstFp); } void CHtFile::Puts(char * pStr) { if (m_bVarInit) m_varInitBuffer += pStr; else if (m_bLineBuffering) m_lineBuffer += pStr; else fputs(pStr, m_dstFp); } void CHtFile::FlushLineBuffer() { for (size_t i = 0; i < m_lineList[m_lineListIdx].size(); i += 1) fputs(m_lineList[m_lineListIdx][i].c_str(), m_dstFp); m_lineList[m_lineListIdx].clear(); } void CHtFile::VarInitClose() { if (m_bInTask) { // first insert task's temp var declarations m_lineList[m_varInitListIdx].insert(m_lineList[m_varInitListIdx].begin() + m_varInitLineIdx, m_lineList[2].begin(), m_lineList[2].end()); m_varInitLineIdx += m_lineList[2].size(); m_lineList[2].clear(); // SetLineBuffer(0); } m_lineList[m_varInitListIdx].insert(m_lineList[m_varInitListIdx].begin() + m_varInitLineIdx, m_varInitLineList.begin(), m_varInitLineList.end()); m_varInitLineList.clear(); }
5,874
2,563
/**************************************************************************** Copyright (c) 2017-2020 Kevin Wu (Wu Feng) github: http://github.com/kevinwu1024 Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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 NON INFRINGEMENT. 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 "SCBehaviorSystem.h" #include "../cocos/SCViewController.h" #include "../system/SCSystem.h" NAMESPACE_SPEEDCC_BEGIN ///--------- SCBehaviorPurchase SCBehaviorPurchase::SCBehaviorPurchase(const int nFeatureID,SCStore::ResultFunc_t resultFunc) :_nFeatureID(nFeatureID) { this->setResultFunc(resultFunc); } SCBehaviorPurchase::~SCBehaviorPurchase() { SCStore::getInstance()->setPurchaseResultFunc(nullptr); } void SCBehaviorPurchase::setResultFunc(const SCStore::ResultFunc_t& func) { _resultFunc = [func](int nFeatureID,SCStore::EResultType result,void* pInfo) { auto ptrCtrl = SCViewNav()->getCurrentController(); ptrCtrl->showBlackMask(false); ptrCtrl->setTouchAcceptable(true); if(func!=nullptr) { func(nFeatureID,result,pInfo); } }; } void SCBehaviorPurchase::execute(const SCDictionary& par) { auto ptrCtrl = SCViewNav()->getCurrentController(); ptrCtrl->showBlackMask(true); ptrCtrl->setTouchAcceptable(false); SCStore::getInstance()->purchaseFeature(_nFeatureID,_resultFunc); } ///---------- SCBehaviorRequestProduct SCBehaviorRequestProduct::~SCBehaviorRequestProduct() { SCStore::getInstance()->setRequestProductResultFunc(nullptr); } void SCBehaviorRequestProduct::execute(const SCDictionary& par) { SCStore::getInstance()->requestProductInfo(_resultFunc); } ///----------- SCBehaviorRestorePurchased SCBehaviorRestorePurchased::~SCBehaviorRestorePurchased() { SCStore::getInstance()->setRestoreResultFunc(nullptr); } void SCBehaviorRestorePurchased::execute(const SCDictionary& par) { SCStore::getInstance()->restorePurchased(_resultFunc); } NAMESPACE_SPEEDCC_END
2,668
856
#include "ParallelUtils.h" #include <functional> #if defined(_OPENMP) # include <omp.h> #else # include <future> #endif NAMESPACE_UTILITY size_t ParallelUtils::ProcessorCount() { #if defined(_OPENMP) return static_cast<size_t>(omp_get_num_procs()); #else return static_cast<size_t>(std::thread::hardware_concurrency()); #endif } void ParallelUtils::ParallelFor(size_t From, size_t To, const std::function<void(size_t)> &F) { #if defined(_OPENMP) #pragma omp parallel num_threads((int)To) { size_t i = (size_t)omp_get_thread_num(); F(i); } #else std::vector<std::future<void>> futures; for (size_t i = From; i < To; ++i) { auto fut = std::async([i, F]() { F(i); }); futures.push_back(std::move(fut)); } for (size_t i = 0; i < futures.size(); ++i) futures[i].wait(); futures.clear(); #endif } NAMESPACE_UTILITYEND
846
376
#include "MinDistFitness.hh" #define THRESHOLD_WAIST 0.45 /*! \brief constructor * * \param[in] mbs_data Robotran structure * \param[in] sens_info info from the sensor */ MinDistFitness::MinDistFitness(MbsData *mbs_data, SensorsInfo *sens_info): FitnessStage(mbs_data) { max_x_before_fall = 0.0; tf = mbs_data->tf; lim_x_travel = 0.75 * tf; max_fitness = 300.0; this->sens_info = sens_info; } /*! \brief destructor */ MinDistFitness::~MinDistFitness() { } /*! \brief compute variables at each time step */ void MinDistFitness::compute() { double x_before_fall; // threshold_waist prevents from counting positive travelled distance if the robot is falling if (sens_info->get_waist_to_feet() > THRESHOLD_WAIST) { // no interest if going backward x_before_fall = fmin(fmin(sens_info->get_S_MidWaist_P(0),sens_info->get_S_RFoots_P(0)),sens_info->get_S_LFoots_P(0)); if (x_before_fall < 0.0) { x_before_fall = 0.0; } // to consider only the max positive value if (x_before_fall > max_x_before_fall) { max_x_before_fall = x_before_fall; } } } /*! \brief get fitness * * \return fitness */ double MinDistFitness::get_fitness() { return (max_x_before_fall > lim_x_travel) ? max_fitness : max_x_before_fall * (max_fitness/lim_x_travel); } /*! \brief detect if next stage is unlocked * * \return 1 if next stage unlocked, 0 otherwise */ int MinDistFitness::next_stage_unlocked() { return 1.0; }
1,483
631
#include <bits/stdc++.h> using namespace std; const long long M=1e9+7; int k,cnt=-1; long long x,n=1; inline long long fpow(long long a,long long b) { long long r=1; for (;b;b>>=1,(a*=a)%=M) if (b&1) (r*=a)%=M; return r; } int main() { scanf("%d",&k); for (int i=1;i<=k;i++) { scanf("%lld",&x); if (!(x&1)) cnt=1; x%=(M-1);(n*=x)%=(M-1); } n=(n+M-2)%(M-1); long long p=fpow(2,n),q;q=p; p=(p+cnt+M)%M;(p*=333333336LL)%=M; printf("%lld/%lld\n",p,q); return 0; }
481
293
#include "dicom_pch.h" #include "dicom/data/AS.h" #include <sstream> #include <iomanip> #include "dicom/data/detail/atoi.h" namespace { using namespace dicom::data; [[nodiscard]] AS::UnitType char_to_units(char c) { switch (c) { case 'D': return AS::Days; case 'W': return AS::Weeks; case 'M': return AS::Months; case 'Y': return AS::Years; default: return AS::UnitType(-1); } } [[nodiscard]] char units_to_char(AS::UnitType units) { switch (units) { case AS::Days: return 'D'; case AS::Weeks: return 'W'; case AS::Months: return 'M'; case AS::Years: return 'Y'; default: return 'X'; // Something purposefully invalid } } } namespace dicom::data { AS::AS() : AS(std::string()) {} //-------------------------------------------------------------------------------------------------------- AS::AS(const char* value) : AS(std::string(value)) {} //-------------------------------------------------------------------------------------------------------- AS::AS(const std::string_view& value) : AS(std::string(value)) {} //-------------------------------------------------------------------------------------------------------- AS::AS(std::string&& value) : VR(VRType::AS), m_value(std::forward<std::string>(value)) {} //-------------------------------------------------------------------------------------------------------- AS::AS(int32_t age, UnitType units) : VR(VRType::AS) { std::ostringstream ss; ss << std::setw(3) << std::setfill('0') << age << std::setw(0) << units_to_char(units); m_value = ss.str(); } //-------------------------------------------------------------------------------------------------------- AS::AS(const AS& other) = default; AS::AS(AS&& other) = default; AS& AS::operator = (const AS& other) = default; AS& AS::operator = (AS&& other) = default; //-------------------------------------------------------------------------------------------------------- AS::~AS() = default; //-------------------------------------------------------------------------------------------------------- ValidityType AS::Validate() const { /*** Essential checks ***/ // Value is always 4 characters long if (m_value.size() != 4) { return ValidityType::Invalid; } // Value must have numeric digits for the first three characters if (!std::all_of(m_value.begin(), m_value.begin() + 3, isdigit)) { return ValidityType::Invalid; } // Value must have a unit character at the end if (char_to_units(m_value[3]) == -1) { return ValidityType::Invalid; } return ValidityType::Valid; } //-------------------------------------------------------------------------------------------------------- int32_t AS::Age() const { AssertValidated(); return detail::unchecked_atoi<int32_t>(m_value.c_str()); } //-------------------------------------------------------------------------------------------------------- AS::UnitType AS::Units() const { AssertValidated(); return char_to_units(m_value[3]); } //-------------------------------------------------------------------------------------------------------- int32_t AS::Compare(const VR* other) const { auto result = VR::Compare(other); if (result) { return result; } auto typed = static_cast<const AS*>(other); if (Validity() == ValidityType::Invalid || typed->Validity() == ValidityType::Invalid) { return m_value.compare(typed->m_value); } int32_t diff = Units() - typed->Units(); if (diff != 0) { return diff; } diff = Age() - typed->Age(); return diff; } //-------------------------------------------------------------------------------------------------------- bool AS::operator == (const VR* other) const { if (VR::Compare(other) != 0) { return false; } auto typed = static_cast<const AS*>(other); return (m_value == typed->m_value); } //-------------------------------------------------------------------------------------------------------- bool AS::operator != (const VR* other) const { if (VR::Compare(other) != 0) { return true; } auto typed = static_cast<const AS*>(other); return (m_value != typed->m_value); } }
4,746
1,329
#include "EspNowSerialBase.h" const char* EspNowSerialBase::NEWLINE = "\r\n"; const uint8_t EspNowSerialBase::BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; EspNowSerialBase::EspNowSerialBase(void) : _serial(nullptr), _channel(0), _address{0}, _buf{0} { uint8_t addr[ESP_NOW_ETH_ALEN] = {0}; esp_read_mac(addr, ESP_MAC_WIFI_STA); memcpy(this->_address, addr, ESP_NOW_ETH_ALEN); } EspNowSerialBase::~EspNowSerialBase(void) { } const uint8_t* const EspNowSerialBase::getAddress(void) const { return this->_address; } bool EspNowSerialBase::begin(HardwareSerial& serial) { this->_serial = &serial; if (!WiFi.mode(WIFI_STA)) { return false; } if (!WiFi.disconnect()) { return false; } initEspNow(); return true; } bool EspNowSerialBase::setChannel(const uint8_t channel) { this->_channel = channel; return true; } size_t EspNowSerialBase::write(const char* data, size_t len) { this->_serial->write(data, len); #if defined(ESPNOW_INITIATOR) len = send(data, len); #endif return len; } size_t EspNowSerialBase::printf(const char* format, ...) { va_list args; va_start(args, format); va_list args_copy; va_copy(args_copy, args); char* loc = this->_buf; int len = vsnprintf(loc, sizeof(this->_buf), format, args_copy); va_end(args_copy); if (len < 0) { return 0; } if (len >= sizeof(this->_buf)) { loc = (char*)malloc(len + 1); if (loc == nullptr) { return 0; } len = vsnprintf(loc, len + 1, format, args); } write(loc, len); if (loc != this->_buf) { free(loc); } return len; } size_t EspNowSerialBase::print(const char* str) { return printf("%s", str); } size_t EspNowSerialBase::println(const char* str) { return printf("%s%s", str, NEWLINE); } size_t EspNowSerialBase::println(void) { return printf("%s", NEWLINE); } void EspNowSerialBase::printMacAddress(const uint8_t* macAddr) { static char macStr[ESP_NOW_ETH_ALEN * 3 + 1] = {0}; snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]); print(macStr); } void EspNowSerialBase::dump(const uint8_t* data, size_t len, uint8_t indent, uint8_t width) { println(); printf("Dump Length: %d", len); println(); size_t p = 0; for (; p < len; ++p) { if (p % width == 0) { if (p != 0) { print(" |"); for (size_t cp = p - width; cp < p; ++cp) { printf("%c", isPrintable(data[cp]) ? data[cp] : '.'); } print("|"); println(); } for (size_t i = 0; i < indent; ++i) { print(" "); } } printf("%02x ", data[p]); } if (len % width != 0) { uint8_t remain = width - len % width; for (size_t cp = 0; cp < remain; ++cp) { print(" "); } print(" |"); for (size_t cp = len - len % width; cp < len; ++cp) { printf("%c", isPrintable(data[cp]) ? data[cp] : '.'); } print("|"); println(); } } void EspNowSerialBase::initEspNow(void) { if (esp_now_init() != ESP_OK) { ESP.restart(); } } void EspNowSerialBase::initPeer(const uint8_t* addr, esp_now_peer_info_t& peer) { memset(&peer, 0, sizeof(peer)); memcpy(&(peer.peer_addr), addr, ESP_NOW_ETH_ALEN); peer.channel = this->_channel; peer.encrypt = 0; } bool EspNowSerialBase::setRecvCallback(esp_now_recv_cb_t cb) { esp_err_t e = esp_now_register_recv_cb(cb); return e == ESP_OK; } bool EspNowSerialBase::setSendCallback(esp_now_send_cb_t cb) { esp_err_t e = esp_now_register_send_cb(cb); return e == ESP_OK; } bool EspNowSerialBase::registerPeer(const uint8_t* addr) { esp_now_peer_info_t peerInfo; initPeer(addr, peerInfo); esp_err_t e = esp_now_add_peer(&peerInfo); return e == ESP_OK; } bool EspNowSerialBase::unregisterPeer(const uint8_t* addr) { esp_err_t e = esp_now_del_peer(addr); return e == ESP_OK; } size_t EspNowSerialBase::send(const char* data, size_t len) { esp_err_t e = ESP_OK; esp_now_peer_info_t peer; size_t n = 0; for (size_t i = 0; i < len; i += n) { n = min(sizeof(this->_buf), len - i); memcpy(this->_buf, data + i, n); e = esp_now_fetch_peer(true, &peer); if (e == ESP_ERR_ESPNOW_NOT_FOUND) { // Broadcast esp_now_send(BROADCAST_ADDRESS, (uint8_t*)this->_buf, n); } else { while (e == ESP_OK) { esp_now_send(peer.peer_addr, (uint8_t*)this->_buf, n); e = esp_now_fetch_peer(false, &peer); } } } return len; }
4,977
1,898
#include <cpplib/stdinc.hpp> int32_t main(){ desync(); int t; cin >> t; vi pali = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6}; map<int, int> ipal; ipal[2] = 1; ipal[3] = 7; ipal[4] = 4; ipal[5] = 5; ipal[6] = 9; ipal[7] = 8; while(t--){ int n; cin >> n; string num; cin >> num; int pals = 0; for(char c:num) pals += pali[c-'0']; for(int i=0; i<n; ++i){ int l = (n-i-1)*2, r = (n-i-1)*7; for(int d=9; d>=0; --d){ int aft = pals - pali[d]; if(aft >= l and aft <= r){ pals -= pali[d]; cout << d; break; } } } cout << endl; } return 0; }
806
344
/* * PL/Python main entry points * * src/common/pl/plpython/plpy_main.c */ #include "postgres.h" #include "knl/knl_variable.h" #include "catalog/pg_proc.h" #include "catalog/pg_type.h" #include "commands/trigger.h" #include "executor/spi.h" #include "executor/executor.h" #include "miscadmin.h" #include "pgaudit.h" #include "utils/guc.h" #include "utils/memutils.h" #include "utils/rel.h" #include "utils/rel_gs.h" #include "utils/syscache.h" #include "plpython.h" #include "plpy_main.h" #include "plpy_elog.h" #include "plpy_exec.h" #include "plpy_plpymodule.h" #include "plpy_procedure.h" const int PGAUDIT_MAXLENGTH = 1024; /* exported functions */ #if PY_MAJOR_VERSION >= 3 /* Use separate names to avoid clash in pg_pltemplate */ #define plpython_validator plpython3_validator #define plpython_call_handler plpython3_call_handler #define plpython_inline_handler plpython3_inline_handler #endif extern "C" void _PG_init(void); extern "C" Datum plpython_validator(PG_FUNCTION_ARGS); extern "C" Datum plpython_call_handler(PG_FUNCTION_ARGS); extern "C" Datum plpython_inline_handler(PG_FUNCTION_ARGS); #if PY_MAJOR_VERSION < 3 /* Define aliases plpython2_call_handler etc */ extern "C" Datum plpython2_validator(PG_FUNCTION_ARGS); extern "C" Datum plpython2_call_handler(PG_FUNCTION_ARGS); extern "C" Datum plpython2_inline_handler(PG_FUNCTION_ARGS); #endif PG_MODULE_MAGIC; PG_FUNCTION_INFO_V1(plpython_validator); PG_FUNCTION_INFO_V1(plpython_call_handler); PG_FUNCTION_INFO_V1(plpython_inline_handler); #if PY_MAJOR_VERSION < 3 PG_FUNCTION_INFO_V1(plpython2_validator); PG_FUNCTION_INFO_V1(plpython2_call_handler); PG_FUNCTION_INFO_V1(plpython2_inline_handler); #endif static bool PLy_procedure_is_trigger(Form_pg_proc procStruct); static void plpython_error_callback(void* arg); static void plpython_inline_error_callback(void* arg); static void PLy_init_interp(void); static PLyExecutionContext* PLy_push_execution_context(void); static void PLy_pop_execution_context(void); static void AuditPlpythonFunction(Oid funcoid, const char* funcname, AuditResult result); static const int plpython_python_version = PY_MAJOR_VERSION; /* this doesn't need to be global; use PLy_current_execution_context() */ static THR_LOCAL PLyExecutionContext* PLy_execution_contexts = NULL; THR_LOCAL plpy_t_context_struct g_plpy_t_context = {0}; pthread_mutex_t g_plyLocaleMutex = PTHREAD_MUTEX_INITIALIZER; void PG_init(void) { /* Be sure we do initialization only once (should be redundant now) */ const int** version_ptr; if (g_plpy_t_context.inited) { return; } /* Be sure we don't run Python 2 and 3 in the same session (might crash) */ version_ptr = (const int**)find_rendezvous_variable("plpython_python_version"); if (!(*version_ptr)) { *version_ptr = &plpython_python_version; } else { if (**version_ptr != plpython_python_version) { ereport(FATAL, (errmsg("Python major version mismatch in session"), errdetail("This session has previously used Python major version %d, and it is now attempting to " "use Python major version %d.", **version_ptr, plpython_python_version), errhint("Start a new session to use a different Python major version."))); } } pg_bindtextdomain(TEXTDOMAIN); #if PY_MAJOR_VERSION >= 3 PyImport_AppendInittab("plpy", PyInit_plpy); #endif #if PY_MAJOR_VERSION < 3 if (!PyEval_ThreadsInitialized()) { PyEval_InitThreads(); } #endif Py_Initialize(); #if PY_MAJOR_VERSION >= 3 PyImport_ImportModule("plpy"); #endif #if PY_MAJOR_VERSION >= 3 if (!PyEval_ThreadsInitialized()) { PyEval_InitThreads(); PyEval_SaveThread(); } #endif PLy_init_interp(); PLy_init_plpy(); if (PyErr_Occurred()) { PLy_elog(FATAL, "untrapped error in initialization"); } init_procedure_caches(); g_plpy_t_context.explicit_subtransactions = NIL; PLy_execution_contexts = NULL; g_plpy_t_context.inited = true; } void _PG_init(void) { PG_init(); } /* * This should only be called once from _PG_init. Initialize the Python * interpreter and global data. */ void PLy_init_interp(void) { static PyObject* PLy_interp_safe_globals = NULL; PyObject* mainmod = NULL; mainmod = PyImport_AddModule("__main__"); if (mainmod == NULL || PyErr_Occurred()) { PLy_elog(ERROR, "could not import \"__main__\" module"); } Py_INCREF(mainmod); g_plpy_t_context.PLy_interp_globals = PyModule_GetDict(mainmod); PLy_interp_safe_globals = PyDict_New(); if (PLy_interp_safe_globals == NULL) { PLy_elog(ERROR, "could not create globals"); } PyDict_SetItemString(g_plpy_t_context.PLy_interp_globals, "GD", PLy_interp_safe_globals); Py_DECREF(mainmod); if (g_plpy_t_context.PLy_interp_globals == NULL || PyErr_Occurred()) { PLy_elog(ERROR, "could not initialize globals"); } } Datum plpython_validator(PG_FUNCTION_ARGS) { Oid funcoid = PG_GETARG_OID(0); HeapTuple tuple; Form_pg_proc procStruct; bool is_trigger = false; if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid)) { PG_RETURN_VOID(); } if (!u_sess->attr.attr_sql.check_function_bodies) { PG_RETURN_VOID(); } AutoMutexLock plpythonLock(&g_plyLocaleMutex); if (g_plpy_t_context.Ply_LockLevel == 0) { plpythonLock.lock(); } PyLock pyLock(&(g_plpy_t_context.Ply_LockLevel)); PG_TRY(); { PG_init(); /* Get the new function's pg_proc entry */ tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); if (!HeapTupleIsValid(tuple)) { elog(ERROR, "cache lookup failed for function %u", funcoid); } procStruct = (Form_pg_proc)GETSTRUCT(tuple); is_trigger = PLy_procedure_is_trigger(procStruct); if (is_trigger) { elog(ERROR, "PL/Python does not support trigger"); } ReleaseSysCache(tuple); /* We can't validate triggers against any particular table ... */ PLy_procedure_get(funcoid, InvalidOid, is_trigger); } PG_CATCH(); { pyLock.Reset(); plpythonLock.unLock(); PG_RE_THROW(); } PG_END_TRY(); PG_RETURN_VOID(); } #if PY_MAJOR_VERSION < 3 Datum plpython2_validator(PG_FUNCTION_ARGS) { return plpython_validator(fcinfo); } #endif /* PY_MAJOR_VERSION < 3 */ Datum plpython_call_handler(PG_FUNCTION_ARGS) { AutoMutexLock plpythonLock(&g_plyLocaleMutex); if (g_plpy_t_context.Ply_LockLevel == 0) { plpythonLock.lock(); } Datum retval; PLyExecutionContext* exec_ctx = NULL; ErrorContextCallback plerrcontext; PyLock pyLock(&(g_plpy_t_context.Ply_LockLevel)); PG_TRY(); { PG_init(); /* Note: SPI_finish() happens in plpy_exec.cpp, which is dubious design */ if (SPI_connect() != SPI_OK_CONNECT) { elog(ERROR, "SPI_connect failed"); } /* * Push execution context onto stack. It is important that this get * popped again, so avoid putting anything that could throw error between * here and the PG_TRY. */ exec_ctx = PLy_push_execution_context(); /* * Setup error traceback support for ereport() */ plerrcontext.callback = plpython_error_callback; plerrcontext.previous = t_thrd.log_cxt.error_context_stack; t_thrd.log_cxt.error_context_stack = &plerrcontext; } PG_CATCH(); { pyLock.Reset(); plpythonLock.unLock(); PG_RE_THROW(); } PG_END_TRY(); Oid funcoid = fcinfo->flinfo->fn_oid; PLyProcedure* proc = NULL; PG_TRY(); { if (CALLED_AS_TRIGGER(fcinfo)) { elog(ERROR, "PL/Python does not support trigger"); Relation tgrel = ((TriggerData*)fcinfo->context)->tg_relation; HeapTuple trv; proc = PLy_procedure_get(funcoid, RelationGetRelid(tgrel), true); exec_ctx->curr_proc = proc; trv = PLy_exec_trigger(fcinfo, proc); retval = PointerGetDatum(trv); } else { proc = PLy_procedure_get(funcoid, InvalidOid, false); exec_ctx->curr_proc = proc; retval = PLy_exec_function(fcinfo, proc); if (AUDIT_EXEC_ENABLED) { AuditPlpythonFunction(funcoid, proc->proname, AUDIT_OK); } } } PG_CATCH(); { if (AUDIT_EXEC_ENABLED) { AuditPlpythonFunction(funcoid, proc->proname, AUDIT_FAILED); } PLy_pop_execution_context(); PyErr_Clear(); pyLock.Reset(); plpythonLock.unLock(); PG_RE_THROW(); } PG_END_TRY(); PG_TRY(); { /* Pop the error context stack */ t_thrd.log_cxt.error_context_stack = plerrcontext.previous; /* ... and then the execution context */ PLy_pop_execution_context(); } PG_CATCH(); { pyLock.Reset(); plpythonLock.unLock(); PG_RE_THROW(); } PG_END_TRY(); return retval; } #if PY_MAJOR_VERSION < 3 Datum plpython2_call_handler(PG_FUNCTION_ARGS) { return plpython_call_handler(fcinfo); } #endif /* PY_MAJOR_VERSION < 3 */ Datum plpython_inline_handler(PG_FUNCTION_ARGS) { AutoMutexLock plpythonLock(&g_plyLocaleMutex); if (g_plpy_t_context.Ply_LockLevel == 0) { plpythonLock.lock(); } PyLock pyLock(&(g_plpy_t_context.Ply_LockLevel)); InlineCodeBlock* codeblock = (InlineCodeBlock*)DatumGetPointer(PG_GETARG_DATUM(0)); FunctionCallInfoData fake_fcinfo; FmgrInfo flinfo; PLyProcedure proc; PLyExecutionContext* exec_ctx = NULL; ErrorContextCallback plerrcontext; errno_t rc = EOK; PG_TRY(); { PG_init(); /* Note: SPI_finish() happens in plpy_exec.c, which is dubious design */ if (SPI_connect() != SPI_OK_CONNECT) { elog(ERROR, "SPI_connect failed"); } rc = memset_s(&fake_fcinfo, sizeof(fake_fcinfo), 0, sizeof(fake_fcinfo)); securec_check(rc, "\0", "\0"); rc = memset_s(&flinfo, sizeof(flinfo), 0, sizeof(flinfo)); securec_check(rc, "\0", "\0"); fake_fcinfo.flinfo = &flinfo; flinfo.fn_oid = InvalidOid; flinfo.fn_mcxt = CurrentMemoryContext; rc = memset_s(&proc, sizeof(PLyProcedure), 0, sizeof(PLyProcedure)); securec_check(rc, "\0", "\0"); proc.pyname = PLy_strdup("__plpython_inline_block"); proc.result.out.d.typoid = VOIDOID; /* * Push execution context onto stack. It is important that this get * popped again, so avoid putting anything that could throw error between * here and the PG_TRY. (plpython_inline_error_callback doesn't currently * need the stack entry, but for consistency with plpython_call_handler we * do it in this order.) */ exec_ctx = PLy_push_execution_context(); /* * Setup error traceback support for ereport() */ plerrcontext.callback = plpython_inline_error_callback; plerrcontext.previous = t_thrd.log_cxt.error_context_stack; t_thrd.log_cxt.error_context_stack = &plerrcontext; } PG_CATCH(); { plpythonLock.unLock(); pyLock.Reset(); PG_RE_THROW(); } PG_END_TRY(); PG_TRY(); { PLy_procedure_compile(&proc, codeblock->source_text); exec_ctx->curr_proc = &proc; PLy_exec_function(&fake_fcinfo, &proc); if (AUDIT_EXEC_ENABLED) { AuditPlpythonFunction(InvalidOid, proc.pyname, AUDIT_OK); } } PG_CATCH(); { if (AUDIT_EXEC_ENABLED) { AuditPlpythonFunction(InvalidOid, proc.pyname, AUDIT_FAILED); } PLy_pop_execution_context(); PLy_procedure_delete(&proc); PyErr_Clear(); plpythonLock.unLock(); pyLock.Reset(); PG_RE_THROW(); } PG_END_TRY(); PG_TRY(); { /* Pop the error context stack */ t_thrd.log_cxt.error_context_stack = plerrcontext.previous; /* ... and then the execution context */ PLy_pop_execution_context(); /* Now clean up the transient procedure we made */ PLy_procedure_delete(&proc); } PG_CATCH(); { plpythonLock.unLock(); pyLock.Reset(); PG_RE_THROW(); } PG_END_TRY(); PG_RETURN_VOID(); } #if PY_MAJOR_VERSION < 3 Datum plpython2_inline_handler(PG_FUNCTION_ARGS) { return plpython_inline_handler(fcinfo); } #endif /* PY_MAJOR_VERSION < 3 */ static bool PLy_procedure_is_trigger(Form_pg_proc procStruct) { return (procStruct->prorettype == TRIGGEROID || (procStruct->prorettype == OPAQUEOID && procStruct->pronargs == 0)); } static void plpython_error_callback(void* arg) { PLyExecutionContext* exec_ctx = PLy_current_execution_context(); if (AUDIT_EXEC_ENABLED) { AuditPlpythonFunction(InvalidOid, PLy_procedure_name(exec_ctx->curr_proc), AUDIT_FAILED); } if (exec_ctx->curr_proc != NULL) { errcontext("PL/Python function \"%s\"", PLy_procedure_name(exec_ctx->curr_proc)); } } static void plpython_inline_error_callback(void* arg) { if (AUDIT_EXEC_ENABLED) { AuditPlpythonFunction(InvalidOid, "__plpython_inline_block", AUDIT_FAILED); } errcontext("PL/Python anonymous code block"); } PLyExecutionContext* PLy_current_execution_context(void) { if (PLy_execution_contexts == NULL) { elog(ERROR, "no Python function is currently executing"); } return PLy_execution_contexts; } static PLyExecutionContext* PLy_push_execution_context(void) { PLyExecutionContext* context = (PLyExecutionContext*)PLy_malloc(sizeof(PLyExecutionContext)); context->curr_proc = NULL; context->scratch_ctx = AllocSetContextCreate(u_sess->top_transaction_mem_cxt, "PL/Python scratch context", ALLOCSET_DEFAULT_MINSIZE, ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE); context->next = PLy_execution_contexts; PLy_execution_contexts = context; return context; } static void PLy_pop_execution_context(void) { PLyExecutionContext* context = PLy_execution_contexts; if (context == NULL) { elog(ERROR, "no Python function is currently executing"); } PLy_execution_contexts = context->next; MemoryContextDelete(context->scratch_ctx); PLy_free(context); } static void AuditPlpythonFunction(Oid funcoid, const char* funcname, AuditResult result) { char details[PGAUDIT_MAXLENGTH]; errno_t rc = EOK; if (result == AUDIT_OK) { if (funcoid == InvalidOid) { // for AnonymousBlock rc = snprintf_s(details, PGAUDIT_MAXLENGTH, PGAUDIT_MAXLENGTH - 1, "Execute Plpython anonymous code block(oid = %u). ", funcoid); } else { // for normal function rc = snprintf_s(details, PGAUDIT_MAXLENGTH, PGAUDIT_MAXLENGTH - 1, "Execute PLpython function(oid = %u). ", funcoid); } } else { // for abnormal function rc = snprintf_s(details, PGAUDIT_MAXLENGTH, PGAUDIT_MAXLENGTH - 1, "Execute PLpython function(%s). ", funcname); } securec_check_ss(rc, "", ""); audit_report(AUDIT_FUNCTION_EXEC, result, funcname, details); }
15,633
5,578
/// A file or directory on your system. // @classmod kv.File // @pragma nostrip #include "lua-kv.hpp" #include LKV_JUCE_HEADER #define LKV_TYPE_NAME_FILE "File" using namespace juce; LKV_EXPORT int luaopen_kv_File (lua_State* L) { sol::state_view lua (L); auto t = lua.create_table(); t.new_usertype<File> (LKV_TYPE_NAME_FILE, sol::no_constructor, sol::call_constructor, sol::factories ( /// Non-existent file // @function File.__call // @within Metamethods []() { return File(); }, /// File from absolute path // @string abspath Absolute file path. // @function File.__call // @within Metamethods // @usage // local f = kv.File ("/path/to/file/or/dir") // -- do something with file [](const char* path) { return File (String::fromUTF8 (path)); } ), /// File name with extension (string)(readonly). // @class field // @name File.name // @within Attributes "name", sol::readonly_property ([](File& self) { return self.getFileName().toStdString(); }), /// Absolute file path (string)(readonly). // @class field // @name File.path // @within Attributes "path", sol::readonly_property ([](File& self) { return self.getFullPathName().toStdString(); }) ); auto M = t.get<sol::table> (LKV_TYPE_NAME_FILE); t.clear(); sol::stack::push (L, M); return 1; }
1,568
494
/* * * Copyright (C) 2002-2013, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmdata * * Author: Joerg Riesmeier * * Purpose: test program for classes DcmDate, DcmTime and DcmDateTime * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/ofstd/oftest.h" #include "dcmtk/dcmdata/dcvrda.h" #include "dcmtk/dcmdata/dcvrtm.h" #include "dcmtk/dcmdata/dcvrdt.h" #include "dcmtk/dcmdata/dcdeftag.h" #define CHECK_EQUAL(string) do { \ strstream << OFStringStream_ends; \ OFSTRINGSTREAM_GETOFSTRING(strstream, res); \ OFCHECK_EQUAL(res, string); \ strstream.clear(); \ strstream.str(""); \ } while (0) #define CHECK_STREAM_EQUAL(val, string) do { \ strstream << val; \ CHECK_EQUAL(string); \ strstream.clear(); \ strstream.str(""); \ } while(0) OFTEST(dcmdata_dateTime) { double timeZone; OFDate dateVal; OFTime timeVal; OFDateTime dateTime; OFString string; DcmDate dcmDate(DCM_StudyDate); DcmTime dcmTime(DCM_StudyTime); DcmDateTime dcmDateTime(DCM_DateTime); OFOStringStream strstream; // Determine the local time zone, needed because setOFTime loses the timezone timeVal.setCurrentTime(); const double localTimeZone = timeVal.getTimeZone(); OFDate curDateVal(2011, 5, 9); OFTime curTimeVal(10, 35, 20, localTimeZone); OFDateTime curDateTimeVal(curDateVal, curTimeVal); dcmDate.setOFDate(curDateVal); dcmDate.print(strstream); CHECK_EQUAL("(0008,0020) DA [20110509] # 8, 1 StudyDate\n"); OFCHECK(dcmDate.getOFDate(dateVal).good()); OFCHECK_EQUAL(dateVal, curDateVal); dcmTime.setOFTime(curTimeVal); dcmTime.print(strstream); CHECK_EQUAL("(0008,0030) TM [103520] # 6, 1 StudyTime\n"); OFCHECK(dcmTime.getOFTime(timeVal).good()); OFCHECK_EQUAL(timeVal, curTimeVal); dcmDateTime.setOFDateTime(curDateTimeVal); dcmDateTime.print(strstream); CHECK_EQUAL("(0040,a120) DT [20110509103520] # 14, 1 DateTime\n"); OFCHECK(dcmDateTime.getOFDateTime(dateTime).good()); OFCHECK_EQUAL(dateTime, curDateTimeVal); OFCHECK(dateTime.getISOFormattedDateTime(string, OFTrue /*seconds*/, OFTrue /*fraction*/, OFFalse /*timeZone*/, OFFalse /*delimiter*/)); OFCHECK_EQUAL(string, "20110509103520.000000"); dcmTime.putString("12"); dcmTime.print(strstream); CHECK_EQUAL("(0008,0030) TM [12] # 2, 1 StudyTime\n"); OFCHECK(dcmTime.getOFTime(timeVal).good()); CHECK_STREAM_EQUAL(timeVal, "12:00:00"); dcmTime.putString("1203"); dcmTime.print(strstream); CHECK_EQUAL("(0008,0030) TM [1203] # 4, 1 StudyTime\n"); OFCHECK(dcmTime.getOFTime(timeVal).good()); CHECK_STREAM_EQUAL(timeVal, "12:03:00"); dcmTime.putString("120315"); dcmTime.print(strstream); CHECK_EQUAL("(0008,0030) TM [120315] # 6, 1 StudyTime\n"); OFCHECK(dcmTime.getOFTime(timeVal).good()); CHECK_STREAM_EQUAL(timeVal, "12:03:15"); dcmTime.putString("120301.99"); dcmTime.print(strstream); CHECK_EQUAL("(0008,0030) TM [120301.99] # 10, 1 StudyTime\n"); OFCHECK(dcmTime.getOFTime(timeVal).good()); timeVal.getISOFormattedTime(string, OFTrue /*seconds*/, OFTrue /*fraction*/, OFFalse /*timeZone*/); OFCHECK_EQUAL(string, "12:03:01.990000"); dcmTime.putString("12:03"); dcmTime.print(strstream); CHECK_EQUAL("(0008,0030) TM [12:03] # 6, 1 StudyTime\n"); OFCHECK(dcmTime.getOFTime(timeVal).good()); CHECK_STREAM_EQUAL(timeVal, "12:03:00"); dcmTime.putString("12:03:15"); dcmTime.print(strstream); CHECK_EQUAL("(0008,0030) TM [12:03:15] # 8, 1 StudyTime\n"); OFCHECK(dcmTime.getOFTime(timeVal).good()); CHECK_STREAM_EQUAL(timeVal, "12:03:15"); OFCHECK(DcmTime::getTimeZoneFromString("+0030", timeZone).good()); OFCHECK_EQUAL(timeZone, 0.5); OFCHECK(DcmTime::getTimeZoneFromString("+1130", timeZone).good()); OFCHECK_EQUAL(timeZone, 11.5); OFCHECK(DcmTime::getTimeZoneFromString("-0100", timeZone).good()); OFCHECK_EQUAL(timeZone, -1); OFCHECK(DcmTime::getTimeZoneFromString("-0530", timeZone).good()); OFCHECK_EQUAL(timeZone, -5.5); OFCHECK(DcmTime::getTimeZoneFromString("01130", timeZone).bad()); OFCHECK(DcmTime::getTimeZoneFromString("+100", timeZone).bad()); OFCHECK(DcmTime::getTimeZoneFromString("UTC+1", timeZone).bad()); dcmDateTime.putString("200204101203+0500"); dcmDateTime.print(strstream); CHECK_EQUAL("(0040,a120) DT [200204101203+0500] # 18, 1 DateTime\n"); OFCHECK(dcmDateTime.getOFDateTime(dateTime).good()); CHECK_STREAM_EQUAL(dateTime, "2002-04-10 12:03:00"); dcmDateTime.putString("20020410"); dcmDateTime.print(strstream); CHECK_EQUAL("(0040,a120) DT [20020410] # 8, 1 DateTime\n"); OFCHECK(dcmDateTime.getOFDateTime(dateTime).good()); dateTime.getISOFormattedDateTime(string, OFTrue /*seconds*/, OFFalse /*fraction*/, OFFalse /*timeZone*/); OFCHECK_EQUAL(string, "2002-04-10 00:00:00"); }
5,565
2,323
#include<iostream> #include<cstdio> #include<cstring> using namespace std; /** * 利用动态规划思想求解数字三角形(POJ 1163), 题目来源IOI 1994 * 将一个问题分解为子问题递归求解,并且将中间结果保存以避免重复计算的办法 * 1.问题具有最优子结构性质(问题的最优解所包含的子问题的解也是最优的) * 2.无后效性(当前若干个状态值一旦确定,此后过程的演变就只和这若干个状态值有关,与之前采取哪种方式演变到若干个状态无关) * 问题描述:求出累加和最大的最佳路径上的数字之和, * 路径上每一步只能从一个数走到下一层和它最近的左边的数或右边的数。 * @author 作者名 */ #define MAX_NUM 100 int d[MAX_NUM + 10][MAX_NUM + 10];//存放待计算的数字三角形 int N;//存放行数 int maxSum[MAX_NUM + 10][MAX_NUM + 10];//存放当前数字到底边的最佳路径之和 /** * 计算路径和 * @r 数字三角形的行 * @j 数字三角形的列 * @return 从第i行第j列的数字到底边的最佳路径和 */ int MaxSum(int r, int j) { if(r == N) return d[r][j];//底边数字的路径和即为数字本身 if(maxSum[r+1][j] == -1)//如果MaxSum(r+1, j)没有计算过 maxSum[r+1][j] = MaxSum(r+1, j); if(maxSum[r+1][j+1] == -1)//如果MaxSum(r+1, j+1)没有计算过 maxSum[r+1][j+1] = MaxSum(r+1, j+1); if(maxSum[r+1][j] > maxSum[r+1][j+1]) return maxSum[r+1][j] + d[r][j]; return maxSum[r+1][j+1] + d[r][j];//返回当前数字到底边的最佳路径和 } /** * 输入数字三角形 */ int main() { scanf("%d", &N);//输入行数 //将maxSum全部置成-1, 表示开始所有的MaxSum(r, j)都没有计算过 memset(maxSum, -1, sizeof(maxSum)); for(int i = 1; i <= N; i++) for(int j = 1; j <= i; j++) scanf("%d", &d[i][j]);//输入数字三角形 printf("%d", MaxSum(1, 1));//输出最佳路径和 return 0; }
1,225
948
#include<bits/stdc++.h> //#define mx 100010 //#define mod 1000000007 #define pi 2*acos(0.0) //#define ll long long int //#define pp pair<int,int> //#define ull unsigned long long int //#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c //#define mem(arr,val) memset(arr,val,sizeof(arr)) //const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; //const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; //int biton(int p,int pos){return p=p|(1<<pos);} //int bitoff(int p,int pos){return p=p&~(1<<pos);} //bool bitcheck(int p,int pos){return (bool)(p&(1<<pos));} //ll POW(ll b,ll p) {ll Ans=1; while(p){if(p&1)Ans=(Ans*b);b=(b*b);p>>=1;}return Ans;} //ll BigMod(ll b,ll p,ll Mod) {ll Ans=1; while(p){if(p&1)Ans=(Ans*b)%Mod;b=(b*b)%Mod;p>>=1;}return Ans;} //ll ModInverse(ll p,ll Mod) {return BigMod(p,Mod-2,Mod);} using namespace std; double dis(double x1,double y1,double x2,double y2){ return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } int main(){ // freopen("Input.txt","r",stdin); freopen("Output.txt","w",stdout); // ios_base::sync_with_stdio(false); cin.tie(NULL); int t; scanf("%d",&t); for(int cs=1;cs<=t;cs++){ double x1,y1,x2,y2,x3,y3,x4,y4; scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4); double a=dis(x1,y1,x2,y2); double b=dis(x2,y2,x3,y3); double c=dis(x3,y3,x4,y4); double d=dis(x4,y4,x1,y1); double ac=dis(x4,y4,x2,y2); double bd=dis(x1,y1,x3,y3); // double angle_da=(180.0/(1.0*pi))*acos((a*a+d*d-ac*ac)/(2.0*a*d)); // double angle_ab=(180.0/(1.0*pi))*acos((a*a+b*b-bd*bd)/(2.0*a*b)); // double angle_bc=(180.0/(1.0*pi))*acos((b*b+c*c-ac*ac)/(2.0*b*c)); // double angle_cd=(180.0/(1.0*pi))*acos((c*c+d*d-bd*bd)/(2.0*c*d)); // cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl; // cout<<setprecision(5)<<angle_da<<" "<<angle_ab<<" "<<angle_bc<<" "<<angle_cd<<endl; if(a==b&&b==c&&c==d){ printf("Case %d: Square\n",cs); } } return 0; } /** Input: 6 0 0 2 0 2 2 0 2 0 0 3 0 3 2 0 2 0 0 8 4 5 0 3 4 0 0 2 0 3 2 1 2 0 0 5 0 4 3 1 3 0 0 5 0 4 3 1 4 Output: Case 1: Square Case 2: Rectangle Case 3: Rhombus Case 4: Parallelogram Case 5: Trapezium Case 6: Ordinary Quadrilateral **/
2,383
1,248
// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by the GPL v2 license that can // be found in the LICENSE file. // // Driver program for creating verity hash images. #include <stdio.h> #include <stdlib.h> #include <memory> #include <base/files/file.h> #include <base/logging.h> #include <brillo/syslog_logging.h> #include "verity/file_hasher.h" namespace { void print_usage(const char* name) { // We used to advertise more algorithms, but they've never been implemented: // sha512 sha384 sha mdc2 ripemd160 md4 md2 fprintf( stderr, "Usage:\n" " %s <arg>=<value>...\n" "Options:\n" " mode One of 'create' or 'verify'\n" " alg Hash algorithm to use. Only sha256 for now\n" " payload Path to the image to hash\n" " payload_blocks Size of the image, in blocks (4096 bytes)\n" " hashtree Path to a hash tree to create or read from\n" " root_hexdigest Digest of the root node (in hex) for verification\n" " salt Salt (in hex)\n" "\n", name); } typedef enum { VERITY_NONE = 0, VERITY_CREATE, VERITY_VERIFY } verity_mode_t; static unsigned int parse_blocks(const char* block_s) { return (unsigned int)strtoul(block_s, NULL, 0); } } // namespace static int verity_create(const char* alg, const char* image_path, unsigned int image_blocks, const char* hash_path, const char* salt); void splitarg(char* arg, char** key, char** val) { char* sp = NULL; *key = strtok_r(arg, "=", &sp); *val = strtok_r(NULL, "=", &sp); } int main(int argc, char** argv) { verity_mode_t mode = VERITY_CREATE; const char* alg = NULL; const char* payload = NULL; const char* hashtree = NULL; const char* salt = NULL; unsigned int payload_blocks = 0; int i; char *key, *val; for (i = 1; i < argc; i++) { splitarg(argv[i], &key, &val); if (!key) continue; if (!val) { fprintf(stderr, "missing value: %s\n", key); print_usage(argv[0]); return -1; } if (!strcmp(key, "alg")) { alg = val; } else if (!strcmp(key, "payload")) { payload = val; } else if (!strcmp(key, "payload_blocks")) { payload_blocks = parse_blocks(val); } else if (!strcmp(key, "hashtree")) { hashtree = val; } else if (!strcmp(key, "root_hexdigest")) { // Silently drop root_hexdigest for now... } else if (!strcmp(key, "mode")) { // Silently drop the mode for now... } else if (!strcmp(key, "salt")) { salt = val; } else { fprintf(stderr, "bogus key: '%s'\n", key); print_usage(argv[0]); return -1; } } if (!alg || !payload || !hashtree) { fprintf(stderr, "missing data: %s%s%s\n", alg ? "" : "alg ", payload ? "" : "payload ", hashtree ? "" : "hashtree"); print_usage(argv[0]); return -1; } if (mode == VERITY_CREATE) { return verity_create(alg, payload, payload_blocks, hashtree, salt); } else { LOG(FATAL) << "Verification not done yet"; } return -1; } static int verity_create(const char* alg, const char* image_path, unsigned int image_blocks, const char* hash_path, const char* salt) { auto source = std::make_unique<base::File>( base::FilePath(image_path), base::File::FLAG_OPEN | base::File::FLAG_READ); LOG_IF(FATAL, source && !source->IsValid()) << "Failed to open the source file: " << image_path; auto destination = std::make_unique<base::File>( base::FilePath(hash_path), base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); LOG_IF(FATAL, destination && !destination->IsValid()) << "Failed to open destination file: " << hash_path; // Create the actual worker and create the hash image. verity::FileHasher hasher(std::move(source), std::move(destination), image_blocks, alg); LOG_IF(FATAL, !hasher.Initialize()) << "Failed to initialize hasher"; if (salt) hasher.set_salt(salt); LOG_IF(FATAL, !hasher.Hash()) << "Failed to hash hasher"; LOG_IF(FATAL, !hasher.Store()) << "Failed to store hasher"; hasher.PrintTable(true); return 0; }
4,416
1,533
#ifndef MATERIALDESCRIPTION_H #define MATERIALDESCRIPTION_H #include <memory> #include <vector> #include <map> #include <functional> #include <WCESpectralAveraging.hpp> #include "BeamDirection.hpp" // Need to include rather than forward declare to default incoming and outgoing directions to CBeamDirection() #include "BSDFDirections.hpp" // Needed to have CBSDFHemisphere as a member of the BSDF materials. Could forward declare if BSDF material was changed to hide members using the pimpl ideom. namespace FenestrationCommon { enum class Side; enum class Property; enum class MaterialType; enum class WavelengthRange; class CSeries; } // namespace FenestrationCommon namespace SpectralAveraging { // enum class SampleProperty; class CSpectralSample; class CPhotovoltaicSample; class CAngularSpectralSample; class CSingleAngularMeasurement; class CAngularMeasurements; } // namespace SpectralAveraging namespace SingleLayerOptics { class CSurface; struct RMaterialProperties { public: RMaterialProperties(double aTf, double aTb, double aRf, double aRb); double getProperty(FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side) const; private: std::map<FenestrationCommon::Side, std::shared_ptr<CSurface>> m_Surface; }; static double NIRRatio = 0.49; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterial ////////////////////////////////////////////////////////////////////////////////////////// //! \breif Base virtual class for any material definition. //! //! It represents material properties over the certain wavelength range. It also defines //! interface for angular dependency of material properties. class CMaterial { public: CMaterial(double minLambda, double maxLambda); explicit CMaterial(FenestrationCommon::WavelengthRange t_Range); virtual void setSourceData(FenestrationCommon::CSeries &); virtual void setDetectorData(FenestrationCommon::CSeries & t_DetectorData); // Get certain material property over the entire range virtual double getProperty(FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const = 0; // Get properties for every band defined in the material virtual std::vector<double> getBandProperties( FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const = 0; std::vector<RMaterialProperties> getBandProperties(); std::shared_ptr<SpectralAveraging::CSpectralSample> getSpectralSample(); std::vector<double> getBandWavelengths(); virtual void setBandWavelengths(const std::vector<double> & wavelengths); size_t getBandSize(); // Return index of wavelength range for passed value. Returns -1 if index is out of range int getBandIndex(double t_Wavelength); double getMinLambda() const; double getMaxLambda() const; virtual void Flipped(bool flipped); [[nodiscard]] bool isWavelengthInRange(double wavelength) const; protected: double m_MinLambda; double m_MaxLambda; std::vector<double> trimWavelengthToRange(const std::vector<double> & wavelengths) const; // Set state in order not to calculate wavelengths every time virtual std::vector<double> calculateBandWavelengths() = 0; bool m_WavelengthsCalculated; std::vector<double> m_Wavelengths; }; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterialSingleBand ////////////////////////////////////////////////////////////////////////////////////////// //! \brief Simple material with no angular dependence on reflection or transmittance. //! //! This is mainly used for shading device materials class CMaterialSingleBand : public CMaterial { public: CMaterialSingleBand( double t_Tf, double t_Tb, double t_Rf, double t_Rb, double minLambda, double maxLambda); CMaterialSingleBand(double t_Tf, double t_Tb, double t_Rf, double t_Rb, FenestrationCommon::WavelengthRange t_Range); double getProperty(FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; std::vector<double> getBandProperties( FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; private: std::vector<double> calculateBandWavelengths() override; protected: std::map<FenestrationCommon::Side, std::shared_ptr<CSurface>> m_Property; }; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterialSingleBandBSDF ////////////////////////////////////////////////////////////////////////////////////////// //! \brief Simple material with angular dependence on reflection or transmittance. //! //! This is mainly used for shading device materials class CMaterialSingleBandBSDF : public CMaterial { public: CMaterialSingleBandBSDF(std::vector<std::vector<double>> const & t_Tf, std::vector<std::vector<double>> const & t_Tb, std::vector<std::vector<double>> const & t_Rf, std::vector<std::vector<double>> const & t_Rb, CBSDFHemisphere const & t_Hemisphere, double minLambda, double maxLambda); CMaterialSingleBandBSDF(std::vector<std::vector<double>> const & t_Tf, std::vector<std::vector<double>> const & t_Tb, std::vector<std::vector<double>> const & t_Rf, std::vector<std::vector<double>> const & t_Rb, CBSDFHemisphere const & t_Hemisphere, FenestrationCommon::WavelengthRange t_Range); double getProperty(FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; std::vector<double> getBandProperties( FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; std::vector<std::vector<double>> const & getBSDFMatrix(FenestrationCommon::Property const & t_Property, FenestrationCommon::Side const & t_Side) const; CBSDFHemisphere getHemisphere() const; private: std::vector<double> calculateBandWavelengths() override; // Checks to make sure a matrix has the same number of values as the BSDF hemisphere // has directions. Assumption: All the inner vectors have the same number of values // This should probably be somewhere more general, just putting it here for now void validateMatrix(std::vector<std::vector<double>> const & matrix, CBSDFHemisphere const & m_Hemisphere) const; protected: std::map<std::pair<FenestrationCommon::Property, FenestrationCommon::Side>, std::vector<std::vector<double>>> m_Property; CBSDFHemisphere m_Hemisphere; }; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterialDualBand ////////////////////////////////////////////////////////////////////////////////////////// //! \brief Material that for given solar and partial range (visible, uv) will calculate //! equivalent optical properties for the entire range class IMaterialDualBand : public CMaterial { public: // ratio is calculated outside of the class and can be provided here. // TODO: Need to confirm with the team if we actually need this approach // (ratio should be calculated and not quessed) IMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange, const std::shared_ptr<CMaterial> & t_FullRange, double t_Ratio = NIRRatio); // ratio is calculated based on provided solar radiation values IMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange, const std::shared_ptr<CMaterial> & t_FullRange, const FenestrationCommon::CSeries & t_SolarRadiation); void setSourceData(FenestrationCommon::CSeries & t_SourceData) override; void setDetectorData(FenestrationCommon::CSeries & t_DetectorData) override; double getProperty(FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; std::vector<double> getBandProperties( FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; protected: std::vector<double> calculateBandWavelengths() override; // Checks if material is within valid range. Otherwise, algorithm is not valid. void checkIfMaterialWithingSolarRange(const CMaterial & t_Material) const; void createUVRange(); // Creates after UV range and stores data into m_Materials virtual void createNIRRange(const std::shared_ptr<CMaterial> & t_PartialRange, const std::shared_ptr<CMaterial> & t_SolarRange, double t_Fraction) = 0; // Creates all of the required ranges in m_Materials from a ratio void createRangesFromRatio(double t_Ratio); // Creates all of the required ranges in m_Materials from solar radiation void createRangesFromSolarRadiation(const FenestrationCommon::CSeries & t_SolarRadiation); std::vector<double> getWavelengthsFromMaterials() const; // Properties over the rest of range will depend on partial range as well. // We do want to keep correct properties of partial range, but will want to update // properties for other partial ranges that are not provided by the user. // double getModifiedProperty(double t_Range, double t_Solar, double t_Fraction) const; std::shared_ptr<CMaterial> getMaterialFromWavelegth(double wavelength) const; std::shared_ptr<CMaterial> m_MaterialFullRange; std::shared_ptr<CMaterial> m_MaterialPartialRange; std::function<void(void)> m_RangeCreator; std::vector<std::shared_ptr<CMaterial>> m_Materials; }; class CMaterialDualBand : public IMaterialDualBand { public: // ratio is calculated outside of the class and can be provided here. // TODO: Need to confirm with the team if we actually need this approach // (ratio should be calculated and not quessed) CMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange, const std::shared_ptr<CMaterial> & t_FullRange, double t_Ratio = NIRRatio); // ratio is calculated based on provided solar radiation values CMaterialDualBand(const std::shared_ptr<CMaterial> & t_PartialRange, const std::shared_ptr<CMaterial> & t_FullRange, const FenestrationCommon::CSeries & t_SolarRadiation); private: // Creates after UV range and stores data into m_Materials virtual void createNIRRange(const std::shared_ptr<CMaterial> & t_PartialRange, const std::shared_ptr<CMaterial> & t_FullRange, double t_Fraction) override; }; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterialDualBandBSDF ////////////////////////////////////////////////////////////////////////////////////////// //! \brief Material that for given solar and partial range (visible, uv) will calculate //! equivalent optical properties for the entire range. Uses BSDF matrices and results are //! therefore angular dependent. class CMaterialDualBandBSDF : public IMaterialDualBand { public: // ratio is calculated outside of the class and can be provided here. // TODO: Need to confirm with the team if we actually need this approach // (ratio should be calculated and not quessed) CMaterialDualBandBSDF(const std::shared_ptr<CMaterialSingleBandBSDF> & t_PartialRange, const std::shared_ptr<CMaterialSingleBandBSDF> & t_FullRange, double t_Ratio = NIRRatio); // ratio is calculated based on provided solar radiation values CMaterialDualBandBSDF(const std::shared_ptr<CMaterialSingleBandBSDF> & t_PartialRange, const std::shared_ptr<CMaterialSingleBandBSDF> & t_FullRange, const FenestrationCommon::CSeries & t_SolarRadiation); protected: // Creates after UV range and stores data into m_Materials void createNIRRange(const std::shared_ptr<CMaterial> & t_PartialRange, const std::shared_ptr<CMaterial> & t_SolarRange, double t_Fraction) override; }; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterialSample ////////////////////////////////////////////////////////////////////////////////////////// //! /brief Material that contains data measured over the range of wavelengths. //! //! It also provides material properties at certain angle. Assumes that material properties //! at certain angle can be calculated by using coated and uncoated algorithms class CMaterialSample : public CMaterial { public: CMaterialSample( const std::shared_ptr<SpectralAveraging::CSpectralSample> & t_SpectralSample, double t_Thickness, FenestrationCommon::MaterialType t_Type, double minLambda, double maxLambda); CMaterialSample( const std::shared_ptr<SpectralAveraging::CSpectralSample> & t_SpectralSample, double t_Thickness, FenestrationCommon::MaterialType t_Type, FenestrationCommon::WavelengthRange t_Range); void setSourceData(FenestrationCommon::CSeries & t_SourceData) override; void setDetectorData(FenestrationCommon::CSeries & t_DetectorData) override; // In this case sample property is taken. Standard spectral data file contains T, Rf, Rb // that is measured at certain wavelengths. double getProperty(FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; // Get properties at each wavelength and at given incident angle std::vector<double> getBandProperties( FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; void setBandWavelengths(const std::vector<double> & wavelengths) override; void Flipped(bool flipped) override; protected: std::vector<double> calculateBandWavelengths() override; std::shared_ptr<SpectralAveraging::CAngularSpectralSample> m_AngularSample; }; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterialPhotovoltaic ////////////////////////////////////////////////////////////////////////////////////////// class CMaterialPhotovoltaic : public CMaterialSample { public: CMaterialPhotovoltaic( const std::shared_ptr<SpectralAveraging::CPhotovoltaicSample> & t_SpectralSample, double t_Thickness, FenestrationCommon::MaterialType t_Type, double minLambda, double maxLambda); CMaterialPhotovoltaic( const std::shared_ptr<SpectralAveraging::CPhotovoltaicSample> & t_SpectralSample, double t_Thickness, FenestrationCommon::MaterialType t_Type, FenestrationCommon::WavelengthRange t_Range); [[nodiscard]] FenestrationCommon::CSeries jscPrime(FenestrationCommon::Side t_Side) const; private: std::shared_ptr<SpectralAveraging::CPhotovoltaicSample> m_PVSample; }; ////////////////////////////////////////////////////////////////////////////////////////// /// CMaterialMeasured ////////////////////////////////////////////////////////////////////////////////////////// // Material that contains data measured over the range of wavelengths. It also provides material // properties at certain angle. Assumes that material properties at certain angle can be // calculated by using coated and uncoated algorithms class CMaterialMeasured : public CMaterial { public: CMaterialMeasured( const std::shared_ptr<SpectralAveraging::CAngularMeasurements> & t_Measurements, double minLambda, double maxLambda); CMaterialMeasured( const std::shared_ptr<SpectralAveraging::CAngularMeasurements> & t_Measurements, FenestrationCommon::WavelengthRange t_Range); void setSourceData(FenestrationCommon::CSeries & t_SourceData) override; // In this case sample property is taken. Standard spectral data file contains T, Rf, Rb // that is measured at certain wavelengths. double getProperty(FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; // Get properties at each wavelength and at given incident angle std::vector<double> getBandProperties( FenestrationCommon::Property t_Property, FenestrationCommon::Side t_Side, const CBeamDirection & t_IncomingDirection = CBeamDirection(), const CBeamDirection & t_OutgoingDirection = CBeamDirection()) const override; private: std::vector<double> calculateBandWavelengths() override; std::shared_ptr<SpectralAveraging::CAngularMeasurements> m_AngularMeasurements; }; } // namespace SingleLayerOptics #endif
20,346
5,217
#include <bits/stdc++.h> using namespace std; class Solution { public: bool verify(vector<int>& postorder, int left, int right) { if (left >= right) return true; int root = postorder[right]; int index = right-1; while (index >= 0 && postorder[index] > root) { --index; } int mid = index; while (index >= 0) { if (postorder[index] > root) { return false; } else { --index; } } return verify(postorder, left, mid) && verify(postorder, mid + 1, right - 1); } bool verifyPostorder(vector<int>& postorder) { return verify(postorder, 0, postorder.size()-1); } }; int main() { vector<int> postorder{5,4,3,2,1}; Solution solution; cout << solution.verifyPostorder(postorder) << endl; return 0; }
882
276
#include "Game.h" Game::Game() : mWindow(sf::VideoMode(640, 480), "SFML Application") , mPlayer() { mPlayer.setRadius(40.f); mPlayer.setPosition(100.f, 100.f); mPlayer.setFillColor(sf::Color::Cyan); } void Game::run() { while (mWindow.isOpen()) { processEvents(); update(); render(); } } void Game::processEvents() { sf::Event event; while (mWindow.pollEvent(event)) { if (event.type == sf::Event::Closed) { mWindow.close(); } } } void Game::update() { } void Game::render() { mWindow.clear(); mWindow.draw(mPlayer); mWindow.display(); }
596
243
// // cluster.cpp // Functions for triplet clustering and for propagating // the triplet cluster labels to points // // Author: Jens Wilberg, Lukas Aymans, Christoph Dalitz // Date: 2019-04-02 // License: see ../LICENSE // #include <algorithm> #include <cmath> #include <fstream> #include "cluster.h" #include "hclust/fastcluster.h" // compute mean of *a* with size *m* double mean(const double *a, size_t m) { double sum = 0; for (size_t i = 0; i < m; ++i) { sum += a[i]; } return sum / m; } // compute standard deviation of *a* with size *m* double sd(const double *a, size_t m) { double sum = 0, result; double mean_val = mean(a, m); for (size_t k = 0; k < m; ++k) { double tmp = mean_val - a[k]; sum += (tmp * tmp); } result = (1.0 / (m - 1.0)) * sum; return std::sqrt(result); } //------------------------------------------------------------------- // computation of condensed distance matrix. // The distance matrix is computed from the triplets in *triplets* // and saved in *result*. *triplet_metric* is used as distance metric. //------------------------------------------------------------------- void calculate_distance_matrix(const std::vector<triplet> &triplets, const PointCloud &cloud, double *result, ScaleTripletMetric &triplet_metric) { size_t const triplet_size = triplets.size(); size_t k = 0; for (size_t i = 0; i < triplet_size; ++i) { for (size_t j = i + 1; j < triplet_size; j++) { result[k++] = triplet_metric(triplets[i], triplets[j]); } } } //------------------------------------------------------------------- // Computation of the clustering. // The triplets in *triplets* are clustered by the fastcluster algorithm // and the result is returned as cluster_group. *t* is the cut distance // and *triplet_metric* is the distance metric for the triplets. // *opt_verbose* is the verbosity level for debug outputs. the clustering // is returned in *result*. //------------------------------------------------------------------- void compute_hc(const PointCloud &cloud, cluster_group &result, const std::vector<triplet> &triplets, double s, double t, bool tauto, double dmax, bool is_dmax, Linkage method, int opt_verbose) { const size_t triplet_size = triplets.size(); size_t k, cluster_size; hclust_fast_methods link; if (!triplet_size) { // if no triplets are generated return; } // choose linkage method switch (method) { case SINGLE: link = HCLUST_METHOD_SINGLE; break; case COMPLETE: link = HCLUST_METHOD_COMPLETE; break; case AVERAGE: link = HCLUST_METHOD_AVERAGE; break; } double *distance_matrix = new double[(triplet_size * (triplet_size - 1)) / 2]; double *cdists = new double[triplet_size - 1]; int *merge = new int[2 * (triplet_size - 1)], *labels = new int[triplet_size]; ScaleTripletMetric metric(s); calculate_distance_matrix(triplets, cloud, distance_matrix, metric); hclust_fast(triplet_size, distance_matrix, link, merge, cdists); // splitting the dendrogram into clusters if (tauto) { // automatic stopping criterion where cdist is unexpected large for (k = (triplet_size - 1) / 2; k < (triplet_size - 1); ++k) { if ((cdists[k - 1] > 0.0 || cdists[k] > 1.0e-8) && (cdists[k] > cdists[k - 1] + 2 * sd(cdists, k + 1))) { break; } } if (opt_verbose) { double automatic_t; double prev_cdist = (k > 0) ? cdists[k - 1] : 0.0; if (k < (triplet_size - 1)) { automatic_t = (prev_cdist + cdists[k]) / 2.0; } else { automatic_t = cdists[k - 1]; } std::cout << "[Info] optimal cdist threshold: " << automatic_t << std::endl; } } else { // fixed threshold t for (k = 0; k < (triplet_size - 1); ++k) { if (cdists[k] >= t) { break; } } } cluster_size = triplet_size - k; cutree_k(triplet_size, merge, cluster_size, labels); // generate clusters for (size_t i = 0; i < cluster_size; ++i) { cluster_t new_cluster; result.push_back(new_cluster); } for (size_t i = 0; i < triplet_size; ++i) { result[labels[i]].push_back(i); } if (opt_verbose > 1) { // write debug file const char *fname = "debug_cdist.csv"; std::ofstream of(fname); of << std::fixed; // set float style if (of.is_open()) { for (size_t i = 0; i < (triplet_size - 1); ++i) { of << cdists[i] << std::endl; } } else { std::cerr << "[Error] could not write file '" << fname << "'\n"; } of.close(); } // cleanup delete[] distance_matrix; delete[] cdists; delete[] merge; delete[] labels; } //------------------------------------------------------------------- // Remove all clusters in *cl_group* which contains less then *m* // triplets. *cl_group* will be modified. //------------------------------------------------------------------- void cleanup_cluster_group(cluster_group &cl_group, size_t m, int opt_verbose) { size_t old_size = cl_group.size(); cluster_group::iterator it = cl_group.begin(); while (it != cl_group.end()) { if (it->size() < m) { it = cl_group.erase(it); } else { ++it; } } if (opt_verbose > 0) { std::cout << "[Info] in pruning removed clusters: " << old_size - cl_group.size() << std::endl; } } //------------------------------------------------------------------- // Convert the triplet indices ind *cl_group* to point indices. // *triplets* contains all triplets and *cl_group* will be modified. //------------------------------------------------------------------- void cluster_triplets_to_points(const std::vector<triplet> &triplets, cluster_group &cl_group) { for (size_t i = 0; i < cl_group.size(); ++i) { cluster_t point_indices, &current_cluster = cl_group[i]; for (std::vector<size_t>::const_iterator triplet_index = current_cluster.begin(); triplet_index < current_cluster.end(); ++triplet_index) { const triplet &current_triplet = triplets[*triplet_index]; point_indices.push_back(current_triplet.point_index_a); point_indices.push_back(current_triplet.point_index_b); point_indices.push_back(current_triplet.point_index_c); } // sort point-indices and remove duplicates std::sort(point_indices.begin(), point_indices.end()); std::vector<size_t>::iterator new_end = std::unique(point_indices.begin(), point_indices.end()); point_indices.resize(std::distance(point_indices.begin(), new_end)); // replace triplet cluster with point cluster current_cluster = point_indices; } } //------------------------------------------------------------------- // Adds the cluster ids to the points in *cloud* // *cl_group* contains the clusters with the point indices. For every // point the corresponding cluster id is saved. For gnuplot the points // which overlap between multiple clusteres are saved in seperate // clusters in *cl_group* //------------------------------------------------------------------- void add_clusters(PointCloud &cloud, cluster_group &cl_group, bool gnuplot) { for (size_t i = 0; i < cl_group.size(); ++i) { const std::vector<size_t> &current_cluster = cl_group[i]; for (std::vector<size_t>::const_iterator point_index = current_cluster.begin(); point_index != current_cluster.end(); ++point_index) { cloud[*point_index].cluster_ids.insert(i); } } // add point indices to the corresponding cluster/vertex vector. this is for // the gnuplot output if (gnuplot) { std::vector<cluster_t> verticies; for (size_t i = 0; i < cloud.size(); ++i) { const Point &p = cloud[i]; if (p.cluster_ids.size() > 1) { // if the point is in multiple clusters add it to the corresponding // vertex or create one if none exists bool found = false; for (std::vector<cluster_t>::iterator v = verticies.begin(); v != verticies.end(); ++v) { if (cloud[v->at(0)].cluster_ids == p.cluster_ids) { v->push_back(i); found = true; } } if (!found) { cluster_t v; v.push_back(i); verticies.push_back(v); } // remove the point from all other clusters for (std::set<size_t>::iterator it = p.cluster_ids.begin(); it != p.cluster_ids.end(); ++it) { cluster_t &cluster = cl_group[*it]; cluster.erase(std::remove(cluster.begin(), cluster.end(), i), cluster.end()); } } } // extend clusters with verticies cl_group.reserve(cl_group.size() + verticies.size()); cl_group.insert(cl_group.end(), verticies.begin(), verticies.end()); } }
8,965
2,945
// Copyright 2017 John T. Foster // Licensed under the Apache License, Version 2.0 (the "License"); // you may not us // 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 "puffrs.h" #include "puffrs_discretization_factory.h" puffrs::Puffrs::Puffrs( const Teuchos::RCP<const Teuchos::Comm<int> >& kComm, Teuchos::RCP<Teuchos::ParameterList> parameters, Teuchos::RCP<puffrs::Discretization> puffrs_discretization) { const auto kDiscretizationParameters = Teuchos::rcpFromRef(parameters->sublist("discretization", true)); if (puffrs_discretization.is_null()) { puffrs::DiscretizationFactory discretiztaion_factory( kDiscretizationParameters); auto puffrs_discretization = discretiztaion_factory.Create(kComm); } }
1,197
382
#include "Cpp/Warnings.h" INTRA_PUSH_DISABLE_REDUNDANT_WARNINGS #include "Sort.h" #include "Range/Sort.hh" #include "Container/Sequential/Array.h" #include "IO/FormattedWriter.h" #include "Utils/Debug.h" INTRA_PUSH_DISABLE_ALL_WARNINGS #include <algorithm> INTRA_WARNING_POP using namespace Intra; static const short arrayForSortTesting[] = { 2, 4234, -9788, 23, 5, 245, 2, 24, 5, -9890, 2, 5, 4552, 54, 3, -932, 123, 342, 24321, -234 }; void TestSort(IO::FormattedWriter& output) { Array<short> arrUnsorted = arrayForSortTesting; output.PrintLine("Not sorted array: ", arrUnsorted); Array<short> arrStdSort = arrUnsorted; std::sort(arrStdSort.begin(), arrStdSort.end()); output.PrintLine("std::sort'ed array: ", arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrStdSort), arrStdSort); Array<short> arrInsertion = arrUnsorted; Range::InsertionSort(arrInsertion); output.PrintLine("InsertionSort'ed array: ", arrInsertion); INTRA_ASSERT_EQUALS(arrInsertion, arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrInsertion), arrInsertion); Array<short> arrShell = arrUnsorted; Range::ShellSort(arrShell); output.PrintLine("ShellSort'ed array: ", arrShell); INTRA_ASSERT_EQUALS(arrShell, arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrShell), arrShell); Array<short> arrQuick = arrUnsorted; Range::QuickSort(arrQuick); output.PrintLine("QuickSort'ed array: ", arrQuick); INTRA_ASSERT_EQUALS(arrQuick, arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrQuick), arrQuick); Array<short> arrRadix = arrUnsorted; Range::RadixSort(arrRadix.AsRange()); output.PrintLine("RadixSort'ed array: ", arrRadix); INTRA_ASSERT_EQUALS(arrRadix, arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrRadix), arrRadix); Array<short> arrMerge = arrUnsorted; Range::MergeSort(arrMerge); output.PrintLine("MergeSort'ed array: ", arrMerge); INTRA_ASSERT_EQUALS(arrMerge, arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrMerge), arrMerge); Array<short> arrHeap = arrUnsorted; Range::HeapSort(arrHeap); output.PrintLine("HeapSort'ed array: ", arrHeap); INTRA_ASSERT_EQUALS(arrHeap, arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrHeap), arrHeap); Array<short> arrSelection = arrUnsorted; Range::SelectionSort(arrSelection); output.PrintLine("SelectionSort'ed array: ", arrSelection); INTRA_ASSERT_EQUALS(arrSelection, arrStdSort); INTRA_ASSERT1(Range::IsSorted(arrSelection), arrSelection); } INTRA_WARNING_POP
2,416
1,003
#pragma once #ifndef ___WAVEFILE_HPP___ #define ___WAVEFILE_HPP___ #include "pcmwave.hpp" #include <cstdint> #include <fstream> #include <string> // リニアPCM専用 struct PCMWaveFileHeader { std::uint8_t riffID[4]; std::uint32_t size; std::uint8_t waveID[4]; std::uint8_t fmtID[4]; std::uint32_t fmtSize; std::uint16_t format; std::uint16_t channel; std::uint32_t sampleRate; std::uint32_t bytePerSec; std::uint16_t blockSize; std::uint16_t bitPerSample; std::uint8_t dataID[4]; std::uint32_t dataSize; PCMWaveFileHeader(){} PCMWaveFileHeader(int) : riffID{'R', 'I', 'F', 'F'}, waveID{'W', 'A', 'V', 'E'}, fmtID{'f', 'm', 't', ' '}, fmtSize(16), format(1), dataID{'d', 'a', 't', 'a'} {} }; class WaveInFile { private: std::ifstream ifs_; public: WaveInFile(const std::string& filename); ~WaveInFile(){} bool isEOF() const; PCMWave read(); }; class WaveOutFile { private: std::ofstream ofs_; public: WaveOutFile(const std::string& filename); ~WaveOutFile(); void write(const PCMWave& wave); }; #endif
1,148
487
/* * * Copyright 2018 gRPC authors. * * 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 <grpc/support/port_platform.h> #include "src/core/ext/filters/client_channel/server_address.h" namespace grpc_core { // // ServerAddress // ServerAddress::ServerAddress( const grpc_resolved_address& address, grpc_channel_args* args, std::map<const char*, std::unique_ptr<AttributeInterface>> attributes) : address_(address), args_(args), attributes_(std::move(attributes)) {} ServerAddress::ServerAddress( const void* address, size_t address_len, grpc_channel_args* args, std::map<const char*, std::unique_ptr<AttributeInterface>> attributes) : args_(args), attributes_(std::move(attributes)) { memcpy(address_.addr, address, address_len); address_.len = static_cast<socklen_t>(address_len); } namespace { int CompareAttributes( const std::map<const char*, std::unique_ptr<ServerAddress::AttributeInterface>>& attributes1, const std::map<const char*, std::unique_ptr<ServerAddress::AttributeInterface>>& attributes2) { auto it2 = attributes2.begin(); for (auto it1 = attributes1.begin(); it1 != attributes1.end(); ++it1) { // attributes2 has fewer elements than attributes1 if (it2 == attributes2.end()) return -1; // compare keys int retval = strcmp(it1->first, it2->first); if (retval != 0) return retval; // compare values retval = it1->second->Cmp(it2->second.get()); if (retval != 0) return retval; ++it2; } // attributes1 has fewer elements than attributes2 if (it2 != attributes2.end()) return 1; // equal return 0; } } // namespace int ServerAddress::Cmp(const ServerAddress& other) const { if (address_.len > other.address_.len) return 1; if (address_.len < other.address_.len) return -1; int retval = memcmp(address_.addr, other.address_.addr, address_.len); if (retval != 0) return retval; retval = grpc_channel_args_compare(args_, other.args_); if (retval != 0) return retval; return CompareAttributes(attributes_, other.attributes_); } } // namespace grpc_core
2,653
827
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <string> #include <sstream> #include <map> #include <queue> #include <stack> #include <algorithm> #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) using namespace std; typedef long long ll; double dp[101][70][40][30]; int main() { ll N, D; cin >> N >> D; int I = 0, J = 0, K = 0; memset(dp, 0.0, sizeof(dp)); while ( D % 2 == 0 ) { I++; D /= 2; } while ( D % 3 == 0 ) { J++; D /= 3; } while ( D % 5 == 0 ) { K++; D /= 5; } if ( D != 1 ) { cout << "0.0" << endl; return 0; } dp[0][0][0][0] = 1.0; REP(n, N) REP(i, I+1) REP(j, J+1) REP(k, K+1) { double p = dp[n][i][j][k] / 6.0; int i1 = min(i+1, I); int i2 = min(i+2, I); int j1 = min(j+1, J); int k1 = min(k+1, K); dp[n+1][i][j][k] += p; dp[n+1][i1][j][k] += p; dp[n+1][i][j1][k] += p; dp[n+1][i2][j][k] += p; dp[n+1][i][j][k1] += p; dp[n+1][i1][j1][k] += p; } printf("%0.6lf\n", dp[N][I][J][K]); return 0; }
1,091
605
#include <iostream> using namespace std; int main() { int i,j,k; int n; cout<<"Enter the size of the array: "; cin>>n; int arr[n]; cout<<"Enter the elements of the array: "; for(i=0;i<n;i++) { cin>>arr[i]; } int sum; cout<<"Enter the Sum: "; cin>>sum; int ans=0; for(i=0;i<n - 2;i++) { for (int j = i+1; j < n-1; j++) { for (int k = j+1; k < n; k++) { if (arr[i] + arr[j] + arr[k] < sum) { ans++; } } } } cout<<"The number of such pairs is :"<<ans; return 0; }
666
258
/* ** COMPLOT PROJECT ** AUTHOR: ** Zacharie ABIDAT */ #ifndef MENU_HPP_ #define MENU_HPP_ #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <SFML/Graphics/Font.hpp> #include "Button.hpp" #include "Square.hpp" #include <iostream> #include <cstdlib> class Menu { public: Menu(sf::RenderWindow *); ~Menu(); void draw(); void event_clicked(); void event_pressed(); void clicked_settings(); void clicked_menu(); void pressed_settings(); void pressed_menu(); bool get_verif(); void set_verif(bool); protected: private: sf::RenderWindow *app; sf::Texture bg_texture; sf::Sprite bg_sprite; Button *play_button; Button *multi_button; Button *settings_button; Button *exit_button; Button *low_sound_button; Button *high_sound_button; Button *menu_button; std::vector<Square *> list_square; bool settings; bool verif; }; #endif /* !MENU_HPP_ */
1,057
346
// Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license. // See LICENSE.txt in the project root for license information. #pragma once #ifndef DFX_API_CLOUD_MEASUREMENT_STREAM_API_H #define DFX_API_CLOUD_MEASUREMENT_STREAM_API_H #include "dfx/api/CloudAPI_Export.hpp" #include "dfx/api/CloudConfig.hpp" #include "dfx/api/CloudStatus.hpp" #include <condition_variable> #include <cstdint> #include <deque> #include <map> #include <mutex> #include <string> #include <vector> namespace dfx::api { class CloudAPI; /** * @brief MeasurementResult is the message type of result data from the server. */ struct DFXCLOUD_EXPORT MeasurementResult { uint64_t chunkOrder; ///< The Chunk Order std::string faceID; ///< The Face ID std::map<std::string, std::vector<float>> signalData; int64_t frameEndTimestampMS; int64_t timestampMS; }; struct DFXCLOUD_EXPORT MeasurementMetric { float uploadRate; }; struct DFXCLOUD_EXPORT MeasurementWarning { int warningCode; std::string warningMessage; int64_t timestampMS; }; /** * @brief Asynchronous callback signature to receive a Measurement ID. * * Provides the Measurement ID being used from this Measurement instance. */ typedef std::function<void(const std::string& measurementID)> MeasurementIDCallback; /** * @brief Asynchronous callback signature to receive Measurement results. * * Provides the actual measurement results from the server for individual * signals like heart rate, or signal-to-noise ratio. */ typedef std::function<void(const MeasurementResult& result)> MeasurementResultCallback; /** * @brief Asynchronous callback signature to receive Measurement metrics. * * Provides diagnostic information on the connection speed. */ typedef std::function<void(const MeasurementMetric& result)> MeasurementMetricCallback; /** * @brief Asynchronous callback signature to receive Measurement warnings. * * The warning Callback is used on gRPC streams to provide warning notifications when * a signal can't be provided because a criteria has not been met. The connection has not been * terminated and the server will continue to attempt to process but it is advice that would * improve the signals being provided. */ typedef std::function<void(const MeasurementWarning& warning)> MeasurementWarningCallback; /** * @brief Measurement is used to send payload chunks to the DFX Server and get back results. * * The sendChunk operation is used to provide the server with payload chunks which the * server will process and reply with result data. Because of the latency involved in * the network communication, uploading, processing and result return this class has * been designed to work on a background thread and offers two forms of use. * * If you prefer asynchronous results, you can register callbacks of the message * types you are interested in and you will be called immediately when there are * results. The callback itself needs to be thread-safe. If there are any queued * messages, those will be delivered the instant a callback is registered and the * queue will be cleared. * * If you prefer synchronous results, you can poll the Measurement for results * using the getResult (and associated signatures) with an optional timeout. If * you provide no timeout, it will wait until a response is received which might * be when the underlying connection itself dies. */ class DFXCLOUD_EXPORT MeasurementStreamAPI { public: enum class CreateProperty { UserProfileID, DeviceVersion, Notes, Mode, ///< For streaming set Mode="STREAMING" PartnerID, Resolution ///< Resolution=0 averages results (default), Resolution=100 is non-averaged }; /** * @brief MeasurementStreamAPI constructor. */ MeasurementStreamAPI(); /** * @brief Measurement destructor. */ virtual ~MeasurementStreamAPI(); /** * @brief Setup the stream. * * @param config * @param studyID * @return status of operation, CLOUD_OK on SUCCESS */ virtual CloudStatus setupStream(const CloudConfig& config, const std::string& studyID, const std::map<CreateProperty, std::string>& createProperties = {}); /** * @brief Asynchronously send a payload chunk to the server for processing. * * @param config the connection configuration to use when sending the chunk. * @param chunk the payload chunk of bytes obtained from DFX SDK. * @param isLastChunk flag indicating if this is the last chunk for proper measurement completion. * @return status of the measurement connection, CLOUD_OK on SUCCESS */ virtual CloudStatus sendChunk(const CloudConfig& config, const std::vector<uint8_t>& chunk, bool isLastChunk); /** * @brief Waits for the measurement connection to close ensuring that all results * have been properly received. * * In order for the server to properly close the connection when it has completed * processing all the chunks, the last chunk needs to be flagged on the sendChunk * call or this wait for completion may wait a very long time. * * @param config the connection configuration to use when waiting. * @param timeoutMillis the amount of time to wait for completion, zero is wait forever. * @return status of the measurement connection at close, CLOUD_OK on SUCCESS */ virtual CloudStatus waitForCompletion(const CloudConfig& config, int32_t timeoutMillis = 0); /** * @brief cancel will inform the server that the Measurement should be terminated. * * This will notify the server of the intent to cancel but leave all internal * state setup to receive any final messages the server might wish to deliver. * * @param config the connection configuration to use when cancelling. * @return status of operation, CLOUD_OK on SUCCESS */ virtual CloudStatus cancel(const CloudConfig& config); /** * @brief Resets this measurement back so another stream can be setup. * * The current measurement will be cancelled and the state immediately cleared * so any undelivered messages would be lost, but the instance will be * able to perform another setupStream() without having to be entirely * recreated. * * @param config the connection configuration to use when cancelling. * @return status of operation, CLOUD_OK on SUCCESS */ virtual CloudStatus reset(const CloudConfig& config); /** * @brief Register an asynchronous callback for receiving the Measurement ID. * * @param callback the callback to invoke when a Measurement ID is available. * @return status of operation, CLOUD_OK on SUCCESS */ virtual CloudStatus setMeasurementIDCallback(const MeasurementIDCallback& callback); /** * @brief Register an asynchronous callback for receiving results. * * @param callback the callback to invoke when a result is available. * @return status of operation, CLOUD_OK on SUCCESS */ virtual CloudStatus setResultCallback(const MeasurementResultCallback& callback); /** * @brief Register an asynchronous callback for receiving metrics. * * @param callback the callback to invoke when a metric is available. * @return status of operation, CLOUD_OK on SUCCESS */ virtual CloudStatus setMetricCallback(const MeasurementMetricCallback& callback); /** * @brief Register an asynchronous callback for receiving warnings. * * @param callback the callback to invoke when a warning message is available. * @return status of operation, CLOUD_OK on SUCCESS */ virtual CloudStatus setWarningCallback(const MeasurementWarningCallback& callback); /** * @brief Synchronously poll for a Measurement ID until timeout expires or connection * dies. * * @param measurementID the measurement ID if the CloudStatus is CLOUD_OK. * @param timeoutMillis the amount of time to wait for value, zero is wait forever. * @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if * measurement has been terminated. */ virtual CloudStatus getMeasurementID(std::string& measurementID, int32_t timeoutMillis = 0); /** * @brief Synchronously poll for a Measurement Result until timeout expires or * connection dies. * * @param result a measurement result if the CloudStatus is CLOUD_OK. * @param timeoutMillis the amount of time to wait for value, zero is wait forever. * @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if * measurement has been terminated. */ virtual CloudStatus getResult(MeasurementResult& result, int32_t timeoutMillis = 0); /** * @brief Synchronously poll for a Measurement Metric until timeout expires or * connection dies. * * @param result a measurement metric if the CloudStatus is CLOUD_OK. * @param timeoutMillis the amount of time to wait for value, zero is wait forever. * @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if * measurement has been terminated. */ virtual CloudStatus getMetric(MeasurementMetric& metric, int32_t timeoutMillis = 0); /** * @brief Synchronously poll for a Measurement Warning until timeout expires or * connection dies. * * @param result a measurement warning if the CloudStatus is CLOUD_OK. * @param timeoutMillis the amount of time to wait for value, zero is wait forever. * @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error status if * measurement has been terminated. */ virtual CloudStatus getWarning(MeasurementWarning& warning, int32_t timeoutMillis = 0); protected: /** * @brief handleMeasurementID is called by derived implementations when they * receive a measurement ID. * * @param measurementID the measurementID received. * @return status of operation, CLOUD_OK on SUCCESS */ CloudStatus handleMeasurementID(const std::string& measurementID); /** * @brief handleResult is called by derived implementations when they * receive a measurement result. * * @param result the measurement result received. * @return status of operation, CLOUD_OK on SUCCESS */ CloudStatus handleResult(const MeasurementResult& result); /** * @brief handleMetric is called by derived implementations when they * receive a measurement metric. * * @param metric the measurement metric received. * @return status of operation, CLOUD_OK on SUCCESS */ CloudStatus handleMetric(const MeasurementMetric& metric); /** * @brief handleWarning is called by derived implementations when they * receive a measurement warning. * * @param warning the measurement warning received. * @return status of operation, CLOUD_OK on SUCCESS */ CloudStatus handleWarning(const MeasurementWarning& warning); /** * @brief isMeasurementClosed is called by derived implementations when * they are interested if the measurement has been closed. * * @param status of the closed connection, if it is closed. * @return true if the connection has been closed, false if it still active. */ bool isMeasurementClosed(CloudStatus& status); /** * @brief closeMeasurement is called by derived implementations when * they need to ensure the measurement is closed, either the connection * has died or the measurement has processed it's last chunk. * * @param status of the closed connection that the derived implementation would like to use. * @return status of the closed connection that was used. */ CloudStatus closeMeasurement(const CloudStatus& status); private: std::shared_ptr<CloudAPI> cloudAPI; /** * @brief waitForQueuedData is an internal method which holds the implementation for how * all the various message types are handled when a get request is performed. * * @tparam T the message type. * @param condition the condition variable protecting the message type. * @param timeoutMillis the number of milliseconds, or zero for infinite that should be waited. * @param queue the queue for message type holding any queued values. * @param result the value obtained after waiting. * @return CLOUD_OK on success, CLOUD_TIMEOUT on timeout or another error if connection * has been closed. */ template <typename T> CloudStatus waitForQueuedData(std::condition_variable& condition, int32_t timeoutMillis, std::deque<T>& queue, T& result); template <typename T, typename F> CloudStatus setCallbackVariable(F& variableCallback, std::deque<T>& queue, const F& callback); template <typename T, typename F> CloudStatus handle(std::condition_variable& condition, std::deque<T>& queue, const F& callback, const T& result); std::mutex measurementMutex; std::condition_variable cvWaitForCompletion; bool measurementClosed; CloudStatus measurementStatus; MeasurementIDCallback measurementIDCallback; std::condition_variable cvWaitForMeasurementID; std::deque<std::string> measurementIDs; MeasurementResultCallback resultCallback; std::condition_variable cvWaitForResults; std::deque<MeasurementResult> measurementResults; MeasurementMetricCallback metricCallback; std::condition_variable cvWaitForMetrics; std::deque<MeasurementMetric> measurementMetrics; MeasurementWarningCallback warningCallback; std::condition_variable cvWaitForWarnings; std::deque<MeasurementWarning> measurementWarnings; }; } // namespace dfx::api #endif // DFX_API_CLOUD_MEASUREMENT_STREAM_API_H
14,009
3,702
#include <errno.h> #include <signal.h> #include <stdio.h> #include <string.h> #include "v8.h" #include <node.h> using namespace v8; void AddonCompile(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); { String::Utf8Value source(args[0]); FILE* source_file = fopen(*source, "rb"); if (source_file == NULL) { printf("Error loading file"); return; } fseek(source_file, 0, SEEK_END); int size = ftell(source_file); rewind(source_file); char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = static_cast<int>(fread(&chars[i], 1, size - i, source_file)); if (read < 0) { printf("Failed to read %s\n", *source); return; } i += read; } fclose(source_file); Local<String> source_str = String::NewFromUtf8(isolate, chars); const char* v8_flag ="--nolazy --log_code --noharmony_shipping " "--nologfile_per_isolate --serialize_toplevel"; v8::V8::SetFlagsFromString(v8_flag, strlen(v8_flag)); ScriptCompiler::Source script_source(source_str, ScriptOrigin(v8::Undefined(isolate))); ScriptCompiler::CompileUnbound(isolate, &script_source, v8::ScriptCompiler::kProduceCodeCache); if (!script_source.GetCachedData()) { printf("Error executing file"); return; } if (script_source.GetCachedData()->rejected) { printf("Cache rejected"); return; } int length = script_source.GetCachedData()->length; uint8_t* cache = new uint8_t[length]; memcpy(cache, script_source.GetCachedData()->data, length); String::Utf8Value cache_file(args[1]); FILE* fp = fopen(*cache_file, "wb"); fwrite(cache, 1, length, fp); fclose(fp); } Handle<String> success = String::NewFromUtf8(isolate, "compile successfully"); args.GetReturnValue().Set(success); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "addonCompile", AddonCompile); } NODE_MODULE(compile, Init)
2,080
736
#include "BossStateIdle.h" #include "BossBehaviourScript.h" #include "EnemyControllerScript/EnemyControllerScript.h" #include "ComponentAnimation.h" BossStateIdle::BossStateIdle(BossBehaviourScript* AIBoss) { boss = AIBoss; trigger = "Idle"; } BossStateIdle::~BossStateIdle() { } void BossStateIdle::HandleIA() { if (timer > (duration + baseDuration)) { boss->currentState = (BossState*)boss->precast; } } void BossStateIdle::Update() { boss->enemyController->LookAt2D(boss->playerPosition); } void BossStateIdle::Enter() { duration = (std::rand() % 100) / 100.f; boss->anim->SendTriggerToStateMachine(trigger.c_str()); }
639
264
#include<iostream> int main() { char ch{'a'}; std::cout<<ch<<'\n'; std::cout<<static_cast<int>(ch)<<'\n'; std::cout<<ch<<'\n'; std::cout<<static_cast<int>(45)<<'\n'; return 0; }
205
90
#include "Order.h" Order::Order(int id, ORD_TYPE r_Type, REGION r_region, int DST, double MON, int ArrT) { ID = (id > 0 && id < 1000) ? id : 0; //1<ID<999 type = r_Type; Region = r_region; //should we check for the validaity of the distance? and what we will do if it's invalid?! Distance = DST; totalMoney = MON; ArrTime = ArrT; } Order::~Order() { } int Order::GetID() { return ID; } ORD_TYPE Order::GetType() const { return type; } REGION Order::GetRegion() const { return Region; } void Order::SetDistance(int d) { Distance = d>0?d:0; } int Order::GetDistance() const { return Distance; } void Order::SetWaitingTime(int timestep) { WaitingTime = timestep - ArrTime; } int Order::getWaitingTime() const { return WaitingTime; } int Order::getPriority() const { return (ArrTime*Distance/totalMoney); } int Order::getFinishTime() const { return FinishTime; } int Order::getServiceTime() const { return ServTime; } int Order::getArrivalTime() const { return ArrTime; } int Order::CalcTime(int timeStep, int Speed) { ServTime = Distance / Speed; WaitingTime = timeStep - ArrTime; FinishTime = ArrTime + WaitingTime + ServTime; return FinishTime + ServTime; } bool Order::IsWaiting(int TS) { return (TS <= WaitingTime + ArrTime); } double Order::GetMoney() { return totalMoney; }
1,313
520