blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
838dbe78f1e3943ef2d9b67fc4fb31505fc6dfd2
8e09889e156b37d025e96b4d6ab8357bad382042
/source/source_game_baocao/SourceGame/Sound.cpp
10d4c184813499790e4b56e7dcdac2f1fd14c709
[]
no_license
hnqtin/CastleVania
5e6d36189279e5ddc969eb806a3b06718443dcdf
39715eb0cc780abe092b1e9c82fba108fa7b8cd1
refs/heads/master
2020-03-28T11:04:04.651190
2018-08-21T15:35:26
2018-08-21T15:35:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,773
cpp
#include "Sound.h" #if MEMORY_LEAK_DEBUG == 1 #include <vld.h> #endif WAVEFORMATEX Sound::bufferFormat_; DSBUFFERDESC Sound::bufferDescription_; LPDIRECTSOUND8 Sound::audioHandler_; HWND Sound::windowsHandler_; // ----------------------------------------------- // Name: T6_Sound::T6_Sound() // Desc: Get the audio Name and Path, ready to load. // ----------------------------------------------- Sound::Sound(const char* audioPath) { loadAudio(audioPath); } Sound::~Sound(void) { soundBuffer_->Stop(); } // ----------------------------------------------- // Name: T6_Sound::initializeSoundClass() // Desc: Initialize the basic PROPERTIESs for loading audio // ----------------------------------------------- HRESULT Sound::initializeSoundClass(HWND windowsHandler) { windowsHandler_ = windowsHandler; HRESULT result; result = DirectSoundCreate8(0, &audioHandler_, 0); result = result | audioHandler_->SetCooperativeLevel(windowsHandler_, DSSCL_PRIORITY); ZeroMemory(&bufferFormat_, sizeof(WAVEFORMATEX)); ZeroMemory(&bufferDescription_, sizeof(DSBUFFERDESC)); bufferFormat_.wFormatTag = AUDIO_FORMAT_TAG; bufferFormat_.nChannels = AUDIO_NUM_OF_CHANNEL; bufferFormat_.nSamplesPerSec = AUDIO_SAMPLE_SPEED; bufferFormat_.wBitsPerSample = AUDIO_BITS_PER_SAMPLE; bufferFormat_.nBlockAlign = AUDIO_BLOCK_ALIGN(bufferFormat_.wBitsPerSample, bufferFormat_.nChannels); bufferFormat_.nAvgBytesPerSec = AUDIO_AVERAGE_BPS(bufferFormat_.nSamplesPerSec, bufferFormat_.nBlockAlign); bufferDescription_.dwFlags = AUDIO_FLAGS; bufferDescription_.guid3DAlgorithm = AUDIO_GUID; bufferDescription_.dwSize = sizeof(DSBUFFERDESC); return result; } // ----------------------------------------------- // Name: T6_Sound::releaseSoundClass() // Desc: Release the basic PROPERTIES after used (close game). // ----------------------------------------------- HRESULT Sound::releaseSoundClass() { if (audioHandler_ != 0) return audioHandler_->Release(); return S_OK; } // ----------------------------------------------- // Name: T6_Sound::loadAudio() // Desc: Load the Audio stored in audioPath. // ----------------------------------------------- wchar_t* convert(const char* str) { int n = strlen(str); wchar_t*s = new wchar_t[n+1]; for (int i = 0;i < n;i++) s[i] = str[i]; s[n] = 0; return s; } HRESULT Sound::loadAudio(const char* audioPath_) { HRESULT result; CWaveFile audioObject; result = audioObject.Open((char*)audioPath_, 0, 1); if (!FAILED(result)) { bufferDescription_.dwBufferBytes = audioObject.GetSize(); bufferDescription_.lpwfxFormat = audioObject.m_pwfx; result = audioHandler_->CreateSoundBuffer(&bufferDescription_, &soundBuffer_, 0); VOID* pointerToLockedBuffer = 0; DWORD lockedSize = 0; result = result | (soundBuffer_)->Lock(0, AUDIO_BUFFER_SIZE, &pointerToLockedBuffer, &lockedSize, 0, 0, DSBLOCK_ENTIREBUFFER); if (!FAILED(result)) { DWORD readedData = 0; audioObject.ResetFile(); result = audioObject.Read((BYTE*)pointerToLockedBuffer, lockedSize, &readedData); if (!FAILED(result)) { (soundBuffer_)->Unlock(pointerToLockedBuffer, lockedSize, 0, 0); } } } audioObject.Close(); return result; } // ----------------------------------------------- // T6_Sound::play() // Desc: Play loaded audio, may choose loop or no. // ----------------------------------------------- HRESULT Sound::play(bool isLoop, DWORD priority) { return soundBuffer_->Play(0, priority, isLoop & DSBPLAY_LOOPING); } // ----------------------------------------------- // T6_Sound:stop() // Desc: Stop the audio if it is playing. // ----------------------------------------------- HRESULT Sound::stop() { HRESULT result = soundBuffer_->Stop(); soundBuffer_->SetCurrentPosition(0); return result; }
[ "thangdang96@ea7db802-35ff-44dd-bbf9-911a299f04d8" ]
thangdang96@ea7db802-35ff-44dd-bbf9-911a299f04d8
c42dd04555194bcc627b95c5d1fadc5615ba9f31
499a4f2c530023a39ed7a0d2d6077d570c37e651
/SDK/RoCo_CinematicCamera_structs.hpp
f1259d44f4d6410b120cdacd52a7e253d05c73ad
[]
no_license
zH4x/RoCo-SDK
e552653bb513b579ab0b1ea62343365db476f998
6019053276aecca48b75edd58171876570fc6342
refs/heads/master
2023-05-06T20:57:27.585479
2021-05-23T06:44:59
2021-05-23T06:44:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,326
hpp
#pragma once // Rogue Company (0.59) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "RoCo_Basic.hpp" #include "RoCo_CinematicCamera_enums.hpp" #include "RoCo_Engine_classes.hpp" #include "RoCo_CoreUObject_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Script Structs //--------------------------------------------------------------------------- // ScriptStruct CinematicCamera.CameraLookatTrackingSettings // 0x0050 struct FCameraLookatTrackingSettings { unsigned char bEnableLookAtTracking : 1; // 0x0000(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char bDrawDebugLookAtTrackingPosition : 1; // 0x0000(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_Transient, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData00[0x3]; // 0x0001(0x0003) MISSED OFFSET float LookAtTrackingInterpSpeed; // 0x0004(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData01[0x10]; // 0x0008(0x0010) MISSED OFFSET TSoftObjectPtr<class AActor> ActorToTrack; // 0x0018(0x0028) (CPF_Edit, CPF_BlueprintVisible, CPF_Interp, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) struct FVector RelativeOffset; // 0x0040(0x000C) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char bAllowRoll : 1; // 0x004C(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData02[0x3]; // 0x004D(0x0003) MISSED OFFSET }; // ScriptStruct CinematicCamera.CameraFilmbackSettings // 0x000C struct FCameraFilmbackSettings { float SensorWidth; // 0x0000(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) float SensorHeight; // 0x0004(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) float SensorAspectRatio; // 0x0008(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_BlueprintReadOnly, CPF_ZeroConstructor, CPF_EditConst, CPF_IsPlainOldData, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) }; // ScriptStruct CinematicCamera.CameraLensSettings // 0x0018 struct FCameraLensSettings { float MinFocalLength; // 0x0000(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) float MaxFocalLength; // 0x0004(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) float MinFStop; // 0x0008(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) float MaxFStop; // 0x000C(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) float MinimumFocusDistance; // 0x0010(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) int DiaphragmBladeCount; // 0x0014(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) }; // ScriptStruct CinematicCamera.CameraTrackingFocusSettings // 0x0038 struct FCameraTrackingFocusSettings { TSoftObjectPtr<class AActor> ActorToTrack; // 0x0000(0x0028) (CPF_Edit, CPF_BlueprintVisible, CPF_Interp, CPF_UObjectWrapper, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) struct FVector RelativeOffset; // 0x0028(0x000C) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char bDrawDebugTrackingFocusPoint : 1; // 0x0034(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_Transient, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData00[0x3]; // 0x0035(0x0003) MISSED OFFSET }; // ScriptStruct CinematicCamera.CameraFocusSettings // 0x0058 struct FCameraFocusSettings { ECameraFocusMethod FocusMethod; // 0x0000(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData00[0x3]; // 0x0001(0x0003) MISSED OFFSET float ManualFocusDistance; // 0x0004(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) struct FCameraTrackingFocusSettings TrackingFocusSettings; // 0x0008(0x0038) (CPF_Edit, CPF_BlueprintVisible, CPF_NativeAccessSpecifierPublic) unsigned char bDrawDebugFocusPlane : 1; // 0x0040(0x0001) (CPF_Edit, CPF_Transient, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData01[0x3]; // 0x0041(0x0003) MISSED OFFSET struct FColor DebugFocusPlaneColor; // 0x0044(0x0004) (CPF_Edit, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char bSmoothFocusChanges : 1; // 0x0048(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData02[0x3]; // 0x0049(0x0003) MISSED OFFSET float FocusSmoothingInterpSpeed; // 0x004C(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) float FocusOffset; // 0x0050(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_Interp, CPF_NoDestructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData03[0x4]; // 0x0054(0x0004) MISSED OFFSET }; // ScriptStruct CinematicCamera.NamedFilmbackPreset // 0x0020 struct FNamedFilmbackPreset { struct FString Name; // 0x0000(0x0010) (CPF_ZeroConstructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) struct FCameraFilmbackSettings FilmbackSettings; // 0x0010(0x000C) (CPF_NoDestructor, CPF_NativeAccessSpecifierPublic) unsigned char UnknownData00[0x4]; // 0x001C(0x0004) MISSED OFFSET }; // ScriptStruct CinematicCamera.NamedLensPreset // 0x0028 struct FNamedLensPreset { struct FString Name; // 0x0000(0x0010) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_HasGetValueTypeHash, CPF_NativeAccessSpecifierPublic) struct FCameraLensSettings LensSettings; // 0x0010(0x0018) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData, CPF_NoDestructor, CPF_NativeAccessSpecifierPublic) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
3233a689f641bca304706af614c07ffbac535dd3
539c347f5c04ee50cfb5626f6e78f75026fe6be8
/AbstractFactory/AbstractFactory/MarinaraSauce.h
1d5d48ef4e5411f85215d2adc8887d3889ab5008
[]
no_license
fanghao6666/HeadFirstDesignPattenC-
46e8a34578df26568af87082760e2efa1f01d858
048311f2590d106ca88d28614576295b3aaa57df
refs/heads/master
2020-07-29T19:46:59.794218
2019-09-26T10:39:48
2019-09-26T10:39:48
209,937,452
0
1
null
null
null
null
UTF-8
C++
false
false
72
h
#pragma once #include "Sauce.h" class MarinaraSauce : public Sauce { };
351a25e3cdba2f63ca36aa1ac1b33a21f449e460
7487baa200db22dea823989ac539a31f4d5d784f
/src/Modules/Module.h
ba5c5b57aa445e4e7729c37f6fdd247ac485cc10
[]
no_license
korbdev/Krybot
ef2bc0c1cb0c076e02f00cf1072d38b88e8b4516
4da696435ba87896802a4e91452ed5c6df965bbd
refs/heads/master
2016-08-10T09:00:56.004546
2015-07-07T01:06:21
2015-07-07T01:06:21
36,465,000
0
0
null
null
null
null
UTF-8
C++
false
false
667
h
/* * Module.h * * Created on: 09.06.2015 * Author: rkorb */ #ifndef MODULE_H_ #define MODULE_H_ #include <string> #include <Communication/Message.h> #include <Communication/Connection.h> using namespace std; class Module{ protected: Connection* connection; bool running; thread t; public: Module():connection(0),running(false){} Module(Module& other) = delete; Module& operator=(Module& other) = delete; virtual ~Module(); virtual void processMessage(Message msg) = 0; void start(Connection* connection, int interval); void stop(); void operator()(int interval); bool isRunning() const; string getName() const; }; #endif /* MODULE_H_ */
07deee6abbde629d0944646dde674d15ebe82955
3ab8ea4fafe88677ae9c5c4177b54a5ae5e2fbbf
/双向链表/双向链表/DList.cpp
ae2dc28e93f8df5275cd93745eb4b0238914ab29
[]
no_license
ChunGang5/mygit
aed05fb61798c90edcebf0f6eadf530a1dc58e1f
5dd29a6404cc94ed04806cf00e71962484cc52c4
refs/heads/master
2021-07-18T05:20:53.400038
2020-06-11T14:48:07
2020-06-11T14:48:07
171,126,954
2
0
null
null
null
null
GB18030
C++
false
false
3,257
cpp
#include "DList.h" #include<assert.h> DListNode* BuyDListNode(int val) { DListNode* newNode = (DListNode*)new(DListNode); if (NULL == newNode) { assert(0); return NULL; } newNode->next = NULL; newNode->prev = NULL; newNode->val = val; return newNode; } DListNode* CreatDList() { DListNode* head = BuyDListNode(0); head->next = head; head->prev = head; return head; } void DListNodePushBack(DListNode* pHead, int val) { if (NULL == pHead) { return; } DListNode* newNode = BuyDListNode(val); newNode->prev = pHead->prev; newNode->next = pHead; newNode->prev->next = newNode; pHead->prev = newNode; } void DListNodePopBack(DListNode* pHead) { //检测链表是否不存在 assert(pHead); if (pHead == NULL) { return; } //检测是否是空链表 if (pHead->next == NULL) { return; } DListNode* pop = pHead->prev; pHead->prev = pop->prev; pop->prev->next = pHead; delete pop; } void DListInsert(DListNode* pos, int val) { //将值为val的新节点加入到pos节点之前 DListNode* newNode = BuyDListNode(val); newNode->next = pos; newNode->prev = pos->prev; pos->prev = newNode; newNode->prev->next = newNode; } void DListErass(DListNode* pos) { if (NULL == pos) { return; } pos->prev->next = pos->next; pos->next->prev = pos->prev; delete pos; } void DListPushFront(DListNode* pHead, int val) { if (NULL == pHead) { return; } DListInsert(pHead->next, val); //此链表是带头结点的双向链表 } void DListPopFront(DListNode* pHead) { if (NULL == pHead) { return; } DListErass(pHead->next); } DListNode* DListFind(DListNode* pHead, int val) { if (NULL == pHead) { return NULL; } DListNode* cur = pHead->next; while (cur != pHead) { if (cur->val == val) { return cur; } cur = cur->next; } return NULL; } void DListDestroy(DListNode** pHead) { DListNode* cur = NULL; if (*pHead == NULL) { return; } cur = (*pHead)->next; while (cur != *pHead) { (*pHead)->next = cur->next; delete cur; cur = (*pHead)->next; } delete *pHead; *pHead = NULL; } int main() { DListNode* p1=BuyDListNode(0); DListNode* p2=BuyDListNode(1); DListNode* p3=BuyDListNode(2); p1->next = p2; p1->prev = p3; p2->next = p3; p2->prev = p1; p3->next = p1; p3->prev = p2; DListInsert(p2, 5); /*DListNodePushBack(p1, 3); DListNodePopBack(p1);*/ cout << p1->next->val << endl; cout << p1->next->next->val << endl; cin.get(); return 0; } //5 //5 3 1 4 2 //2 4 5 1 3 //3 //#include<iostream> //#include<vector> //using namespace std; //int main() //{ // // while (1) // { // int num = 0; // cin >> num; // vector<int> arr1(num); // vector<int> arr2(num); // int count = 0; // for (int i = 0; i < num; i++) // { // cin >> arr1[i]; // } // for (int i = 0; i < num; i++) // { // cin >> arr2[i]; // } // for (int i = 0; i < num; i++) // { // for (int j = 0; j < num; j++) // { // if (arr1[i] == arr2[j]) // { // if (j < i) // { // count++; // } // } // } // } // cout << count << endl; // } // return 0; //} //#include<iostream> //#include<vector> //using namespace std; //int main() //{ // int num = 5; // vector<int> arr(5); //for (int i = 0; i < num; i++) // { // cin >> arr[i]; // } // return 0; //}
d78e46a8adf674edf6f182ddf4f50577125c33a6
5c059952f18d77441381e02632c531016b061ba6
/enbsim/config.h
578ec9cc180f941e5d388efb95e2987661b1ec5f
[ "Apache-2.0" ]
permissive
OpenNetworkingFoundation/xranc
24aaa38f4c5cb3cbf13273772616914f657a7e81
4ccd05599332ed65265ec6e8dd2f81a2cd29128f
refs/heads/master
2020-08-04T16:00:25.816598
2020-01-27T23:03:46
2020-01-27T23:03:46
212,194,822
3
3
Apache-2.0
2020-01-27T23:03:47
2019-10-01T20:37:24
C
UTF-8
C++
false
false
1,678
h
/* * Copyright 2017-present Open Networking Foundation * * 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 _CONFIG_H #define _CONFIG_H #include <string> #include <map> using namespace std; struct Cell { string plmn_id; string eci; string ip_addr; }; class Config { public: map<string, Cell> active_cells; unsigned int l2_meas_report_interval_ms; unsigned int rx_signal_meas_report_interval_ms; unsigned int xranc_cellconfigrequest_interval_seconds; string xranc_bind_ip; string xranc_port; bool admission_success; bool bearer_success; unsigned int no_meas_link_removal_ms; unsigned int idle_ue_removal_ms; unsigned int nb_response_timeout_ms; static Config* Instance(); void parse(string config_file); void get_plmn_id(char *ip, uint8_t *plmn_id); void get_eci(char *ip, uint8_t *eci); friend ostream & operator << (ostream &out, const Config &c); private: Config() {}; Config(Config const&) {}; static Config* pInstance; }; void get_plmn_id(char *ip, uint8_t *plmn_id); #endif
c76f87f3cf089f67347eb11a9c9094ffc2095e43
fe34aca1ddeeee075cc6d0b6ba726af9a64c1a16
/trunk/SMVS/StackWalker.h
48ea240ee38c6f26f8e1e52854aff8fee26f6118
[]
no_license
LearnerJason/SMVS
0c558874a27097940101ac6cec928f48e4c765c8
8105b2a8403b01ae467660cd5d6ea27e2ec2e5b2
refs/heads/master
2022-12-05T09:53:40.216127
2020-08-04T03:22:45
2020-08-04T03:22:45
284,647,830
2
0
null
null
null
null
UTF-8
C++
false
false
10,287
h
#ifndef __STACKWALKER_H__ #define __STACKWALKER_H__ #if defined(_MSC_VER) /********************************************************************** * * StackWalker.h * * * * LICENSE (http://www.opensource.org/licenses/bsd-license.php) * * Copyright (c) 2005-2009, Jochen Kalmbach * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Jochen Kalmbach nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * **********************************************************************/ // #pragma once is supported starting with _MSC_VER 1000, // so we need not to check the version (because we only support _MSC_VER >= 1100)! #pragma once #include <windows.h> #if _MSC_VER >= 1900 #pragma warning(disable : 4091) #endif // special defines for VC5/6 (if no actual PSDK is installed): #if _MSC_VER < 1300 typedef unsigned __int64 DWORD64, *PDWORD64; #if defined(_WIN64) typedef unsigned __int64 SIZE_T, *PSIZE_T; #else typedef unsigned long SIZE_T, *PSIZE_T; #endif #endif // _MSC_VER < 1300 class StackWalkerInternal; // forward class StackWalker { public: typedef enum StackWalkOptions { // No addition info will be retrieved // (only the address is available) RetrieveNone = 0, // Try to get the symbol-name RetrieveSymbol = 1, // Try to get the line for this symbol RetrieveLine = 2, // Try to retrieve the module-infos RetrieveModuleInfo = 4, // Also retrieve the version for the DLL/EXE RetrieveFileVersion = 8, // Contains all the above RetrieveVerbose = 0xF, // Generate a "good" symbol-search-path SymBuildPath = 0x10, // Also use the public Microsoft-Symbol-Server SymUseSymSrv = 0x20, // Contains all the above "Sym"-options SymAll = 0x30, // Contains all options (default) OptionsAll = 0x3F } StackWalkOptions; StackWalker(int options = OptionsAll, // 'int' is by design, to combine the enum-flags LPCSTR szSymPath = NULL, DWORD dwProcessId = GetCurrentProcessId(), HANDLE hProcess = GetCurrentProcess()); StackWalker(DWORD dwProcessId, HANDLE hProcess); virtual ~StackWalker(); typedef BOOL(__stdcall* PReadProcessMemoryRoutine)( HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead, LPVOID pUserData // optional data, which was passed in "ShowCallstack" ); BOOL LoadModules(); BOOL ShowCallstack( HANDLE hThread = GetCurrentThread(), const CONTEXT* context = NULL, PReadProcessMemoryRoutine readMemoryFunction = NULL, LPVOID pUserData = NULL // optional to identify some data in the 'readMemoryFunction'-callback ); BOOL ShowObject(LPVOID pObject); #if _MSC_VER >= 1300 // due to some reasons, the "STACKWALK_MAX_NAMELEN" must be declared as "public" // in older compilers in order to use it... starting with VC7 we can declare it as "protected" protected: #endif enum { STACKWALK_MAX_NAMELEN = 1024 }; // max name length for found symbols protected: // Entry for each Callstack-Entry typedef struct CallstackEntry { DWORD64 offset; // if 0, we have no valid entry CHAR name[STACKWALK_MAX_NAMELEN]; CHAR undName[STACKWALK_MAX_NAMELEN]; CHAR undFullName[STACKWALK_MAX_NAMELEN]; DWORD64 offsetFromSmybol; DWORD offsetFromLine; DWORD lineNumber; CHAR lineFileName[STACKWALK_MAX_NAMELEN]; DWORD symType; LPCSTR symTypeString; CHAR moduleName[STACKWALK_MAX_NAMELEN]; DWORD64 baseOfImage; CHAR loadedImageName[STACKWALK_MAX_NAMELEN]; } CallstackEntry; typedef enum CallstackEntryType { firstEntry, nextEntry, lastEntry } CallstackEntryType; virtual void OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName); virtual void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion); virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry& entry); virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr); virtual void OnOutput(LPCSTR szText); StackWalkerInternal* m_sw; HANDLE m_hProcess; DWORD m_dwProcessId; BOOL m_modulesLoaded; LPSTR m_szSymPath; int m_options; int m_MaxRecursionCount; static BOOL __stdcall myReadProcMem(HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead); friend StackWalkerInternal; }; // class StackWalker // The "ugly" assembler-implementation is needed for systems before XP // If you have a new PSDK and you only compile for XP and later, then you can use // the "RtlCaptureContext" // Currently there is no define which determines the PSDK-Version... // So we just use the compiler-version (and assumes that the PSDK is // the one which was installed by the VS-IDE) // INFO: If you want, you can use the RtlCaptureContext if you only target XP and later... // But I currently use it in x64/IA64 environments... //#if defined(_M_IX86) && (_WIN32_WINNT <= 0x0500) && (_MSC_VER < 1400) #if defined(_M_IX86) #ifdef CURRENT_THREAD_VIA_EXCEPTION // TODO: The following is not a "good" implementation, // because the callstack is only valid in the "__except" block... #define GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(c, contextFlags) \ do \ { \ memset(&c, 0, sizeof(CONTEXT)); \ EXCEPTION_POINTERS* pExp = NULL; \ __try \ { \ throw 0; \ } \ __except (((pExp = GetExceptionInformation()) ? EXCEPTION_EXECUTE_HANDLER \ : EXCEPTION_EXECUTE_HANDLER)) \ { \ } \ if (pExp != NULL) \ memcpy(&c, pExp->ContextRecord, sizeof(CONTEXT)); \ c.ContextFlags = contextFlags; \ } while (0); #else // clang-format off // The following should be enough for walking the callstack... #define GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(c, contextFlags) \ do \ { \ memset(&c, 0, sizeof(CONTEXT)); \ c.ContextFlags = contextFlags; \ __asm { \ call x \ x: pop eax \ mov c.Eip, eax \ mov c.Ebp, ebp \ mov c.Esp, esp \ }; \ } while (0); // clang-format on #endif #else // The following is defined for x86 (XP and higher), x64 and IA64: #define GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(c, contextFlags) \ do \ { \ memset(&c, 0, sizeof(CONTEXT)); \ c.ContextFlags = contextFlags; \ RtlCaptureContext(&c); \ } while (0); #endif #endif //defined(_MSC_VER) #endif // __STACKWALKER_H__
c0236c9eddc23f8edd86ffac9374d2cd9b4c1c2d
9ac8e8c2287ab7d634a82fd6a529bfb68a06f3fb
/Ch.19/Sketcher/Elements.cpp
3a2d1efa55f54fdcb602e7158d688431441a8cd4
[]
no_license
ktjones/BVC2010
9fedc88e3fc259258db064fedc434e4be8f8a682
5610c380a624e183cb21718a72a2621971fe6fde
refs/heads/master
2021-01-09T23:42:17.416378
2014-05-01T02:10:03
2014-05-01T02:10:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,917
cpp
// Element.cpp : implementation file // #include "stdafx.h" #include "Sketcher.h" #include "Elements.h" #include <algorithm> #include <cmath> IMPLEMENT_SERIAL(CElement, CObject, VERSION_NUMBER) IMPLEMENT_SERIAL(CLine, CElement, VERSION_NUMBER) IMPLEMENT_SERIAL(CRectangle, CElement, VERSION_NUMBER) IMPLEMENT_SERIAL(CCircle, CElement, VERSION_NUMBER) IMPLEMENT_SERIAL(CCurve, CElement, VERSION_NUMBER) IMPLEMENT_SERIAL(CEllipse, CElement, VERSION_NUMBER) IMPLEMENT_SERIAL(CText, CElement, VERSION_NUMBER) // CElement CElement::CElement() { } CElement::~CElement() { } // CElement member functions // Get the bounding rectangle for an element CRect CElement::GetBoundRect() const { CRect boundingRect(m_EnclosingRect); // Object to store bounding rectangle // Increase the rectangle by the pen width and return it int Offset = m_PenWidth == 0 ? 1 : m_PenWidth; // Width must be at least 1 boundingRect.InflateRect(Offset, Offset); return boundingRect; } void CElement::Serialize(CArchive & ar) { CObject::Serialize(ar); // Call the base class function if (ar.IsStoring()) { ar << m_PenWidth // the pen width << m_Color // Store the color, << m_EnclosingRect; // and the enclosing rectangle } else { ar >> m_PenWidth // the pen width >> m_Color // the color >> m_EnclosingRect; // and the enclosing rectangle } } // CLine CLine::CLine(void) { } // CLine class constructor CLine::CLine(const CPoint & start, const CPoint & end, COLORREF aColor, int aPenStyle, int penWidth) : m_StartPoint(start), m_EndPoint(end) { m_PenWidth = penWidth; // Set pen width m_LineStyle = aPenStyle; m_Color = aColor; // Set line color // Defi ne the enclosing rectangle m_EnclosingRect = CRect(start, end); m_EnclosingRect.NormalizeRect(); } CLine::~CLine(void) { } // Draw a CLine object void CLine::Draw(CDC* pDC, CElement* pElement) { // Create a pen for this object and // initialize it to the object color and line width m_PenWidth CPen aPen; if(!aPen.CreatePen(m_LineStyle, m_PenWidth, this==pElement ? SELECT_COLOR : m_Color)) { // Pen creation failed. Abort the program AfxMessageBox(_T("Pen creation failed drawing a line"), MB_OK); AfxAbort(); } CPen* pOldPen = pDC->SelectObject(& aPen); // Select the pen // Now draw the line pDC->MoveTo(m_StartPoint); pDC->LineTo(m_EndPoint); pDC->SelectObject(pOldPen); // Restore the old pen } void CLine::Move(const CSize & aSize) { m_StartPoint += aSize; // Move the start point m_EndPoint += aSize; // and the end point m_EnclosingRect += aSize; // Move the enclosing rectangle } void CLine::Serialize(CArchive & ar) { CElement::Serialize(ar); // Call the base class function if (ar.IsStoring()) { ar << m_StartPoint // Store the line start point, << m_EndPoint; // and the end point } else { ar >> m_StartPoint // Retrieve the line start point, >> m_EndPoint; // and the end point } } // CRectangle CRectangle::CRectangle(void) { } // CRectangle class constructor CRectangle::CRectangle(const CPoint & start, const CPoint & end, COLORREF aColor, int aPenStyle, int penWidth) { m_Color = aColor; // Set rectangle color m_LineStyle = aPenStyle; m_PenWidth = penWidth; // Set pen width // Define the enclosing rectangle m_EnclosingRect = CRect(start, end); m_EnclosingRect.NormalizeRect(); } CRectangle::~CRectangle(void) { } // Draw a CRectangle object void CRectangle::Draw(CDC* pDC, CElement* pElement) { // Create a pen for this object and // initialize it to the object color and line width of m_PenWidth CPen aPen; if(!aPen.CreatePen(m_LineStyle, m_PenWidth, this==pElement ? SELECT_COLOR : m_Color)) { // Pen creation failed AfxMessageBox(_T("Pen creation failed drawing a rectangle"), MB_OK); AfxAbort(); } // Select the pen CPen* pOldPen = pDC->SelectObject( & aPen); // Select the brush CBrush* pOldBrush=(CBrush*)pDC->SelectStockObject(NULL_BRUSH); // Now draw the rectangle pDC->Rectangle(m_EnclosingRect); pDC->SelectObject(pOldBrush); // Restore the old brush pDC->SelectObject(pOldPen); // Restore the old pen } void CRectangle::Move(const CSize & aSize) { m_EnclosingRect+= aSize; // Move the rectangle } void CRectangle::Serialize(CArchive & ar) { CElement::Serialize(ar); // Call the base class function } // CCircle CCircle::CCircle(void) { } CCircle::CCircle(const CPoint& start, const CPoint& end, COLORREF aColor, int aPenStyle, int penWidth) { // First calculate the radius // We use floating point because that is required by // the library function (in cmath) for calculating a square root. long radius = static_cast <long>(sqrt(static_cast <double>((end.x-start.x)*(end.x-start.x)+(end.y-start.y)*(end.y-start.y)))); // Now calculate the rectangle enclosing // the circle assuming the MM_TEXT mapping mode m_EnclosingRect = CRect(start.x-radius, start.y-radius,start.x+radius, start.y+radius); m_EnclosingRect.NormalizeRect(); // Normalize-in case it's not MM_TEXT m_Color = aColor; // Set the color for the circle m_PenWidth = penWidth; // Set pen width m_LineStyle = aPenStyle; } CCircle::~CCircle(void) { } // Draw a circle void CCircle::Draw(CDC* pDC, CElement* pElement) { // Create a pen for this object and // initialize it to the object color and line width of m_PenWidth CPen aPen; if(!aPen.CreatePen(m_LineStyle, m_PenWidth, this==pElement ? SELECT_COLOR : m_Color)) { // Pen creation failed AfxMessageBox(_T("Pen creation failed drawing a circle"), MB_OK); AfxAbort(); } // Select the pen CPen* pOldPen = pDC-> SelectObject(& aPen); // Select a null brush CBrush* pOldBrush = (CBrush*)pDC->SelectStockObject(NULL_BRUSH); // Now draw the circle pDC->Ellipse(m_EnclosingRect); pDC->SelectObject(pOldPen); // Restore the old pen pDC->SelectObject(pOldBrush); // Restore the old brush } void CCircle::Move(const CSize & aSize) { m_EnclosingRect+= aSize; // Move rectangle defining the circle } void CCircle::Serialize(CArchive & ar) { CElement::Serialize(ar); // Call the base class function } // Curve CCurve::CCurve(void) { } CCurve::CCurve(const CPoint& first, const CPoint& second, COLORREF aColor, int aPenStyle, int penWidth) { // Store the points m_Points.push_back(first); m_Points. push_back(second); m_Color = aColor; m_EnclosingRect = CRect(min(first.x, second.x), min(first.y, second.y),max(first.x, second.x), max(first.y, second.y)); m_PenWidth = penWidth; // Set pen width m_LineStyle = aPenStyle; } CCurve::~CCurve(void) { } // Draw a curve void CCurve::Draw(CDC* pDC, CElement* pElement) { // Create a pen for this object and // initialize it to the object color and line width of m_PenWidth CPen aPen; if(!aPen.CreatePen(m_LineStyle, m_PenWidth, this==pElement ? SELECT_COLOR : m_Color)) { // Pen creation failed AfxMessageBox(_T("Pen creation failed drawing a curve"), MB_OK); AfxAbort(); } // Select the pen CPen* pOldPen = pDC->SelectObject(& aPen); // Now draw the curve pDC->MoveTo(m_Points[0]); for(size_t i=1; i<m_Points.size(); ++i) { pDC->LineTo(m_Points[i]); } pDC->SelectObject(pOldPen); // Restore the old pen } void CCurve::Move(const CSize & aSize) { m_EnclosingRect += aSize; // Move the rectangle // Now move all the points std::for_each(m_Points.begin(), m_Points.end(),[& aSize](CPoint& p){p+=aSize;}); } // Add a segment to the curve void CCurve::AddSegment(const CPoint& point) { m_Points.push_back(point); // Add the point to the end // Modify the enclosing rectangle for the new point m_EnclosingRect=CRect(min(point.x,m_EnclosingRect.left),min(point.y,m_EnclosingRect.top),max(point.x,m_EnclosingRect.right),max(point.y,m_EnclosingRect.bottom)); } void CCurve::Serialize(CArchive & ar) { CElement::Serialize(ar); // Call the base class function // Serialize the vector of points if (ar.IsStoring()) { ar << m_Points.size(); // Store the point count // Now store the points for(size_t i = 0 ; i < m_Points.size() ; ++i) { ar << m_Points[i]; } } else { size_t nPoints(0); // Stores number of points ar >> nPoints; // Retrieve the number of points // Now retrieve the points CPoint point; for(size_t i = 0 ; i < nPoints ; ++i) { ar >> point; m_Points.push_back(point); } } } // CEllipse CEllipse::CEllipse(void) { } CEllipse::CEllipse(const CPoint& center, const CPoint& end, COLORREF aColor, int aPenStyle, int penWidth) { // First calculate the left rect coords (start) // We use floating point because that is required by // the library function (in cmath) for calculating a square root. CPoint start(center); start.Offset(center.x-end.x,center.y-end.y); // Now calculate the rectangle enclosing // the circle assuming the MM_TEXT mapping mode m_EnclosingRect = CRect(start,end); m_EnclosingRect.NormalizeRect(); // Normalize-in case it's not MM_TEXT m_Color = aColor; // Set the color for the circle m_PenWidth = penWidth; // Set pen width m_LineStyle = aPenStyle; } CEllipse::~CEllipse(void) { } // Draw a circle void CEllipse::Draw(CDC* pDC, CElement* pElement) { // Create a pen for this object and // initialize it to the object color and line width of m_PenWidth CPen aPen; if(!aPen.CreatePen(m_LineStyle, m_PenWidth, this==pElement ? SELECT_COLOR : m_Color)) { // Pen creation failed AfxMessageBox(_T("Pen creation failed drawing a circle"), MB_OK); AfxAbort(); } // Select the pen CPen* pOldPen = pDC->SelectObject(& aPen); // Select a null brush CBrush* pOldBrush = (CBrush*)pDC->SelectStockObject(NULL_BRUSH); // Now draw the circle pDC->Ellipse(m_EnclosingRect); pDC->SelectObject(pOldPen); // Restore the old pen pDC->SelectObject(pOldBrush); // Restore the old brush } void CEllipse::Move(const CSize & aSize) { m_EnclosingRect+= aSize; // Move rectangle defining the circle } void CEllipse::Serialize(CArchive & ar) { CElement::Serialize(ar); // Call the base class function } // Draw Text CText::CText(const CString & aString, const CRect & rect, COLORREF aColor) { m_PenWidth = 1; // Set the pen width m_Color = aColor; // Set the color for the text m_String = aString; // Make a copy of the string m_EnclosingRect = rect; m_EnclosingRect.NormalizeRect(); } void CText::Draw(CDC* pDC, CElement* pElement) { COLORREF Color(m_Color); // Initialize with element color if(this==pElement) { Color = SELECT_COLOR; // Set selected color } // Set the text color and output the text pDC-> SetTextColor(Color); pDC-> DrawText(m_String, m_EnclosingRect, DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOCLIP); } void CText::Move(const CSize & size) { m_EnclosingRect += size; // Move the rectangle } void CText::Serialize(CArchive & ar) { CElement::Serialize(ar); // Call the base class function if (ar.IsStoring()) { ar << m_String; // Store the text string } else { ar >> m_String; // Retrieve the text string } }
b2d0766c593d87d6f3a89f691d614a6e7cc4c7bd
3b31bbc1074ba61c115209156413ffdf419cf9f8
/newnnfw/tools/nnapi_quickcheck/tests/gather_1.cpp
0d5b30eb6fa9b4b3e36fb344dffd250526b43957
[ "MIT", "Apache-2.0" ]
permissive
mojunsang26/Tizen-NN-Runtime
caa35a5aa8137fc8dfc376805c92ac333be9c06b
ff50aa626ef101483d03550533ac7110ddca5afc
refs/heads/master
2020-04-09T07:19:22.780932
2019-10-30T02:31:03
2019-10-30T02:31:03
160,150,527
0
0
Apache-2.0
2018-12-03T07:34:44
2018-12-03T07:34:44
null
UTF-8
C++
false
false
4,167
cpp
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. 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 "gtest/gtest.h" #include "support/tflite/kernels/register.h" #include "tensorflow/contrib/lite/model.h" #include "tensorflow/contrib/lite/builtin_op_data.h" #include "env.h" #include "memory.h" #include "util/environment.h" #include "support/tflite/Diff.h" #include "support/tflite/interp/FunctionBuilder.h" #include <chrono> #include <iostream> using namespace tflite; using namespace tflite::ops::builtin; TEST(NNAPI_Quickcheck_gather_1, simple_test) { // Set random seed int SEED = std::chrono::system_clock::now().time_since_epoch().count(); nnfw::util::env::IntAccessor("SEED").access(SEED); // Set random test parameters int verbose = 0; int tolerance = 1; nnfw::util::env::IntAccessor("VERBOSE").access(verbose); nnfw::util::env::IntAccessor("TOLERANCE").access(tolerance); #define INT_VALUE(NAME, VALUE) IntVar NAME##_Value(#NAME, VALUE); #include "gather_1.lst" #undef INT_VALUE const int32_t INPUT_DATA = INPUT_DATA_Value(); const int32_t INDEX_DATA = INDEX_DATA_Value(); const int32_t OUTPUT_DATA = INDEX_DATA; std::cout << "Configurations:" << std::endl; #define PRINT_NEWLINE() \ { \ std::cout << std::endl; \ } #define PRINT_VALUE(value) \ { \ std::cout << " " << #value << ": " << (value) << std::endl; \ } PRINT_VALUE(SEED); PRINT_NEWLINE(); PRINT_VALUE(INPUT_DATA); PRINT_VALUE(INDEX_DATA); PRINT_NEWLINE(); PRINT_VALUE(OUTPUT_DATA); #undef PRINT_VALUE #undef PRINT_NEWLINE auto setup = [&](Interpreter &interp) { // Comment from 'context.h' // // Parameters for asymmetric quantization. Quantized values can be converted // back to float using: // real_value = scale * (quantized_value - zero_point); // // Q: Is this necessary? TfLiteQuantizationParams quantization; quantization.scale = 1; quantization.zero_point = 0; // On AddTensors(N) call, T/F Lite interpreter creates N tensors whose index is [0 ~ N) interp.AddTensors(3); // Configure INPUT_DATA interp.SetTensorParametersReadWrite(0, kTfLiteFloat32 /* type */, "input" /* name */, {INPUT_DATA} /* dims */, quantization); // Configure INDEX_DATA interp.SetTensorParametersReadWrite(1, kTfLiteInt32 /* type */, "index" /* name */, {INDEX_DATA} /* dims */, quantization); // Configure OUTPUT_VALUES interp.SetTensorParametersReadWrite(2, kTfLiteFloat32 /* type */, "output_data" /* name */, {OUTPUT_DATA} /* dims */, quantization); auto *param = reinterpret_cast<TfLiteGatherParams *>(malloc(sizeof(TfLiteGatherParams))); param->axis = 0; // Add GATHER Node // Run GATHER and store its result into Tensor #2 // - Read input data and index_data from Tensor #0 and #1, respectively interp.AddNodeWithParameters({0, 1}, {2}, nullptr, 0, reinterpret_cast<void *>(param), BuiltinOpResolver().FindOp(BuiltinOperator_GATHER, 1)); // Set Tensor #0 and #1 as Input, and Tensor #2 as Output interp.SetInputs({0, 1}); interp.SetOutputs({2}); }; const nnfw::support::tflite::interp::FunctionBuilder builder(setup); RandomTestParam param; param.verbose = verbose; param.tolerance = tolerance; int res = RandomTestRunner{SEED, param}.run(builder); EXPECT_EQ(res, 0); }
257233edcd09adde9ce833694a90de75f27c60ad
b9ddbb0e5e70d5ea428be072f40d9d668f563039
/src/constraint/constraint-equality.cpp
6a8eb459dfdee756c70c36f1ce92d264e7f70c60
[]
no_license
jkw0701/HQP_basic
e3cb191432a1d62adbd39ece670d51b11f515aba
298918c306e48d711e2c54acada25b1d375f58f1
refs/heads/master
2022-11-30T01:28:01.176926
2020-08-04T08:30:01
2020-08-04T08:30:01
284,919,216
2
1
null
null
null
null
UTF-8
C++
false
false
1,862
cpp
#include "constraint/constraint-equality.h" using namespace HQP::constraint; ConstraintEquality::ConstraintEquality(const std::string & name) : ConstraintBase(name) {} ConstraintEquality::ConstraintEquality(const std::string & name, const unsigned int rows, const unsigned int cols) : ConstraintBase(name, rows, cols), m_b(VectorXd::Zero(rows)) {} ConstraintEquality::ConstraintEquality(const std::string & name, Cref_matrixXd A, Cref_vectorXd b) : ConstraintBase(name, A), m_b(b) { assert(A.rows() == b.rows()); } unsigned int ConstraintEquality::rows() const { assert(m_A.rows() == m_b.rows()); return (unsigned int)m_A.rows(); } unsigned int ConstraintEquality::cols() const { return (unsigned int)m_A.cols(); } void ConstraintEquality::resize(const unsigned int r, const unsigned int c) { m_A.setZero(r, c); m_b.setZero(r); } bool ConstraintEquality::isEquality() const { return true; } bool ConstraintEquality::isInequality() const { return false; } bool ConstraintEquality::isBound() const { return false; } const VectorXd & ConstraintEquality::vector() const { return m_b; } const VectorXd & ConstraintEquality::lowerBound() const { assert(false); return m_b; } const VectorXd & ConstraintEquality::upperBound() const { assert(false); return m_b; } VectorXd & ConstraintEquality::vector() { return m_b; } VectorXd & ConstraintEquality::lowerBound() { assert(false); return m_b; } VectorXd & ConstraintEquality::upperBound() { assert(false); return m_b; } bool ConstraintEquality::setVector(Cref_vectorXd b) { m_b = b; return true; } bool ConstraintEquality::setLowerBound(Cref_vectorXd) { assert(false); return false; } bool ConstraintEquality::setUpperBound(Cref_vectorXd) { assert(false); return false; } bool ConstraintEquality::checkConstraint(Cref_vectorXd x, double tol) const { return (m_A*x - m_b).norm() < tol; }
cb46bc0dc0eae5912153f7b4629927f6ed376fb6
873a38a120108e3c57c97cbd478dc8786adc7199
/Work/Direct3D 11/Code/Source/DXTextRenderer.cpp
34b3624eaabc8dd9cb7a53d593f4bbfbe000da87
[]
no_license
ab316/TrumpSuit
111106b29b3df2075e71de1b11996f92ff50ffb5
bd48d3c0489d66fdab1991aa2baf1ff750452883
refs/heads/master
2020-12-24T13:28:52.586503
2015-07-25T01:31:30
2015-07-25T01:31:30
39,667,523
0
0
null
null
null
null
UTF-8
C++
false
false
7,617
cpp
#include "DXStdafx.h" #include "DXTexture.h" #include "DX3DDriver.h" #include "DXGraphicsDriver.h" #include "DXBitmapFontFile.h" #include "DXSprite.h" #include "DXTextRenderer.h" namespace DXFramework { // DXFramework namespace begin CDXTextRenderer::CDXTextRenderer() : m_p3dDriver(nullptr), m_pBitmapFontGlyphData(nullptr), m_pSprite(nullptr), m_pTexCurrentFont(nullptr), m_pTexDefaultFont(nullptr), m_pVS(nullptr), m_pPS(nullptr), m_pBSTransparent(nullptr), m_fStartX(0.0f), m_fStartY(0.0f), m_fFontSize(0.0f), m_fGlyphWidth(0.0f), m_fGlyphHeight(0.0f), m_fReciprocalBackBufferWidth(1.0f), m_fReciprocalBackBufferHeight(1.0f), m_fTextureWidth(512.0f), m_fTextureHeight(256.0f), m_bStateSaved(false) { //m_fTexErrorX = 1.0f / 1280.0f; //m_fTexErrorY = 1.0f / 1280.0f; m_f4FontColor = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); m_pSprite = new CDXSprite(); } CDXTextRenderer::~CDXTextRenderer() { DX_SAFE_DELETE(m_pSprite); } HRESULT CDXTextRenderer::Startup(CDX3DDriver* p3DDriver, WCHAR* szDefaultFontTexture, WCHAR* szDefaultGlyphDataFile, float fDefaultSizeInPixel) { HRESULT hr = S_OK; #define DX_ERROR_DEFAULTFONTTEXTURE_FAIL L"ERROR!!! Unable to create default font texture." #define DX_ERROR_DEFAULTFONTGLYPHFILE_FAIL L"ERROR!!! Unable to create default font glyph data." #define DX_ERROR_DEFAULTFONTVB_FAIL L"ERROR!!! Unable to create default text vertex buffer." #define DX_ERROR_SPRITE_FAIL L"ERROR!!! Unable to create sprite." m_p3dDriver = p3DDriver; m_fFontSize = fDefaultSizeInPixel; CDXGraphicsDriver* pGraphics = CDXGraphicsDriver::GetInstance(); ///////////////////////// DEFAULT FONT TEXTURE /////////////////////////////// // Create a texture for the default font. DXTexture2DDesc descTex; ZeroMemory(&descTex, sizeof(descTex)); descTex.bFileTexture = true; descTex.bindFlags = DX_BIND_SHADER_RESOURCE; descTex.gpuUsage = DX_GPU_READ_ONLY; wcscpy_s(descTex.textureData.szFileName, DX_MAX_FILE_NAME, szDefaultFontTexture); DX_V(pGraphics->CreateAndRecreateResource(DX_RESOURCE_TYPE_TEXTURE, &descTex, (IDXResource**)&m_pTexDefaultFont)); if (FAILED(hr)) { DX_DEBUG_OUTPUT0(DX_ERROR_DEFAULTFONTTEXTURE_FAIL); return hr; } DX_RESOURCE_SET_DEBUG_NAME(m_pTexDefaultFont, "DEFAULT FONT"); m_pTexCurrentFont = m_pTexDefaultFont; /////////////////////////////////////////////////////////////////////////////// m_pBitmapFontGlyphData = new CDXBitmapFontFile(); DX_V(m_pBitmapFontGlyphData->LoadFont(szDefaultGlyphDataFile)); if (FAILED(hr)) { DX_DEBUG_OUTPUT0(DX_ERROR_DEFAULTFONTGLYPHFILE_FAIL); return hr; } m_pGlyphData = (DXBitmapFontGlyphData*)m_pBitmapFontGlyphData->GetGlyphData(); //////////////////////////////// SPRITE /////////////////////////////////////// DX_V(m_pSprite->Create(L"TEXT RENDERER", pGraphics->GetQuadVertexShader(), DX_MAX_TEXT_VERTICES)); if (FAILED(hr)) { DX_DEBUG_OUTPUT0(DX_ERROR_SPRITE_FAIL); return hr; } m_pSprite->SetInputRectCoordMode(false); /////////////////////////////////////////////////////////////////////////////// m_pBSTransparent = pGraphics->GetTransparentBlend(); m_pVS = pGraphics->GetQuadVertexShader(); m_pPS = pGraphics->GetQuadPixelShader(); return hr; } void CDXTextRenderer::Shutdown() { DX_SAFE_RELEASE(m_pTexDefaultFont); DX_SAFE_DELETE(m_pBitmapFontGlyphData); if (m_pSprite) { m_pSprite->Destroy(); } } void CDXTextRenderer::OnBackBufferResize(float fBackBufferWidth, float fBackBufferHeight) { m_fReciprocalBackBufferWidth = 1.0f / fBackBufferWidth; m_fReciprocalBackBufferHeight = 1.0f / fBackBufferHeight; m_pSprite->OnBackBufferResize(fBackBufferWidth, fBackBufferHeight); // Just to update the glyph dimensions. SetFontSize(m_fFontSize); } void CDXTextRenderer::BeginText(float fStartX, float fStartY, bool bInPixels, bool bSaveState) { static CDXGraphicsDriver* pGraphics = CDXGraphicsDriver::GetInstance(); m_bStateSaved = bSaveState; if (bSaveState) { m_pTexTemp = m_p3dDriver->GetPSTexture(0); m_pBSTemp = m_p3dDriver->GetBlendState(); m_pVSTemp = m_p3dDriver->GetVertexShader(); m_pPSTemp = m_p3dDriver->GetPixelShader(); } m_p3dDriver->SetPSTextures(0, 1, &m_pTexCurrentFont); m_p3dDriver->SetBlendState(m_pBSTransparent, nullptr); m_p3dDriver->SetVertexShader(m_pVS); m_p3dDriver->SetPixelShader(m_pPS); if (bInPixels) { NormalizedScreenSpaceToProjectionSpace(fStartX*m_fReciprocalBackBufferWidth, fStartY*m_fReciprocalBackBufferHeight, &m_fStartX, &m_fStartY); } else { NormalizedScreenSpaceToProjectionSpace(fStartX, fStartY, &m_fStartX, &m_fStartY); } m_pSprite->BeginBatchRendering(); } void CDXTextRenderer::EndText() { m_pSprite->EndBatchRendering(); if (m_bStateSaved) { m_p3dDriver->SetBlendState(m_pBSTemp, nullptr); m_p3dDriver->SetPSTextures(0, 1, &m_pTexTemp); m_p3dDriver->SetVertexShader(m_pVSTemp); m_p3dDriver->SetPixelShader(m_pPSTemp); m_bStateSaved = false; } } void CDXTextRenderer::RenderTextProjectionSpace(LPCWSTR szText, float fX, float fY, float fDepth) { int iNumVertices = 0; int iStringLength = (int)wcslen(szText); float fStartX = fX; float fStartY = fY; int i; int iRenderableChars = 0; for (i=0; i<iStringLength; i++) { if (szText[i] > ' ' && szText[i] <= '~') { ++iRenderableChars; } } for (i=0; i<iStringLength; i++) { // If the number of vertices are going to be more than the vertex buffer's // size, then we break the loop and render what has already been filled. if (iNumVertices+6 > DX_MAX_TEXT_VERTICES) { break; } if (szText[i] == '\n') { fStartX = fX; fStartY -= m_fGlyphHeight; continue; } DXBitmapFontGlyphData* pGlyph = &m_pGlyphData[szText[i]]; float xFactor = m_fTextureWidth * m_fGlyphWidth / 48.0f; float yFactor = m_fTextureHeight * m_fGlyphHeight / 48.0f; float offsetX = pGlyph->fOffsetX * xFactor; float offsetY = pGlyph->fOffsetY * yFactor; float width = (pGlyph->rectTex.fRight - pGlyph->rectTex.fLeft) * xFactor; float height = (pGlyph->rectTex.fBottom - pGlyph->rectTex.fTop) * yFactor; float fX1 = fStartX + offsetX; float fX2 = fX1 + width; float fY1 = fStartY - offsetY; float fY2 = fY1 - height; DXRect rect(fX1, fY1, fX2, fY2); DXRect rectTex(pGlyph->rectTex.fLeft, pGlyph->rectTex.fTop, pGlyph->rectTex.fRight, pGlyph->rectTex.fBottom); m_pSprite->BatchRenderSprite(&rect, &rectTex, &m_f4FontColor, fDepth); iNumVertices += 6; fStartX += pGlyph->fAdvanceX * xFactor; } // If there are still more characters to process, then pass the remaining // to a recursive call to this method. if (iNumVertices < iRenderableChars * 6) { RenderTextProjectionSpace( &(szText[i]), fStartX, fStartY, fDepth); } } void CDXTextRenderer::GetTextMetrics(LPCWSTR szText, float fFontSize, UINT uiInLength, float* pfOffsetsInPixels) { float fStartX = 0.0f; float xFactor = m_fTextureWidth * 2 * fFontSize * m_fReciprocalBackBufferWidth / 48.0f; for (UINT i=0; i<uiInLength; i++) { DXBitmapFontGlyphData* pGlyph = &m_pGlyphData[szText[i]]; float offsetX = pGlyph->fOffsetX * xFactor; float width = (pGlyph->rectTex.fRight - pGlyph->rectTex.fLeft) * xFactor; fStartX += pGlyph->fAdvanceX * xFactor; pfOffsetsInPixels[i] = fStartX; } } } // DXFramework namespace end
4003049faa16098a8363e4045de9e3302afbf00e
6702a19fb2dded0e8cfa09870b20d86259b085d2
/SDKs/NoesisGUI/Include/NsGui/Underline.h
09bb961191f0e4211a1a8bfb58baf9552ff6c86e
[]
no_license
whztt07/IceCrystal
e1096f31b1032170b04c1af64c89109b555b94d0
288e18d179d0968327e29791462834f1ce9134e6
refs/heads/master
2023-08-31T15:02:01.193081
2021-10-06T12:17:44
2021-10-06T12:17:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
993
h
//////////////////////////////////////////////////////////////////////////////////////////////////// // NoesisGUI - http://www.noesisengine.com // Copyright (c) Noesis Technologies S.L. All Rights Reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __GUI_UNDERLINE_H__ #define __GUI_UNDERLINE_H__ #include <NsCore/Noesis.h> #include <NsGui/Span.h> #include <NsCore/ReflectionDeclare.h> namespace Noesis { //////////////////////////////////////////////////////////////////////////////////////////////////// /// An inline-level flow content element which causes content to render with an underlined text /// decoration. //////////////////////////////////////////////////////////////////////////////////////////////////// class NS_GUI_CORE_API Underline: public Span { public: Underline(); Underline(Inline* childInline); NS_DECLARE_REFLECTION(Underline, Span) }; } #endif
08e6d0189f6ff9f1910095d62da33d2dfb7ddd07
80f52a93aa300f0b7180ace7e42796232a80f235
/thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_metadata.cpp
408039db827dca5c675a7710892e8ae5fdbb6d3c
[ "Apache-2.0" ]
permissive
joway/fbthrift
b23b3299797cabf3e7f2367ce57f846f3257f170
e0d568ec7084502c653537a50f150428786d8037
refs/heads/master
2023-06-28T05:57:17.911824
2020-11-15T09:42:29
2020-11-15T09:43:48
313,297,638
0
0
Apache-2.0
2020-11-16T12:50:25
2020-11-16T12:39:03
null
UTF-8
C++
false
false
38,132
cpp
/** * Autogenerated by Thrift for src/module.thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include <thrift/lib/cpp2/gen/module_metadata_cpp.h> #include "thrift/compiler/test/fixtures/complex-struct/gen-cpp2/module_metadata.h" namespace apache { namespace thrift { namespace detail { namespace md { using ThriftMetadata = ::apache::thrift::metadata::ThriftMetadata; using ThriftPrimitiveType = ::apache::thrift::metadata::ThriftPrimitiveType; using ThriftType = ::apache::thrift::metadata::ThriftType; using ThriftService = ::apache::thrift::metadata::ThriftService; using ThriftServiceContext = ::apache::thrift::metadata::ThriftServiceContext; using ThriftFunctionGenerator = void (*)(ThriftMetadata&, ThriftService&); void EnumMetadata<::cpp2::MyEnum>::gen(ThriftMetadata& metadata) { auto res = metadata.enums_ref()->emplace("module.MyEnum", ::apache::thrift::metadata::ThriftEnum{}); if (!res.second) { return; } ::apache::thrift::metadata::ThriftEnum& enum_metadata = res.first->second; enum_metadata.name_ref() = "module.MyEnum"; using EnumTraits = TEnumTraits<::cpp2::MyEnum>; for (std::size_t i = 0; i < EnumTraits::size; ++i) { enum_metadata.elements_ref()->emplace(static_cast<int32_t>(EnumTraits::values[i]), EnumTraits::names[i].str()); } } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::MyStructFloatFieldThrowExp>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.MyStructFloatFieldThrowExp", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_MyStructFloatFieldThrowExp = res.first->second; module_MyStructFloatFieldThrowExp.name_ref() = "module.MyStructFloatFieldThrowExp"; module_MyStructFloatFieldThrowExp.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_MyStructFloatFieldThrowExp_fields[] = { std::make_tuple(1, "myLongField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(2, "MyByteField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BYTE_TYPE)), std::make_tuple(3, "myStringField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(4, "myFloatField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_FLOAT_TYPE)), }; for (const auto& f : module_MyStructFloatFieldThrowExp_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_MyStructFloatFieldThrowExp.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::MyStructMapFloatThrowExp>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.MyStructMapFloatThrowExp", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_MyStructMapFloatThrowExp = res.first->second; module_MyStructMapFloatThrowExp.name_ref() = "module.MyStructMapFloatThrowExp"; module_MyStructMapFloatThrowExp.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_MyStructMapFloatThrowExp_fields[] = { std::make_tuple(1, "myLongField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(2, "mapListOfFloats", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<List>(std::make_unique<List>(std::make_unique<Typedef>("module.floatTypedef", std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_FLOAT_TYPE)))))), }; for (const auto& f : module_MyStructMapFloatThrowExp_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_MyStructMapFloatThrowExp.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::MyDataItem>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.MyDataItem", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_MyDataItem = res.first->second; module_MyDataItem.name_ref() = "module.MyDataItem"; module_MyDataItem.is_union_ref() = false; return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::MyStruct>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.MyStruct", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_MyStruct = res.first->second; module_MyStruct.name_ref() = "module.MyStruct"; module_MyStruct.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_MyStruct_fields[] = { std::make_tuple(1, "MyIntField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(2, "MyStringField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(3, "MyDataField", false, std::make_unique<Typedef>("module.MyDataItem", std::make_unique<Struct< ::cpp2::MyDataItem>>("module.MyDataItem"))), std::make_tuple(4, "myEnum", false, std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum")), std::make_tuple(5, "MyBoolField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BOOL_TYPE)), std::make_tuple(6, "MyByteField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BYTE_TYPE)), std::make_tuple(7, "MyShortField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I16_TYPE)), std::make_tuple(8, "MyLongField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(9, "MyDoubleField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE)), std::make_tuple(10, "lDouble", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE))), std::make_tuple(11, "lShort", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I16_TYPE))), std::make_tuple(12, "lInteger", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE))), std::make_tuple(13, "lLong", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE))), std::make_tuple(14, "lString", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(15, "lBool", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BOOL_TYPE))), std::make_tuple(16, "lByte", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BYTE_TYPE))), std::make_tuple(17, "mShortString", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I16_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(18, "mIntegerString", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(19, "mStringMyStruct", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE), std::make_unique<Typedef>("module.MyStruct", std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct")))), std::make_tuple(20, "mStringBool", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BOOL_TYPE))), std::make_tuple(21, "mIntegerInteger", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE))), std::make_tuple(22, "mIntegerBool", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BOOL_TYPE))), std::make_tuple(23, "sShort", false, std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I16_TYPE))), std::make_tuple(24, "sMyStruct", false, std::make_unique<Set>(std::make_unique<Typedef>("module.MyStruct", std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct")))), std::make_tuple(25, "sLong", false, std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE))), std::make_tuple(26, "sString", false, std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(27, "sByte", false, std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BYTE_TYPE))), std::make_tuple(28, "mListList", false, std::make_unique<Map>(std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)))), }; for (const auto& f : module_MyStruct_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_MyStruct.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::SimpleStruct>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.SimpleStruct", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_SimpleStruct = res.first->second; module_SimpleStruct.name_ref() = "module.SimpleStruct"; module_SimpleStruct.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_SimpleStruct_fields[] = { std::make_tuple(1, "age", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(2, "name", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), }; for (const auto& f : module_SimpleStruct_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_SimpleStruct.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::ComplexNestedStruct>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.ComplexNestedStruct", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_ComplexNestedStruct = res.first->second; module_ComplexNestedStruct.name_ref() = "module.ComplexNestedStruct"; module_ComplexNestedStruct.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_ComplexNestedStruct_fields[] = { std::make_tuple(1, "setOfSetOfInt", false, std::make_unique<Set>(std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)))), std::make_tuple(2, "listofListOfListOfListOfEnum", false, std::make_unique<List>(std::make_unique<List>(std::make_unique<List>(std::make_unique<List>(std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum")))))), std::make_tuple(3, "listOfListOfMyStruct", false, std::make_unique<List>(std::make_unique<List>(std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct")))), std::make_tuple(4, "setOfListOfListOfLong", false, std::make_unique<Set>(std::make_unique<List>(std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE))))), std::make_tuple(5, "setOfSetOfsetOfLong", false, std::make_unique<Set>(std::make_unique<Set>(std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE))))), std::make_tuple(6, "mapStructListOfListOfLong", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<List>(std::make_unique<List>(std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct"))))), std::make_tuple(7, "mKeyStructValInt", false, std::make_unique<Map>(std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct"), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE))), std::make_tuple(8, "listOfMapKeyIntValInt", false, std::make_unique<List>(std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)))), std::make_tuple(9, "listOfMapKeyStrValList", false, std::make_unique<List>(std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE), std::make_unique<List>(std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct"))))), std::make_tuple(10, "mapKeySetValLong", false, std::make_unique<Map>(std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE))), std::make_tuple(11, "mapKeyListValLong", false, std::make_unique<Map>(std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE))), std::make_tuple(12, "mapKeyMapValMap", false, std::make_unique<Map>(std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)))), std::make_tuple(13, "mapKeySetValMap", false, std::make_unique<Map>(std::make_unique<Set>(std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE))), std::make_unique<Map>(std::make_unique<List>(std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)))), std::make_tuple(14, "NestedMaps", false, std::make_unique<Map>(std::make_unique<Map>(std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)))), std::make_tuple(15, "mapKeyIntValList", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<List>(std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct")))), std::make_tuple(16, "mapKeyIntValSet", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BOOL_TYPE)))), std::make_tuple(17, "mapKeySetValInt", false, std::make_unique<Map>(std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BOOL_TYPE)), std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum"))), std::make_tuple(18, "mapKeyListValSet", false, std::make_unique<Map>(std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), std::make_unique<Set>(std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))))), }; for (const auto& f : module_ComplexNestedStruct_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_ComplexNestedStruct.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::MyUnion>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.MyUnion", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_MyUnion = res.first->second; module_MyUnion.name_ref() = "module.MyUnion"; module_MyUnion.is_union_ref() = true; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_MyUnion_fields[] = { std::make_tuple(1, "myEnum", false, std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum")), std::make_tuple(2, "myStruct", false, std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct")), std::make_tuple(3, "myDataItem", false, std::make_unique<Struct< ::cpp2::MyDataItem>>("module.MyDataItem")), std::make_tuple(4, "complexNestedStruct", false, std::make_unique<Typedef>("module.ComplexNestedStruct", std::make_unique<Struct< ::cpp2::ComplexNestedStruct>>("module.ComplexNestedStruct"))), std::make_tuple(5, "longValue", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(6, "intValue", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), }; for (const auto& f : module_MyUnion_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_MyUnion.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::defaultStruct>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.defaultStruct", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_defaultStruct = res.first->second; module_defaultStruct.name_ref() = "module.defaultStruct"; module_defaultStruct.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_defaultStruct_fields[] = { std::make_tuple(1, "myLongDFset", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(2, "myLongDF", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(3, "portDFset", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), std::make_tuple(4, "portNum", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), std::make_tuple(5, "myBinaryDFset", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BINARY_TYPE)), std::make_tuple(6, "myBinary", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BINARY_TYPE)), std::make_tuple(7, "myByteDFSet", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BYTE_TYPE)), std::make_tuple(8, "myByte", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BYTE_TYPE)), std::make_tuple(9, "myDoubleDFset", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE)), std::make_tuple(10, "myDoubleDFZero", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE)), std::make_tuple(12, "myDouble", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE)), std::make_tuple(13, "field3", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(14, "myList", false, std::make_unique<List>(std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum"))), std::make_tuple(15, "mySet", false, std::make_unique<Set>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(16, "simpleStruct", false, std::make_unique<Struct< ::cpp2::SimpleStruct>>("module.SimpleStruct")), std::make_tuple(17, "listStructDFset", false, std::make_unique<List>(std::make_unique<Struct< ::cpp2::SimpleStruct>>("module.SimpleStruct"))), std::make_tuple(18, "myUnion", false, std::make_unique<Typedef>("module.MyUnion", std::make_unique<Union< ::cpp2::MyUnion>>("module.MyUnion"))), std::make_tuple(19, "listUnionDFset", false, std::make_unique<List>(std::make_unique<Typedef>("module.MyUnion", std::make_unique<Union< ::cpp2::MyUnion>>("module.MyUnion")))), std::make_tuple(20, "mapNestlistStructDfSet", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<List>(std::make_unique<Struct< ::cpp2::SimpleStruct>>("module.SimpleStruct")))), std::make_tuple(21, "mapJavaTypeDFset", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(22, "emptyMap", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE))), std::make_tuple(23, "enumMapDFset", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE), std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum")))), }; for (const auto& f : module_defaultStruct_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_defaultStruct.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::MyStructTypeDef>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.MyStructTypeDef", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_MyStructTypeDef = res.first->second; module_MyStructTypeDef.name_ref() = "module.MyStructTypeDef"; module_MyStructTypeDef.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_MyStructTypeDef_fields[] = { std::make_tuple(1, "myLongField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE)), std::make_tuple(2, "myLongTypeDef", false, std::make_unique<Typedef>("module.longTypeDef", std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE))), std::make_tuple(3, "myStringField", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(4, "myStringTypedef", false, std::make_unique<Typedef>("module.stringTypedef", std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(5, "myMapField", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I16_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(6, "myMapTypedef", false, std::make_unique<Typedef>("module.mapTypedef", std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I16_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)))), std::make_tuple(7, "myListField", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE))), std::make_tuple(8, "myListTypedef", false, std::make_unique<Typedef>("module.listTypedef", std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE)))), std::make_tuple(9, "myMapListOfTypeDef", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I16_TYPE), std::make_unique<List>(std::make_unique<Typedef>("module.listTypedef", std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_DOUBLE_TYPE)))))), }; for (const auto& f : module_MyStructTypeDef_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_MyStructTypeDef.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::MyUnionFloatFieldThrowExp>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.MyUnionFloatFieldThrowExp", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_MyUnionFloatFieldThrowExp = res.first->second; module_MyUnionFloatFieldThrowExp.name_ref() = "module.MyUnionFloatFieldThrowExp"; module_MyUnionFloatFieldThrowExp.is_union_ref() = true; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_MyUnionFloatFieldThrowExp_fields[] = { std::make_tuple(1, "myEnum", false, std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum")), std::make_tuple(2, "setFloat", false, std::make_unique<List>(std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_FLOAT_TYPE)))), std::make_tuple(3, "myDataItem", false, std::make_unique<Struct< ::cpp2::MyDataItem>>("module.MyDataItem")), std::make_tuple(4, "complexNestedStruct", false, std::make_unique<Typedef>("module.ComplexNestedStruct", std::make_unique<Struct< ::cpp2::ComplexNestedStruct>>("module.ComplexNestedStruct"))), }; for (const auto& f : module_MyUnionFloatFieldThrowExp_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_MyUnionFloatFieldThrowExp.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::TypeRemapped>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.TypeRemapped", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_TypeRemapped = res.first->second; module_TypeRemapped.name_ref() = "module.TypeRemapped"; module_TypeRemapped.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_TypeRemapped_fields[] = { std::make_tuple(1, "lsMap", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(2, "ioMap", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Typedef>("module.FMap", std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE))))), std::make_tuple(3, "BigInteger", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), std::make_tuple(4, "binaryTestBuffer", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_BINARY_TYPE)), }; for (const auto& f : module_TypeRemapped_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_TypeRemapped.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::emptyXcep>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.emptyXcep", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_emptyXcep = res.first->second; module_emptyXcep.name_ref() = "module.emptyXcep"; module_emptyXcep.is_union_ref() = false; return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::reqXcep>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.reqXcep", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_reqXcep = res.first->second; module_reqXcep.name_ref() = "module.reqXcep"; module_reqXcep.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_reqXcep_fields[] = { std::make_tuple(1, "message", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(2, "errorCode", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), }; for (const auto& f : module_reqXcep_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_reqXcep.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::optXcep>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.optXcep", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_optXcep = res.first->second; module_optXcep.name_ref() = "module.optXcep"; module_optXcep.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_optXcep_fields[] = { std::make_tuple(1, "message", true, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(2, "errorCode", true, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), }; for (const auto& f : module_optXcep_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_optXcep.fields_ref()->push_back(std::move(field)); } return res.first->second; } const ::apache::thrift::metadata::ThriftStruct& StructMetadata<::cpp2::complexException>::gen(ThriftMetadata& metadata) { auto res = metadata.structs_ref()->emplace("module.complexException", ::apache::thrift::metadata::ThriftStruct{}); if (!res.second) { return res.first->second; } ::apache::thrift::metadata::ThriftStruct& module_complexException = res.first->second; module_complexException.name_ref() = "module.complexException"; module_complexException.is_union_ref() = false; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_complexException_fields[] = { std::make_tuple(1, "message", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(2, "listStrings", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(3, "errorEnum", false, std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum")), std::make_tuple(4, "unionError", true, std::make_unique<Union< ::cpp2::MyUnion>>("module.MyUnion")), std::make_tuple(5, "structError", false, std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct")), std::make_tuple(6, "lsMap", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), }; for (const auto& f : module_complexException_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_complexException.fields_ref()->push_back(std::move(field)); } return res.first->second; } void ExceptionMetadata<::cpp2::emptyXcep>::gen(ThriftMetadata& metadata) { auto res = metadata.exceptions_ref()->emplace("module.emptyXcep", ::apache::thrift::metadata::ThriftException{}); if (!res.second) { return; } ::apache::thrift::metadata::ThriftException& module_emptyXcep = res.first->second; module_emptyXcep.name_ref() = "module.emptyXcep"; } void ExceptionMetadata<::cpp2::reqXcep>::gen(ThriftMetadata& metadata) { auto res = metadata.exceptions_ref()->emplace("module.reqXcep", ::apache::thrift::metadata::ThriftException{}); if (!res.second) { return; } ::apache::thrift::metadata::ThriftException& module_reqXcep = res.first->second; module_reqXcep.name_ref() = "module.reqXcep"; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_reqXcep_fields[] = { std::make_tuple(1, "message", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(2, "errorCode", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), }; for (const auto& f : module_reqXcep_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_reqXcep.fields_ref()->push_back(std::move(field)); } } void ExceptionMetadata<::cpp2::optXcep>::gen(ThriftMetadata& metadata) { auto res = metadata.exceptions_ref()->emplace("module.optXcep", ::apache::thrift::metadata::ThriftException{}); if (!res.second) { return; } ::apache::thrift::metadata::ThriftException& module_optXcep = res.first->second; module_optXcep.name_ref() = "module.optXcep"; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_optXcep_fields[] = { std::make_tuple(1, "message", true, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(2, "errorCode", true, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I32_TYPE)), }; for (const auto& f : module_optXcep_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_optXcep.fields_ref()->push_back(std::move(field)); } } void ExceptionMetadata<::cpp2::complexException>::gen(ThriftMetadata& metadata) { auto res = metadata.exceptions_ref()->emplace("module.complexException", ::apache::thrift::metadata::ThriftException{}); if (!res.second) { return; } ::apache::thrift::metadata::ThriftException& module_complexException = res.first->second; module_complexException.name_ref() = "module.complexException"; static const std::tuple<int32_t, const char*, bool, std::unique_ptr<MetadataTypeInterface>> module_complexException_fields[] = { std::make_tuple(1, "message", false, std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE)), std::make_tuple(2, "listStrings", false, std::make_unique<List>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), std::make_tuple(3, "errorEnum", false, std::make_unique<Enum< ::cpp2::MyEnum>>("module.MyEnum")), std::make_tuple(4, "unionError", true, std::make_unique<Union< ::cpp2::MyUnion>>("module.MyUnion")), std::make_tuple(5, "structError", false, std::make_unique<Struct< ::cpp2::MyStruct>>("module.MyStruct")), std::make_tuple(6, "lsMap", false, std::make_unique<Map>(std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_I64_TYPE), std::make_unique<Primitive>(ThriftPrimitiveType::THRIFT_STRING_TYPE))), }; for (const auto& f : module_complexException_fields) { ::apache::thrift::metadata::ThriftField field; field.id_ref() = std::get<0>(f); field.name_ref() = std::get<1>(f); field.is_optional_ref() = std::get<2>(f); std::get<3>(f)->writeAndGenType(*field.type_ref(), metadata); module_complexException.fields_ref()->push_back(std::move(field)); } } } // namespace md } // namespace detail } // namespace thrift } // namespace apache
9c63adc4b5e137aa6394067a649335fbe5291387
b74dea911cf644ab1b6a6c8c448708ee09e6581f
/SDK/platform/nxp_kinetis_e/sys/system_SKEAZ1284.cpp
1c692bbdca6d9fd1eb2bd129a13ccb1d1feaa9a0
[ "Unlicense" ]
permissive
ghsecuritylab/CppSDK
bbde19f9d85975dd12c366bba4874e96cd614202
50da768a887241d4e670b3ef73c041b21645620e
refs/heads/master
2021-02-28T14:02:58.205901
2018-08-23T15:08:15
2018-08-23T15:08:15
245,703,236
0
0
NOASSERTION
2020-03-07T20:47:45
2020-03-07T20:47:44
null
UTF-8
C++
false
false
11,398
cpp
/* ** ################################################################### ** Compilers: ARM Compiler ** Freescale C/C++ for Embedded ARM ** GNU C Compiler ** GNU C Compiler - CodeSourcery Sourcery G++ ** IAR ANSI C/C++ Compiler for ARM ** ** Reference manual: MKE06P80M48SF0RM, Rev. 1, Dec 2013 ** Version: rev. 1.3, 2014-05-28 ** Build: b140528 ** ** Abstract: ** Provides a system configuration function and a global variable that ** contains the system frequency. It configures the device and initializes ** the oscillator (PLL) that is part of the microcontroller device. ** ** Copyright (c) 2014 Freescale Semiconductor, Inc. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** o Redistributions of source code must retain the above copyright notice, this list ** of conditions and the following disclaimer. ** ** o Redistributions in binary form must reproduce the above copyright notice, this ** list of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. ** ** o Neither the name of Freescale Semiconductor, Inc. nor the names of its ** contributors may be used to endorse or promote products derived from this ** software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ** http: www.freescale.com ** mail: [email protected] ** ** Revisions: ** - rev. 1.0 (2013-07-30) ** Initial version. ** - rev. 1.1 (2013-10-29) ** Definition of BITBAND macros updated to support peripherals with 32-bit acces disabled. ** - rev. 1.2 (2014-01-10) ** CAN module: corrected address of TSIDR1 register. ** CAN module: corrected name of MSCAN_TDLR bit DLC to TDLC. ** FTM0 module: added access macro for EXTTRIG register. ** NVIC module: registers access macros improved. ** SCB module: unused bits removed, mask, shift macros improved. ** Defines of interrupt vectors aligned to RM. ** - rev. 1.3 (2014-05-28) ** The declaration of clock configurations has been moved to separate header file system_MKE02Z2.h ** Module access macro {module}_BASES replaced by {module}_BASE_PTRS. ** I2C module: renamed status register S to S1 to match RM naming. ** ** ################################################################### */ /*! * @file SKEAZ1284 * @version 1.3 * @date 2014-05-28 * @brief Device specific configuration file for SKEAZ1284 (implementation file) * * Provides a system configuration function and a global variable that contains * the system frequency. It configures the device and initializes the oscillator * (PLL) that is part of the microcontroller device. */ #include <stdint.h> #include <include/SKEAZ1284.h> /* ---------------------------------------------------------------------------- -- Core clock ---------------------------------------------------------------------------- */ uint32_t SystemCoreClock = DEFAULT_SYSTEM_CLOCK; /* ---------------------------------------------------------------------------- -- SystemInit() ---------------------------------------------------------------------------- */ void SystemInit (void) { #if (DISABLE_WDOG) /* WDOG->TOVAL: TOVAL=0xE803 */ WDOG->TOVAL = WDOG_TOVAL_TOVAL(0xE803); /* Timeout value */ /* WDOG->CS2: WIN=0,FLG=0,??=0,PRES=0,??=0,??=0,CLK=1 */ WDOG->CS2 = WDOG_CS2_CLK(0x01); /* 1-kHz clock source */ /* WDOG->CS1: EN=0,INT=0,UPDATE=1,TST=0,DBG=0,WAIT=1,STOP=1 */ WDOG->CS1 = WDOG_CS1_UPDATE_MASK | WDOG_CS1_TST(0x00) | WDOG_CS1_WAIT_MASK | WDOG_CS1_STOP_MASK; #endif /* (DISABLE_WDOG) */ #if (CLOCK_SETUP == 0) /* ICS->C2: BDIV|=1 */ ICS->C2 |= ICS_C2_BDIV(0x01); /* Update system prescalers */ /* SIM->CLKDIV: ??=0,??=0,OUTDIV1=0,??=0,??=0,??=0,OUTDIV2=0,??=0,??=0,??=0,OUTDIV3=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0 */ SIM->CLKDIV = SIM_CLKDIV_OUTDIV1(0x00); /* Update system prescalers */ /* Switch to FEI Mode */ /* ICS_C1: CLKS=0,RDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ ICS->C1 = ICS_C1_CLKS(0x00) | ICS_C1_RDIV(0x00) | ICS_C1_IREFS_MASK | ICS_C1_IRCLKEN_MASK; /* ICS->C2: BDIV=1,LP=0 */ ICS->C2 = (uint8_t)((ICS->C2 & (uint8_t)~(uint8_t)( ICS_C2_BDIV(0x06) | ICS_C2_LP_MASK )) | (uint8_t)( ICS_C2_BDIV(0x01) )); /* OSC->CR: OSCEN=0,??=0,OSCSTEN=0,OSCOS=0,??=0,RANGE=0,HGO=0,OSCINIT=0 */ OSC->CR = 0x00U; while((ICS->S & ICS_S_IREFST_MASK) == 0x00U) { /* Check that the source of the FLL reference clock is the internal reference clock. */ } while((ICS->S & 0x0CU) != 0x00U) { /* Wait until output of the FLL is selected */ } #elif (CLOCK_SETUP == 1) /* SIM->CLKDIV: ??=0,??=0,OUTDIV1=0,??=0,??=0,??=0,OUTDIV2=1,??=0,??=0,??=0,OUTDIV3=1,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0 */ SIM->CLKDIV = (SIM_CLKDIV_OUTDIV2_MASK | SIM_CLKDIV_OUTDIV3_MASK); /* Update system prescalers */ /* Switch to FEE Mode */ /* ICS->C2: BDIV=0,LP=0 */ ICS->C2 &= (uint8_t)~(uint8_t)((ICS_C2_BDIV(0x07) | ICS_C2_LP_MASK)); /* OSC->CR: OSCEN=1,??=0,OSCSTEN=0,OSCOS=1,??=0,RANGE=1,HGO=0,OSCINIT=0 */ OSC->CR = (OSC_CR_OSCEN_MASK | OSC_CR_OSCOS_MASK | OSC_CR_RANGE_MASK); /* ICS->C1: CLKS=0,RDIV=3,IREFS=0,IRCLKEN=1,IREFSTEN=0 */ ICS->C1 = (ICS_C1_CLKS(0x00) | ICS_C1_RDIV(0x03) | ICS_C1_IRCLKEN_MASK); while((ICS->S & ICS_S_IREFST_MASK) != 0x00U) { /* Check that the source of the FLL reference clock is the external reference clock. */ } while((ICS->S & 0x0CU) != 0x00U) { /* Wait until output of the FLL is selected */ } #elif (CLOCK_SETUP == 2) /* SIM->CLKDIV: ??=0,??=0,OUTDIV1=0,??=0,??=0,??=0,OUTDIV2=0,??=0,??=0,??=0,OUTDIV3=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0 */ SIM->CLKDIV = SIM_CLKDIV_OUTDIV1(0x00); /* Update system prescalers */ /* Switch to FBI Mode */ /* ICS->C1: CLKS=1,RDIV=0,IREFS=1,IRCLKEN=1,IREFSTEN=0 */ ICS->C1 = ICS_C1_CLKS(0x01) | ICS_C1_RDIV(0x00) | ICS_C1_IREFS_MASK | ICS_C1_IRCLKEN_MASK; /* ICS->C2: BDIV=0,LP=0 */ ICS->C2 &= (uint8_t)~(uint8_t)((ICS_C2_BDIV(0x07) | ICS_C2_LP_MASK)); /* OSC->CR: OSCEN=0,??=0,OSCSTEN=0,OSCOS=0,??=0,RANGE=0,HGO=0,OSCINIT=0 */ OSC->CR = 0x00U; while((ICS->S & ICS_S_IREFST_MASK) == 0x00U) { /* Check that the source of the FLL reference clock is the internal reference clock. */ } while((ICS->S & 0x0CU) != 0x04U) { /* Wait until internal reference clock is selected as ICS output */ } /* Switch to BLPI Mode */ /* ICS->C2: BDIV=0,LP=1 */ ICS->C2 = (uint8_t)((ICS->C2 & (uint8_t)~(uint8_t)( ICS_C2_BDIV(0x07) )) | (uint8_t)( ICS_C2_LP_MASK )); while((ICS->S & ICS_S_IREFST_MASK) == 0x00U) { /* Check that the source of the FLL reference clock is the internal reference clock. */ } #elif (CLOCK_SETUP == 3) /* SIM->CLKDIV: ??=0,??=0,OUTDIV1=0,??=0,??=0,??=0,OUTDIV2=0,??=0,??=0,??=0,OUTDIV3=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0,??=0 */ SIM->CLKDIV = SIM_CLKDIV_OUTDIV1(0x00); /* Update system prescalers */ /* Switch to FBE Mode */ /* ICS->C2: BDIV=0,LP=0 */ ICS->C2 &= (uint8_t)~(uint8_t)((ICS_C2_BDIV(0x07) | ICS_C2_LP_MASK)); /* OSC->CR: OSCEN=1,??=0,OSCSTEN=0,OSCOS=1,??=0,RANGE=1,HGO=0,OSCINIT=0 */ OSC->CR = (OSC_CR_OSCEN_MASK | OSC_CR_OSCOS_MASK | OSC_CR_RANGE_MASK); /* ICS->C1: CLKS=2,RDIV=3,IREFS=0,IRCLKEN=1,IREFSTEN=0 */ ICS->C1 = (ICS_C1_CLKS(0x02) | ICS_C1_RDIV(0x03) | ICS_C1_IRCLKEN_MASK); while((ICS->S & ICS_S_IREFST_MASK) != 0x00U) { /* Check that the source of the FLL reference clock is the external reference clock. */ } while((ICS->S & 0x0CU) != 0x08U) { /* Wait until external reference clock is selected as ICS output */ } /* Switch to BLPE Mode */ /* ICS->C2: BDIV=0,LP=1 */ ICS->C2 = (uint8_t)((ICS->C2 & (uint8_t)~(uint8_t)( ICS_C2_BDIV(0x07) )) | (uint8_t)( ICS_C2_LP_MASK )); while((ICS->S & 0x0CU) != 0x08U) { /* Wait until external reference clock is selected as ICS output */ } #endif } /* ---------------------------------------------------------------------------- -- SystemCoreClockUpdate() ---------------------------------------------------------------------------- */ void SystemCoreClockUpdate (void) { uint32_t ICSOUTClock; /* Variable to store output clock frequency of the ICS module */ uint8_t Divider; if ((ICS->C1 & ICS_C1_CLKS_MASK) == 0x0u) { /* Output of FLL is selected */ if ((ICS->C1 & ICS_C1_IREFS_MASK) == 0x0u) { /* External reference clock is selected */ ICSOUTClock = CPU_XTAL_CLK_HZ; /* System oscillator drives ICS clock */ Divider = (uint8_t)(1u << ((ICS->C1 & ICS_C1_RDIV_MASK) >> ICS_C1_RDIV_SHIFT)); ICSOUTClock = (ICSOUTClock / Divider); /* Calculate the divided FLL reference clock */ if ((OSC->CR & OSC_CR_RANGE_MASK) != 0x0u) { ICSOUTClock /= 32u; /* If high range is enabled, additional 32 divider is active */ } } else { ICSOUTClock = CPU_INT_CLK_HZ; /* The internal reference clock is selected */ } ICSOUTClock *= 1280u; /* Apply 1280 FLL multiplier */ } else if ((ICS->C1 & ICS_C1_CLKS_MASK) == 0x40u) { /* Internal reference clock is selected */ ICSOUTClock = CPU_INT_CLK_HZ; } else if ((ICS->C1 & ICS_C1_CLKS_MASK) == 0x80u) { /* External reference clock is selected */ ICSOUTClock = CPU_XTAL_CLK_HZ; } else { /* Reserved value */ return; } ICSOUTClock = ICSOUTClock >> ((ICS->C2 & ICS_C2_BDIV_MASK) >> ICS_C2_BDIV_SHIFT); SystemCoreClock = (ICSOUTClock / (1u + ((SIM->CLKDIV & SIM_CLKDIV_OUTDIV1_MASK) >> SIM_CLKDIV_OUTDIV1_SHIFT))); }
d1d036fb39778990e23aef9ae6c9ca025aacbf1d
cdea87e9889ce65e81d66c3f6df3199747c86609
/src/LZ4MetadataOnGPU.cpp
e9db96eee99c19795f7995c59556bcfd25a06000
[]
permissive
nsakharnykh/nvcomp
ebdfc4fbf9fcf2cb2c2b931e163cca65be1794f5
8640ba9d4f4916ff5e12fbbe3b03617518f551d4
refs/heads/main
2023-04-23T03:09:15.309774
2020-12-19T18:36:01
2020-12-19T18:36:01
323,417,590
0
0
BSD-3-Clause
2020-12-21T18:31:31
2020-12-21T18:31:31
null
UTF-8
C++
false
false
5,012
cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LZ4MetadataOnGPU.h" #include "CudaUtils.h" #include <cassert> #include <stdexcept> namespace nvcomp { /****************************************************************************** * PUBLIC STATIC METHODS ****************************************************** *****************************************************************************/ size_t LZ4MetadataOnGPU::getSerializedSizeOf(const LZ4Metadata& metadata) { return (LZ4Metadata::OffsetAddr + metadata.getNumChunks() + 1) * sizeof(size_t); } size_t LZ4MetadataOnGPU::getCompressedDataOffset(const LZ4Metadata& metadata) { return getSerializedSizeOf(metadata); } /****************************************************************************** * CONSTRUCTORS / DESTRUCTOR ************************************************** *****************************************************************************/ LZ4MetadataOnGPU::LZ4MetadataOnGPU( const void* const ptr, const size_t maxSize) : m_ptr(ptr), m_maxSize(maxSize), m_numChunks(-1), m_serializedSize(0) { if (ptr == nullptr) { throw std::runtime_error("Cannot have nullptr for metadata location."); } } LZ4MetadataOnGPU::LZ4MetadataOnGPU(const LZ4MetadataOnGPU& other) : LZ4MetadataOnGPU(other.m_ptr, other.m_maxSize) { m_numChunks = other.m_numChunks; m_serializedSize = other.m_serializedSize; } /****************************************************************************** * PUBLIC METHODS ************************************************************* *****************************************************************************/ LZ4MetadataOnGPU& LZ4MetadataOnGPU::operator=(const LZ4MetadataOnGPU& other) { m_ptr = other.m_ptr; m_maxSize = other.m_maxSize; m_numChunks = other.m_numChunks; m_serializedSize = other.m_serializedSize; return *this; } size_t LZ4MetadataOnGPU::getSerializedSize() const { if (m_serializedSize == 0) { throw std::runtime_error("Serialized size has not been set."); } assert(m_numChunks > 0); return m_serializedSize; } const size_t* LZ4MetadataOnGPU::compressed_prefix_ptr() const { return static_cast<const size_t*>(m_ptr) + LZ4Metadata::OffsetAddr; } LZ4Metadata LZ4MetadataOnGPU::copyToHost() { size_t metadata_bytes; CudaUtils::copy( &metadata_bytes, ((size_t*)m_ptr) + LZ4Metadata::MetadataBytes, 1, DEVICE_TO_HOST); if (metadata_bytes > m_maxSize) { throw std::runtime_error( "Compressed data is too small to contain " "metadata of size " + std::to_string(metadata_bytes) + " / " + std::to_string(m_maxSize)); } std::vector<uint8_t> metadata_buffer(metadata_bytes); CudaUtils::copy( metadata_buffer.data(), static_cast<const uint8_t*>(m_ptr), metadata_bytes, DEVICE_TO_HOST); set_serialized_size(metadata_bytes); LZ4Metadata metadata = LZ4Metadata(metadata_buffer.data(), metadata_buffer.size()); assert(getSerializedSizeOf(metadata) == metadata_bytes); return metadata; } /****************************************************************************** * PROTECTED METHODS ********************************************************** *****************************************************************************/ size_t LZ4MetadataOnGPU::max_size() const { return m_maxSize; } void LZ4MetadataOnGPU::set_serialized_size(const size_t size) { m_serializedSize = size; } } // namespace nvcomp
8e62f292341ad77836e946c768639c59d110ecfb
da9234381bb80e40ed777891c069d7b39e504244
/algorithm/geometryutils.h
31387a62b801a0204da6035660b9047b12fb4dfd
[]
no_license
JdeRobot/slam-visual_markers
c9ea9388f23f5eb4409a7fe22e871adc19774e74
0dee6fd7089faf7433a5cb8803fe33d9b2a3fcb0
refs/heads/master
2021-01-01T16:47:46.230412
2018-10-08T20:31:34
2018-10-08T20:31:34
97,924,083
1
0
null
2018-10-08T20:26:24
2017-07-21T08:19:36
C
UTF-8
C++
false
false
5,988
h
#ifndef GEOMETRYUTILS_H #define GEOMETRYUTILS_H #include <progeo/progeo.h> #include <opencv2/calib3d/calib3d.hpp> #include <eigen3/Eigen/Dense> namespace Ardrone { class Pose { private: HPoint3D m_Position; HPoint3D m_BaseFoa; HPoint3D m_Foa; float m_Roll; float m_Pitch; float m_Yaw; Eigen::Matrix4d m_RT; double m_Weight; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW Pose(); Pose(float x, float y, float z, float h, float roll, float pitch, float yaw, float foax = 0.0f, float foay = 0.0f, float foaz = 0.0f); Pose(const Eigen::Matrix4d& rt); void SetBaseFoa(float foax, float foay, float foaz, float h = 1.0f); void Update(float x, float y, float z, float h, float roll, float pitch, float yaw); void Update(const Eigen::Matrix4d& rt); HPoint3D GetPosition() { return m_Position; } HPoint3D GetFoa() { return m_Foa; } float GetX() const { return m_Position.X; } float GetY() const { return m_Position.Y; } float GetZ() const { return m_Position.Z; } float GetH() const { return m_Position.H; } float GetRoll() const { return m_Roll; } float GetPitch() const { return m_Pitch; } float GetYaw() const { return m_Yaw; } float GetBaseFoaX() const { return m_BaseFoa.X; } float GetBaseFoaY() const { return m_BaseFoa.Y; } float GetBaseFoaZ() const { return m_BaseFoa.Z; } float GetBaseFoaH() const { return m_BaseFoa.H; } float GetFoaX() const { return m_Foa.X; } float GetFoaY() const { return m_Foa.Y; } float GetFoaZ() const { return m_Foa.Z; } float GetFoaH() const { return m_Foa.H; } const Eigen::Matrix4d& GetRT() { return m_RT; } double GetWeight() { return m_Weight; } void SetWeight(double weight) { m_Weight = weight; } }; class Line { private: float x0, y0, z0; float u1, u2, u3; float h; public: Line(HPoint3D a, HPoint3D b) { /**** Ecuaciones paramétricas de la recta ****/ // x = x0 + u1*t = a.X + (b.X-a.X)*t // y = y0 + u2*t = a.Y + (b.Y-a.Y)*t // z = z0 + u3*t = a.Z + (b.Z-a.Z)*t /*********************************************/ x0 = a.X; y0 = a.Y; z0 = a.Z; u1 = b.X - a.X; u2 = b.Y - a.Y; u3 = b.Z - a.Z; h = b.H; } HPoint3D GetPoint(float t) const { HPoint3D result; result.X = x0 + u1*t; result.Y = y0 + u2*t; result.Z = z0 + u3*t; result.H = h; return result; } float X0() const { return x0; } float Y0() const { return y0; } float Z0() const { return z0; } float U1() const { return u1; } float U2() const { return u2; } float U3() const { return u3; } }; class Plane { private: float a, b, c; float x0, y0, z0; float h; public: Plane(HPoint3D o, HPoint3D n) { /******** Ecuación normal plano ********/ // o es un punto del plano y o-n el vector normal // A*(x-x0) + B*(y-y0) + C*(z-z0) = 0 // (n.X - o.X)*(x-o.X) + (n.Y - o.Y)*(y-o.Y) + (n.Z - o.Z)*(z-o.Z) = 0 /***************************************/ a = n.X - o.X; b = n.Y - o.Y; c = n.Z - o.Z; x0 = o.X; y0 = o.Y; z0 = o.Z; h = n.H; } float A() const { return a; } float B() const { return b; } float C() const { return c; } float X0() const { return x0; } float Y0() const { return y0; } float Z0() const { return z0; } }; class GeometryUtils { public: /** * Dada una recta calcula el punto correspondiente a una determinada distancia del punto a. * a y b determinan la recta */ static HPoint3D GetPointOfLine(HPoint3D a, HPoint3D b, double dist); /** * Calcula el punto de intersección de una recta y un plano */ static HPoint3D GetPointOfLineAndPlane(const Line& line, const Plane& plane); static Eigen::Matrix4d BuildRTMat(float x, float y, float z, float rotX, float rotY, float rotZ); static float quatToRoll(float qw, float qx, float qy, float qz); static float quatToPitch(float qw, float qx, float qy, float qz); static float quatToYaw(float qw, float qx, float qy, float qz); static double StandardRad(double t); static double StandardRad2(double t); /** * Convert rotation matrix to roll, pitch, yaw angles */ static void RotationMatrixToRPY(const Eigen::Matrix3d& rot, double& roll, double& pitch, double& yaw); /** * Convert roll, pitch, yaw angles to rotation matrix */ static void RPYToRotationMatrix(double roll, double pitch, double yaw, Eigen::Matrix3f& rot); static double GetDistance(double x, double y, double z); static double GetRadialError(const Pose& realPose, const Pose& estimatedPose); static double GetXError(const Pose& realPose, const Pose& estimatedPose); static double GetYError(const Pose& realPose, const Pose& estimatedPose); static double GetZError(const Pose& realPose, const Pose& estimatedPose); static double GetAngularError(const Pose& realPose, const Pose& estimatedPose); static double GetRollError(const Pose& realPose, const Pose& estimatedPose); static double GetPitchError(const Pose& realPose, const Pose& estimatedPose); static double GetYawError(const Pose& realPose, const Pose& estimatedPose); }; } #endif // GEOMETRYUTILS_H
724671b4c301fb76ed99b6840b77cadb230d2ebf
ad5b72656f0da99443003984c1e646cb6b3e67ea
/src/common/transformations/tests/common_optimizations/convert_nms_gather_path_to_unsigned_test.cpp
629e9079522b62429d74bdf0039c0c371f4ddb53
[ "Apache-2.0" ]
permissive
novakale/openvino
9dfc89f2bc7ee0c9b4d899b4086d262f9205c4ae
544c1acd2be086c35e9f84a7b4359439515a0892
refs/heads/master
2022-12-31T08:04:48.124183
2022-12-16T09:05:34
2022-12-16T09:05:34
569,671,261
0
0
null
null
null
null
UTF-8
C++
false
false
11,108
cpp
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <ngraph/function.hpp> #include <ngraph/opsets/opset8.hpp> #include <ngraph/pass/manager.hpp> #include <transformations/common_optimizations/convert_nms_gather_path_to_unsigned.hpp> #include <transformations/init_node_info.hpp> #include "common_test_utils/ngraph_test_utils.hpp" #include "ngraph/pass/visualize_tree.hpp" using namespace testing; using namespace ngraph; using namespace std; TEST_F(TransformationTestsF, test_convert_to_unsigned_nms_gather_1) { // if Convert doesn't exist { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); // usually input to gather data goes after reshape NMS scores auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, squeeze_node, opset8::Constant::create(element::i32, Shape{1}, {0})); function = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); } { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::u64); auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); function_ref = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); } } TEST_F(TransformationTestsF, test_convert_to_unsigned_nms_gather_2) { // if Convert already exists { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::i32); // usually input to gather data goes after reshape NMS scores auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); function = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); } { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::u32); auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); function_ref = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); } } TEST_F(TransformationTestsF, test_convert_to_unsigned_nms_gather_with_onnx_slice) { // if Convert already exists and Slice is present instead of StridedSlice { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto start = opset8::Constant::create(element::i32, Shape{1}, {3}); auto stop = opset8::Constant::create(element::i32, Shape{1}, {4}); auto step = opset8::Constant::create(element::i32, Shape{1}, {1}); auto slice_node = make_shared<opset8::Slice>(nms->output(0), start, stop, step); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(slice_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::i32); // usually input to gather data goes after reshape NMS scores auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); function = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); } { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto start = opset8::Constant::create(element::i32, Shape{1}, {3}); auto stop = opset8::Constant::create(element::i32, Shape{1}, {4}); auto step = opset8::Constant::create(element::i32, Shape{1}, {1}); auto slice_node = make_shared<opset8::Slice>(nms->output(0), start, stop, step); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(slice_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::u32); auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); function_ref = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); } } TEST(TransformationTests, test_convert_to_unsigned_nms_gather_3) { // if NMS output goes not into Gather indices no converts should be inserted auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto gather = make_shared<opset8::Gather>(nms->output(0), opset8::Constant::create(element::i32, Shape{1}, {2}), opset8::Constant::create(element::i32, Shape{1}, {0})); shared_ptr<Function> f = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); pass::Manager manager; manager.register_pass<pass::InitNodeInfo>(); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); manager.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); ASSERT_EQ(count_ops_of_type<opset1::Convert>(f), 0); }
2b50b1e873f60dbf4c2276cbf79673ba6e1880ed
ea8ca702551a1dfd09039a56ccb04692508829f6
/src/rpcserver.h
dfd20f96e5ec93dcabe4c9744c04d205e892679c
[ "MIT" ]
permissive
freecreators/freecreateors
04c589ec24272feb372c37c5da6cfb28db60db66
ef29609c99d4dddba761c964374cfa0e21939f23
refs/heads/master
2021-01-22T11:28:19.012441
2017-05-29T02:19:07
2017-05-29T02:19:07
92,698,667
3
0
null
null
null
null
UTF-8
C++
false
false
13,689
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _BITCOINRPC_SERVER_H_ #define _BITCOINRPC_SERVER_H_ 1 #include "uint256.h" #include "rpcprotocol.h" #include <list> #include <map> class CBlockIndex; class CBlockThinIndex; class CNetAddr; void StartRPCThreads(); void StopRPCThreads(); /* Type-check arguments; throws JSONRPCError if wrong type given. Does not check that the right number of arguments are passed, just that any passed are the correct type. Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); */ void RPCTypeCheck(const json_spirit::Array& params, const std::list<json_spirit::Value_type>& typesExpected, bool fAllowNull=false); /* Check for expected keys/value types in an Object. Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); */ void RPCTypeCheck(const json_spirit::Object& o, const std::map<std::string, json_spirit::Value_type>& typesExpected, bool fAllowNull=false); /* Run func nSeconds from now. Uses boost deadline timers. Overrides previous timer <name> (if any). */ void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds); //! Convert boost::asio address to CNetAddr CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address); typedef json_spirit::Value(*rpcfn_type)(const json_spirit::Array& params, bool fHelp); class CRPCCommand { public: std::string name; rpcfn_type actor; bool okSafeMode; bool threadSafe; bool reqWallet; }; class JSONRequest { public: json_spirit::Value id; std::string strMethod; json_spirit::Array params; JSONRequest() { id = json_spirit::Value::null; } void parse(const json_spirit::Value& valRequest); }; /** * Bitcoin RPC command dispatcher. */ class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](std::string name) const; std::string help(std::string name) const; /** * Execute a method. * @param method Method to execute * @param params Array of arguments (JSON objects) * @returns Result of the call. * @throws an exception (json_spirit::Value) when an error happens. */ json_spirit::Value execute(const std::string &method, const json_spirit::Array &params) const; }; extern const CRPCTable tableRPC; extern void InitRPCMining(); extern void ShutdownRPCMining(); extern int64_t nWalletUnlockTime; extern int64_t AmountFromValue(const json_spirit::Value& value); extern json_spirit::Value ValueFromAmount(int64_t amount); bool IsStringBoolPositive(std::string& value); bool IsStringBoolNegative(std::string& value); bool GetStringBool(std::string& value, bool &fOut); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern double GetHeaderDifficulty(const CBlockThinIndex* blockindex = NULL); extern double GetPoWMHashPS(); extern double GetPoSKernelPS(); extern std::string HexBits(unsigned int nBits); extern std::string HelpRequiringPassphrase(); extern void EnsureWalletIsUnlocked(); // // Utilities: convert hex-encoded Values // (throws error if not hex). // extern uint256 ParseHashV(const json_spirit::Value& v, std::string strName); extern uint256 ParseHashO(const json_spirit::Object& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const json_spirit::Value& v, std::string strName); extern std::vector<unsigned char> ParseHexO(const json_spirit::Object& o, std::string strKey); extern json_spirit::Value getconnectioncount(const json_spirit::Array& params, bool fHelp); // in rpcnet.cpp extern json_spirit::Value getpeerinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value ping(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addnode(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaddednodeinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnettotals(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value dumpwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value importwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value dumpprivkey(const json_spirit::Array& params, bool fHelp); // in rpcdump.cpp extern json_spirit::Value importprivkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendalert(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnetworkinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getsubsidy(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getstakesubsidy(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getstakinginfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value checkkernel(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getwork(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getworkex(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblocktemplate(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value submitblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnewaddress(const json_spirit::Array& params, bool fHelp); // in rpcwallet.cpp extern json_spirit::Value getnewextaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaccountaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value setaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaddressesbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendtoaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value signmessage(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value verifymessage(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getreceivedbyaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getreceivedbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getbalance(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value movecmd(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendfrom(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendmany(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addmultisigaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value createmultisig(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addredeemscript(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listreceivedbyaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listreceivedbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listtransactions(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listaddressgroupings(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listaccounts(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listsinceblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value gettransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value backupwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value keypoolrefill(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletpassphrase(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletpassphrasechange(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletlock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value encryptwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value validateaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value reservebalance(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value checkwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value repairwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value resendtx(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value makekeypair(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value validatepubkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnewpubkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp); // in rcprawtransaction.cpp extern json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value decodescript(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value signrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getbestblockhash(const json_spirit::Array& params, bool fHelp); // in rpcblockchain.cpp extern json_spirit::Value getblockcount(const json_spirit::Array& params, bool fHelp); // in rpcblockchain.cpp extern json_spirit::Value getdifficulty(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value settxfee(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getrawmempool(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblockhash(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblockbynumber(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value setbestblockbyheight(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value rewindchain(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value nextorphan(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getcheckpoint(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnewstealthaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value liststealthaddresses(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value importstealthaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendtostealthaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value clearwallettransactions(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value scanforalltxns(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value scanforstealthtxns(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendsdctoanon(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendanontoanon(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendanontosdc(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value estimateanonfee(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value anonoutputs(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value anoninfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value reloadanondata(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value txnreport(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgenable(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgdisable(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsglocalkeys(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgoptions(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgscanchain(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgscanbuckets(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgaddkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsggetpubkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgsend(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgsendanon(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsginbox(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgoutbox(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value smsgbuckets(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value thinscanmerkleblocks(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value thinforcestate(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value extkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value mnemonic(const json_spirit::Array& params, bool fHelp); #endif
[ "lenovo@LAPTOP-D9O5PPS6" ]
lenovo@LAPTOP-D9O5PPS6
be9f0292fa62c0258bc478e80e7e5b8950d681fe
2a6c97e4bc7e329ae5fcea951c996d20c461fd74
/ExamplesAndPractice/FirstCPP/FirstCPP/main.cpp
a2b35790a16229f014e55a19d551cf1b05cbee1c
[]
no_license
EdgarVi/CptS-122
690d5760ffcd25fa37c7fbd13980d063d6f13d35
daddf23bfc473191df3d754ff3f74f283b0a052a
refs/heads/main
2023-01-23T18:47:50.792774
2020-12-10T23:56:57
2020-12-10T23:56:57
320,418,852
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
cpp
#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; /* It is poor programming practice to use, using statements */ int function(int num[]); /* Function overloading? */ int add(int n1, int n2); double add(double n1, double n2); string add(string s1, string s2); int main(void) { std::cout << "Hello world" << std::endl; /* cout is an object, cout has a type associated with it, std::ostream */ cout << "Enter a number: "; int num = 0; cin >> num; /* cin std::istream use >> to extract */ //cout << "The number is: " << num << endl; //cout << "this is a problem" << endl; //int num[16]; //cout << function(num) << endl; string s1 = "cat", s2 = "dog"; cout << add(4, 5) << endl; cout << add(4.0, 5.0) << endl; cout << add(4.0, (1.0 * 5)) << endl; cout << add(s1, s2) << endl; return 0; } /* C++ is object oriented, C is procedural Encapsulation */ /* Interview Question: Find size of array */ int function(int num[]) { int size = sizeof(num) / sizeof(int); return size; } int add(int n1, int n2) { return n1 + n2; } double add(double n1, double n2) { return n1 + n2; } string add(string s1, string s2) { /* concatenate strings, only works with standards strings */ return s1 + s2; }
4fd3e1ce27d2910b2e977189be8f93f79513f74f
3a77e7ffa78b51e1be18576f0c3e99048be8734f
/be/src/vec/exprs/vbitmap_predicate.h
bdb3ea2b00e0f7a0c3370159c0162d67604ee515
[ "OpenSSL", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-facebook-patent-rights-2", "PSF-2.0", "dtoa", "MIT", "GPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
yiguolei/incubator-doris
e73e2c44c7e3a3869d379555a29abfe48f97de6c
ada01b7ba6eac5d442b7701b78cea44235ed5017
refs/heads/master
2023-08-18T23:28:09.915740
2023-08-05T05:18:18
2023-08-05T05:18:44
160,305,067
1
1
Apache-2.0
2023-07-07T08:05:16
2018-12-04T05:43:20
Java
UTF-8
C++
false
false
2,356
h
// 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. #pragma once #include <fmt/format.h> #include <memory> #include <string> #include "common/object_pool.h" #include "common/status.h" #include "udf/udf.h" #include "vec/exprs/vexpr.h" namespace doris { class BitmapFilterFuncBase; class RowDescriptor; class RuntimeState; class TExprNode; namespace vectorized { class Block; class VExprContext; } // namespace vectorized } // namespace doris namespace doris::vectorized { // used for bitmap runtime filter class VBitmapPredicate final : public VExpr { ENABLE_FACTORY_CREATOR(VBitmapPredicate); public: VBitmapPredicate(const TExprNode& node); ~VBitmapPredicate() override = default; Status execute(VExprContext* context, Block* block, int* result_column_id) override; Status prepare(RuntimeState* state, const RowDescriptor& desc, VExprContext* context) override; Status open(RuntimeState* state, VExprContext* context, FunctionContext::FunctionStateScope scope) override; void close(VExprContext* context, FunctionContext::FunctionStateScope scope) override; const std::string& expr_name() const override; void set_filter(std::shared_ptr<BitmapFilterFuncBase>& filter); std::shared_ptr<BitmapFilterFuncBase> get_bitmap_filter_func() const override { return _filter; } std::string debug_string() const override { return fmt::format(" VBitmapPredicate:{}", VExpr::debug_string()); } private: std::shared_ptr<BitmapFilterFuncBase> _filter; std::string _expr_name; }; } // namespace doris::vectorized
e47be8fc8740fe3e429cae4446c26babe20e894f
7c677ef495a8475a8832ffd2724266c32dd294cd
/lab2_8/main.cpp
bde413d42cedaeade832229c58af4692be7efed4
[]
no_license
Userbot505/Labs_PSTU
0240fe9265fa5ed68d69cdce386b1523b8f8ff18
35cfb4338685d40e99727437956d7c5e0c94b597
refs/heads/master
2022-10-01T17:06:24.959730
2020-06-08T17:48:40
2020-06-08T17:48:40
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,703
cpp
#include "Vector.h" #include "StVector.h" #include <Windows.h> int main() { SetConsoleCP(1251); // ввод русской кирилицы SetConsoleOutputCP(1251); // вывод русской кирилицы Group g; // доп перем Vector v; // группы StVector stV; // студенты int x; // доп перем string str; // доп перем while (true) { if (g == Group()) // если работаем со всеми группами { cout << "\n1. Вывести группы\n2. Выбрать группу\n3. Сформировать список с сортировкой студентов\n4. Сформировать список с сортировкой по убыванию номеров групп\n5. Выход\n-->"; cin >> x; switch (x) { case 1: v.show(); break; case 2: cout << "Название? "; cin >> str; g = v.getGroupByName(str); stV.setGroup(g); break; case 3: v.query1(); break; case 4: v.query2(); break; case 5: return 0; } } else // если работаем с конкретной группой { cout << "\nТекущая группа - " << g << endl; cout << "1. Вывести список\n2. Добавить\n3. Удалить по номеру\n4. Изменить по номеру\n5. Назад\n-->"; cin >> x; switch (x) { case 1: stV.show(); break; case 2: stV.add(); break; case 3: stV.del(); break; case 4: stV.update(); break; case 5: g = Group(); stV.setGroup(g); break; } } } }
fe8ffee7ca39ee12fdaf3b2a9a6dca31ac7ce7d6
3cc352b29b8042b4a9746796b851d8469ff9ff62
/src/kmers/naif_kmer/KmerFreqAffixesMap.h
ed8d32e103d588ee148e9392d279283265fdf78b
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
CompRD/BroadCRD
1412faf3d1ffd9d1f9907a496cc22d59ea5ad185
303800297b32e993abd479d71bc4378f598314c5
refs/heads/master
2020-12-24T13:53:09.985406
2019-02-06T21:38:45
2019-02-06T21:38:45
34,069,434
4
0
null
null
null
null
UTF-8
C++
false
false
17,288
h
/////////////////////////////////////////////////////////////////////////////// // SOFTWARE COPYRIGHT NOTICE AGREEMENT // // This software and its documentation are copyright (2011) by the // // Broad Institute. All rights are reserved. This software is supplied // // without any warranty or guaranteed support whatsoever. The Broad // // Institute is not responsible for its use, misuse, or functionality. // /////////////////////////////////////////////////////////////////////////////// #ifndef KMERS__NAIF_KMER__KMER_FREQ_AFFIXES_MAP_H #define KMERS__NAIF_KMER__KMER_FREQ_AFFIXES_MAP_H #include "kmers/KmerSpectra.h" #include "kmers/naif_kmer/NaifKmerizer.h" #include "kmers/naif_kmer/KernelKmerStorer.h" #include "kmers/naif_kmer/KmerMap.h" #include "system/WorklistN.h" static inline String TagKFAM(String S = "KFAM") { return Date() + " (" + S + "): "; } class FreqAffixes { uint64_t _freq : 56; uint64_t _pre : 4; // 1 bit per possible base uint64_t _suf : 4; // 1 bit per possible base unsigned _n_bases(const unsigned bit4) const { return ((bit4 & 1u) + ((bit4 >> 1) & 1u) + ((bit4 >> 2) & 1u) + ((bit4 >> 3) & 1u)); } unsigned _base(const unsigned bit4, const unsigned i) const { unsigned n = 0; if (bit4 & 1u) n++; if (n > i) return 0u; if (bit4 & 2u) n++; if (n > i) return 1u; if (bit4 & 4u) n++; if (n > i) return 2u; if (bit4 & 8u) n++; if (n > i) return 3u; return 4u; } String _str_affixes(const unsigned aff, const bool fw) const { String s = "[" + (((aff & 1u) ? hieroglyph(fw ? 0 : 3) : " ") + ((aff & 2u) ? hieroglyph(fw ? 1 : 2) : " ") + ((aff & 4u) ? hieroglyph(fw ? 2 : 1) : " ") + ((aff & 8u) ? hieroglyph(fw ? 3 : 0) : " ")) + "]"; return s; } public: FreqAffixes() : _freq(0), _pre(0), _suf(0) {} void set_freq (const size_t freq) { _freq = freq; } void set_prefix(const unsigned base) { _pre |= (1u << (base & 3)); } void set_suffix(const unsigned base) { _suf |= (1u << (base & 3)); } size_t freq() const { return _freq; } bool has_prefix(const unsigned base) const { return _pre & (1u << (base & 3)); } bool has_suffix(const unsigned base) const { return _suf & (1u << (base & 3)); } size_t n_prefixes(const bool fw = true) const { return (fw ? _n_bases(_pre) : _n_bases(_suf)); } size_t n_suffixes(const bool fw = true) const { return (fw ? _n_bases(_suf) : _n_bases(_pre)); } size_t n_affixes() const { return _n_bases(_pre) + _n_bases(_suf); } unsigned prefix(const unsigned i, const bool fw = true) const { return (fw ? _base(_pre, i) : 3u ^ _base(_suf, i)); } unsigned suffix(const unsigned i, const bool fw = true) const { return (fw ? _base(_suf, i) : 3u ^ _base(_pre, i)); } String str_prefixes(const bool fw = true) const { return _str_affixes(fw ? _pre : _suf, fw); } String str_suffixes(const bool fw = true) const { return _str_affixes(fw ? _suf : _pre, fw); } }; template<class KMER_t> class KmerFreqAffixes : public KMER_t, public FreqAffixes { public: KmerFreqAffixes(const KMER_t & kmer) : KMER_t(kmer), FreqAffixes() {} explicit KmerFreqAffixes(const unsigned K = 0) : KMER_t(K), FreqAffixes() {} friend bool operator < (const KmerFreqAffixes & a, const KmerFreqAffixes & b) { return (static_cast<const KMER_t &>(a) < static_cast<const KMER_t &>(b)); } }; TRIVIALLY_SERIALIZABLE(KmerFreqAffixes<Kmer29>); TRIVIALLY_SERIALIZABLE(KmerFreqAffixes<Kmer60>); TRIVIALLY_SERIALIZABLE(KmerFreqAffixes<Kmer124>); TRIVIALLY_SERIALIZABLE(KmerFreqAffixes<Kmer248>); TRIVIALLY_SERIALIZABLE(KmerFreqAffixes<Kmer504>); template<class KMER_REC_t> class KmerAffixesMapNavigator { typedef typename KMER_REC_t::kmer_type Kmer_t; const KmerMap<KMER_REC_t> & _kmap; Kmer_t _kmer_fw; Kmer_t _kmer_rc; bool _fw; KMER_REC_t _kmer_rec; public: KmerAffixesMapNavigator(const KmerMap<KMER_REC_t> & kmap, const Kmer_t & kmer) : _kmap(kmap), _kmer_fw(kmer), _kmer_rc(reverse_complement(kmer)), _fw(_kmer_fw < _kmer_rc), _kmer_rec(kmap(_fw ? _kmer_fw : _kmer_rc)) { ForceAssert(_kmer_rec.is_valid_kmer()); } KMER_REC_t & rec() const { return _kmer_rec; } Kmer_t & fw() const { return _kmer_fw; } Kmer_t & rc() const { return _kmer_rc; } unsigned n_prefixes() const { return _kmer_rec.n_prefixes(_fw); } unsigned n_suffixes() const { return _kmer_rec.n_suffixes(_fw); } unsigned prefix(unsigned i_pre) const { return _kmer_rec.prefix(i_pre, _fw); } unsigned suffix(unsigned i_suf) const { return _kmer_rec.suffix(i_suf, _fw); } void next_by_prefix(const unsigned i_pre) { ForceAssertLt(i_pre, n_prefixes()); unsigned base_fw = prefix(i_pre); unsigned base_rc = 3u ^ base_fw; _kmer_fw.push_left (base_fw); _kmer_rc.push_right(base_rc); _fw = (_kmer_fw < _kmer_rc); _kmer_rec = _kmap(_fw ? _kmer_fw : _kmer_rc); ForceAssert(_kmer_rec.is_valid_kmer()); } void next_by_suffix(const unsigned i_suf) { ForceAssertLt(i_suf, n_suffixes()); unsigned base_fw = suffix(i_suf); unsigned base_rc = 3u ^ base_fw; _kmer_fw.push_right(base_fw); _kmer_rc.push_left (base_rc); _fw = (_kmer_fw < _kmer_rc); _kmer_rec = _kmap(_fw ? _kmer_fw : _kmer_rc); ForceAssert(_kmer_rec.is_valid_kmer()); } }; /* template<class KMER_t> void navigate_suffixes_up_to(const KMER_t kmer_final_fw, BaseVec * bv_p, const size_t nb_max, const size_t n_branches_max) { if (kmer_final_fw != _kmer_fw && n_branches_max > 0 && bv_p->size() < nb_max) { while (n_suffixes() == 1 && kmer_final_fw != _kmer_fw && bv_p->size() < nb_max) { bv_p.push_back(suffix(0)); next_by_suffix(0); } const unsigned n_suf = n_suffixes(); for (unsigned i_suf = 0; i_suf < n_suf; i_suf++) { BaseVec bv; while (bv.size() < nb_max) { if (n_suffixes() == 0); } } } } */ template<class KMER_REC_t> class AffixesAddProc { typedef typename KMER_REC_t::kmer_type Kmer_t; KmerMap<KMER_REC_t> & _kmap; const size_t _n_threads; const unsigned _verbosity; public: AffixesAddProc(KmerMap<KMER_REC_t> * kmap_p, const size_t n_threads, const unsigned verbosity) : _kmap(*kmap_p), _n_threads(n_threads), _verbosity(verbosity) {} AffixesAddProc(const AffixesAddProc & that) : _kmap(that._kmap), _n_threads(that._n_threads), _verbosity(that._verbosity) {} void operator() (const size_t i_thread) { const size_t nh = _kmap.size_hash(); const size_t ih0 = i_thread * nh / _n_threads; const size_t ih1 = (i_thread + 1) * nh / _n_threads; //cout << "nt= " << _n_threads << " it= " << i_thread << " ih0= " << ih0 << " ih1= " << ih1 << endl; for (size_t ih = ih0; ih < ih1; ih++) { if (i_thread == 0 && _verbosity > 0) dots_pct(ih, ih1); KMER_REC_t & krec0 = _kmap[ih]; if (krec0.is_valid_kmer()) { // ---- search for prefixes { KmerFWRC<Kmer_t> kmerFR(krec0); kmerFR.push_left(0); for (unsigned base = 0; base < 4; base++) { kmerFR.set(0, base); if (_kmap(kmerFR.canonical()).is_valid_kmer()) krec0.set_prefix(base); } } // ---- search for suffixes { const unsigned K = krec0.K(); KmerFWRC<Kmer_t> kmerFR(krec0); kmerFR.push_right(0); for (unsigned base = 0; base < 4; base++) { kmerFR.set(K - 1, base); if (_kmap(kmerFR.canonical()).is_valid_kmer()) krec0.set_suffix(base); } } } } } }; template<class KMER_REC_t> void kmer_freq_affixes_map_build_parallel(const size_t K, const BaseVecVec & bvv, const Validator & validator_kf, const double hash_table_ratio, KmerMap<KMER_REC_t> * kmap_p, const size_t verbosity, const size_t n_threads, const size_t mean_mem_ceil = 0) { const bool do_affixes = false; // ---- build kmer vector with frequencies and affixes vec<KMER_REC_t> kvec; if (do_affixes) { KernelKmerAffixesStorer<KMER_REC_t> storer(bvv, K, &kvec, &validator_kf); naif_kmerize(&storer, n_threads, verbosity, mean_mem_ceil); } else { KernelKmerStorer<KMER_REC_t> storer(bvv, K, &kvec, &validator_kf); naif_kmerize(&storer, n_threads, verbosity, mean_mem_ceil); } if (verbosity > 0) cout << TagKFAM() << setw(14) << kvec.size() << " records found." << endl; // ---- sort kvec by highest kmer frequency // since we are building a chain hash we want to add first the // high frequency kmers so that, when we recall them (which will happen // often) they'll come up first. if (verbosity > 0) cout << TagKFAM() << "Sorting records." << endl; sort(kvec.begin(), kvec.end(), &(kmer_freq_gt<KMER_REC_t>)); // ---- convert from vec<kmer> to hash table if (verbosity > 0) cout << TagKFAM() << "Building " << K << "-mer hash table." << endl; kmap_p->from_kmer_vec(kvec, hash_table_ratio, verbosity); if (!do_affixes) { if (verbosity > 0) cout << TagKFAM() << "Finding affixes in parallel." << endl; AffixesAddProc<KMER_REC_t> adder(kmap_p, n_threads, verbosity); if (n_threads <= 1) adder(0); else parallelFor(0ul,n_threads,adder,n_threads); } if (verbosity > 0) cout << TagKFAM() << "Done building " << K << "-mer hash table." << endl; if (verbosity > 0) kmer_affixes_map_freq_table_print(*kmap_p); //kmer_affixes_map_verify(*kmap_p); } template <class KMER_REC_t> void kmer_freq_affixes_map_build_parallel(const size_t K, const BaseVecVec & bvv, const double hash_table_ratio, KmerMap<KMER_REC_t> * kmap_p, const size_t verbosity, const size_t n_threads, const size_t mean_mem_ceil = 0) { Validator validator_kf; kmer_freq_affixes_map_build_parallel(K, bvv, validator_kf, hash_table_ratio, kmap_p, verbosity, n_threads, mean_mem_ceil); } template <class KMER_REC_t> void kmer_spectrum_from_kmer_freq_map(const KmerMap<KMER_REC_t> & kmap, KmerSpectrum * kspec_p) { const size_t nh = kmap.size_hash(); for (size_t ih = 0; ih != nh; ih++) { const KMER_REC_t & krec = kmap[ih]; if (krec.is_valid_kmer()) { const size_t freq = krec.freq(); if (kspec_p->size() <= freq) kspec_p->resize(freq + 1, 0); (*kspec_p)[freq]++; } } } // ---- print a table of the kmer frequency regarding number of affixes template<class KMER_REC_t> void kmer_affixes_map_freq_table_print(const KmerMap<KMER_REC_t> & kmap) { const size_t nh = kmap.size_hash(); vec<vec<size_t> > n_kmers(5, vec<size_t>(5, 0)); vec<vec<size_t> > kf(5, vec<size_t>(5, 0)); size_t n_kmers_total = 0; for (size_t ih = 0; ih < nh; ih++) { const KMER_REC_t & krec = kmap[ih]; if (krec.is_valid_kmer()) { unsigned n_pre = krec.n_prefixes(); unsigned n_suf = krec.n_suffixes(); n_kmers[n_pre][n_suf]++; n_kmers_total++; kf[n_pre][n_suf] += krec.freq(); } } // ---- output table of flows cout << TagKFAM() << endl; for (size_t n_pre = 0; n_pre <= 4; n_pre++) { cout << TagKFAM() << "n_kmers(" << n_pre << "-" << n_pre << ")= " << setw(10) << n_kmers[n_pre][n_pre] << " (mean_freq= " << setw(6) << kf[n_pre][n_pre] / (n_kmers[n_pre][n_pre] + 1) << ")" << endl; for (size_t n_suf = n_pre + 1; n_suf <= 4; n_suf++) { size_t nk = (n_kmers[n_pre][n_suf] + n_kmers[n_suf][n_pre]); size_t kf2 = (kf[n_pre][n_suf] + kf[n_suf][n_pre]); cout << TagKFAM() << "n_kmers(" << n_pre << "-" << n_suf << ")= " << setw(10) << nk << " (mean_freq= " << setw(6) << kf2 / (nk + 1) << ")" << endl; } cout << TagKFAM() << endl; } cout << TagKFAM() << "n_kmers(tot)= " << setw(10) << n_kmers_total << endl; cout << TagKFAM() << endl; } template<class KMER_REC_t> void kmer_affixes_vec_freq_table_print(const vec<KMER_REC_t> & kvec) { const size_t nh = kvec.size(); vec<vec<size_t> > n_kmers(5, vec<size_t>(5, 0)); vec<vec<size_t> > kf(5, vec<size_t>(5, 0)); size_t n_kmers_total = 0; for (size_t ih = 0; ih < nh; ih++) { const KMER_REC_t & krec = kvec[ih]; unsigned n_pre = krec.n_prefixes(); unsigned n_suf = krec.n_suffixes(); n_kmers[n_pre][n_suf]++; n_kmers_total++; kf[n_pre][n_suf] += krec.freq(); } // ---- output table of flows cout << TagKFAM() << endl; for (size_t n_pre = 0; n_pre <= 4; n_pre++) { cout << TagKFAM() << "n_kmers(" << n_pre << "-" << n_pre << ")= " << setw(10) << n_kmers[n_pre][n_pre] << " (mean_freq= " << setw(6) << kf[n_pre][n_pre] / (n_kmers[n_pre][n_pre] + 1) << ")" << endl; for (size_t n_suf = n_pre + 1; n_suf <= 4; n_suf++) { size_t nk = (n_kmers[n_pre][n_suf] + n_kmers[n_suf][n_pre]); size_t kf2 = (kf[n_pre][n_suf] + kf[n_suf][n_pre]); cout << TagKFAM() << "n_kmers(" << n_pre << "-" << n_suf << ")= " << setw(10) << nk << " (mean_freq= " << setw(6) << kf2 / (nk + 1) << ")" << endl; } cout << TagKFAM() << endl; } cout << TagKFAM() << "n_kmers(tot)= " << setw(10) << n_kmers_total << endl; cout << TagKFAM() << endl; } // ---- Makes sure that the affixes make sense template<class KMER_REC_t> void kmer_freq_affixes_map_verify(const KmerMap<KMER_REC_t> & kmap) { typedef typename KMER_REC_t::kmer_type Kmer_t; const size_t nh = kmap.size_hash(); size_t n_aff = 0; size_t n_aff_exist = 0; for (size_t ih = 0; ih != nh; dots_pct(ih++, nh)) { const KMER_REC_t & krec0 = kmap[ih]; if (krec0.is_valid_kmer()) { unsigned n_pres = krec0.n_prefixes(); unsigned n_sufs = krec0.n_suffixes(); // ---- look at prefixes for (unsigned i = 0; i != n_pres; i++) { n_aff++; KmerFWRC<Kmer_t> kmerFR(krec0); kmerFR.push_left(krec0.prefix(i)); if (kmap(kmerFR.canonical()).is_valid_kmer()) n_aff_exist++; } for (unsigned i = 0; i != n_sufs; i++) { n_aff++; KmerFWRC<Kmer_t> kmerFR(krec0); kmerFR.push_right(krec0.suffix(i)); if (kmap(kmerFR.canonical()).is_valid_kmer()) n_aff_exist++; } } } cout << "n_affixes= " << n_aff << endl << "n_found = " << n_aff_exist << endl; } template<class KMER_REC_t> void base_vec_extension(const unsigned K, const KmerMap<KMER_REC_t> & kmap, const BaseVec & bv, const unsigned nb_extra, BaseVec * bv_extra_p, const bool get_pre) { typedef typename KMER_REC_t::kmer_type Kmer_t; const size_t nb = bv.size(); bv_extra_p->clear(); SubKmers<BaseVec, Kmer_t> sub_kmer0(K, bv, get_pre ? 0 : nb - K); const Kmer_t kmer0 = get_pre ? sub_kmer0.rc() : sub_kmer0.fw(); for (size_t i = 0; i < K; i++) bv_extra_p->push_back(kmer0[i]); KmerAffixesMapNavigator<KMER_REC_t> knav(kmap, kmer0); // get_pre = true => follow suffixes of RC of first kmer // get_pre = false => follow suffixes of FW of last kmer while (bv_extra_p->size() < K + nb_extra && knav.n_suffixes() == 1) { bv_extra_p->push_back(knav.suffix(0)); knav.next_by_suffix(0); } } template<class KMER_REC_t> void base_vec_extensions_compute(const unsigned K, const KmerMap<KMER_REC_t> & kmap, const BaseVecVec bvv_in, BaseVecVec * bvv_adj_p, const unsigned nb_extra) { typedef typename KMER_REC_t::kmer_type Kmer_t; const size_t nbv = bvv_in.size(); for (size_t ibv = 0; ibv < nbv; ibv++) { const BaseVec & bv_in = bvv_in[ibv]; // ---- find prefix extension BaseVec bv_pre; base_vec_extension(K, kmap, bv_in, nb_extra, &bv_pre, true); if (bv_pre.size() == K + nb_extra) bvv_adj_p->push_back(bv_pre); // ---- find suffix extension BaseVec bv_suf; base_vec_extension(K, kmap, bv_in, nb_extra, &bv_suf, false); if (bv_suf.size() == K + nb_extra) bvv_adj_p->push_back(bv_suf); } } #endif
00b1646922534b86bbc0eaf7d9715a9de8247c82
f4908233b0dcd8dbd1829d3c8d60d62fe6e6ff93
/billboards.cpp
2be772684d286f13ce1c56c8f5b09b457b07c223
[]
no_license
sachiin/algo-codes
2114b25f9c811814cce1172d10f47638fed5901f
3507099b5a3393a1261a77297c958d8abc0600a5
refs/heads/master
2021-01-17T05:21:00.891821
2013-06-03T20:21:09
2013-06-03T20:21:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
725
cpp
#include<iostream> using namespace std; #include<cstdio> #include<vector> #include<algorithm> #include<climits> int main() { int N,K; cin >> N >> K; long long m; vector<long long> arr; for(int i =0;i<N;i++) { cin >> m; arr.push_back(m); } //vector<vector<long long > >dp(N+1,vector<long long>(K+1,0)); vector<long long> dp1(K+1,0); vector<long long> dp2(K+1,0); for(int i = 1;i<=N;i++) { long long maxval =-1; for(int j = 0;j<=K;j++) { if(maxval < dp2[j]) maxval = dp2[j]; } dp1[0] = maxval; for(int j=1;j<=min(i,K);j++) { dp1[j] = dp2[j-1]+arr[i-1]; } for(int j=0;j<=K;j++) { dp2[j] = dp1[j]; } } long long maxval = 0; for(int i =0;i<=K;i++) { if(maxval < dp2[i]) maxval = dp2[i]; } cout << maxval <<endl; return 0; }
d22985714b829204e3c7f16fb74e7e66dcaa0990
46412e20a683a80f6b7462dc12fb6d38a6da4b5d
/hardware/arduino_slave/arduino_slave.ino
a1882e3b964f06813db2a5f5e297e395d5788069
[]
no_license
sattarovvadim/iotmeetup
db09da9a09601879bce110a2755abd81000ba59f
acf9c7e96d48d8661281092cc634985e9c204f14
refs/heads/master
2022-12-15T05:35:24.074401
2020-08-19T16:33:12
2020-08-19T16:33:12
288,719,621
2
0
null
null
null
null
UTF-8
C++
false
false
4,542
ino
#include <Wire.h> #include <ArduinoJson.h> #include <Servo.h> #include "defines.h" // Номера пинов исполнительных узлов #define PIN_IN_PIR_DETECT 2 #define PIN_OUT_SIMPLE_LED 4 #define PIN_OUT_220V_SOCK 3 #define PIN_IN_IS_LIGHT 5 #define PIN_OUT_SONIC_TRIG 8 // Trig дальномера #define PIN_IN_SONIC_ECHO 9 // Echo дальномера #define PIN_IN_BARRIER 6 #define PIN_OUT_SERVO 7 #define PIN_IN_POTENT 3 // аналоговый вход A3 #define PIN_IN_TEMPER 1 // аналоговый вход A2 Servo servo; int potent = 0; void setup() { Wire.begin(I2C_ARDUINO_ADDRESS); /* присоединиться к шине i2c с указанным адресом */ Wire.onReceive(receiveEvent); /* зарегистрировать колбек при получении события из шины */ Wire.onRequest(requestEvent); /* зарегистрировать колбек при получении запроса из шины */ Serial.begin(115200); /* открыть порт для отладки */ pinMode(PIN_OUT_SIMPLE_LED, OUTPUT); pinMode(PIN_OUT_220V_SOCK, OUTPUT); digitalWrite(PIN_OUT_220V_SOCK, HIGH); pinMode(PIN_IN_IS_LIGHT, INPUT); pinMode(PIN_OUT_SONIC_TRIG, OUTPUT); pinMode(PIN_IN_SONIC_ECHO, INPUT); pinMode(PIN_IN_PIR_DETECT, INPUT); pinMode(PIN_IN_BARRIER, INPUT); servo.attach(PIN_OUT_SERVO); servo.write(0); } void loop() { potent = map(analogRead(PIN_IN_POTENT), 0, 1023, 0, 100); } // колбек-обработчик при получении данных из шины I2C void receiveEvent(int howMany) { String data = ""; while (0 < Wire.available()) { char c = Wire.read(); data += c; } Serial.println(data); parseCommand(data); } void parseCommand(String &input) { StaticJsonDocument<jsonCapacity> doc; DeserializationError err = deserializeJson(doc, input); if (err) { Serial.print("deserializeJson() failed with code "); Serial.println(err.c_str()); return; } JsonObject root = doc.as<JsonObject>(); char command = 0; int value = 0; for (JsonPair kv : root) { value = kv.value().as<int>(); Serial.println(kv.key().c_str()); Serial.println(value); if (command = nodes_list.set_value(kv.key().c_str(), value)) { processCommand(command, value); } } } void processCommand(char command, int value) { Serial.println("command"); Serial.println(command); switch (command) { case 1: digitalWrite(PIN_OUT_SIMPLE_LED, value ? HIGH : LOW); break; case 2: digitalWrite(PIN_OUT_220V_SOCK, value ? LOW : HIGH); break; case 3: servo.write(value); } } void requestEvent() { readInputs(); char buffer[numNodes]; nodes_list.get_values(buffer); Wire.write(buffer, numNodes); } void readInputs() { nodes_list.set_value(101, !digitalRead(PIN_IN_IS_LIGHT)); nodes_list.set_value(102, potent); nodes_list.set_value(103, read_distance_cm()); nodes_list.set_value(104, digitalRead(PIN_IN_PIR_DETECT)); nodes_list.set_value(105, !digitalRead(PIN_IN_BARRIER)); nodes_list.set_value(106, read_temper()); } int read_distance_cm() { int impulseTime = 0; digitalWrite(PIN_OUT_SONIC_TRIG, LOW); // Убираем импульс delayMicroseconds(2); // для лучшего измерения digitalWrite(PIN_OUT_SONIC_TRIG, HIGH); // Подаем импульс на вход trig дальномера delayMicroseconds(10); // Импульс длится 10 микросекунд digitalWrite(PIN_OUT_SONIC_TRIG, LOW); // Отключаем подачу импульса impulseTime = pulseIn(PIN_IN_SONIC_ECHO, HIGH); // Принимаем импульс и подсчитываем его длину return impulseTime / 58; // 58 это преобразование из длины импульса микросекундах в сантиметры } int read_temper() { int val = analogRead(PIN_IN_TEMPER); // Данные, полученные с установленного термистора // 590 - 0 // 470 - 23 - эксперимент // 400 - 36.6 - эксперимент // 100 - 95 - эксперимент // 75 - 100 // 5,2 единицы АЦП - на один градус Цельсия Serial.println(val); // return map(val, 75, 590, 100, 0); return map(val, 100, 400, 95, 37); }
8eff97d98c211c264b25689e56cb3d02f51a86ca
c49ea222f9c12b4bc5a318cef0edde7bd80ee289
/BankingSystemV2/LoginForm.cpp
2e2e6dfaabdab75913b97b81a43918c10c007a05
[]
no_license
bradbow/BankingSystem
042179adb46b375abddd0166e344fed666ff44f2
36d4128e3ff613f3424d1a28d6e9f2cb9cd6b3e9
refs/heads/master
2021-01-01T18:06:38.370763
2011-10-30T13:10:50
2011-10-30T13:10:50
2,629,659
2
0
null
null
null
null
UTF-8
C++
false
false
44
cpp
#include "StdAfx.h" #include "LoginForm.h"
2c045ea13640c538c36c641833d529bdc993d0c7
0a83e23b76d18a7dd7fc403b058bbb2bd7444a05
/cli.hpp
13a2da52df96932810978fcd86daa7d4045a3bb2
[]
no_license
orycohen/hole_filling
6af4b0208d4aa1699f425315c56044dc58c94350
8fb5a0fce4c708eb6d5436b7fe4945892ca5c029
refs/heads/master
2022-11-04T17:59:29.742695
2020-06-15T19:29:11
2020-06-15T19:29:11
272,522,048
0
0
null
null
null
null
UTF-8
C++
false
false
313
hpp
#ifndef cli_hpp #define cli_hpp #include <opencv2/opencv.hpp> // This funtion has the responsibility of printing the prompt void printPrompt(); // This function is given a command to execute int executeCommand(char *command); // A small welcome message and explaination. void welcome(); #endif /* cli_hpp */
69e4a3448126b94087f6400d38dd32516642656f
15f2d5148f302f2ba716b49cc14ea6dec0fed98c
/msl_expressions/autogenerated/include/Plans/Standards/Own/constraints/OwnStdSingleRobot1467383326416Constraints.h
dbea6640841a61d8f1ebdacfc10d24c9019f874e
[ "MIT" ]
permissive
dasys-lab/cnc-msl
20937039153e3335d36d2c45ac354bee471534e0
e55f40a0baebc754283f5cf130c36e31abf8ee64
refs/heads/master
2021-09-28T18:59:18.962448
2018-05-07T13:47:33
2018-05-07T13:47:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
345
h
#ifndef OwnStdSingleRobotCONSTRAINT_H_ #define OwnStdSingleRobot_H_ #include "engine/BasicConstraint.h" #include <memory> using namespace std; using namespace alica; namespace alica { class ConstraintDescriptor; class RunningPlan; } namespace alicaAutogenerated { } /* namespace alica */ #endif /* OwnStdSingleRobotCONSTRAINT_H_ */
e50d856feb31ce67d59c187973ed1f17c298b154
8cbc8bf55e9b5cff587aab2d551b7540d5668b7c
/Kernel/JVM/internal/JavaClassFileParser.cpp
c3f170b822d001e8755bd6e363d2287c47a1acce
[]
no_license
mailmindlin/All-The-Mice
d07114c9bc4558572210dada9dd205aeccfd89c7
0757179f50b02462558d40e0c79d134533884f1e
refs/heads/master
2016-09-16T17:18:11.471930
2016-05-06T13:00:19
2016-05-06T13:00:19
42,206,622
1
0
null
2015-09-26T00:28:01
2015-09-09T21:48:02
C
UTF-8
C++
false
false
5,835
cpp
#include "JavaClassFileParser.h" #include <JVM/JavaClass.hpp> #include <JVM/ConstantPoolType.h> namespace JVM { static inline uint32_t get4(void*& p) { uint32_t result = *(reinterpret_cast<uint32_t*>(p)); p += 4; return result; } static inline uint16_t get2(void*& p) { uint16_t result = *(reinterpret_cast<uint16_t*>(p)); p += 2; return result; } bool JavaClassFileParser::parseInterfaces(uint16_t*& interfaces, void*& data, size_t numInterfaces) { if (interfaces == NULL) return false; for(int i = 0; i < numInterfaces; i++) interfaces[i] = get2(data); } bool JavaClassFileParser::parseConstantPool(cp_info**& pool, void*& data, size_t numConstants) { if(constant_pool == NULL) return false; //Why does it start @ i=1? for(int i=1; i<numConstants; i++) { pool[i] = reinterpret_cast<cp_info*>(data); uint8_t tag = pool[i]->tag; unsigned int size = getConstantSizeByType(tag); data+= size; //printf("Constant pool %d type %d\n",i,(u1)constant_pool[i]->tag); if(isWideCpType(tag) { pool[i + 1] = NULL; i++; } } return TRUE; } bool JavaClassFileParser::parseFields(JavaField*& fields, void*& data, size_t numFields) { if (fields == NULL) return false; for(int i = 0; i < numFields; i++) { fields[i].modifiers = get2(data); fields[i].name_index = get2(data); fields[i].descriptor_index = get2(data); fields[i].attributes_count = get2(data); if(fields[i].attributes_count>0) { //skip attributes - we do not need in simple cases for(int a=0; a<fields[i].attributes_count; a++) { uint16_t name_index = get2(data); //printf("Attribute name index = %d\n", name_index); uint32_t len = get4(data); data+= len; } } } return true; } bool JavaClassFileParser::parseMethods(method_info_ref*& methods, void*& data, size_t numMethods) { if (methods == NULL) return false; for(int i = 0; i < numMethods; i++) { methods[i]->base = reinterpret_cast<method_info*>(data); method_info& method = methods[i]; method.modifiers = get2(data); method.name_index = get2(data); method.descriptor_index = get2(data); method.attributes_count = get2(data); //CString strName, strDesc; //GetStringFromConstPool(methods[i].name_index, strName); //GetStringFromConstPool(methods[i].descriptor_index, strDesc); //wprintf(_T("Method = %s%s\n"),strName, strDesc); //printf("Method has total %d attributes\n",methods[i].attributes_count); if(method->attributes_count > 0) { method.code = new Code_attribute; //skip attributes for(int a = 0; a < method->attributes_count; a++) { uint16_t name_index = get2(p); String* name = lookupAttr(name_index);//TODO fix //TODO is there a better way to do this? (maybe compare the indecies?) if (name->equalsIgnoreCase("Code", 4)) { //TODO finish porting char* ca = reinterpret_cast<char*>(p); method.codeRef->attribute_name_index=name_index;//already scanned; method.codeRef->attribute_length = get4(ca); method.codeRef->max_stack = get2(ca); pCode_attr->max_locals=get2(ca); pCode_attr->code_length=get4(ca); if(pCode_attr->code_length>0) { pCode_attr->code = new u1[pCode_attr->code_length]; memcpy(pCode_attr->code,ca, pCode_attr->code_length); /* printf("\nCODE\n"); for(u4 i=0;i<pCode_attr->code_length;i++) printf("%d ", pCode_attr->code[i]); printf("\nENDCODE\n"); */ } else { // may be native code ?? method->codeRef->code=NULL; } ca+=pCode_attr->code_length; pCode_attr->exception_table_length = getu2(ca);ca+=2; if(pCode_attr->exception_table_length > 0) { pCode_attr->exception_table = new Exception_table[pCode_attr->exception_table_length]; for(int ext= 0; ext<pCode_attr->exception_table_length; ext++) { pCode_attr->exception_table[ext].start_pc = getu2(ca); ca+=2; pCode_attr->exception_table[ext].end_pc = getu2(ca); ca+=2; pCode_attr->exception_table[ext].handler_pc = getu2(ca); ca+=2; pCode_attr->exception_table[ext].catch_type = getu2(ca); ca+=2; } } } //printf("Attribute name index = %d\n", name_index); uint32_t len = get4(p); p+= len; } } } } bool JavaClassFileParser::parseClass(JavaClassFile*& clazz, void*& data, size_t len) { if (data == NULL || len < sizeof(JavaClassFile) + 20) return false; void* p = data; if ((file.magic = get4(p)) != 0xCAFEBABE) return false; clazz->minor = get2(p); clazz->major = get2(p); if ((clazz->constantPoolSize = get2(p)) > 0) { clazz->constantPool = new cp_info*[clazz->constantPoolSize - 1]; parseConstantPool(clazz->constantPool, p, clazz->constantPoolSize); } else { clazz->constantPool = NULL; } clazz->modifiers = get2(p); clazz->this_class = get2(p); clazz->super_class = get2(p); if ((clazz->numInterfaces = get2(p)) > 0) { clazz->interfaces = new uint16_t[clazz->numInterfaces]; parseInterfaces(clazz->interfaces, p, clazz->numInterfaces); } else { clazz->interfaces = NULL; } if ((clazz->numFields = get2(p)) > 0) { clazz->fields = new JavaField*[clazz->numFields]; parseFields(clazz->fields, p, clazz->numFields); } else { clazz->fields = NULL; } //parse methods if ((clazz->numMethods = get2(p)) > 0) { clazz->methods = new method_info[clazz->numMethods]; parseMethods(clazz->methods, p, clazz->numMethods); } else { clazz->methods = NULL; } if ((clazz->numAttributes = get2(p)) > 0) { clazz->attributes = new attribute_info[clazz->numAttributes]; parseAttributes(clazz->attributes, p, clazz->numAttributes); } else { clazz->attributes = NULL; } return true; } }
0aa1d3fa3f09e66ef13c1f0ce020768fa06cc4bb
c30c3466c34c41b49e8c8b2791e0d44ae6277cb2
/Voronoi Villages/src.cpp
18c027d95a62629f83ef54dfc92addd266119db8
[]
no_license
theAnton-forks/Competitive-Programming-Portfolio
784eb9ff5441f1a81f5501d690f9094698bc34c7
fb3f099d7ecc37b9117d64faa4c1bdf89e1f18d2
refs/heads/master
2022-12-14T03:18:04.941318
2020-09-03T05:22:46
2020-09-03T05:22:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
428
cpp
#include <bits/stdc++.h> typedef long long ll; const int maxn = 1e6 + 1e2; int val[maxn]; int res = 2000000000; int main(){ std::ios::sync_with_stdio(false); int n; std::cin >> n; for(int i = 0; i < n; i++){ std::cin >> val[i]; } std::sort(val, val + n); for(int i = 1; i < n - 1; i++){ res = std::min(res, val[i + 1] - val[i - 1]); } std::cout.precision(1); std::cout << std::fixed << res / 2.0 << '\n'; }
faac80a8063818cc7bd76b25f95ee7d79c5081c9
38b9daafe39f937b39eefc30501939fd47f7e668
/tutorials/2WayCouplingOceanWave3D/EvalResults180628-Eta-ux-uy/26.4/uniform/time
045b77ebeab1324cd11f358ac0c7d95a9fa37f70
[]
no_license
rubynuaa/2-way-coupling
3a292840d9f56255f38c5e31c6b30fcb52d9e1cf
a820b57dd2cac1170b937f8411bc861392d8fbaa
refs/heads/master
2020-04-08T18:49:53.047796
2018-08-29T14:22:18
2018-08-29T14:22:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,005
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 3.0.1 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "26.4/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 26.4000000000000021; name "26.4"; index 2950; deltaT 0.00732601; deltaT0 0.00732601; // ************************************************************************* //
8158e9f1758d6f952fb644477a55fa82de327f1f
785df77400157c058a934069298568e47950e40b
/applications/tools/discrete/curveList2d/curveList2d.cxx
86cafe4ee37d1880f96ef97eac77381258f27ee3
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
6,938
cxx
#include <Entity2d_Polygon.hxx> #include <Entity2d_Box.hxx> #include <Geo_ApprxCurve_System.hxx> #include <Geo2d_ApprxCurve.hxx> #include <Pln_Curve.hxx> #include <Global_Timer.hxx> #include <boost/archive/polymorphic_binary_iarchive.hpp> #include <boost/archive/polymorphic_binary_oarchive.hpp> #include <boost/archive/polymorphic_text_iarchive.hpp> #include <boost/archive/polymorphic_text_oarchive.hpp> #include <Geom2d_Curve.hxx> #include <vector> namespace tnbLib { auto& appxInfo = sysLib::gl_approx_curve2d_info; typedef std::shared_ptr<Pln_Curve> curve_t; typedef std::shared_ptr<Geo_ApprxCurve<Handle(Geom2d_Curve), true>> randAppx_t; typedef std::shared_ptr<Geo_ApprxCurve<Handle(Geom2d_Curve), false>> uniAppx_t; typedef std::shared_ptr<Entity2d_Polygon> poly_t; static std::vector<curve_t> myCurves; static std::vector<poly_t> myPolygons; static double d; static bool randPnt = true; static bool verbose = false; static randAppx_t myRandAppx; static uniAppx_t myUniAppx; void setTarget(double x) { appxInfo->SetApprox(x*d); } void setAngle(double x) { appxInfo->SetAngle(x); } void setMinSize(double x) { appxInfo->SetMinSize(x*d); } void setMaxNbSubdivision(int n0) { auto n = std::max(1, n0); appxInfo->SetMaxNbSubdivision(n); } void setInitNbSubdivision(int n0) { auto n = std::max(1, n0); appxInfo->SetInitNbSubdivision(n); } void setNbSamples(int n0) { auto n = std::max(1, n0); appxInfo->SetNbSamples(n); } void printInfo() { Info << " - nb. of samples: " << appxInfo->NbSamples() << endl; Info << " - nb. of initial subdivisions: " << appxInfo->InitNbSubdivision() << endl; Info << " - max. nb. of subdivisions: " << appxInfo->MaxNbSubdivision() << endl; Info << " - target size: " << appxInfo->Approx() << endl; Info << " - min. size: " << appxInfo->MinSize() << endl; Info << " - angle: " << appxInfo->Angle() << endl; Info << " - diameter: " << d << endl; } void execute(const curve_t& myCurve) { if (randPnt) { Global_Timer timer; timer.SetInfo(Global_TimerInfo_ms); myRandAppx = std::make_shared<Geo_ApprxCurve<Handle(Geom2d_Curve), true>> ( myCurve->Geometry(), myCurve->FirstParameter(), myCurve->LastParameter(), appxInfo ); myRandAppx->Perform(); myUniAppx = nullptr; myPolygons.push_back(myRandAppx->Chain()); } else { Global_Timer timer; timer.SetInfo(Global_TimerInfo_ms); myUniAppx = std::make_shared<Geo_ApprxCurve<Handle(Geom2d_Curve), false>> ( myCurve->Geometry(), myCurve->FirstParameter(), myCurve->LastParameter(), appxInfo ); myUniAppx->Perform(); myRandAppx = nullptr; myPolygons.push_back(myUniAppx->Chain()); } if (verbose) { Info << endl; Info << " - time estimation: " << global_time_duration << " ms" << endl; Info << endl; if (myRandAppx) { Info << " - nb. of points: " << myRandAppx->Chain()->NbPoints() << endl; } if (myUniAppx) { Info << " - nb. of points: " << myUniAppx->Chain()->NbPoints() << endl; } } } void execute() { if (verbose) { printInfo(); } Global_Timer timer; timer.SetInfo(Global_TimerInfo_ms); for (const auto& x : myCurves) { Debug_Null_Pointer(x); execute(x); } if (verbose) { Info << endl; Info << " - total time estimation: " << global_time_duration << " ms" << endl; Info << endl; } } void estimateD() { auto iter = myCurves.begin(); auto box = (*iter)->BoundingBox(0); iter++; while (iter NOT_EQUAL myCurves.end()) { box = Entity2d_Box::Union(box, (*iter)->BoundingBox(0)); iter++; } d = box.Diameter(); } void loadCurves(const std::string& name) { fileName fn(name); std::fstream file; file.open(fn, ios::in); if (file.fail()) { FatalErrorIn(FunctionSIG) << "file was not found" << endl << abort(FatalError); } boost::archive::polymorphic_text_iarchive ia(file); ia >> myCurves; if (NOT myCurves.size()) { FatalErrorIn(FunctionSIG) << "the curve is null" << endl << abort(FatalError); } for (const auto& x : myCurves) { if (NOT x) { FatalErrorIn(FunctionSIG) << "null curve has been detected!" << endl << abort(FatalError); } } estimateD(); } void exportToPlt(const std::string& name) { fileName fn(name); OFstream f(fn); for (const auto& x : myPolygons) { if (x) { x->ExportToPlt(f); } } } } #ifdef DebugInfo #undef DebugInfo #endif // DebugInfo #include <chaiscript/chaiscript.hpp> namespace tnbLib { typedef std::shared_ptr<chaiscript::Module> module_t; void setGlobals(const module_t& mod) { mod->add(chaiscript::fun([](double x)-> void {setAngle(x); }), "setAngle"); mod->add(chaiscript::fun([](double x)-> void {setTarget(x); }), "setTarget"); mod->add(chaiscript::fun([](double x)-> void {setMinSize(x); }), "setMinSize"); mod->add(chaiscript::fun([](int n)-> void {setMaxNbSubdivision(n); }), "setMaxNbSubdivision"); mod->add(chaiscript::fun([](int n)-> void {setInitNbSubdivision(n); }), "setInitNbSubdivision"); mod->add(chaiscript::fun([](int n)-> void {setNbSamples(n); }), "setNbSamples"); mod->add(chaiscript::fun([](bool v)-> void {verbose = v; }), "setVerbose"); mod->add(chaiscript::fun([](const std::string& name)-> void {loadCurves(name); }), "loadCurves"); mod->add(chaiscript::fun([]()-> void {execute(); }), "execute"); mod->add(chaiscript::fun([](const std::string& name)-> void {exportToPlt(name); }), "exportToPlt"); } std::string getString(char* argv) { std::string argument(argv); return std::move(argument); } Standard_Boolean IsEqualCommand(char* argv, const std::string& command) { auto argument = getString(argv); return argument IS_EQUAL command; } } using namespace tnbLib; int main(int argc, char *argv[]) { FatalError.throwExceptions(); //Cad2d_RemoveNonManifold::verbose = 1; if (argc <= 1) { Info << " - No command is entered" << endl << " - For more information use '--help' command" << endl; FatalError.exit(); } if (argc IS_EQUAL 2) { if (IsEqualCommand(argv[1], "--help")) { Info << "this is help" << endl; } else if (IsEqualCommand(argv[1], "--run")) { chaiscript::ChaiScript chai; auto mod = std::make_shared<chaiscript::Module>(); setGlobals(mod); chai.add(mod); std::string address = ".\\system\\TnbCurvesDiscretizer2d"; fileName myFileName(address); try { chai.eval_file(myFileName); } catch (const chaiscript::exception::eval_error& x) { Info << x.pretty_print() << endl; } catch (const error& x) { Info << x.message() << endl; } catch (const std::exception& x) { Info << x.what() << endl; } } } else { Info << " - No valid command is entered" << endl << " - For more information use '--help' command" << endl; FatalError.exit(); } }
d102592c800e05bde7e119b802f86c66eaec41dd
dbd9dc5fb92e66281c5e4a00e4b44551afebe630
/Practica para PC1/CSatelite.hpp
5599e7ad889610b59dbcddaf8faf08f3855ff2c2
[]
no_license
Diego04s03/PROGRAMACION-II
118e8ab84ae487631e416d68e055a183d36609ce
b5fbb753cd8297d6724f6d15513749898c57f79f
refs/heads/main
2023-04-03T09:53:41.436052
2021-04-15T14:40:04
2021-04-15T14:40:04
352,253,193
3
0
null
null
null
null
UTF-8
C++
false
false
334
hpp
#pragma once #include<iostream> using namespace System; using namespace std; class Satelite { public: Satelite(); ~Satelite(); void mover(int,int); void pintar(); void borrar(); void setX(int); void setY(int); void setDX(int); void setDY(int); void setModelo(char); private: int x, y; int dx, dy; char modelo; };
0943c82eae313187ad9b69b9fe201c670a6913ce
1754c9ca732121677ac6a9637db31419d32dbcf1
/dependencies/libsbml-vs2017-release-32/include/sbml/CompartmentType.h
447d54fe4a4fa8bcb45bf1c8d7ddb26cbf38bce7
[ "BSD-2-Clause" ]
permissive
sys-bio/Libstructural
1701e239e3f4f64674b86e9e1053e9c61fe868a7
fb698bcaeaef95f0d07c010f80c84d2cb6e93793
refs/heads/master
2021-09-14T17:54:17.538528
2018-05-16T21:12:24
2018-05-16T21:12:24
114,693,721
3
1
null
2017-12-18T22:25:11
2017-12-18T22:25:10
null
UTF-8
C++
false
false
33,126
h
/** * @file CompartmentType.h * @brief Definitions of CompartmentType and ListOfCompartmentTypes. * @author Ben Bornstein * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2013-2017 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright (C) 2006-2008 by the California Institute of Technology, * Pasadena, CA, USA * * Copyright (C) 2002-2005 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. Japan Science and Technology Agency, Japan * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ------------------------------------------------------------------------ --> * * @class CompartmentType * @sbmlbrief{core} A <em>compartment type</em> in SBML Level&nbsp;2. * * SBML Level&nbsp;2 Versions&nbsp;2&ndash;4 provide the <em>compartment * type</em> as a grouping construct that can be used to establish a * relationship between multiple Compartment objects. A CompartmentType * object only has an identity, and this identity can only be used to * indicate that particular Compartment objects in the model belong to this * type. This may be useful for conveying a modeling intention, such as * when a model contains many similar compartments, either by their * biological function or the reactions they carry. Without a compartment * type construct, it would be impossible within SBML itself to indicate * that all of the compartments share an underlying conceptual relationship * because each SBML compartment must be given a unique and separate * identity. A CompartmentType has no mathematical meaning in * SBML---it has no effect on a model's mathematical interpretation. * Simulators and other numerical analysis software may ignore * CompartmentType definitions and references to them in a model. * * There is no mechanism in SBML Level 2 for representing hierarchies of * compartment types. One CompartmentType instance cannot be the subtype * of another CompartmentType instance; SBML provides no means of defining * such relationships. * * As with other major structures in SBML, CompartmentType has a mandatory * attribute, "id", used to give the compartment type an identifier. The * identifier must be a text %string conforming to the identifer syntax * permitted in SBML. CompartmentType also has an optional "name" * attribute, of type @c string. The "id" and "name" must be used * according to the guidelines described in the SBML specification (e.g., * Section 3.3 in the Level 2 Version 4 specification). * * CompartmentType was introduced in SBML Level 2 Version 2. It is not * available in SBML Level&nbsp;1 nor in Level&nbsp;3. * * @see Compartment * @see ListOfCompartmentTypes * @see SpeciesType * @see ListOfSpeciesTypes * * * <!-- ------------------------------------------------------------------- --> * @class ListOfCompartmentTypes * @sbmlbrief{core} A list of CompartmentType objects. * * @copydetails doc_what_is_listof */ #ifndef CompartmentType_h #define CompartmentType_h #include <sbml/common/extern.h> #include <sbml/common/sbmlfwd.h> #include <sbml/SBase.h> #include <sbml/ListOf.h> #ifdef __cplusplus #include <string> LIBSBML_CPP_NAMESPACE_BEGIN class SBMLVisitor; class LIBSBML_EXTERN CompartmentType : public SBase { public: /** * Creates a new CompartmentType object using the given SBML @p level and * @p version values. * * @param level an unsigned int, the SBML Level to assign to this * CompartmentType. * * @param version an unsigned int, the SBML Version to assign to this * CompartmentType. * * @copydetails doc_throw_exception_lv * * @copydetails doc_note_setting_lv */ CompartmentType (unsigned int level, unsigned int version); /** * Creates a new CompartmentType object using the given SBMLNamespaces * object @p sbmlns. * * @copydetails doc_what_are_sbmlnamespaces * * It is worth emphasizing that although this constructor does not take an * identifier argument, in SBML Level&nbsp;2 and beyond, the "id" * (identifier) attribute of a CompartmentType object is required to have a * value. Thus, callers are cautioned to assign a value after calling this * constructor. Setting the identifier can be accomplished using the * method setId(@if java String@endif). * * @param sbmlns an SBMLNamespaces object. * * @copydetails doc_throw_exception_namespace * * @copydetails doc_note_setting_lv */ CompartmentType (SBMLNamespaces* sbmlns); /** * Destroys this CompartmentType object. */ virtual ~CompartmentType (); /** * Copy constructor; creates a copy of this CompartmentType object. * * @param orig the object to copy. */ CompartmentType(const CompartmentType& orig); /** * Assignment operator for CompartmentType. * * @param rhs the object whose values are used as the basis of the * assignment. */ CompartmentType& operator=(const CompartmentType& rhs); /** @cond doxygenLibsbmlInternal */ /** * Accepts the given SBMLVisitor for this instance of CompartmentType. * * @param v the SBMLVisitor instance to be used. * * @return the result of calling <code>v.visit()</code>, which indicates * whether the Visitor would like to visit the next CompartmentType object in * the list of compartment types. */ virtual bool accept (SBMLVisitor& v) const; /** @endcond */ /** * Creates and returns a deep copy of this CompartmentType object. * * @return the (deep) copy of this CompartmentType object. */ virtual CompartmentType* clone () const; /** * Returns the value of the "id" attribute of this CompartmentType. * * @note Because of the inconsistent behavior of this function with * respect to assignments and rules, it is now recommended to * use the getIdAttribute() function instead. * * @copydetails doc_id_attribute * * @return the id of this CompartmentType. * * @see getIdAttribute() * @see setIdAttribute(const std::string& sid) * @see isSetIdAttribute() * @see unsetIdAttribute() */ virtual const std::string& getId () const; /** * Returns the value of the "name" attribute of this CompartmentType object. * * @copydetails doc_get_name */ virtual const std::string& getName () const; /** * Predicate returning @c true if this CompartmentType object's "id" * attribute is set. * * @copydetails doc_isset_id */ virtual bool isSetId () const; /** * Predicate returning @c true if this CompartmentType object's "name" * attribute is set. * * @copydetails doc_isset_name */ virtual bool isSetName () const; /** * Sets the value of the "id" attribute of this CompartmentType. * * @copydetails doc_set_id */ virtual int setId(const std::string& sid); /** * Sets the value of the "name" attribute of this CompartmentType. * * @copydetails doc_set_name */ virtual int setName (const std::string& name); /** * Unsets the value of the "name" attribute of this CompartmentType object. * * @copydetails doc_unset_name */ virtual int unsetName (); /** * Returns the libSBML type code for this SBML object. * * @copydetails doc_what_are_typecodes * * @return the SBML type code for this object: * @sbmlconstant{SBML_COMPARTMENT_TYPE, SBMLTypeCode_t} (default). * * @copydetails doc_warning_typecodes_not_unique * * @see getElementName() * @see getPackageName() */ virtual int getTypeCode () const; /** * Returns the XML element name of this object * * For CompartmentType, the element name is always @c "compartmentType". * * @return the name of this element. * * @see getTypeCode() * @see getPackageName() */ virtual const std::string& getElementName () const; /** @cond doxygenLibsbmlInternal */ /** * Subclasses should override this method to write out their contained * SBML objects as XML elements. Be sure to call your parent's * implementation of this method as well. */ virtual void writeElements (XMLOutputStream& stream) const; /** @endcond */ /** * Predicate returning @c true if all the required attributes for this * CompartmentType object have been set. * * The required attributes for a CompartmentType object are: * @li "id" * * @return @c true if the required attributes have been set, @c false * otherwise. */ virtual bool hasRequiredAttributes() const; #ifndef SWIG /** @cond doxygenLibsbmlInternal */ /** * Gets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to retrieve. * * @param value, the address of the value to record. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int getAttribute(const std::string& attributeName, bool& value) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Gets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to retrieve. * * @param value, the address of the value to record. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int getAttribute(const std::string& attributeName, int& value) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Gets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to retrieve. * * @param value, the address of the value to record. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int getAttribute(const std::string& attributeName, double& value) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Gets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to retrieve. * * @param value, the address of the value to record. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int getAttribute(const std::string& attributeName, unsigned int& value) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Gets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to retrieve. * * @param value, the address of the value to record. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int getAttribute(const std::string& attributeName, std::string& value) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Gets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to retrieve. * * @param value, the address of the value to record. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int getAttribute(const std::string& attributeName, const char* value) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Predicate returning @c true if this CompartmentType's attribute * "attributeName" is set. * * @param attributeName, the name of the attribute to query. * * @return @c true if this CompartmentType's attribute "attributeName" has * been set, otherwise @c false is returned. */ virtual bool isSetAttribute(const std::string& attributeName) const; /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Sets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to set. * * @param value, the value of the attribute to set. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int setAttribute(const std::string& attributeName, bool value); /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Sets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to set. * * @param value, the value of the attribute to set. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int setAttribute(const std::string& attributeName, int value); /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Sets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to set. * * @param value, the value of the attribute to set. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int setAttribute(const std::string& attributeName, double value); /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Sets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to set. * * @param value, the value of the attribute to set. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int setAttribute(const std::string& attributeName, unsigned int value); /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Sets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to set. * * @param value, the value of the attribute to set. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int setAttribute(const std::string& attributeName, const std::string& value); /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Sets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to set. * * @param value, the value of the attribute to set. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int setAttribute(const std::string& attributeName, const char* value); /** @endcond */ /** @cond doxygenLibsbmlInternal */ /** * Unsets the value of the "attributeName" attribute of this CompartmentType. * * @param attributeName, the name of the attribute to query. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} */ virtual int unsetAttribute(const std::string& attributeName); /** @endcond */ #endif /* !SWIG */ protected: /** @cond doxygenLibsbmlInternal */ /** * Subclasses should override this method to get the list of * expected attributes. * This function is invoked from corresponding readAttributes() * function. */ virtual void addExpectedAttributes(ExpectedAttributes& attributes); /** * Subclasses should override this method to read values from the given * XMLAttributes set into their specific fields. Be sure to call your * parent's implementation of this method as well. * * @param attributes the XMLAttributes to use. */ virtual void readAttributes (const XMLAttributes& attributes, const ExpectedAttributes& expectedAttributes); void readL2Attributes (const XMLAttributes& attributes); /** * Subclasses should override this method to write their XML attributes * to the XMLOutputStream. Be sure to call your parent's implementation * of this method as well. * * @param stream the XMLOutputStream to use. */ virtual void writeAttributes (XMLOutputStream& stream) const; //std::string mId; //std::string mName; /* the validator classes need to be friends to access the * protected constructor that takes no arguments */ friend class Validator; friend class ConsistencyValidator; friend class IdentifierConsistencyValidator; friend class InternalConsistencyValidator; friend class L1CompatibilityValidator; friend class L2v1CompatibilityValidator; friend class L2v2CompatibilityValidator; friend class L2v3CompatibilityValidator; friend class L2v4CompatibilityValidator; friend class MathMLConsistencyValidator; friend class ModelingPracticeValidator; friend class OverdeterminedValidator; friend class SBOConsistencyValidator; friend class UnitConsistencyValidator; /** @endcond */ }; class LIBSBML_EXTERN ListOfCompartmentTypes : public ListOf { public: /** * Creates a new ListOfCompartmentTypes object. * * The object is constructed such that it is valid for the given SBML * Level and Version combination. * * @param level the SBML Level. * * @param version the Version within the SBML Level. * * @copydetails doc_throw_exception_lv * * @copydetails doc_note_setting_lv */ ListOfCompartmentTypes (unsigned int level, unsigned int version); /** * Creates a new ListOfCompartmentTypes object. * * The object is constructed such that it is valid for the SBML Level and * Version combination determined by the SBMLNamespaces object in @p * sbmlns. * * @param sbmlns an SBMLNamespaces object that is used to determine the * characteristics of the ListOfCompartmentTypes object to be created. * * @copydetails doc_throw_exception_namespace * * @copydetails doc_note_setting_lv */ ListOfCompartmentTypes (SBMLNamespaces* sbmlns); /** * Creates and returns a deep copy of this ListOfCompartmentTypes object. * * @return the (deep) copy of this ListOfCompartmentTypes object. */ virtual ListOfCompartmentTypes* clone () const; /** * Returns the libSBML type code for the objects contained in this ListOf * (i.e., CompartmentType objects, if the list is non-empty). * * @copydetails doc_what_are_typecodes * * @return the SBML type code for the objects contained in this ListOf * instance: @sbmlconstant{SBML_COMPARTMENT_TYPE, SBMLTypeCode_t} (default). * * @see getElementName() * @see getPackageName() */ virtual int getItemTypeCode () const; /** * Returns the XML element name of this object. * * For ListOfCompartmentTypes, the XML element name is @c * "listOfCompartmentTypes". * * @return the name of this element, i.e., @c "listOfCompartmentTypes". */ virtual const std::string& getElementName () const; /** * Get a CompartmentType object from the ListOfCompartmentTypes. * * @param n the index number of the CompartmentType object to get. * * @return the nth CompartmentType object in this ListOfCompartmentTypes. * * @see size() */ virtual CompartmentType * get(unsigned int n); /** * Get a CompartmentType object from the ListOfCompartmentTypes. * * @param n the index number of the CompartmentType object to get. * * @return the nth CompartmentType object in this ListOfCompartmentTypes. * * @see size() */ virtual const CompartmentType * get(unsigned int n) const; /** * Get a CompartmentType object from the ListOfCompartmentTypes * based on its identifier. * * @param sid a string representing the identifier * of the CompartmentType object to get. * * @return CompartmentType object in this ListOfCompartmentTypes * with the given @p sid or @c NULL if no such * CompartmentType object exists. * * @see get(unsigned int n) * @see size() */ virtual CompartmentType* get (const std::string& sid); /** * Get a CompartmentType object from the ListOfCompartmentTypes * based on its identifier. * * @param sid a string representing the identifier * of the CompartmentType object to get. * * @return CompartmentType object in this ListOfCompartmentTypes * with the given @p sid or @c NULL if no such * CompartmentType object exists. * * @see get(unsigned int n) * @see size() */ virtual const CompartmentType* get (const std::string& sid) const; /** * Removes the nth item from this ListOfCompartmentTypes items * and returns a pointer to it. * * The caller owns the returned item and is responsible for deleting it. * * @param n the index of the item to remove. * * @see size() */ virtual CompartmentType* remove (unsigned int n); /** * Removes item in this ListOfCompartmentTypes items with the given identifier. * * The caller owns the returned item and is responsible for deleting it. * If none of the items in this list have the identifier @p sid, then @c * NULL is returned. * * @param sid the identifier of the item to remove. * * @return the item removed. As mentioned above, the caller owns the * returned item. */ virtual CompartmentType* remove (const std::string& sid); /** @cond doxygenLibsbmlInternal */ /** * Get the ordinal position of this element in the containing object * (which in this case is the Model object). * * The ordering of elements in the XML form of SBML is generally fixed * for most components in SBML. For example, the * ListOfCompartmentTypes in a model (in SBML Level 2 Version 4) is the * third ListOf___. (However, it differs for different Levels and * Versions of SBML, so calling code should not hardwire this number.) * * @return the ordinal position of the element with respect to its * siblings, or @c -1 (default) to indicate the position is not significant. */ virtual int getElementPosition () const; /** @endcond */ protected: /** @cond doxygenLibsbmlInternal */ /** * Create a ListOfCompartmentTypes object corresponding to the next token * in the XML input stream. * * @return the SBML object corresponding to next XMLToken in the * XMLInputStream, or @c NULL if the token was not recognized. */ virtual SBase* createObject (XMLInputStream& stream); /** @endcond */ }; LIBSBML_CPP_NAMESPACE_END #endif /* __cplusplus */ #ifndef SWIG LIBSBML_CPP_NAMESPACE_BEGIN BEGIN_C_DECLS /** * Creates a new CompartmentType_t structure using the given SBML @p level * and @p version values. * * @param level an unsigned int, the SBML Level to assign to this * CompartmentType_t. * * @param version an unsigned int, the SBML Version to assign to this * CompartmentType_t. * * @return a pointer to the newly created CompartmentType_t structure. * * @note Once a CompartmentType_t has been added to an SBMLDocument_t, the @p * level and @p version for the document @em override those used to create * the CompartmentType_t. Despite this, the ability to supply the values at * creation time is an important aid to creating valid SBML. Knowledge of * the intended SBML Level and Version determine whether it is valid to * assign a particular value to an attribute, or whether it is valid to add * a structure to an existing SBMLDocument_t. * * @memberof CompartmentType_t */ LIBSBML_EXTERN CompartmentType_t * CompartmentType_create (unsigned int level, unsigned int version); /** * Creates a new CompartmentType_t structure using the given * SBMLNamespaces_t structure. * * @param sbmlns SBMLNamespaces_t, a pointer to an SBMLNamespaces_t structure * to assign to this CompartmentType_t. * * @return a pointer to the newly created CompartmentType_t structure. * * @note Once a CompartmentType_t has been added to an SBMLDocument_t, the * @p sbmlns namespaces for the document @em override those used to create * the CompartmentType_t. Despite this, the ability to supply the values at * creation time is an important aid to creating valid SBML. Knowledge of the * intended SBML Level and Version determine whether it is valid to assign a * particular value to an attribute, or whether it is valid to add a structure * to an existing SBMLDocument_t. * * @memberof CompartmentType_t */ LIBSBML_EXTERN CompartmentType_t * CompartmentType_createWithNS (SBMLNamespaces_t *sbmlns); /** * Frees the given CompartmentType_t structure. * * @param ct the CompartmentType_t structure to be freed. * * @memberof CompartmentType_t */ LIBSBML_EXTERN void CompartmentType_free (CompartmentType_t *ct); /** * Creates a deep copy of the given CompartmentType_t structure * * @param ct the CompartmentType_t structure to be copied. * * @return a (deep) copy of this CompartmentType_t structure. * * @memberof CompartmentType_t */ LIBSBML_EXTERN CompartmentType_t * CompartmentType_clone (const CompartmentType_t *ct); /** * Returns a list of XMLNamespaces_t associated with this CompartmentType_t * structure. * * @param ct the CompartmentType_t structure. * * @return pointer to the XMLNamespaces_t structure associated with * this structure * * @memberof CompartmentType_t */ LIBSBML_EXTERN const XMLNamespaces_t * CompartmentType_getNamespaces(CompartmentType_t *ct); /** * Takes a CompartmentType_t structure and returns its identifier. * * @param ct the CompartmentType_t structure whose identifier is sought. * * @return the identifier of this CompartmentType_t, as a pointer to a string. * * @memberof CompartmentType_t */ LIBSBML_EXTERN const char * CompartmentType_getId (const CompartmentType_t *ct); /** * Takes a CompartmentType_t structure and returns its name. * * @param ct the CompartmentType_t whose name is sought. * * @return the name of this CompartmentType_t, as a pointer to a string. * * @memberof CompartmentType_t */ LIBSBML_EXTERN const char * CompartmentType_getName (const CompartmentType_t *ct); /** * Predicate returning @c true or @c false depending on whether the given * CompartmentType_t structure's identifier is set. * * @param ct the CompartmentType_t structure to query. * * @return @c non-zero (true) if the "id" field of the given * CompartmentType_t is set, zero (false) otherwise. * * @memberof CompartmentType_t */ LIBSBML_EXTERN int CompartmentType_isSetId (const CompartmentType_t *ct); /** * Predicate returning @c true or @c false depending on whether the given * CompartmentType_t structure's name is set. * * @param ct the CompartmentType_t structure to query. * * @return @c non-zero (true) if the "name" field of the given * CompartmentType_t is set, zero (false) otherwise. * * @memberof CompartmentType_t */ LIBSBML_EXTERN int CompartmentType_isSetName (const CompartmentType_t *ct); /** * Assigns the identifier of a CompartmentType_t structure. * * This makes a copy of the string passed as the argument @p sid. * * @param ct the CompartmentType_t structure to set. * @param sid the string to use as the identifier. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t} * * @note Using this function with an id of NULL is equivalent to * unsetting the "id" attribute. * * @memberof CompartmentType_t */ LIBSBML_EXTERN int CompartmentType_setId (CompartmentType_t *ct, const char *sid); /** * Assign the name of a CompartmentType_t structure. * * This makes a copy of the string passed as the argument @p name. * * @param ct the CompartmentType_t structure to set. * @param name the string to use as the name. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_INVALID_ATTRIBUTE_VALUE, OperationReturnValues_t} * * @note Using this function with the name set to NULL is equivalent to * unsetting the "name" attribute. * * @memberof CompartmentType_t */ LIBSBML_EXTERN int CompartmentType_setName (CompartmentType_t *ct, const char *name); /** * Unsets the name of a CompartmentType_t. * * @param ct the CompartmentType_t structure whose name is to be unset. * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} * * @memberof CompartmentType_t */ LIBSBML_EXTERN int CompartmentType_unsetName (CompartmentType_t *ct); /** * Returns the CompartmentType_t structure having a given identifier. * * @param lo the ListOfCompartmentTypes_t structure to search. * @param sid the "id" attribute value being sought. * * @return item in the @p lo ListOfCompartmentTypes with the given @p sid or a * null pointer if no such item exists. * * @see ListOf_t * * @memberof ListOfCompartmentTypes_t */ LIBSBML_EXTERN CompartmentType_t * ListOfCompartmentTypes_getById (ListOf_t *lo, const char *sid); /** * Removes a CompartmentType_t structure based on its identifier. * * The caller owns the returned item and is responsible for deleting it. * * @param lo the list of CompartmentType_t structures to search. * @param sid the "id" attribute value of the structure to remove. * * @return The CompartmentType_t structure removed, or a null pointer if no such * item exists in @p lo. * * @see ListOf_t * * @memberof ListOfCompartmentTypes_t */ LIBSBML_EXTERN CompartmentType_t * ListOfCompartmentTypes_removeById (ListOf_t *lo, const char *sid); END_C_DECLS LIBSBML_CPP_NAMESPACE_END #endif /* !SWIG */ #endif /* CompartmentType_h */
d27e677c242187a374f17648f64ec52a07bb801d
875d985b24b3644836a2ba4ff9c0bd0f82b25013
/PA-2/BST and AVL/test3.cpp
8c183d3281b195a5a966319d6d3a8596771354b0
[]
no_license
FarrukhCyber/Data-Structures
3e8a2678911f6f1cff737b839718f9210cc45636
abae5edbb25227d18d148f08a3599a1a744507b6
refs/heads/main
2023-06-02T00:37:55.620705
2021-06-13T20:56:59
2021-06-13T20:56:59
376,631,775
0
0
null
null
null
null
UTF-8
C++
false
false
5,468
cpp
// Test file for AVL Tree Implementation #include <iostream> #include <cstdio> #include <cstdlib> #include <memory> #include "avl.hpp" using namespace std; int marks = 0; int total_values = 25; int values[25] = {55,43,26,82,93,04,39,95,50,6,62,17,21,49,77,5,32,60,88,16,44,72,80,8,36}; int TreeAfterAddition[25] = {4,5,6,8,16,17,21,26,32,36,39,43,44,49,50,55,60,62,72,77,80,82,88,93,95}; int TreeAfterDeletion[21] = {5,8,16,17,21,26,32,36,39,44,49,50,55,60,62,72,77,80,88,93,95}; int indx=0; int score=0; int step=0; template<class T, class S> void TraverseTree(shared_ptr<node<T,S>> P,int test) { if (P==NULL) { return; } if(P->left) TraverseTree(P->left,test); if(test == 1) { if(P->key == TreeAfterAddition[indx]) score++; } else if(test == 2) { if(P->key == TreeAfterDeletion[indx]) score++; } indx++; if(P->right) TraverseTree(P->right,test); } void test_addition() { cout<<"Test 3.1 - AVL Insertion\n"; int counter = 0; score=0; indx=0; // Case 1 - Correct order of nodes AVL<int,string> B(true); for (int i=0;i<total_values;i++) B.insertNode(shared_ptr<node<int,string>> (make_shared<node<int,string>>(values[i],"CS202"))); //B.insertNode(make_shared<node<int,string>>(values[i],"abc")); TraverseTree(B.getRoot(),1); if(score == 25){ //testing // shared_ptr<node<int,string>> root = B.getRoot(); // cout<< B.isBalanced(root) << "\n" ; // cout<< "height:"<< B.height(root) << "\n" ; // root = B.insertAVL(root, values[24]) ; // cout<< root->right->key<<endl; cout << "Test 3.1.1: Passed" << endl; counter = counter + 4; } else { // Order of nodes is incorrect cout << "Test 3.1.1: Failed" << endl; } // Case 2 - Correct structure of tree score = 0; shared_ptr<node<int,string>> root = B.getRoot(); if (root != NULL) { if(root->key == 43){ score++; } if(root->right->key == 62){ score++; } if(root->left->key == 17){ score++; } if(root->left->left->left->key == 4){ score++; } if(root->left->right->right->key == 36){ score++; } if(root->right->left->right->key == 60){ score++; } if(root->right->right->right->right->key == 95){ score++; } if(root->left->left->right->left->key == 6){ score++; } } if(score == 8) { cout << "Test 3.1.2: Passed" << endl; counter = counter + 5; } else { // Structure of tree is incorrect cout << "Test 3.1.2: Failed" << endl; } cout << "Total Points: " << counter << "/9" << endl << endl; marks = marks + counter; } void test_deletion() { cout<<"Test 3.3 - AVL Deletion" << endl; int counter = 0; score=0; indx=0; // Case 1 - Correct order of nodes AVL<int,string> B(true); for (int i=0;i<total_values;i++) B.insertNode(shared_ptr<node<int,string>> (make_shared<node<int,string>>(values[i],"CS202"))); for (int i=0;i<total_values;i++) B.deleteNode(values[i]); for (int i=0;i<total_values;i++) B.insertNode(shared_ptr<node<int,string>> (make_shared<node<int,string>>(values[i],"CS202"))); B.deleteNode(6); B.deleteNode(82); B.deleteNode(4); B.deleteNode(43); TraverseTree(B.getRoot(),2); if(score == (total_values-4)){ cout << "Test 3.3.1: Passed" << endl; counter = counter + 4; } else { // Order of nodes is incorrect cout << "Test 3.3.1: Failed" << endl; } // Case 2 - Correct structure of tree score=0; shared_ptr<node<int,string>> root = B.getRoot(); if (root != NULL) { if(root->key == 44) score++; if(root->right->key == 62) score++; if(root->left->key == 17) score++; if(root->left->left->left->key == 5) score++; if(root->left->right->right->key == 36) score++; if(root->right->left->right->key == 60) score++; if(root->right->right->right->right->key == 95) score++; if(root->left->left->right->left == NULL) score++; } if(score == 8) { counter = counter + 5; cout << "Test 3.3.2: Passed" << endl; } else { // Structure of tree not okay cout << "Test 3.3.2: Failed" << endl; } cout << "Total Points: " << counter << "/9" << endl; marks = marks + counter; } void test_search() { int counter = 0; cout<<"Test 3.2 - AVL Search" << endl; score=0; indx=0; // Case 1 - Simple search AVL <int,string> B(true); for (int i=0;i<total_values;i++) B.insertNode(shared_ptr<node<int,string>> (make_shared<node<int,string>>(values[i],"abc"))); //B.insertNode(make_shared<node<int,string>>(values[i],"abc")); for (int i=0;i<total_values;i++){ if (B.searchNode(values[i]) != NULL) { if (B.searchNode(values[i])->key == values[i]) { score++; } } } if(score == 25) { cout << "Test 3.2.1: Passed" << endl; counter = counter + 1; } else { cout << "Test 3.2.1: Failed" << endl; } step++; score=0; // Case 2 - Nodes not present if (B.getRoot() != NULL) { score++; } if(B.searchNode(100) == NULL) score++; if(B.searchNode(1) == NULL) score++; if(B.searchNode(99) == NULL) score++; if(B.searchNode(40) == NULL) score++; if(score == 5) { cout << "Test 3.2.2: Passed" << endl; counter = counter + 1; } else { cout << "Test 3.2.2: Failed" << endl; } cout << "Total Points: " << counter << "/2" << endl << endl; step++; marks = marks + counter; } void testcases() { test_addition(); test_search(); // test_deletion(); } int main() { cout<<"Test 3 - AVL Tree" << endl << endl; testcases(); cout << endl << "Total Marks: " << marks << "/20" <<endl; if (marks == 20) { cout << "Perfect! Onto the last one :')" << endl; } }
f6943b64be077000749ed3fce1959e84bb7a97a2
768a640567c5e23269f7fe25757cb903d2b19e50
/Ortho.cpp
5294cc85a54b43a0ee3fb04cd57e2f9f93e8e7ec
[]
no_license
schleo13/Orthogonalisation
7803aa529de84ef78f2861d1bd34ea2a8b92ec88
6aab3f25d8cf1c7f0c4a36733946f61014c3c251
refs/heads/main
2023-08-22T17:30:11.248590
2021-10-22T12:17:50
2021-10-22T12:17:50
403,101,673
0
0
null
null
null
null
UTF-8
C++
false
false
8,849
cpp
#include "readMatrix.hpp" template<typename T> T matrixNormInfI(matrix<T> X){ matrix<T>mone (X.size1(),X.size2()); for(int vc = 0; vc < X.size2(); vc++) mone(vc,vc) = 1.0; matrix<T> mm = prod(trans(X),X); mm = mone-mm; vector<T> v(mm.size1()); for(int i = 0; i < mm.size1(); i++){ T c = 0.0; for(int j = 0; j< mm.size2();j++){ if(mm(i,j) < 0) mm(i,j)= mm(i,j)*(-1); c = c + mm(i,j); } v(i)=c; } T mx = 0; for(int i = 0; i < v.size(); i++){ if(v(i) > mx) mx = v(i); } return mx; } template<typename T> T matrixNormInfQR(matrix<T> X, matrix<T> Q, matrix<T>R){ matrix<T> mm = prod(Q,R); mm = X-mm; vector<T> v(mm.size1()); for(int i = 0; i < mm.size1(); i++){ T c = 0.0; for(int j = 0; j< mm.size2();j++){ if(mm(i,j) < 0) mm(i,j)= mm(i,j)*(-1); c = c + mm(i,j); } v(i)=c; } T mx = 0; for(int i = 0; i < v.size(); i++){ if(v(i) > mx) mx = v(i); } return mx; } //CGS algorithm returns QR template <typename T> array<matrix<T>,2> CGS(matrix<T> X){ //auto start = std::chrono::high_resolution_clock::now(); matrix<T> Q(X.size1(),X.size2()); matrix<T> R(X.size1(),X.size1()); for(int k = 0; k < X.size1();k++){ vector<T> x = column(X,k); for(int j = 0; j < k; j++){ R(j,k) = inner_prod(column(Q,j),x); } for(int j = 0; j < k; j++){ x = x - R(j,k)*column(Q,j); } R(k,k)=norm_2(x); column(Q,k)= x/R(k,k); } array<matrix<T>,2> foo{Q,R}; //auto end = std::chrono::high_resolution_clock::now(); //std::chrono::duration<double, std::milli> float_ms = end - start; //cout<<"Benötigte Zeit : "<<float_ms.count()<<endl; //cout<<"CGS_________Q = "<<Q<<"\n"<<endl; //cout<<"CGS_________R = "<<R<<"\n"<<endl; return foo; } //MGS algorithm returns QR template<typename T> array<matrix<T>,2> MGS(matrix<T> X){ auto start = std::chrono::high_resolution_clock::now(); matrix<T> Q (X.size1(),X.size2()); matrix<T> R(X.size2(),X.size2()); for(int k = 0; k < X.size2(); k++ ){ vector<T> x = column(X,k); for(int j = 0; j < k; j++){ R(j,k) = inner_prod(column(Q,j),x); x = x - R(j,k)*column(Q,j); } R(k,k)=norm_2(x); column(Q,k)= x/R(k,k); } //for(int i = 0; i < X.size2(); i ++) //column(Q,i)= column(Q,i)*norm_2(column(X,i)); array<matrix<T>,2> foo = {Q,R}; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> float_ms = end - start; // cout<<"Benötigte Zeit : "<<float_ms.count()<<endl; // cout<<"MGS_I = "<< matrixNormInfI(foo[0])<<endl; // cout<<"MGS_QR = "<<matrixNormInfQR(X,foo[0],foo[1])<<endl; return foo; } //Householder algorithm returns QR template <typename T> array<matrix<T>,2> Householder(matrix<T> X){ // auto start = std::chrono::high_resolution_clock::now(); vector<T> x(X.size1()); matrix<T> Q(X.size1(), X.size2()); matrix<T> R = X; for(int vc = 0; vc < Q.size1(); vc++) Q(vc,vc) = 1.0; for(int j =0; j < X.size2(); j++){ range je (j,X.size2()); T nu = norm_2(project(column(R,j),je)); T s = R(j,j); if(s < 0){s =-1;} else{ s = 1;} T u1 = R(j,j)-s*nu; vector<T> w = project(column(R,j),je)/u1; w(0)=1; T tau = -s*u1/nu; range ee(0, X.size2()); matrix<T> R1 = project(R,je,ee); vector<T> Rr = prod(w,R1); matrix<T> Q1 = project(Q,ee,je); vector<T> Qr = prod(Q1,w); w = tau*w; project(R,je,ee)=project(R,je,ee)-outer_prod(w,Rr); project(Q,ee,je)=project(Q,ee,je)-outer_prod(Qr,w); } array<matrix<T>,2> foo = {Q,R}; // auto end = std::chrono::high_resolution_clock::now(); //std::chrono::duration<double, std::milli> float_ms = end - start; //cout<<"Benötigte Zeit : "<<float_ms.count()<<endl; //cout<<"Householder_Q = "<<Q<<"\n"<<endl; //cout<<"Householder_R = "<<R<<"\n"<<endl; return foo; } template<typename T> matrix<T> gg(vector<T> v,int i,int j){ matrix<T> R(v.size(),v.size()); for(int vc = 0; vc <v.size(); vc++){ R(vc,vc) = 1.0; } T nn = sqrt(v(i)*v(i)+v(j)*v(j)); T c = v(i)/nn; T s = v(j)/nn; R(i,i)=c; R(j,j)=c; R(i,j)=s; R(j,i)=s*(-1); return R; } //Givensrotation returns QR template <typename T> array<matrix<T>,2> Givens(matrix<T> X){ // auto start = std::chrono::high_resolution_clock::now(); matrix<T> Q(X.size1(),X.size2()); matrix<T> R = X; for(int vc = 0;vc<X.size1();vc++){ Q(vc,vc) =1.0; } for(int i = 0; i <X.size1()-1; i++){ vector<T> v (X.size1()); matrix<T> G(v.size(),v.size()); for(int j = i+1; j < X.size2();j++){ v = column(R,i); G = gg(v,i,j); Q = prod(Q,trans(G)); R = prod(G,R); //cout<<G<<endl; } //cout<<"iteration = "<<i<<endl; } array<matrix<T>,2> foo = {Q,R}; //auto end = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double, std::milli> float_ms = end - start; // cout<<"Benötigte Zeit : "<<float_ms.count()<<endl; //cout<<"Givens___Q = "<<Q<<"\n"<<endl; //cout<<"Givens___R = "<<R<<"\n"<<endl; return foo; } template<typename T> T matrixNormMax(matrix<T> X){ T mx = 0; for(int i = 0; i < X.size2(); i++){ if(mx < norm_2(column(X,i))){ mx = norm_2(column(X,i)); } } return mx; } template<typename T> T matrixNormMin(matrix<T> X){ T mx =norm_2(column(X,0)); for(int i = 0; i < X.size2(); i++){ if(mx > norm_2(column(X,i))){ mx = norm_2(column(X,i)); } } return mx; } template<typename T> T matrixNormMaxI(matrix<T> X){ matrix<T>mone (X.size1(),X.size2()); for(int vc = 0; vc < X.size2(); vc++) mone(vc,vc) = 1.0; matrix<T> mm = prod(trans(X),X); mm = mone-mm; T mx = 0; for(int i = 0; i < X.size1(); i++){ for(int j = 0; j < X.size2(); j++){ T x = mm(i,j); if(x <0){ x = x*(-1); } if(x > mx) mx = x; } } return mx; } template<typename T> T matrixNormMaxQR(matrix<T> X, matrix<T> Q, matrix<T> R){ matrix<T> mm = prod(Q,R); mm = X-mm; T mx = 0; for(int i = 0; i < X.size1(); i++){ for(int j = 0; j < X.size2(); j++){ T x = mm(i,j); if(x <0){ x = x*(-1); } if(x > mx) mx = x; } } return mx; } template<typename T> matrix<T> randMatrixI(int i, T n ){ srand(time(NULL)); matrix<T> X(i,i); vector<T> y(i); for(int j = 0; j < i; j++)y(j)=rand()*n; row(X,0)= y; for(int j = 1; j < i; j++)X(j,j)=1.0; return X; } template<typename T> matrix<T> randMatrixFull(int i, T n ){ srand(time(NULL)); matrix<T> X(i,i); for(int j = 0; j < i; j++){ for(int k = 0; k <i ; k++){ X(j,k)= rand()*n; } } return X; } template<typename T> matrix<T> Hilbert(int n, T a){ matrix<T> m(n,n); for(int i = 0; i < m.size1(); i++){ for(int j = 0; j <m.size2(); j++){ T h = 1.0/(i+j+1.0); m(j,i) = h; } } return m; } matrix<cpp_dec_float_100> Hilbert100(int n){ matrix<cpp_dec_float_100> m(n,n); for(int i = 0; i < m.size1(); i++){ for(int j = 0; j <m.size2(); j++){ cpp_dec_float_100 h = 1.0/(i+j+1.0); m(j,i) = h; } } return m; } matrix<double> HilbertDouble( int n){ matrix<double> m(n,n); for(int i = 0; i < m.size1(); i++){ for(int j = 0; j <m.size2(); j++){ double h = 1.0/(i+j+1.0); m(j,i) = h; } } return m; } template<typename T> matrix<T> clearEps(matrix<T> M){ cpp_dec_float_100 epp ("0.0000000000001"); for(int i = 0; i < M.size1();i++){ for(int j = 0; j < M.size2();j++){ if(M(i,j) > 0 && M(i,j) < epp || M(i,j) < 0 && M(i,j)*(-1) < epp){ M(i,j) = 0; } } } return M; }
ff773f2862d5276fe8eee35d1839443b7d18ddf5
5de16bedbdabbd552dcebdeec3d2be30b59c80e3
/Invert Binary Tree/solution.cpp
41b4d0596a24e28e11cdff4b2c18929abb33c87a
[]
no_license
kimjaspermui/LeetCode
39f6aa61a27e7bf2aac7de940941ec376f3640e8
c01002206fcc1b3ed35d1ba1e83dffdff5fc16a5
refs/heads/master
2020-12-02T07:51:49.508145
2018-07-15T04:21:48
2018-07-15T04:21:48
96,737,433
0
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { // if null then retun null if (!root) { return root; } // invert left and right trees invertTree(root->left); invertTree(root->right); // invert left and right trees TreeNode* tempRight = root->right; root->right = root->left; root->left = tempRight; return root; } };
609467e5b1c03a564a83969072ed7b65012e3bda
979f022aec7a25402fb24a1fcddacb155dfa23cf
/mystarcraft/Client/UIRoot.h
8f377021975104fa7fa8c6e60202454b2bc03aee
[]
no_license
Kimdeokho/mystarproject
e0a2c5a53f767ede5a7c19f7bb532dee227d766e
d4828e807233e6a783e6b3a46be11efda7c2d978
refs/heads/master
2021-04-29T06:19:47.010767
2020-12-16T12:50:46
2020-12-16T12:50:46
78,000,948
0
0
null
null
null
null
UTF-8
C++
false
false
901
h
#pragma once #include "UI.h" class CUIRoot : public CUI { private: typedef list<CUI*>::iterator UI_ITER; list<CUI*> m_uilist; private: D3DXVECTOR2 m_vstart; D3DXVECTOR2 m_vend; float m_init_dt; float m_fspeed; bool m_is_entryanim; bool m_is_exitanim; bool m_entry_complete; bool m_exit_complete; public: void Set_texturekey(const TCHAR* texkey); void SetStartEndPos(const D3DXVECTOR2& vstart , const D3DXVECTOR2& vend); void Animation(); void Entry_Animation(void); void Exit_Animation(void); void SetEntry(bool bentry); void SetExit(bool bexit); bool GetEntryComplete(void); bool GetExitComplete(void); public: virtual void Initialize(void); virtual void Update(void); virtual void Render(void); virtual bool UI_ptinrect(const D3DXVECTOR2 vpos); virtual void Init_State(void); virtual void Release(void); public: CUIRoot(void); virtual ~CUIRoot(void); };
d2b188d7af660ae40295b5006e4af916fbf68aa9
9e3ff9b563d463683b194514f1ddc0ff82129393
/Main/wxWidgets/contrib/src/stc/scintilla/src/ViewStyle.h
fa23db322cd1bef2ef01da368a3f412813f8a698
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
sidihamady/Comet
b3d5179ea884b060fc875684a2efdf6a3ad97204
b1711a000aad1d632998e62181fbd7454d345e19
refs/heads/main
2023-05-29T03:14:01.934022
2022-04-17T21:56:39
2022-04-17T21:56:39
482,617,765
4
0
null
null
null
null
UTF-8
C++
false
false
3,042
h
// Scintilla source code edit control /** @file ViewStyle.h ** Store information on how the document is to be viewed. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #ifndef VIEWSTYLE_H #define VIEWSTYLE_H /** */ class MarginStyle { public: int style; int width; int mask; bool sensitive; MarginStyle(); }; /** */ class FontNames { private: char *names[STYLE_MAX + 1]; int max; public: FontNames(); ~FontNames(); void Clear(); const char *Save(const char *name); }; enum WhiteSpaceVisibility {wsInvisible=0, wsVisibleAlways=1, wsVisibleAfterIndent=2}; /** */ class ViewStyle { public: FontNames fontNames; Style styles[STYLE_MAX + 1]; LineMarker markers[MARKER_MAX + 1]; Indicator indicators[INDIC_MAX + 1]; int lineHeight; unsigned int maxAscent; unsigned int maxDescent; unsigned int aveCharWidth; unsigned int spaceWidth; bool selforeset; ColourPair selforeground; bool selbackset; ColourPair selbackground; ColourPair selbackground2; int selAlpha; bool whitespaceForegroundSet; ColourPair whitespaceForeground; bool whitespaceBackgroundSet; ColourPair whitespaceBackground; ColourPair selbar; ColourPair selbarlight; bool foldmarginColourSet; ColourPair foldmarginColour; bool foldmarginHighlightColourSet; ColourPair foldmarginHighlightColour; bool hotspotForegroundSet; ColourPair hotspotForeground; bool hotspotBackgroundSet; ColourPair hotspotBackground; bool hotspotUnderline; bool hotspotSingleLine; /// Margins are ordered: Line Numbers, Selection Margin, Spacing Margin enum { margins=5 }; int leftMarginWidth; ///< Spacing margin on left of text int rightMarginWidth; ///< Spacing margin on left of text bool symbolMargin; int maskInLine; ///< Mask for markers to be put into text because there is nowhere for them to go in margin MarginStyle ms[margins]; int fixedColumnWidth; int zoomLevel; WhiteSpaceVisibility viewWhitespace; bool viewIndentationGuides; bool viewEOL; bool showMarkedLines; ColourPair caretcolour; bool showCaretLineBackground; ColourPair caretLineBackground; int caretLineAlpha; ColourPair edgecolour; int edgeState; int caretWidth; bool someStylesProtected; bool extraFontFlag; // >> [:COMET:]:140314: int extraAscent; int extraDescent; // << ViewStyle(); ViewStyle(const ViewStyle &source); ~ViewStyle(); void Init(); void RefreshColourPalette(Palette &pal, bool want); void Refresh(Surface &surface); void ResetDefaultStyle(); void ClearStyles(); void SetStyleFontName(int styleIndex, const char *name); bool ProtectionActive() const; }; #endif
e584aec1e0aeb25ad0d3a651e2f277a0165dc345
a38d2dd386d337da5c1336602644efbafa007e9f
/Lab5/Lab5/main.cpp
47ce0eedcc27c84977d78b64a9740b2c9a8373f5
[]
no_license
ShadmanRohan/CSE225_practice
25af41864bf02fb7196b61e0eec568b748ccc6e1
33f8a077baa582edc93571e0459d8672939659f4
refs/heads/master
2020-04-01T23:49:43.249657
2018-10-19T11:56:42
2018-10-19T12:10:42
153,774,815
1
0
null
null
null
null
UTF-8
C++
false
false
1,778
cpp
#include <iostream> //#include "UnsortedType.h" //#include "UnsortedType.cpp" #include "UnsortedType.h" //#include "ItemType.h" //#include "ItemType.cpp" using namespace std; int main() { UnsortedType l; ItemType i[10]; i[0].Initialize(5); i[1].Initialize(7); i[2].Initialize(6); i[3].Initialize(9); l.putItem(i[0]); l.putItem(i[1]); l.putItem(i[2]); l.putItem(i[3]); l.printList(); int len = l.getLength(); cout<<endl<<"Length is "<<len<<endl; i[4].Initialize(1); l.putItem(i[4]); l.printList(); cout<<endl; bool found; i[5].Initialize(4); i[6] = l.getItem(i[5], found); if(found == false) { cout<<"Item not found"<<endl; } else { cout<<"Item found"<<endl; } i[5].Initialize(5); i[6] = l.getItem(i[5], found); if(found == false) { cout<<"Item not found"<<endl; } else { cout<<"Item found"<<endl; } i[5].Initialize(9); i[6] = l.getItem(i[5], found); if(found == false) { cout<<"Item not found"<<endl; } else { cout<<"Item found"<<endl; } i[5].Initialize(10); i[6] = l.getItem(i[5], found); if(found == false) { cout<<"Item not found"<<endl; } else { cout<<"Item found"<<endl; } if(l.isFull()) { cout<<"List is Full"<<endl; } else { cout<<"List is not FUll"<<endl; } l.deleteItem(i[0]); if(l.isFull()) { cout<<"List is Full"<<endl; } else { cout<<"List is not FUll"<<endl; } l.deleteItem(i[4]); l.printList(); cout<<endl; l.deleteItem(i[2]); l.printList(); cout<<endl; return 0; }
5b83314ba948430d2311fa251d372abedcde7553
df5e68918b0122502b621ede7298fb3df7875672
/functional_factory/HotDrinkFactory.h
b1c15cb6582b38b546d1beadc3e459b0a4b9d2b8
[]
no_license
DesignPatternWorks/modern_cpp_design_patterns
dcd0d4ff44133a350c7210bdfb43a4e0d7b5ce1f
7812172bd1470d6824bb96bf8e2c5bf1b75688b9
refs/heads/master
2020-06-09T21:51:17.075472
2019-03-11T06:55:59
2019-03-11T06:55:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
616
h
// // Created by lcmscheid on 14-02-2019. // #ifndef FUNCTIONAL_FACTORY_HOTDRINKFACTORY_H #define FUNCTIONAL_FACTORY_HOTDRINKFACTORY_H #include "HotDrink.h" class HotDrinkFactory { public: virtual std::unique_ptr<HotDrink> make() const = 0; }; class TeaFactory : public HotDrinkFactory { public: std::unique_ptr<HotDrink> make() const override { return std::make_unique<Tea>(); } }; class CoffeeFactory : public HotDrinkFactory { public: std::unique_ptr<HotDrink> make() const override { return std::make_unique<Coffee>(); } }; #endif //FUNCTIONAL_FACTORY_HOTDRINKFACTORY_H
5fbeb3ed586341aa2aea6cbf3fc4b356c8e559ed
cf47614d4c08f3e6e5abe82d041d53b50167cac8
/CS101_Autumn2020-21/Fibonacci/150_fibonacci.cpp
8218485ff0705aacb1ea99569ea3204300bcd299
[]
no_license
krishna-raj007/BodhiTree-Annotation
492d782dffe3744740f48c4c7e6bbf2ee2c0febd
28a6467038bac7710c4b3e3860a369ca0a6e31bf
refs/heads/master
2023-02-28T18:23:05.880438
2021-02-07T17:55:33
2021-02-07T17:55:33
299,254,966
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
#include<simplecpp> main_program{ //Write your code here long long int n,k; cin>>n; cin>>k; long long int p=1,p1=0; for (int i=1; i<=n; i++){ p1=p1%k; cout<<p1<<endl; long long int temp=p; p=p+p1; p1=temp; } }
7aca81da86e890d0f75fe2666027737e71bc0afc
b209ace562b2fdcfc1e15fb4f95a872fedfd289a
/src/herder/Herder.h
e38027395d8319d44eb31d33be9c621aee665e6b
[ "BSD-3-Clause", "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
SuperBlockChain/core
b0e8f58649f71747cd249da5835379b8a9728c1e
2216d02c548ab6700c950d6bf1da162f38ff26e2
refs/heads/master
2020-03-07T16:30:14.927588
2018-04-01T01:26:58
2018-04-01T01:26:58
127,584,504
0
0
null
null
null
null
UTF-8
C++
false
false
4,585
h
#pragma once // Copyright 2014 SuperBlockChain Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "TxSetFrame.h" #include "lib/json/json-forwards.h" #include "overlay/SuperBlockChainXDR.h" #include "scp/SCP.h" #include "util/Timer.h" #include <functional> #include <memory> #include <string> namespace snb { class Application; class Peer; class XDROutputFileStream; typedef std::shared_ptr<Peer> PeerPtr; /* * Public Interface to the Herder module * * Drives the SCP consensus protocol, is responsible for collecting Txs and * TxSets from the network and making sure Txs aren't lost in ledger close * * LATER: These interfaces need cleaning up. We need to work out how to * make the bidirectional interfaces */ class Herder { public: // Expected time between two ledger close. static std::chrono::seconds const EXP_LEDGER_TIMESPAN_SECONDS; // Maximum timeout for SCP consensus. static std::chrono::seconds const MAX_SCP_TIMEOUT_SECONDS; // timeout before considering the node out of sync static std::chrono::seconds const CONSENSUS_STUCK_TIMEOUT_SECONDS; // Maximum time slip between nodes. static std::chrono::seconds const MAX_TIME_SLIP_SECONDS; // How many seconds of inactivity before evicting a node. static std::chrono::seconds const NODE_EXPIRATION_SECONDS; // How many ledger in the future we consider an envelope viable. static uint32 const LEDGER_VALIDITY_BRACKET; // How many ledgers in the past we keep track of static uint32 const MAX_SLOTS_TO_REMEMBER; static std::unique_ptr<Herder> create(Application& app); enum State { HERDER_SYNCING_STATE, HERDER_TRACKING_STATE, HERDER_NUM_STATE }; enum TransactionSubmitStatus { TX_STATUS_PENDING = 0, TX_STATUS_DUPLICATE, TX_STATUS_ERROR, TX_STATUS_COUNT }; enum EnvelopeStatus { // for some reason this envelope was discarded - either is was invalid, // used unsane qset or was coming from node that is not in quorum ENVELOPE_STATUS_DISCARDED, // envelope data is currently being fetched ENVELOPE_STATUS_FETCHING, // current call to recvSCPEnvelope() was the first when the envelope // was fully fetched so it is ready for processing ENVELOPE_STATUS_READY, // envelope was already processed ENVELOPE_STATUS_PROCESSED, }; virtual State getState() const = 0; virtual std::string getStateHuman() const = 0; // Ensure any metrics that are "current state" gauge-like counters reflect // the current reality as best as possible. virtual void syncMetrics() = 0; virtual void bootstrap() = 0; // restores SCP state based on the last messages saved on disk virtual void restoreSCPState() = 0; virtual bool recvSCPQuorumSet(Hash const& hash, SCPQuorumSet const& qset) = 0; virtual bool recvTxSet(Hash const& hash, TxSetFrame const& txset) = 0; // We are learning about a new transaction. virtual TransactionSubmitStatus recvTransaction(TransactionFramePtr tx) = 0; virtual void peerDoesntHave(snb::MessageType type, uint256 const& itemID, PeerPtr peer) = 0; virtual TxSetFramePtr getTxSet(Hash const& hash) = 0; virtual SCPQuorumSetPtr getQSet(Hash const& qSetHash) = 0; // We are learning about a new envelope. virtual EnvelopeStatus recvSCPEnvelope(SCPEnvelope const& envelope) = 0; // a peer needs our SCP state virtual void sendSCPStateToPeer(uint32 ledgerSeq, PeerPtr peer) = 0; // returns the latest known ledger seq using consensus information // and local state virtual uint32_t getCurrentLedgerSeq() const = 0; // Return the maximum sequence number for any tx (or 0 if none) from a given // sender in the pending or recent tx sets. virtual SequenceNumber getMaxSeqInPendingTxs(AccountID const&) = 0; virtual void triggerNextLedger(uint32_t ledgerSeqToTrigger) = 0; // lookup a nodeID in config and in SCP messages virtual bool resolveNodeID(std::string const& s, PublicKey& retKey) = 0; virtual ~Herder() { } virtual void dumpInfo(Json::Value& ret, size_t limit) = 0; virtual void dumpQuorumInfo(Json::Value& ret, NodeID const& id, bool summary, uint64 index = 0) = 0; }; }
20bf3d2848fe41fecf5b1817d052462694ac1657
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/ui/views/examples/examples_color_mixer.cc
601f25622886c5ef909d9b3332aa57b096012ff7
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
3,967
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/examples_color_mixer.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/color/color_mixer.h" #include "ui/color/color_recipe.h" #include "ui/color/color_transform.h" #include "ui/gfx/color_palette.h" #include "ui/views/examples/examples_color_id.h" namespace views::examples { void AddExamplesColorMixers(ui::ColorProvider* color_provider, const ui::ColorProviderKey& key) { const bool dark_mode = key.color_mode == ui::ColorProviderKey::ColorMode::kDark; using Ids = ExamplesColorIds; ui::ColorMixer& mixer = color_provider->AddMixer(); mixer[Ids::kColorAnimatedImageViewExampleBorder] = {SK_ColorBLACK}; mixer[Ids::kColorAnimationExampleForeground] = {SK_ColorBLACK}; mixer[Ids::kColorAnimationExampleBackground] = {SK_ColorWHITE}; mixer[Ids::kColorAccessibilityExampleBackground] = {SK_ColorWHITE}; mixer[Ids::kColorBubbleExampleBackground1] = {SK_ColorWHITE}; mixer[Ids::kColorBubbleExampleBackground2] = {SK_ColorGRAY}; mixer[Ids::kColorBubbleExampleBackground3] = {SK_ColorCYAN}; mixer[Ids::kColorBubbleExampleBackground4] = { SkColorSetRGB(0xC1, 0xB1, 0xE1)}; mixer[Ids::kColorDesignerGrabHandle] = {gfx::kGoogleGrey500}; mixer[Ids::kColorDesignerGrid] = {SK_ColorBLACK}; mixer[Ids::kColorFadeAnimationExampleBorder] = {gfx::kGoogleGrey900}; mixer[Ids::kColorFadeAnimationExampleBackground] = {SK_ColorWHITE}; mixer[Ids::kColorFadeAnimationExampleForeground] = {gfx::kGoogleBlue800}; mixer[Ids::kColorInkDropExampleBase] = {SK_ColorBLACK}; mixer[Ids::kColorInkDropExampleBorder] = {SK_ColorBLACK}; mixer[Ids::kColorLabelExampleBlueLabel] = {SK_ColorBLUE}; mixer[Ids::kColorLabelExampleBorder] = {SK_ColorGRAY}; mixer[Ids::kColorLabelExampleThickBorder] = {SK_ColorRED}; mixer[Ids::kColorLabelExampleLowerShadow] = {SK_ColorGRAY}; mixer[Ids::kColorLabelExampleUpperShadow] = {SK_ColorRED}; mixer[Ids::kColorLabelExampleCustomBackground] = {SK_ColorLTGRAY}; mixer[Ids::kColorLabelExampleCustomBorder] = {SK_ColorGRAY}; mixer[Ids::kColorMenuButtonExampleBorder] = {SK_ColorGRAY}; mixer[Ids::kColorMultilineExampleBorder] = {SK_ColorGRAY}; mixer[Ids::kColorMultilineExampleColorRange] = {SK_ColorRED}; mixer[Ids::kColorMultilineExampleForeground] = {SK_ColorBLACK}; mixer[Ids::kColorMultilineExampleLabelBorder] = {SK_ColorCYAN}; mixer[Ids::kColorMultilineExampleSelectionBackground] = {SK_ColorGRAY}; mixer[Ids::kColorMultilineExampleSelectionForeground] = {SK_ColorBLACK}; mixer[Ids::kColorNotificationExampleImage] = {SK_ColorGREEN}; mixer[Ids::kColorScrollViewExampleBigSquareFrom] = {SK_ColorRED}; mixer[Ids::kColorScrollViewExampleBigSquareTo] = {SK_ColorGREEN}; mixer[Ids::kColorScrollViewExampleSmallSquareFrom] = {SK_ColorYELLOW}; mixer[Ids::kColorScrollViewExampleSmallSquareTo] = {SK_ColorGREEN}; mixer[Ids::kColorScrollViewExampleTallFrom] = {SK_ColorRED}; mixer[Ids::kColorScrollViewExampleTallTo] = {SK_ColorCYAN}; mixer[Ids::kColorScrollViewExampleWideFrom] = {SK_ColorYELLOW}; mixer[Ids::kColorScrollViewExampleWideTo] = {SK_ColorCYAN}; mixer[Ids::kColorTableExampleEvenRowIcon] = {SK_ColorRED}; mixer[Ids::kColorTableExampleOddRowIcon] = {SK_ColorBLUE}; mixer[Ids::kColorTextfieldExampleBigRange] = {SK_ColorBLUE}; mixer[Ids::kColorTextfieldExampleName] = {SK_ColorGREEN}; mixer[Ids::kColorTextfieldExampleSmallRange] = {SK_ColorRED}; mixer[Ids::kColorVectorExampleImageBorder] = {SK_ColorBLACK}; mixer[Ids::kColorWidgetExampleContentBorder] = {SK_ColorGRAY}; mixer[Ids::kColorWidgetExampleDialogBorder] = {SK_ColorGRAY}; mixer[Ids::kColorButtonBackgroundFab] = {dark_mode ? ui::kColorRefSecondary30 : ui::kColorRefPrimary90}; } } // namespace views::examples
450b51d9d2afa9997df5e8bcee89604f201e7550
9c451121eaa5e0131110ad0b969d75d9e6630adb
/hdu/6000-6999/6287 口算训练.cpp
e1f41a192dfd7fd273954bd2b68e0c7d36750ccb
[]
no_license
tokitsu-kaze/ACM-Solved-Problems
69e16c562a1c72f2a0d044edd79c0ab949cc76e3
77af0182401904f8d2f8570578e13d004576ba9e
refs/heads/master
2023-09-01T11:25:12.946806
2023-08-25T03:26:50
2023-08-25T03:26:50
138,472,754
5
1
null
null
null
null
UTF-8
C++
false
false
4,884
cpp
#include <bits/stdc++.h> using namespace std; namespace fastIO{ #define BUF_SIZE 100000 #define OUT_SIZE 100000 //fread->read bool IOerror=0; // inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;} inline char nc(){ static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE; if(p1==pend){ p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin); if(pend==p1){IOerror=1;return -1;} } return *p1++; } inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';} template<class T> inline bool read(T &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(sign)x=-x; return true; } inline bool read(double &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(ch=='.'){ double tmp=1; ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0'); } if(sign)x=-x; return true; } inline bool read(char *s){ char ch=nc(); for(;blank(ch);ch=nc()); if(IOerror)return false; for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch; *s=0; return true; } inline bool read(char &c){ for(c=nc();blank(c);c=nc()); if(IOerror){c=-1;return false;} return true; } template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);} #undef OUT_SIZE #undef BUF_SIZE }; using namespace fastIO; /************* debug begin *************/ string to_string(string s){return '"'+s+'"';} string to_string(const char* s){return to_string((string)s);} string to_string(const bool& b){return(b?"true":"false");} template<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();} template<class A,class B>string to_string(pair<A,B> p){return "("+to_string(p.first)+", "+to_string(p.second)+")";} template<class A>string to_string(const vector<A> v){ int f=1;string res="{";for(const auto x:v){if(!f)res+= ", ";f=0;res+=to_string(x);}res+="}"; return res; } void debug_out(){puts("");} template<class T,class... U>void debug_out(const T& h,const U&... t){cout<<" "<<to_string(h);debug_out(t...);} #ifdef tokitsukaze #define debug(...) cout<<"["<<#__VA_ARGS__<<"]:",debug_out(__VA_ARGS__); #else #define debug(...) 233; #endif /************* debug end *************/ #pragma comment(linker, "/STACK:1024000000,1024000000") #define mem(a,b) memset((a),(b),sizeof(a)) #define MP make_pair #define pb push_back #define fi first #define se second #define sz(x) (int)x.size() #define all(x) x.begin(),x.end() using namespace __gnu_cxx; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> PII; typedef pair<ll,ll> PLL; typedef vector<int> VI; typedef vector<ll> VL; void go(); int main(){ #ifdef tokitsukaze freopen("TEST.txt","r",stdin); #endif go();return 0; } const int INF=0x3f3f3f3f; const ll LLINF=0x3f3f3f3f3f3f3f3f; const double PI=acos(-1.0); const double eps=1e-6; const int MAX=1e5+10; const ll mod=1e9+7; /********************************* head *********************************/ struct Segment_Tree { int root[MAX],tot,ls[MAX*20],rs[MAX*20],v[MAX*20],ql,qr,qv; void init() { mem(root,0); ls[0]=rs[0]=0; v[0]=0; tot=1; } int newnode() { ls[tot]=rs[tot]=0; v[tot]=0; return tot++; } void pushup(int id) { v[id]=v[ls[id]]+v[rs[id]]; } void insert(int l,int r,int &id,int pos) { int mid; if(!id) id=newnode(); if(l==r) { v[id]+=qv; return; } mid=(l+r)>>1; if(pos<=mid) insert(l,mid,ls[id],pos); else if(pos>=mid+1) insert(mid+1,r,rs[id],pos); pushup(id); } int query(int l,int r,int &id) { int mid; int res=0; if(!id) return 0; if(l>=ql&&r<=qr) return v[id]; mid=(l+r)>>1; if(ql<=mid) res+=query(l,mid,ls[id]); if(qr>mid) res+=query(mid+1,r,rs[id]); return res; } }tr; int prime[MAX]; vector<int> p; void init(int n) { int i,j; mem(prime,0); p.clear(); for(i=2;i<=n;i++) { if(prime[i]) continue; p.pb(i); for(j=i+i;j<=n;j+=i) { if(!prime[j]) prime[j]=i; } } } int n; void work(int x,int id) { int t,cnt=0; while(x>1) { t=prime[x]; if(!t) { tr.qv=1; tr.insert(1,n,tr.root[x],id); return; } while(x%t==0&&x>1) { x/=t; cnt++; } tr.qv=cnt; cnt=0; tr.insert(1,n,tr.root[t],id); } } int gao(int x,int l,int r) { int t,cnt=0,flag=0; tr.ql=l; tr.qr=r; while(x>1) { t=prime[x]; if(!t) { tr.qv=1; flag|=(tr.query(1,n,tr.root[x])<1); return flag; } while(x%t==0&&x>1) { x/=t; cnt++; } flag|=(tr.query(1,n,tr.root[t])<cnt); cnt=0; } return flag; } void go() { int t,q,i,x,l,r; read(t); init(MAX-10); while(t--) { read(n,q); tr.init(); for(i=1;i<=n;i++) { read(x); work(x,i); } while(q--) { read(l,r,x); gao(x,l,r)?puts("No"):puts("Yes"); } } }
74ec7b1743f044e3a7aadc0bb69f6bfc96ed3f46
6de9dc1cd719893d12bc3e5bbe3c5419667bec7e
/LinkedList/LeetCode 142. Linked List Cycle II(solve2).cpp
942c7193f6aad10ad3dfbb63f6eba9b53cf10d62
[]
no_license
ideask/CodeTraining
1208192fa1ecc9967e869cac19b9d3df40d25002
030e2a975ceb9fb675b064ae92f367d08fab9d00
refs/heads/master
2020-06-16T14:15:54.627148
2019-10-11T16:05:53
2019-10-11T16:05:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,132
cpp
#include <iostream> using namespace std; struct LinkNode{ int val; LinkNode *next; LinkNode(int x): val(x), next(NULL){}; }; class solution{ public: LinkNode *detectCycle(LinkNode *head){ LinkNode *SlowHead = head; LinkNode *FastHead = head; LinkNode *MeetHead = NULL; while(FastHead){ SlowHead = SlowHead->next; FastHead = FastHead->next; if(FastHead == NULL){ return NULL; } FastHead = FastHead->next; if(FastHead == SlowHead){ MeetHead = FastHead; break; } } if(MeetHead == NULL){ return NULL; } while(MeetHead && head){ if(MeetHead == head){ return MeetHead; } MeetHead = MeetHead->next; head = head->next; } return NULL; } }; int main(){ LinkNode a(1); LinkNode b(2); LinkNode c(3); LinkNode d(4); LinkNode e(5); LinkNode f(6); LinkNode g(7); a.next = &b; b.next = &c; c.next = &d; d.next = &e; e.next = &f; f.next = &g; g.next = &c; solution solve; LinkNode *node = solve.detectCycle(&a); if (node){ printf("%d\n", node->val); } else{ printf("NULL\n"); } return 0; }
89967a83aaaabeab843994b82bb802833b800f1c
085773150c69419e6b033d7360cd939cf1c35981
/src/robot.cpp
e11e6f75112302c6314079cb29b2f2c7075576d7
[]
no_license
daniel-lee-user/C-Robot
59669ae1f38daaed012ab179ed44586e7b31c094
66873ff6b0fa44a02a801c8d5d3d249fc2d7205e
refs/heads/master
2020-03-30T02:56:13.497459
2018-09-27T23:30:57
2018-09-27T23:30:57
150,659,186
0
0
null
null
null
null
UTF-8
C++
false
false
741
cpp
/* * robot.cpp * * Created on: Sep 16, 2018 * Author: Admin */ #include "Chassis.h" #include "Motor.h" #include "SmartMotor.h" #include "Shooter.h" #include <iostream> using namespace std; int main() { /* Chassis* testChassis = new Chassis(3, 4); testChassis -> moveStraight(1.0); testChassis -> wait(3000); testChassis -> pointTurn(-0.6); testChassis -> wait(500); testChassis -> brake(); Shooter* testShooter = new Shooter(5); testShooter -> shoot(); */ Chassis* coolChassis = new Chassis(3, 4); Shooter* coolShooter = new Shooter(6); coolChassis -> moveStraight(1.0); coolChassis -> wait(3000); coolChassis -> pointTurn(-0.6); coolChassis -> wait(500); coolChassis -> brake(); coolShooter -> shoot(); }
355e0ed3f6e57c42d6f1df9eb1a8f6b32db86b32
40a2a72e0a09686fce0c5a1d14a7a1449038955f
/src/qe/qe.h
cf118bd0b18a87ed86d882fa4e42428375c88b28
[ "Apache-2.0" ]
permissive
moophis/CS222-Simple-Data-Management-System
0f10e31fca117fd97ff58f60b184f20f6e5ead5b
55b34eccc4d66c0c0ed201992fd0a2cd4e4711d5
refs/heads/master
2020-12-03T05:20:53.188138
2014-12-13T23:32:10
2014-12-13T23:32:10
24,794,600
0
0
null
null
null
null
UTF-8
C++
false
false
14,280
h
#ifndef _qe_h_ #define _qe_h_ #include <vector> #include <cfloat> #include <climits> #include "../rbf/rbfm.h" #include "../rm/rm.h" #include "../ix/ix.h" # define QE_EOF (-1) // end of the index scan using namespace std; typedef enum{ MIN = 0, MAX, SUM, AVG, COUNT } AggregateOp; enum { ERR_NO_INPUT = -401, // error: empty data input ERR_NO_ATTR = -402, // error: cannot find attribute ERR_INV_TYPE = -403, // error: invalid type }; // The following functions use the following // format for the passed data. // For INT and REAL: use 4 bytes // For VARCHAR: use 4 bytes for the length followed by // the characters struct Value { AttrType type; // type of value void *data; // value }; struct Condition { string lhsAttr; // left-hand side attribute CompOp op; // comparison operator bool bRhsIsAttr; // TRUE if right-hand side is an attribute and not a value; FALSE, otherwise. string rhsAttr; // right-hand side attribute if bRhsIsAttr = TRUE Value rhsValue; // right-hand side value if bRhsIsAttr = FALSE }; class Iterator { // All the relational operators and access methods are iterators. public: virtual RC getNextTuple(void *data) = 0; virtual void getAttributes(vector<Attribute> &attrs) const = 0; virtual ~Iterator() {}; }; class TableScan : public Iterator { // A wrapper inheriting Iterator over RM_ScanIterator public: RelationManager &rm; RM_ScanIterator *iter; string tableName; vector<Attribute> attrs; vector<string> attrNames; RID rid; TableScan(RelationManager &rm, const string &tableName, const char *alias = NULL):rm(rm) { //Set members this->tableName = tableName; // Get Attributes from RM rm.getAttributes(tableName, attrs); // Get Attribute Names from RM unsigned i; for(i = 0; i < attrs.size(); ++i) { // convert to char * attrNames.push_back(attrs[i].name); } // Call rm scan to get iterator iter = new RM_ScanIterator(); rm.scan(tableName, "", NO_OP, NULL, attrNames, *iter); // Set alias if(alias) this->tableName = alias; }; // Start a new iterator given the new compOp and value void setIterator() { iter->close(); delete iter; iter = new RM_ScanIterator(); rm.scan(tableName, "", NO_OP, NULL, attrNames, *iter); }; RC getNextTuple(void *data) { return iter->getNextTuple(rid, data); }; void getAttributes(vector<Attribute> &attrs) const { // __trace(); attrs.clear(); attrs = this->attrs; unsigned i; // For attribute in vector<Attribute>, name it as rel.attr for(i = 0; i < attrs.size(); ++i) { string tmp = tableName; tmp += "."; tmp += attrs[i].name; attrs[i].name = tmp; } }; ~TableScan() { iter->close(); }; }; class IndexScan : public Iterator { // A wrapper inheriting Iterator over IX_IndexScan public: RelationManager &rm; RM_IndexScanIterator *iter; string tableName; string attrName; vector<Attribute> attrs; char key[PAGE_SIZE]; RID rid; IndexScan(RelationManager &rm, const string &tableName, const string &attrName, const char *alias = NULL):rm(rm) { // Set members this->tableName = tableName; this->attrName = attrName; // __trace(); // cout << "IndexScan: attrName: " << attrName << endl; // Get Attributes from RM rm.getAttributes(tableName, attrs); // Call rm indexScan to get iterator iter = new RM_IndexScanIterator(); rm.indexScan(tableName, attrName, NULL, NULL, true, true, *iter); // Set alias if(alias) this->tableName = alias; }; // Start a new iterator given the new key range void setIterator(void* lowKey, void* highKey, bool lowKeyInclusive, bool highKeyInclusive) { iter->close(); delete iter; iter = new RM_IndexScanIterator(); rm.indexScan(tableName, attrName, lowKey, highKey, lowKeyInclusive, highKeyInclusive, *iter); }; RC getNextTuple(void *data) { int rc = iter->getNextEntry(rid, key); if(rc == 0) { rc = rm.readTuple(tableName.c_str(), rid, data); } return rc; }; void getAttributes(vector<Attribute> &attrs) const { // __trace(); attrs.clear(); attrs = this->attrs; unsigned i; // For attribute in vector<Attribute>, name it as rel.attr for(i = 0; i < attrs.size(); ++i) { string tmp = tableName; tmp += "."; tmp += attrs[i].name; attrs[i].name = tmp; } }; ~IndexScan() { iter->close(); }; }; class Filter : public Iterator { // Filter operator public: Filter(Iterator *input, // Iterator of input R const Condition &condition // Selection condition ); ~Filter(){}; RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; private: Iterator *_iterator; Condition _condition; }; class Project : public Iterator { // Projection operator public: Project(Iterator *input, // Iterator of input R const vector<string> &attrNames); // vector containing attribute names ~Project(){}; RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; private: Iterator *_iterator; vector<string> _attrNames; }; // Partition builder: used by GHJoin partitioning phase. // On its construction, each partition only has one page of buffer. class PartitionBuilder { public: PartitionBuilder(const string &partitionName, const vector<Attribute> &attrs); ~PartitionBuilder(); // Insert tuple into the partition. Buffer page will be automatically // be flushed when it's filled. RC insertTuple(void *tuple); // Flush remaining buffer (used in the last step) RC flushLastPage(); void getAttributes(vector<Attribute> &attrs); string getPartitionName(); private: RC init(); // create the partition file and initialize file handle private: string _fileName; vector<Attribute> _attrs; FileHandle _fileHandle; RecordBasedFileManager *_rbfm; SpaceManager *_sm; PagedFileManager *_pfm; char _buffer[PAGE_SIZE]; }; // Partition reader: used by GHJoin probing phase. // On its retrieval, all pages will be buffered. class PartitionReader { public: PartitionReader(const string &partitionName, const vector<Attribute> &attrs); ~PartitionReader(); // Get next tuple from the partition while caching it in memory RC getNextTuple(void *tuple, RID &rid, unsigned &size); // Get tuple from cache (should first continuously call getNextTuple() // until reaching the end. RC getTupleFromCache(void *tuple, unsigned &size, const RID &rid); void getAttributes(vector<Attribute> &attrs); unsigned getPageCount(); string getPartitionName(); private: RC init(); // open the partition file and get the file handle private: string _fileName; vector<Attribute> _attrs; FileHandle _fileHandle; unsigned _pageCount; unsigned _curPageNum; // current page number unsigned _curSlotNum; // current slot number RecordBasedFileManager *_rbfm; SpaceManager *_sm; PagedFileManager *_pfm; char **_buffer; // to hold the whole partition }; class GHJoin : public Iterator { // Grace hash join operator public: GHJoin(Iterator *leftIn, // Iterator of input R Iterator *rightIn, // Iterator of input S const Condition &condition, // Join condition (CompOp is always EQ) const unsigned numPartitions // # of partitions for each relation (decided by the optimizer) ); ~GHJoin(); RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; enum IterType { LEFT = 0, RIGHT }; private: RC partition(Iterator *iter, IterType iterType); void allocatePartition(Iterator *iter, IterType iterType); void deallocatePartition(IterType iterType); string getPartitionName(IterType iterType, unsigned num); // 1st hashing unsigned hash1(char *value, unsigned size); // 2nd hashing unsigned hash2(char *value, unsigned size); RC matchTuples(void *data); // Internal helper function. private: // Use join number to handle multiple joins in one query static int _joinNumberGlobal; int _joinNumber; Iterator *_leftIn; Iterator *_rightIn; vector<Attribute> _leftAttrs; vector<Attribute> _rightAttrs; Condition _condition; unsigned _numPartitions; vector<PartitionBuilder *> _leftPartitions; vector<PartitionBuilder *> _rightPartitions; PartitionReader * _leftReader; PartitionReader * _rightReader; unsigned _curPartition; // the current partition to read unordered_map<unsigned, vector<RID> > _hashMap; // the hash map for the second hashing // Buffered right tuple (Assume that always load left relations into the hash map) static char _rtuple[PAGE_SIZE]; static unsigned _rsize; unsigned _curLeftMapIndex; }; class BNLJoin : public Iterator { // Block nested-loop join operator public: BNLJoin(Iterator *leftIn, // Iterator of input R TableScan *rightIn, // TableScan Iterator of input S const Condition &condition, // Join condition const unsigned numRecords // # of records can be loaded into memory, i.e., memory block size (decided by the optimizer) ){}; ~BNLJoin(){}; RC getNextTuple(void *data){return QE_EOF;}; // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const{}; }; class INLJoin : public Iterator { // Index nested-loop join operator public: INLJoin(Iterator *leftIn, // Iterator of input R IndexScan *rightIn, // IndexScan Iterator of input S const Condition &condition // Join condition ); ~INLJoin(){}; RC getNextTuple(void *data); // For attribute in vector<Attribute>, name it as rel.attr void getAttributes(vector<Attribute> &attrs) const; private: RC matchTuples(void *data); private: Iterator *_leftIn; IndexScan *_rightIn; Condition _condition; vector<Attribute> _leftAttrs; vector<Attribute> _rightAttrs; // // Whether the rightIn has been called setIterator() // bool _initialized; RecordBasedFileManager *_rbfm; // Buffer for left relation tuples static char _ltuple[PAGE_SIZE]; static unsigned _lsize; }; class Aggregate : public Iterator { // Aggregation operator public: // Mandatory for graduate teams only // Basic aggregation Aggregate(Iterator *input, // Iterator of input R Attribute aggAttr, // The attribute over which we are computing an aggregate AggregateOp op // Aggregate operation ); // Optional for everyone. 5 extra-credit points // Group-based hash aggregation Aggregate(Iterator *input, // Iterator of input R Attribute aggAttr, // The attribute over which we are computing an aggregate Attribute groupAttr, // The attribute over which we are grouping the tuples AggregateOp op, // Aggregate operation const unsigned numPartitions // Number of partitions for input (decided by the optimizer) ) {}; ~Aggregate(){}; RC getNextTuple(void *data); // Please name the output attribute as aggregateOp(aggAttr) // E.g. Relation=rel, attribute=attr, aggregateOp=MAX // output attrname = "MAX(rel.attr)" void getAttributes(vector<Attribute> &attrs) const; private: RC process(); private: Iterator *_iterator; Attribute _aggAttr; AggregateOp _op; bool _gotResult; // Check whether we have got the result int _count; int _intSum; float _floatSum; int _intMin; float _floatMin; int _intMax; float _floatMax; }; #endif
72dce498ccf98541bdaae94015875aae44a9f42a
b65d3857428281466507674f8ca4f376490c81a2
/src/Box2DWorld.cpp
a1af004051fb2864fcbfd232a57c20ffb14993d3
[]
no_license
DCurro/gtmiami
24f59311f1769c1b0f33cdee5c02a777f79a53a3
02727faa870e61ad9496e5b944ff3d945383e62b
refs/heads/master
2021-09-24T16:31:07.733654
2018-10-12T00:45:29
2018-10-12T00:45:29
107,069,651
0
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
#include "Box2DWorld.hpp" #include <vector> #include <algorithm> #include "ClassChecker.hpp" #include "NavigationCell.hpp" #include "PlayEntity.hpp" Box2DWorld::Box2DWorld(const b2Vec2& gravity) : b2World(gravity) { } Box2DWorld::~Box2DWorld() { } #pragma Protected Methods void Box2DWorld::DrawJoint(b2Joint* joint) { b2World::DrawJoint(joint); } void Box2DWorld::DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color) { PlayEntity* bodyUserData = NULL; if (shape->GetBody()->GetUserData() != NULL) { bodyUserData = (PlayEntity*)shape->GetBody()->GetUserData(); } PlayEntity* fixtureUserData = NULL; if (shape->GetUserData() != NULL) { fixtureUserData = (PlayEntity*)shape->GetUserData(); } b2World::DrawShape(shape, xf, color); }
17258ccdd3f62cecf47041002b9c6877a34db370
4f4ddc396fa1dfc874780895ca9b8ee4f7714222
/src/xtp/Samples/CommandBars/MSDI/SomeView.cpp
d5f687abdc0287cdfb34b04e7b51f607616159cf
[]
no_license
UtsavChokshiCNU/GenSym-Test2
3214145186d032a6b5a7486003cef40787786ba0
a48c806df56297019cfcb22862dd64609fdd8711
refs/heads/master
2021-01-23T23:14:03.559378
2017-09-09T14:20:09
2017-09-09T14:20:09
102,960,203
3
5
null
null
null
null
UTF-8
C++
false
false
3,020
cpp
// SomeView.cpp : implementation of the CSomeView class // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // [email protected] // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MSDI.h" #include "SomeDoc.h" #include "SomeView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSomeView IMPLEMENT_DYNCREATE(CSomeView, CEditView) BEGIN_MESSAGE_MAP(CSomeView, CEditView) //{{AFX_MSG_MAP(CSomeView) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CEditView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CEditView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CEditView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSomeView construction/destruction CSomeView::CSomeView() { } CSomeView::~CSomeView() { } BOOL CSomeView::PreCreateWindow(CREATESTRUCT& cs) { BOOL bPreCreated = CEditView::PreCreateWindow(cs); cs.style &= ~(ES_AUTOHSCROLL|WS_HSCROLL); // Enable word-wrapping return bPreCreated; } ///////////////////////////////////////////////////////////////////////////// // CSomeView drawing void CSomeView::OnDraw(CDC* /*pDC*/) { } ///////////////////////////////////////////////////////////////////////////// // CSomeView printing BOOL CSomeView::OnPreparePrinting(CPrintInfo* pInfo) { // default CEditView preparation return CEditView::DoPreparePrinting(pInfo); } void CSomeView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) { CEditView::OnBeginPrinting(pDC, pInfo); } void CSomeView::OnEndPrinting(CDC* pDC, CPrintInfo* pInfo) { CEditView::OnEndPrinting(pDC, pInfo); } ///////////////////////////////////////////////////////////////////////////// // CSomeView diagnostics #ifdef _DEBUG void CSomeView::AssertValid() const { CEditView::AssertValid(); } void CSomeView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } CSomeDoc* CSomeView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSomeDoc))); return (CSomeDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSomeView message handlers
1baeb273038cfa991fe8fd7ace279baee9a13dd7
0f2a65e0d0f7a24c63ddd4d87a29c65dd95e743e
/src/visible.hpp
ba157cbcaf4ab7bd4e7e1cf031f6cbfb617ae168
[]
no_license
SondreHusevold/DungeonWarrior
bda016be46eefc4aaee517a8bb489753e20ffffd
2d8e1431e5c7596a37c06c5efa3cb8fe018d73c2
refs/heads/master
2021-06-21T19:51:01.972860
2017-08-17T14:06:10
2017-08-17T14:06:10
100,608,111
0
0
null
null
null
null
UTF-8
C++
false
false
1,698
hpp
#ifndef VISIBLE_HPP /* * Base klasse for alt som er synlig. * Har en char som representerer bildet, informasjon om elementet, metoder for å aktivere/deaktivere synlighet, beveglighet og tilgang. */ #define VISIBLE_HPP #include "position.hpp" #include <string> class visible:public position{ char icon_; std::string info_; bool visible_; bool accessable_; bool moveable_; public: // See resources.qrc static const char NAKED_PLAYER='@'; static const char ARMORED_PLAYER='A'; static const char LOOTABLE='L'; static const char GHOST='F'; static const char PRIEST='R'; static const char ELF='E'; static const char STAIR_DOWN='D'; static const char FLOOR='.'; static const char STAIR_UP='U'; static const char CHEST='C'; static const char ARMORED_CAPE_PLAYER='P'; static const char CREATURE_BARD='B'; static const char CREATURE_BOSS='O'; static const char CREATURE_GIRL='W'; static const char CREATURE_KING='K'; static const char CREATURE_NINJA='N'; static const char HOUSE='H'; static const char DEFAULT_MONSTER='M'; static const char SKELETON='S'; static const char TREE='T'; static const char WALL='#'; static const int NO_ACTION=0; static const int NEXT_LEVEL=1; static const int PREV_LEVEL=2; visible(char icon, std::string info, int x, int y); virtual int access()=0;//return en av konstantene char get_icon(); void set_icon(char c); void set_visible(bool v); void set_accessable(bool a); void set_moveable(bool m); void set_info(std::string newinfo); bool is_visible(); bool is_moveable(); bool is_accessable(); bool is_visible(bool v); virtual std::string to_string();//hva er dette? virtual ~visible(){} }; #endif
198adb5b2f4c5b5f024c23726614ed1185a2617c
028823a52e2ef93fd3a53d74ae6c5e459a2f954e
/omniWheelCareRobot/rosCode/devel/include/dobot/GetPTPCoordinateParamsRequest.h
33cd36b6a70b1c329cad5cdf1c913e55729c5fe6
[]
no_license
wzh1998/Care_Robot
fe6ac33f4762dfa996b70326ff8adb30965c5320
f416514348825b1a405718c93834906d7263f980
refs/heads/master
2022-11-07T19:40:19.235642
2021-09-05T15:11:44
2021-09-05T15:11:44
214,085,698
2
0
null
2022-10-18T19:25:13
2019-10-10T04:22:25
Makefile
UTF-8
C++
false
false
5,093
h
// Generated by gencpp from file dobot/GetPTPCoordinateParamsRequest.msg // DO NOT EDIT! #ifndef DOBOT_MESSAGE_GETPTPCOORDINATEPARAMSREQUEST_H #define DOBOT_MESSAGE_GETPTPCOORDINATEPARAMSREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace dobot { template <class ContainerAllocator> struct GetPTPCoordinateParamsRequest_ { typedef GetPTPCoordinateParamsRequest_<ContainerAllocator> Type; GetPTPCoordinateParamsRequest_() { } GetPTPCoordinateParamsRequest_(const ContainerAllocator& _alloc) { (void)_alloc; } typedef boost::shared_ptr< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> const> ConstPtr; }; // struct GetPTPCoordinateParamsRequest_ typedef ::dobot::GetPTPCoordinateParamsRequest_<std::allocator<void> > GetPTPCoordinateParamsRequest; typedef boost::shared_ptr< ::dobot::GetPTPCoordinateParamsRequest > GetPTPCoordinateParamsRequestPtr; typedef boost::shared_ptr< ::dobot::GetPTPCoordinateParamsRequest const> GetPTPCoordinateParamsRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace dobot namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'dobot': ['/home/sz/omniWheelCareRobot/rosCode/src/dobot_ws/src/dobot/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > { static const char* value() { return "d41d8cd98f00b204e9800998ecf8427e"; } static const char* value(const ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL; static const uint64_t static_value2 = 0xe9800998ecf8427eULL; }; template<class ContainerAllocator> struct DataType< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > { static const char* value() { return "dobot/GetPTPCoordinateParamsRequest"; } static const char* value(const ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > { static const char* value() { return "\n\ "; } static const char* value(const ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream&, T) {} ROS_DECLARE_ALLINONE_SERIALIZER }; // struct GetPTPCoordinateParamsRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream&, const std::string&, const ::dobot::GetPTPCoordinateParamsRequest_<ContainerAllocator>&) {} }; } // namespace message_operations } // namespace ros #endif // DOBOT_MESSAGE_GETPTPCOORDINATEPARAMSREQUEST_H
4953d4fad6e9a0ba1459ce9e28afc97da85163ef
d3a4ba3b8a7003556bc3f384ce2fe475ec7a16a5
/copierworker.h
e5344755047cc4efedee57dd4250021797addb48
[]
no_license
dryajov/filecopier
1838f855b6a58f87fa4f1f5432f5b0645a9929a6
cb62399d7b11a58ac5cdf93dec23e5d51a81b0f5
refs/heads/master
2020-05-24T13:42:57.125910
2015-01-09T00:02:15
2015-01-09T00:02:15
29,211,341
0
0
null
null
null
null
UTF-8
C++
false
false
974
h
#ifndef COPIERWORKER_H #define COPIERWORKER_H #include <QObject> #include <QFile> #include <QMutex> #include <QWaitCondition> #include "engines/copyenginedefault.h" class CopierWorker : public QObject, ICopyEngineCallback { Q_OBJECT public: CopierWorker(QString source, QString dest, QString basePath = QString()); ~CopierWorker(); void resume() { if (m_copyEngine) m_copyEngine->resume(); } void pause() { if (m_copyEngine) m_copyEngine->pause(); } void cancel() { if (m_copyEngine) m_copyEngine->cancel(); } void writtenBytes(long long &bytes); signals: void bytesWritten(qint64); void error(QString file); void done(); public slots: void run(); private: void writtenBytes(long long bytes); private: QString m_source; QString m_dest; QString m_basePath; ICopyEngine *m_copyEngine; }; #endif // COPIERWORKER_H
c5ab0f23fc9c81abe4ee31c33fff89ad72a05054
f88f36f96e86f28a12d373e4c8ff4cbe2de9f8d0
/Algorithms/Algorithms/number.h
012339ff0700bf31eb6457e8bde703d56f2746fa
[]
no_license
dlyz/cp-algorithms
c6107d9f8d5b349abb7148d3bee12d8c2175089a
90d10bddfe7ee00dd7fa25937ae6c4484ef4651d
refs/heads/master
2021-01-01T17:49:33.888101
2017-11-07T12:39:51
2017-11-07T12:39:51
98,166,793
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,729
h
#pragma once #include "header.h" template<typename T> T gcd(T a, T b) { return b ? gcd(b, a%b) : a; } template<typename T> T lcm(T a, T b) { return a/gcd(a, b)*b; } //до n включительно int GetPrimes(int n, vector<bool>& prime) { int cnt = 0; n++; prime.assign(n, true); if (n >= 0) prime[0] = false; if (n >= 1) prime[1] = false; forn(i, n) { if (prime[i]) { ++cnt; for(int j = 2*i; j < n; j += i) { prime[j] = false; } } } return cnt; } //до n включительно vint GetPrimes(int n) { vector<bool> vb; GetPrimes(n, vb); vint res; forn(i, vb.size()) { if (vb[i]) res.push_back(i); } return res; } // TODO: improve to sqrt(n) // TODO: go only with primes void GetPrimeDivisors(int64 n, vector<pii>& v) { v.clear(); for(int i = 2; i <= n; i++) { if (n%i == 0) { v.push_back(mp(i, 0)); do { ++v.back().second; n /= i; } while (n%i == 0); } } } // TODO: improve to sqrt(n) void GetPrimeDivisors(int64 n, vint& v) { v.clear(); for(int i = 2; i <= n && n > 1; i++) { while(n%i == 0) { v.push_back(i); n /= i; } } } template<typename T, typename U> T Pow(const T& x, U y) { if (y == 0) return T(1); T p = Pow(x, y >> 1); p *= p; if (y & 1) { p *= x; } return p; } template<typename T, typename U> T PowMod(const T& x, U y, const T& MOD) { if (y == 0) return T(1); T p = Pow(x, y >> 1); p *= p; p %= MOD; if (y & 1) { p *= x; p %= MOD; } return p; } // TODO: TEST! template<typename T, typename U> T PowNRec(const T& x, U y) { int cnt = 0; U ty = y; while (ty) { ++cnt; ty >>= 1; } T p = T(1); while (cnt) { p *= p; if (y & bit(--cnt)) { p *= x; } } return p; }
[ "lda@LYZDA" ]
lda@LYZDA
50fd34d9f839fa28c42606df263813b4e096f901
5bd1f7d195bcabd66c13136b372fa12ab42aef1b
/catkin_ws/devel/include/astar/GoToPosRequest.h
8ad30c0211ceb32af3c559962ce1959e72be286d
[]
no_license
Richardwang0326/sis_project
7533bbf870d64aae9ca992ca9d796b2f1e20b282
e22916e2db8ba37066c1a44f48eee47999267bc5
refs/heads/main
2023-02-07T16:23:46.964205
2020-12-18T02:45:43
2020-12-18T02:45:43
319,234,302
0
0
null
null
null
null
UTF-8
C++
false
false
4,576
h
// Generated by gencpp from file astar/GoToPosRequest.msg // DO NOT EDIT! #ifndef ASTAR_MESSAGE_GOTOPOSREQUEST_H #define ASTAR_MESSAGE_GOTOPOSREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace astar { template <class ContainerAllocator> struct GoToPosRequest_ { typedef GoToPosRequest_<ContainerAllocator> Type; GoToPosRequest_() : pos(0) { } GoToPosRequest_(const ContainerAllocator& _alloc) : pos(0) { (void)_alloc; } typedef int8_t _pos_type; _pos_type pos; typedef boost::shared_ptr< ::astar::GoToPosRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::astar::GoToPosRequest_<ContainerAllocator> const> ConstPtr; }; // struct GoToPosRequest_ typedef ::astar::GoToPosRequest_<std::allocator<void> > GoToPosRequest; typedef boost::shared_ptr< ::astar::GoToPosRequest > GoToPosRequestPtr; typedef boost::shared_ptr< ::astar::GoToPosRequest const> GoToPosRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::astar::GoToPosRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::astar::GoToPosRequest_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::astar::GoToPosRequest_<ContainerAllocator1> & lhs, const ::astar::GoToPosRequest_<ContainerAllocator2> & rhs) { return lhs.pos == rhs.pos; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::astar::GoToPosRequest_<ContainerAllocator1> & lhs, const ::astar::GoToPosRequest_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace astar namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::astar::GoToPosRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::astar::GoToPosRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::astar::GoToPosRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::astar::GoToPosRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::astar::GoToPosRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::astar::GoToPosRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::astar::GoToPosRequest_<ContainerAllocator> > { static const char* value() { return "82b076b0db1717b26c92c819d52e9d17"; } static const char* value(const ::astar::GoToPosRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x82b076b0db1717b2ULL; static const uint64_t static_value2 = 0x6c92c819d52e9d17ULL; }; template<class ContainerAllocator> struct DataType< ::astar::GoToPosRequest_<ContainerAllocator> > { static const char* value() { return "astar/GoToPosRequest"; } static const char* value(const ::astar::GoToPosRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::astar::GoToPosRequest_<ContainerAllocator> > { static const char* value() { return "\n" "int8 pos\n" ; } static const char* value(const ::astar::GoToPosRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::astar::GoToPosRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.pos); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct GoToPosRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::astar::GoToPosRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::astar::GoToPosRequest_<ContainerAllocator>& v) { s << indent << "pos: "; Printer<int8_t>::stream(s, indent + " ", v.pos); } }; } // namespace message_operations } // namespace ros #endif // ASTAR_MESSAGE_GOTOPOSREQUEST_H
cb62050b99a42105bd05a0f25916ee61eaf29962
799c01371abc94f433071e411005432fd30c0bc3
/Student XML/src/Exam.cpp
f0674711954fbe8a25b3caa5489af188532b8a67
[]
no_license
mushkoff/EGTprojects
02df58b42d951cb19d970fed3cb3436903b8f678
a7cb401cd5cd1a9225f47c69eac7264b5e3c7e69
refs/heads/master
2020-12-30T13:08:02.377710
2017-06-23T10:32:52
2017-06-23T10:32:52
91,326,599
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
862
cpp
/* * Exam.cpp * * Created on: 26.05.2017 ã. * Author: user */ #include "Exam.h" Exam::Exam(string name, string teacher, double grade) { setName(name); setTeacher(teacher); setGrade(grade); } Exam::Exam() { setName(" "); setTeacher(" "); setGrade(0.0); } Exam::~Exam() { // TODO Auto-generated destructor stub } const string& Exam::getName() const { return name; } const string& Exam::getTeacher() const { return teacher; } double Exam::getGrade() const { return grade; } void Exam::setGrade(double grade) { this->grade = grade; } void Exam::setName(const string& name) { this->name = name; } void Exam::setTeacher(const string& teacher) { this->teacher = teacher; } void Exam::printInfo() { cout<<"Exam object is: "<<getName()<<endl; cout<<"The lector is: "<<getTeacher()<<endl; cout<<"The grade is: "<<getGrade()<<endl; }
304cc1c6e01662eca155b722e29629f59abf7795
9eba93e5540436ba2e1f7935e0e9ab9a10353c86
/src/core/Debuger.cpp
151f74195daa089f93986caee992024313a4930c
[ "Unlicense" ]
permissive
stonedreamforest/what
fc5fd026849365f1c93cc3de584b197e8423d053
4256f849fe963e2c5cd0145fb1e7652ae2245768
refs/heads/master
2020-04-05T12:27:18.020181
2019-11-14T09:57:30
2019-11-14T09:57:30
156,870,621
4
1
null
null
null
null
UTF-8
C++
false
false
1,585
cpp
#include "Debuger.h" #pragma comment(lib,"ntdll.lib") EXTERN_C NTSYSAPI LONG NTAPI NtSuspendProcess(HANDLE ProcessHandle); EXTERN_C NTSYSAPI LONG NTAPI NtResumeProcess(HANDLE ProcessHandle); Debuger::Debuger() { } Debuger::~Debuger() { } void Debuger::run() { if (m_hProcess != nullptr) { NtResumeProcess(m_hProcess); } } void Debuger::stop() { if (m_hProcess != nullptr) { NtSuspendProcess(m_hProcess); } } void Debuger::set_bp(void* Address) { if (m_hProcess != nullptr && Address != nullptr) { DWORD Old = 0; unsigned char byteCode = 0; SIZE_T BytesRead = 0; SIZE_T BytesWritten = 0; NtSuspendProcess(m_hProcess); ReadProcessMemory(m_hProcess , Address , &byteCode , 1 , &BytesRead); VirtualProtectEx(m_hProcess , Address , 1 , PAGE_EXECUTE_READWRITE , &Old); WriteProcessMemory(m_hProcess , Address , &m_cli , 1 , &BytesWritten); VirtualProtectEx(m_hProcess , Address , 1 , Old , &Old); m_vecBPList.push_back(std::make_pair(Address , byteCode)); NtResumeProcess(m_hProcess); } } bool Debuger::unset_bp(void* Address) { if (m_hProcess != nullptr && Address != nullptr) { for (size_t i = 0; i < m_vecBPList.size(); i++) { if (Address == m_vecBPList[i].first) { DWORD Old = 0; SIZE_T BytesWritten = 0; VirtualProtectEx(m_hProcess , Address , 1 , PAGE_EXECUTE_READWRITE , &Old); WriteProcessMemory(m_hProcess , Address , &m_vecBPList[i].second , 1 , &BytesWritten); VirtualProtectEx(m_hProcess , Address , 1 , Old , &Old); m_vecBPList.erase(m_vecBPList.begin() + i); return true; } } } return false; }
278d2cc7d382f0c11d055896ff74e8d61fdaaeb7
e16a922542786c77bff0d4a981d494db59cd593c
/day05/ex00/Bureaucrat.hpp
fca21716790d3d0460045965616e1a2a04a4b24d
[]
no_license
vkaz/CPP_POOL-42
4cbe837c539fd33dd3658b91f32f1020928a259d
8b4b334a3ae47b408fbcea28ce534a9028b04616
refs/heads/master
2020-05-03T22:40:42.554339
2019-04-13T09:41:51
2019-04-13T09:41:51
178,847,734
0
0
null
null
null
null
UTF-8
C++
false
false
1,256
hpp
#ifndef BUREAUCRAT_HPP # define BUREAUCRAT_HPP # include <iostream> # include <string> # include <exception> class Bureaucrat { private: std::string _name; int _grade; public: Bureaucrat(); ~Bureaucrat(); Bureaucrat(Bureaucrat const &rhs); Bureaucrat(std::string name, int grade); Bureaucrat &operator=(Bureaucrat const &rhs); class GradeTooHighException : public std::exception { public: GradeTooHighException(); ~GradeTooHighException() throw(); GradeTooHighException(GradeTooHighException const &rhs); GradeTooHighException &operator=(GradeTooHighException const &rhs); char const *what() const throw(); }; class GradeTooLowException : public std::exception { public: GradeTooLowException(); ~GradeTooLowException() throw(); GradeTooLowException(GradeTooLowException const &rhs); GradeTooLowException &operator=(GradeTooLowException const &rhs); char const *what() const throw(); }; std::string getName() const; void increment(); void decrement(); int getGrade() const; }; std::ostream &operator<<(std::ostream &out, const Bureaucrat &rhs); #endif
76d185810ae9ad6424c39a69b2b5377c6dac9d50
111c3ebecfa9eac954bde34b38450b0519c45b86
/SDK_Perso/include/EagleFM/FMBase/Header/FMEngineeringStructure/ADElement.h
88d0e13142102b26b5bca5df67b22c3b1db2864e
[]
no_license
1059444127/NH90
25db189bb4f3b7129a3c6d97acb415265339dab7
a97da9d49b4d520ad169845603fd47c5ed870797
refs/heads/master
2021-05-29T14:14:33.309737
2015-10-05T17:06:10
2015-10-05T17:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,666
h
#ifndef __ADElement_h__ #define __ADElement_h__ #include "Base.h" #include "FMDynamics/DynamicBody.h" #include "FMAerodynamics/AerodynamicBody.h" #include "FMEngineeringStructure/ControlSurface.h" #include "FMSpace/IBasicAtmosphere.h" #include <ed/vector.h> namespace EagleFM { class RigidBody; //структура-хранилище, описывающая управляющую поверхность, включая ее аэродинамику struct ADControl { ADControl(AerodynamicBody* ab, ControlSurface* cs) { pADBody = ab; pControlSurface = cs; } //не хозяин AerodynamicBody *pADBody; ControlSurface *pControlSurface; }; typedef ed::vector<ADControl> ADControlVector; //Класс, представляющий аэродинамический элемент конструкции планера //(несущие, управляющие поверхности, фюзеляж, парашют, шассии и т.д.). //Имеет собственные позицию и ориентацию. По данным об общей позиции и ориентации //планера, учитывая собственные данные, вычисляет по аэродинамическому телу (AerodynamicBody*) //аэродинамическую силу, центр ее давления //и собственный момент демпфирования class FMBASE_API ADElement { public: ADElement(AerodynamicBody*); ADElement(AerodynamicBody*, const DynamicState&); void initShakeFilter() { ShakeFilterOn = true; } //пока просто вклчается флаг void initMachCrit(double Mach0, double Mach1, double Mach2, double K1, double K2); //три точки и два к-та void initStrengthProp(RigidBody* pRBody, int Element, double ForceMax, double ForceDamage, double IF_p = 2.0); //задать прочностные характеристики void addControlSurface(AerodynamicBody*, ControlSurface*); void setIF(DynamicBody *pDBody, double IF, bool CheckAlredy = false); //поломать (0...1) 0 - совсем сломали, 1 - целый, checkAlredy = true - запрещает увеличивать IF //управление (может следует сделать localDState public ??) void setYawPitchRoll(float _yaw, float _pitch, float _roll) { selfDState.yaw = _yaw; selfDState.pitch = _pitch; selfDState.roll = _roll; } void setYaw(float _yaw) { selfDState.yaw = _yaw; } void setPitch(float _pitch) { selfDState.pitch = _pitch; } void setRoll(float _roll) { selfDState.roll = _roll;} void setADFactor(int Num, double Value) { if(Num >= 0 && Num < 100) ADFactors[Num] = Value; } //Аэродинамический расчет - ( физическое тело(планер),точки подстилающей поверхности, нормаль к подст.пов., тип поверхности void calcElementsAerodynamics(DynamicBody *pDBody, const Vec3 &SurfacePointPosition_w, const Vec3 &SurfaceNormal_w, int SurfaceType, bool ShakeOn = true); void checkFailureLoad(double dt); //проверить разрушающую АД нагрузку // Доступ Vec3 getADForce_l() const { return ADForce_l; } Vec3 getADForce_pos_l() const { return ADForce_pos_l; } Vec3 getOwnADDamperMoment_l() const { return OwnADDamperMoment_l; } double getMach() const { return Mach; } double getSpeedVim() const { return SpeedVim; } double getAoA() const { return AoA; } double getAoS() const { return AoS; } double getNormalHeight() const { return NormalHeight; } float getYaw() const { return selfDState.yaw; } float getPitch() const { return selfDState.pitch; } float getRoll() const { return selfDState.roll; } double getIntegrityFactor() const { return IntegrityFactor; } AerodynamicBody* getADBody() const { return pADBody;} double getShakeAmplitude() const { return ShakeAmpl; } const DynamicState & getDynamicState() const { return selfDState; } private: //рачет АД силы (в случае выхода из ламинарной зоны - тряска углов и пересчет) void calcAerodynamicForces(double SpeedVim, double Mach, double AoA, double AoS, Vec3 RotV_l_l, Vec3* ADForce_l_l, Vec3* ADForce_pos_l_l, Vec3* OwnADDamperMoment_l_l, double* ShakeAmpl, double* ShakeFreq); protected: DynamicState selfDState; // физические свойства АД элемента планера private: // не хозяин: ADControlVector ADControls; // управляющие элементы (элероны, рули высоты...) AerodynamicBody *pADBody; // аэродинамика элемента планера RigidBody *pRBody; // для разрушения (при определенном Element) // хозяин: Vec3 ADForce_l; // Аэродинамическая сила Vec3 ADForce_pos_l; // Координаты ЦД Vec3 OwnADDamperMoment_l; // Демпфирующий момент double ShakeAmpl; // аплитуда АД тряски double ShakeFreq; // частота АД тряски bool ShakeFilterOn; // генераторы АД тряски включены public: Math::IIR_Filter ShakeFilterAoA; // генератор АД тряски по УА Math::IIR_Filter ShakeFilterAoS; // генератор АД тряски по УС private: Randomizer ShakeRndAoA; // шум АД тряски по УА Randomizer ShakeRndAoS; // шум АД тряски по УС double MachCrit0; // тряска при критическом числе М (начало тряски) double MachCrit1; double MachCrit2; // макс.тряска double MachCritK1; // к-т тряски при числе М выше MachCrit1 double MachCritK2; // к-т тряски при числе М выше MachCrit2 // Прочностные характеристики int Element; // номер в таблице элементов ЛА (для DM) double ForceMax; // сила разрушения double ForceDamage; // сила деформации double IF_pow; // степень ослабления прочностных характеристик в зависимости от IntegrityFactor double ForceMaxCurr; // текущая макс.сила при превышении деформации (для однократного износа) double ForcePrev; // пред.сила для обнаружения факта пребывания и выхода из зоны деформации // Параметры обтекания АД элемента планера double SpeedVim, // Скоростной напор Mach, // Число Маха AoA, // Угол атаки AoS, // Угол скольжения NormalHeight, // Расстояние до подстилающей поверхности IntegrityFactor, // Коэффициент повреждения элемента конструкции ADFactors[100]; // Коэффициенты влияния на аэродинамику элемента конструкции bool Turbulence; // флаг учета турбулентности при расчете АД }; } #endif
3b0c2b4ee9812a47ecf75eb640c88a6dec36784f
67b7465ff4f3914db515ac4b23593760e32f8c2d
/Demo/main.cpp
ad1b4bfd7b706e387a8c27aa0c40e67693a2c80c
[]
no_license
VoyagerWho/Kalejdoskop
8ca2a9e979dd6f511011021de6c9d700fd3a0c59
4b200c0534039eedc9b9eb63f9acc7895dc23994
refs/heads/main
2023-05-08T19:06:53.394329
2021-05-28T17:45:37
2021-05-28T17:45:37
363,961,721
0
1
null
null
null
null
UTF-8
C++
false
false
5,249
cpp
#include <iostream> #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include "Classes/SidebarMenu.h" #include <cmath> #define M_PI 3.141592653589 void displayHandler(const sf::Texture& tex) { sf::RenderWindow window(sf::VideoMode(200, 200), "Display", sf::Style::Default); window.setFramerateLimit(30); sf::Event evnt; sf::Sprite sp; sp.setTexture(tex); while(window.isOpen()) { while(window.pollEvent(evnt)) { switch (evnt.type) { case sf::Event::Closed: window.close(); break; default: break; } } window.clear(sf::Color(64,64,64)); window.draw(sp); window.display(); } } void makeDrawing(sf::RenderTexture& tex) { sf::CircleShape c(30.0f); sf::Texture im; im.loadFromFile("Files/Kalejdoskop.png"); sf::Sprite sp; sp.setTexture(im); //sp.scale(0.25, 0.25); tex.clear(sf::Color::Transparent); c.setFillColor(sf::Color::Red); c.setOutlineColor(sf::Color::Black); c.setOutlineThickness(1.0f); c.setPosition(85.0f, 85.0f); tex.draw(c); c.setFillColor(sf::Color::Blue); c.setOutlineColor(sf::Color::Black); c.setOutlineThickness(1.0f); c.setPosition(115.0f, 55.0f); c.setPointCount(3); tex.draw(c); c.setFillColor(sf::Color::Green); c.setOutlineColor(sf::Color::Black); c.setOutlineThickness(1.0f); c.setPosition(55.0f, 115.0f); c.setPointCount(4); tex.draw(c); c.setFillColor(sf::Color::Magenta); c.setOutlineColor(sf::Color::Black); c.setOutlineThickness(1.0f); c.setPosition(115.0f, 115.0f); c.setPointCount(6); tex.draw(c); c.setFillColor(sf::Color::Cyan); c.setOutlineColor(sf::Color::Black); c.setOutlineThickness(1.0f); c.setPosition(55.0f, 55.0f); c.setPointCount(8); tex.draw(c); tex.draw(sp); tex.display(); } int main() { sf::RenderWindow window(sf::VideoMode(1200, 800), "Demo", sf::Style::Default); window.setFramerateLimit(60); sf::RenderTexture renderTex; renderTex.create(800, 800); makeDrawing(renderTex); sf::Thread displayThread(displayHandler, renderTex.getTexture()); sf::Cursor cursor; sf::Event evnt; sf::Clock clock; float deltaTime=0.0; float angle=0.0f; float speed=0.0f; SidebarMenu sidemenu(window, SidebarMenu::Right, 4); sidemenu.flags ^= SidebarMenu::showLabel | SidebarMenu::visible; sidemenu.buttons[0].setLabelString("Display"); sidemenu.buttons[1].setLabelString("Start"); sidemenu.buttons[2].setLabelString("Stop"); sidemenu.buttons[3].setLabelString("Off"); sidemenu.buttons[3].flags ^= AButtonCircle::showLabel; sidemenu.buttons[3].setTextureRect(sf::IntRect(0, 0, 256, 256)); sidemenu.buttons[3].loadTextureFromFile("Files/OnOff.png"); sf::VertexArray triangle(sf::Triangles, 3); while(window.isOpen()) { deltaTime=clock.restart().asSeconds(); angle+=deltaTime*speed; angle = angle > 2*M_PI ? angle - 2*M_PI : angle; while(window.pollEvent(evnt)) { switch (evnt.type) { case sf::Event::Closed: window.close(); break; case sf::Event::Resized: { window.setView(sf::View(sf::FloatRect(0.0f, 0.0f, window.getSize().x, window.getSize().y))); sidemenu.setPosition(window); }break; case sf::Event::MouseMoved: { cursor.loadFromSystem(sf::Cursor::Arrow); if(sidemenu.onHover(evnt)) cursor.loadFromSystem(sf::Cursor::Hand); window.setMouseCursor(cursor); }break; case sf::Event::MouseButtonPressed: { if(sidemenu.onClick(evnt)) { switch (sidemenu.getOption()) { case 0: { displayThread.launch(); }break; case 1: { speed=M_PI/25; }break; case 2: { speed=0.0f; }break; case 3: { displayThread.terminate(); window.close(); }break; default: break; } } }break; default: break; } } window.clear(sf::Color(64,64,64)); sidemenu.update(deltaTime); window.draw(sidemenu); for(unsigned i=0;i<16;i++) { triangle[0].position = sf::Vector2f(400.0f, 400.0f); triangle[0].texCoords = sf::Vector2f(400.0f, 400.0f); triangle[i%2+1].position = sf::Vector2f(400.0f+400.f*cos(i*(M_PI/8.0)), 400.0f+400.f*sin(i*(M_PI/8.0))); triangle[i%2+1].texCoords = sf::Vector2f(400.0f+400.f*cos((i%2)*(M_PI/8.0)+angle), 400.0f+400.f*sin((i%2)*(M_PI/8.0)+angle)); triangle[i%2+1].position = sf::Vector2f(400.0f+400.f*cos((i+1)*(M_PI/8.0)), 400.0f+400.f*sin((i+1)*(M_PI/8.0))); triangle[i%2+1].texCoords = sf::Vector2f(400.0f+400.f*cos((i%2)*(M_PI/8.0)+angle), 400.0f+400.f*sin((i%2)*(M_PI/8.0)+angle)); window.draw(triangle, &renderTex.getTexture()); } window.display(); } return 0; }
81e77b97cb0ad52cb115d56a3773da95b2be6e73
2a40195da63738b77a31ddab3c9a25c17f137c5a
/Adafruit_GFX/Adafruit_GFX.h
dc616275d6d0f60d7b8f18e1af062e7d8e5728b7
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
TheGreenEngineersCompany/MOS
03216e978f1d8e4376906512a3d60079d9cf3d54
47e4e750eac55b9e0cf94fdcdbaba6bd7ecf8df6
refs/heads/master
2021-01-17T17:38:21.454435
2016-08-09T01:51:48
2016-08-09T01:51:48
62,985,143
0
0
null
null
null
null
UTF-8
C++
false
false
4,147
h
#ifndef _ADAFRUIT_GFX_H #define _ADAFRUIT_GFX_H #if ARDUINO >= 100 #include "Arduino.h" #include "Print.h" #else #include "WProgram.h" #endif #define adagfxswap(a, b) { int16_t t = a; a = b; b = t; } #if !defined(ESP8266) #define swap(a, b) adagfxswap(a, b) #endif class Adafruit_GFX : public Print { public: Adafruit_GFX(int16_t w, int16_t h); // Constructor // This MUST be defined by the subclass: virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0; // These MAY be overridden by the subclass to provide device-specific // optimized code. Otherwise 'generic' versions are used. virtual void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color), drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color), drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color), drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color), fillScreen(uint16_t color), invertDisplay(boolean i); // These exist only with Adafruit_GFX (no subclass overrides) void drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color), fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color), fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint16_t color), drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color), fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color), drawRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color), fillRoundRect(int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color), drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color), drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color, uint16_t bg), drawXBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color), drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, uint16_t bg, uint8_t size), setCursor(int16_t x, int16_t y), setTextColor(uint16_t c), setTextColor(uint16_t c, uint16_t bg), setTextSize(uint8_t s), setTextWrap(boolean w), setRotation(uint8_t r), cp437(boolean x=true); #if ARDUINO >= 100 virtual size_t write(uint8_t); #else virtual void write(uint8_t); #endif int16_t height(void) const; int16_t width(void) const; uint8_t getRotation(void) const; // get current cursor position (get rotation safe maximum values, using: width() for x, height() for y) int16_t getCursorX(void) const; int16_t getCursorY(void) const; protected: const int16_t WIDTH, HEIGHT; // This is the 'raw' display w/h - never changes int16_t _width, _height, // Display w/h as modified by current rotation cursor_x, cursor_y; uint16_t textcolor, textbgcolor; uint8_t textsize, rotation; boolean wrap, // If set, 'wrap' text at right edge of display _cp437; // If set, use correct CP437 charset (default is off) }; class Adafruit_GFX_Button { public: Adafruit_GFX_Button(void); void initButton(Adafruit_GFX *gfx, int16_t x, int16_t y, uint8_t w, uint8_t h, uint16_t outline, uint16_t fill, uint16_t textcolor, char *label, uint8_t textsize); void drawButton(boolean inverted = false); boolean contains(int16_t x, int16_t y); void press(boolean p); boolean isPressed(); boolean justPressed(); boolean justReleased(); private: Adafruit_GFX *_gfx; int16_t _x, _y; uint16_t _w, _h; uint8_t _textsize; uint16_t _outlinecolor, _fillcolor, _textcolor; char _label[10]; boolean currstate, laststate; }; #endif // _ADAFRUIT_GFX_H
eed0d20fc2c9b71fedf72de57ffe886903e70dd4
41d3fe57d1695bdbfa24b6bdd08541a0a02986e9
/project/Recorder.h
89f3eb47c8e425a9f2c8d34d86396c58491a2d3c
[]
no_license
Kazahmedoff/projects
2c381dd4982b8389addc4e3cedae5b411f428b2e
fc64744e2b599ba7c8a40d363dbdaac00d4ad80f
refs/heads/master
2021-09-05T07:29:04.518543
2018-01-25T07:39:58
2018-01-25T07:39:58
68,916,811
0
0
null
null
null
null
UTF-8
C++
false
false
640
h
#pragma once #ifndef RECORDER_H #define RECORDER_H #include "Triangle.h" #include "Image.h" #include <list> using namespace std; using namespace Service::Modeling::Geometry; namespace Service { namespace Saving { class Recodrer : public exception { public: static bool WriteModelToBinarySTL(list<Triangle>&, string); static bool WriteModelToSTL(list<Triangle>&, string); static bool WriteModelToPLY(list<Triangle>&, string); static bool WriteSliceToBinaryFile(Image, string); private: virtual const char* what() const throw() { return "Error was happened in during writing!"; } }; } } #endif //RECORDER_H
2672dd564f679fe5d2f31d8b122a4a9661de3464
54a18855b0578bbad859de93b00b2c030336332f
/The C++ Standard Library/ch14/regextokeniter1.cc
ce813f538fa032ef50ccbfcd4e8dea2dd2702018
[ "LicenseRef-scancode-boost-original" ]
permissive
HuaTsai/Book-Auxiliary-Codes
42bc4600e62e857adaa424ab0ca948354eb3373b
30f92b95a4d43a18e89f96f80ef628aac64bbdbb
refs/heads/main
2023-07-02T22:00:58.004528
2021-08-08T09:45:49
2021-08-08T09:45:49
388,701,511
0
0
null
null
null
null
UTF-8
C++
false
false
1,105
cc
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference, 2nd Edition" * by Nicolai M. Josuttis, Addison-Wesley, 2012 * * (C) Copyright Nicolai M. Josuttis 2012. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <bits/stdc++.h> using namespace std; int main() { string data = "<person>\n" " <first>Nico</first>\n" " <last>Josuttis</last>\n" "</person>\n"; regex reg("<(.*)>(.*)</(\\1)>"); sregex_token_iterator pos(data.cbegin(), data.cend(), reg, {0, 2}), end; for (; pos != end; ++pos) cout << "match: " << pos->str() << endl; cout << endl; string names = "nico, jim, helmut, paul, tim, john paul, rita"; regex sep("[ \t\n]*[,;.][ \t\n]*"); sregex_token_iterator p(names.cbegin(), names.cend(), sep, -1), e; for (; p != e; ++p) cout << "name: " << *p << endl; }
d616320fb2b4a5abc8a7c8c4b0dac31b992b090c
b73db02ce2feec6bf3d48357db5562aea725767b
/src/libs/ecoscope/gep_scope_world_display.cpp
650b1fb5bf5c3ffd95efcb6d3aeeeb447a45a994
[]
no_license
FrankBlabu/GenePool
3b3669d61e9cd0771c49395d7f48b01620cc87db
0c087be6d0953df2054f241c5c4aa7b3b530a93a
refs/heads/master
2022-11-08T00:59:39.065995
2013-03-03T17:42:29
2013-03-03T17:42:29
275,880,460
0
0
null
null
null
null
UTF-8
C++
false
false
1,247
cpp
/* * gep_scope_world_display.cpp - Base class for displaying the worlds current content * * Frank Cieslok, Sep. 2011 */ #define GEP_DEBUG #include <GEPSystemDebug.h> #include <GEPSystemNotifier.h> #include <GEPSystemWorld.h> #include "GEPScopeWorldDisplay.h" namespace GEP { namespace Scope { //#************************************************************************** // CLASS GEP::Scope::WorldDisplay //#************************************************************************** /* Constructor */ WorldDisplay::WorldDisplay(const System::World* world, QWidget* parent) : QWidget (parent), _world (world), _selected_id (System::Object::INVALID) { connect (System::Notifier::getNotifier (), SIGNAL (signalIndividualFocusChanged (const GEP::System::Object::Id&)), SLOT (slotIndividualFocusChanged (const GEP::System::Object::Id&))); } /* Destructor */ WorldDisplay::~WorldDisplay() { } /* Return currently selected id */ const System::Object::Id& WorldDisplay::getSelectedId () const { return _selected_id; } /* Called when the currently selected individual changed */ void WorldDisplay::slotIndividualFocusChanged (const System::Object::Id& id) { _selected_id = id; emit signalUpdate (); } } }
981729d4207c5e968ec2ce13d707812b6056e4ee
3d608f0070da4cfce37da9159ffbc5918573caa5
/src/Intersection.cpp
a23fd053f1ca7c70e351d0ef9febcdcae10de363
[]
no_license
Abhishek2011992/CppND-Program-a-Concurrent-Traffic-Simulation-checkin
cd678aba632521a9b9dfc1dcf296d94a4ec7b088
4f994038dcb27c91ad7b2f41ca0c04a4dbc0ff49
refs/heads/main
2023-03-14T01:16:30.015063
2021-02-19T12:55:37
2021-02-19T12:55:37
340,361,970
0
0
null
null
null
null
UTF-8
C++
false
false
4,776
cpp
#include <iostream> #include <thread> #include <chrono> #include <future> #include <random> #include "Street.h" #include "Intersection.h" #include "Vehicle.h" /* Implementation of class "WaitingVehicles" */ int WaitingVehicles::getSize() { std::lock_guard<std::mutex> lock(_mutex); return _vehicles.size(); } void WaitingVehicles::pushBack(std::shared_ptr<Vehicle> vehicle, std::promise<void> &&promise) { std::lock_guard<std::mutex> lock(_mutex); _vehicles.push_back(vehicle); _promises.push_back(std::move(promise)); } void WaitingVehicles::permitEntryToFirstInQueue() { std::lock_guard<std::mutex> lock(_mutex); // get entries from the front of both queues auto firstPromise = _promises.begin(); auto firstVehicle = _vehicles.begin(); // fulfill promise and send signal back that permission to enter has been granted firstPromise->set_value(); // remove front elements from both queues _vehicles.erase(firstVehicle); _promises.erase(firstPromise); } /* Implementation of class "Intersection" */ Intersection::Intersection() { _type = ObjectType::objectIntersection; _isBlocked = false; } void Intersection::addStreet(std::shared_ptr<Street> street) { _streets.push_back(street); } std::vector<std::shared_ptr<Street>> Intersection::queryStreets(std::shared_ptr<Street> incoming) { // store all outgoing streets in a vector ... std::vector<std::shared_ptr<Street>> outgoings; for (auto it : _streets) { if (incoming->getID() != it->getID()) // ... except the street making the inquiry { outgoings.push_back(it); } } return outgoings; } // adds a new vehicle to the queue and returns once the vehicle is allowed to enter void Intersection::addVehicleToQueue(std::shared_ptr<Vehicle> vehicle) { std::unique_lock<std::mutex> lck(_mtx); std::cout << "Intersection #" << _id << "::addVehicleToQueue: thread id = " << std::this_thread::get_id() << std::endl; lck.unlock(); // add new vehicle to the end of the waiting line std::promise<void> prmsVehicleAllowedToEnter; std::future<void> ftrVehicleAllowedToEnter = prmsVehicleAllowedToEnter.get_future(); _waitingVehicles.pushBack(vehicle, std::move(prmsVehicleAllowedToEnter)); // wait until the vehicle is allowed to enter ftrVehicleAllowedToEnter.wait(); lck.lock(); std::cout << "Intersection #" << _id << ": Vehicle #" << vehicle->getID() << " is granted entry." << std::endl; // FP.6b : use the methods TrafficLight::getCurrentPhase and TrafficLight::waitForGreen to block the execution until the traffic light turns green. if(_trafficLight.getCurrentPhase() == TrafficLightPhase::red) { _trafficLight.waitForGreen(); } lck.unlock(); } void Intersection::vehicleHasLeft(std::shared_ptr<Vehicle> vehicle) { //std::cout << "Intersection #" << _id << ": Vehicle #" << vehicle->getID() << " has left." << std::endl; // unblock queue processing this->setIsBlocked(false); } void Intersection::setIsBlocked(bool isBlocked) { _isBlocked = isBlocked; //std::cout << "Intersection #" << _id << " isBlocked=" << isBlocked << std::endl; } // virtual function which is executed in a thread void Intersection::simulate() // using threads + promises/futures + exceptions { // FP.6a : In Intersection.h, add a private member _trafficLight of type TrafficLight. At this position, start the simulation of _trafficLight. _trafficLight.simulate(); // launch vehicle queue processing in a thread threads.emplace_back(std::thread(&Intersection::processVehicleQueue, this)); } void Intersection::processVehicleQueue() { // print id of the current thread //std::cout << "Intersection #" << _id << "::processVehicleQueue: thread id = " << std::this_thread::get_id() << std::endl; // continuously process the vehicle queue while (true) { // sleep at every iteration to reduce CPU usage std::this_thread::sleep_for(std::chrono::milliseconds(1)); // only proceed when at least one vehicle is waiting in the queue if (_waitingVehicles.getSize() > 0 && !_isBlocked) { // set intersection to "blocked" to prevent other vehicles from entering this->setIsBlocked(true); // permit entry to first vehicle in the queue (FIFO) _waitingVehicles.permitEntryToFirstInQueue(); } } } bool Intersection::trafficLightIsGreen() { // please include this part once you have solved the final project tasks if (_trafficLight.getCurrentPhase() == TrafficLightPhase::green) return true; else return false; return true; // makes traffic light permanently green }
48b92d2a4634a5be1a663e0cd3b5b56da89ba7ec
fec81bfe0453c5646e00c5d69874a71c579a103d
/blazemark/src/eigen/TSMatDMatMult.cpp
5a786a0f2ebc43672c6fd4c5704a08900eb1c860
[ "BSD-3-Clause" ]
permissive
parsa/blaze
801b0f619a53f8c07454b80d0a665ac0a3cf561d
6ce2d5d8951e9b367aad87cc55ac835b054b5964
refs/heads/master
2022-09-19T15:46:44.108364
2022-07-30T04:47:03
2022-07-30T04:47:03
105,918,096
52
7
null
null
null
null
UTF-8
C++
false
false
4,732
cpp
//================================================================================================= /*! // \file src/eigen/TSMatDMatMult.cpp // \brief Source file for the Eigen transpose sparse matrix/dense matrix multiplication kernel // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <iostream> #include <Eigen/Dense> #include <Eigen/Sparse> #include <blaze/util/NumericCast.h> #include <blaze/util/Timing.h> #include <blazemark/eigen/init/Matrix.h> #include <blazemark/eigen/init/SparseMatrix.h> #include <blazemark/eigen/TSMatDMatMult.h> #include <blazemark/system/Config.h> namespace blazemark { namespace eigen { //================================================================================================= // // KERNEL FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Eigen transpose sparse matrix/dense matrix multiplication kernel. // // \param N The number of rows and columns of the matrices. // \param F The number of non-zero elements in each column of the sparse matrix. // \param steps The number of iteration steps to perform. // \return Minimum runtime of the kernel function. // // This kernel function implements the transpose sparse matrix/dense matrix multiplication by // means of the Eigen functionality. */ double tsmatdmatmult( size_t N, size_t F, size_t steps ) { using ::blazemark::element_t; using ::blaze::numeric_cast; using ::Eigen::Dynamic; using ::Eigen::RowMajor; using ::Eigen::ColMajor; ::blaze::setSeed( seed ); ::Eigen::SparseMatrix<element_t,ColMajor,EigenSparseIndexType> A( N, N ); ::Eigen::Matrix<element_t,Dynamic,Dynamic,RowMajor> B( N, N ); ::Eigen::Matrix<element_t,Dynamic,Dynamic,ColMajor> C( N, N ); ::blaze::timing::WcTimer timer; init( A, F ); init( B ); C.noalias() = A * B; for( size_t rep=0UL; rep<reps; ++rep ) { timer.start(); for( size_t step=0UL; step<steps; ++step ) { C.noalias() = A * B; } timer.end(); if( numeric_cast<size_t>( C.rows() ) != N ) std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n"; if( timer.last() > maxtime ) break; } const double minTime( timer.min() ); const double avgTime( timer.average() ); if( minTime * ( 1.0 + deviation*0.01 ) < avgTime ) std::cerr << " Eigen kernel 'tsmatdmatmult': Time deviation too large!!!\n"; return minTime; } //************************************************************************************************* } // namespace eigen } // namespace blazemark
6a260d3c1f0b775c2364e46c406bde2e026524f1
4d5a3fbaeb32cfc1a291ef09199fac654a64537c
/Knight.hpp
1ac27440e056fd940c918c6f19e94d83227bda39
[]
no_license
gheaeckkseqrz/ChessIA
c83300a24ede4904c9ed861345feff621d779c65
1dc8d3fb752643b9f26f350939239d8dca44cae2
refs/heads/master
2016-09-01T19:48:50.564247
2013-12-05T21:34:55
2013-12-05T21:34:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
565
hpp
// // Knight.hpp for ChessIA in /home/wilmot_p/PROG/C++/ChessIA // // Made by WILMOT Pierre // Login <[email protected]> // // Started on Wed Dec 26 23:27:08 2012 WILMOT Pierre // Last update Wed Dec 26 23:56:28 2012 WILMOT Pierre // #ifndef __KNIGHT_HPP__ #define __KNIGHT_HPP__ #include <iostream> #include "PieceInfo.hpp" #include "Move.hpp" class Knight : public PieceInfo { public: Knight(int x, int y, GameData::team t); ~Knight(); std::list<Move *> *getSuccessors(GameData const &g) const; private: int m_directions[8][2]; }; #endif
37c1b454c0796a35edb7c7e616b11333ad9c8978
61cbaba5fd849ad52c3c2ee8ee003554b6389a79
/il2cpp/Classes/Native/Assembly-CSharp.cpp
8d9fe33a0c479ab96f68eb7b001795d3e9ba5cc2
[]
no_license
wallstudio/UnityTest_2019_4_4
9b8c6a6df2b55733659bd7d90d5d686f8b1bdd61
6b30f321504b6377c36f703f1bbb1d8d9ec5ba11
refs/heads/master
2023-02-03T21:42:36.063139
2020-12-09T17:08:37
2020-12-09T17:08:37
310,818,733
0
0
null
null
null
null
UTF-8
C++
false
false
6,376
cpp
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.String struct String_t; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017; // Test struct Test_tD59136436184CD9997A7B05E8FCAF0CB36B7193E; // UnityEngine.MonoBehaviour struct MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t6CDDDF959E7E18A6744E43B613F41CDAC780256A { public: public: }; // System.Object struct Il2CppArrayBounds; // System.Array // System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com { }; // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017 { public: union { struct { }; uint8_t Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017__padding[1]; }; public: }; // UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_com { intptr_t ___m_CachedPtr_0; }; // UnityEngine.Component struct Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: public: }; // UnityEngine.Behaviour struct Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8 : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.MonoBehaviour struct MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 : public Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8 { public: public: }; // Test struct Test_tD59136436184CD9997A7B05E8FCAF0CB36B7193E : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // System.Void UnityEngine.MonoBehaviour::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97 (MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 * __this, const RuntimeMethod* method); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void Test::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Test_Start_mF939AB39145FD162BC81E5E72C83FD4B5183C1C6 (Test_tD59136436184CD9997A7B05E8FCAF0CB36B7193E * __this, const RuntimeMethod* method) { { // } return; } } // System.Void Test::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Test_Update_m6D061B1256A9FFB50D6D817D67F50B6A3F629B35 (Test_tD59136436184CD9997A7B05E8FCAF0CB36B7193E * __this, const RuntimeMethod* method) { { // } return; } } // System.Void Test::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Test__ctor_mDDBEED72519423C0A5663FECEF7BC7A6E28E55B4 (Test_tD59136436184CD9997A7B05E8FCAF0CB36B7193E * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif
1efd8dae68cacb1e19a8df85b694adcc1e1a12b2
20a40118f852dfae02f2b8931d7e2bf75e861733
/loginwidget.cpp
47df245f0d6f0f09314d2a5769db735e49006469
[]
no_license
diba-m/triQadvisor
5c37f46c2e39c3681f342c4c979cf2f5fa3f765b
7a7f83c24d453db954dd31c79e19d8adccf28c8e
refs/heads/master
2020-12-24T19:28:44.746282
2016-05-09T13:11:51
2016-05-09T13:11:51
57,897,602
0
0
null
null
null
null
UTF-8
C++
false
false
1,664
cpp
#include "loginwidget.h" LoginWidget::LoginWidget(){ QVBoxLayout* loginLayout = new QVBoxLayout; QMenuBar* menuBar = new QMenuBar(0); QMenu* fileMenu = menuBar->addMenu(tr("File")); fileMenu->addSeparator(); QAction* exitAction = fileMenu->addAction(tr("Exit")); connect(exitAction, SIGNAL(triggered()), this, SLOT(close())); loginLayout->setMenuBar(menuBar); welcomeLabel = new QLabel; for (int i=0; i<2; i++) { lineEdits[i] = new QLineEdit; } lineEdits[0]->setPlaceholderText("Username"); lineEdits[1]->setPlaceholderText("Password"); lineEdits[1]->setEchoMode(QLineEdit::Password); enterButton = new QPushButton(tr("Sign In")); QFont f("Arial",20,QFont::Bold); QPalette* palette = new QPalette; palette->setColor(QPalette::WindowText,Qt::blue); welcomeLabel->setText(tr("Welcome to TriQAdvisor")); welcomeLabel->setFont(f); welcomeLabel->setAlignment(Qt::AlignCenter); welcomeLabel->setPalette(*palette); loginLayout->addWidget(welcomeLabel); loginLayout->addWidget(lineEdits[0]); loginLayout->addWidget(lineEdits[1]); loginLayout->addWidget(enterButton); connect(enterButton,SIGNAL(clicked()),this,SLOT(sendLogin())); setFixedSize(400,150); setLayout(loginLayout); } QString LoginWidget::getUsername() const{ return lineEdits[0]->text(); } QString LoginWidget::getPassword() const{ return lineEdits[1]->text(); } void LoginWidget::sendLogin(){} //TO DO: SLOT for "ENTER" button still missing
42d0e0a38ed4b7a7a766af41d525158dcb4ad42c
c15373ce87ff810564456e8cbefce653692a8030
/src/footballcoind.cpp
a9f00e38e3cd42c0fec98ef2b01ad46b50e63a91
[ "MIT" ]
permissive
fbcoinone/footballcoin
e7f1ed7b2838f62c98531e8d1f04658cfb5421fe
00b47d5f969527a2e23bc885abbe54d5f9e4b0dc
refs/heads/master
2020-03-20T12:41:03.307288
2018-06-15T03:44:51
2018-06-15T03:44:51
137,437,792
0
0
null
null
null
null
UTF-8
C++
false
false
6,227
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The FootBallcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/footballcoin-config.h> #endif #include <chainparams.h> #include <clientversion.h> #include <compat.h> #include <fs.h> #include <rpc/server.h> #include <init.h> #include <noui.h> #include <scheduler.h> #include <util.h> #include <httpserver.h> #include <httprpc.h> #include <utilstrencodings.h> #include <boost/thread.hpp> #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called FootBallcoin (https://www.footballcoin.org/), * which enables instant payments to anyone, anywhere in the world. FootBallcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ void WaitForShutdown(boost::thread_group* threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { Interrupt(*threadGroup); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; CScheduler scheduler; bool fRet = false; // // Parameters // // If Qt is used, parameters/footballcoin.conf are parsed in qt/footballcoin.cpp's main() gArgs.ParseParameters(argc, argv); // Process help and version before taking care about datadir if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " footballcoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + HelpMessage(HMM_FOOTBALLCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return true; } try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } try { gArgs.ReadConfigFile(gArgs.GetArg("-conf", FOOTBALLCOIN_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { fprintf(stderr, "Error: Command line contains unexpected token '%s', see footballcoind -h for a list of options.\n", argv[i]); return false; } } // -server defaults to true for footballcoind but not for the GUI so do this here gArgs.SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); if (!AppInitBasicSetup()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console return false; } if (gArgs.GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON fprintf(stdout, "FootBallcoin server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #else fprintf(stderr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } // Lock data directory after daemonization if (!AppInitLockDataDirectory()) { // If locking the data directory failed, exit immediately return false; } fRet = AppInitMain(threadGroup, scheduler); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(nullptr, "AppInit()"); } if (!fRet) { Interrupt(threadGroup); threadGroup.join_all(); } else { WaitForShutdown(&threadGroup); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect footballcoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); }
bff58dd0424318844727bac3d64df7f89579b010
3e6140ed39a63a5104fa2a50c765cf0cb7194985
/Semana 3/Exercise 3 H3/Hotel.h
5fa478d329d5a3fdff18913e802e4dd9275c4220
[]
no_license
Bryammm06/Progra-2-2020-2
c35737d0ed7b267cf72a32dd4ce4536ed21ee6e8
0a301afc1647dca8c8a5f2f8b85a7a663f72c4df
refs/heads/master
2023-01-07T05:29:16.743368
2020-11-07T19:49:14
2020-11-07T19:49:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,661
h
#pragma once #include <iostream> #include <string> using namespace std; string hotelLocations[7] = { "Isla de la Cite", "San Luis", "Barrio Latino","Montmartre", "La Defensa", "Campos Eliseos","Plaza de la Concordia" }; string hotelNames[7] = { "Marriot", "Shell", "Portman", "Winston", "Paris","Trivago","Casa Andina" }; class Hotel { private: string name; int starts; string location; bool breakfast; int telephone; bool airportService; public: Hotel() { name = hotelNames[rand() % 7]; starts = rand() % 5 + 1; location = hotelLocations[rand() % 7]; breakfast = rand() % 2; telephone = rand() % 800000 + 1000000; airportService = rand() % 2; } //Getters string getName() { return name; } int getStarts() { return starts; } string getLocation() { return location; } bool getBreakfast() { return breakfast; } int getTelephone() { return telephone; } bool getAirportService() { return airportService; } //Setter void setName(string v) { name = v; } void setStarts(int v) { starts = v; } void setLocation(string v) { location = v; } void setBreakfast(bool v) { breakfast = v; } void setTelephone(int v) { telephone = v; } void setAirportService(bool v) { airportService = v; } void getInformation() { cout << "Name: " << name << endl; cout << "Starts: " << starts << endl; cout << "Location: " << location << endl; cout << "Breakfast: "; if (breakfast) { cout << "YES" << endl; } else { cout << "NO" << endl; } cout << "Telephone: " << telephone << endl; cout << "Airport Service: "; if (airportService) { cout << "YES" << endl; } else { cout << "NO" << endl; } cout << endl; } };
6fdc4ba6a4029e338defe6af1993724f135ade11
06ecc70c4680e0764ebc64031410a59944e4cc76
/IOHIDLib/IOHIDIUnknown.cpp
1cdffa0542e134f3d1e90c3db816d51de67ea2c8
[]
no_license
unofficial-opensource-apple/IOHIDFamily
b07744d67c85dfc552fe5b39060a8b850db1d457
dec587058f4b4ade009a1892b8e51b142eecb4ec
refs/heads/master
2020-12-24T13:29:35.535591
2014-10-30T20:55:30
2014-10-30T20:55:30
27,180,040
2
0
null
null
null
null
UTF-8
C++
false
false
3,380
cpp
/* * * @APPLE_LICENSE_HEADER_START@ * * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <TargetConditionals.h> #include <IOKit/hid/IOHIDDevicePlugIn.h> #include <IOKit/hid/IOHIDServicePlugIn.h> #include "IOHIDIUnknown.h" #include "IOHIDDeviceClass.h" #include "IOHIDUPSClass.h" #if TARGET_OS_EMBEDDED #include "IOHIDEventServiceClass.h" #endif int IOHIDIUnknown::factoryRefCount = 0; void *IOHIDLibFactory(CFAllocatorRef allocator __unused, CFUUIDRef typeID) { if (CFEqual(typeID, kIOHIDDeviceUserClientTypeID)) return (void *) IOHIDObsoleteDeviceClass::alloc(); else if (CFEqual(typeID, kIOHIDDeviceTypeID)) return (void *) IOHIDDeviceClass::alloc(); #if TARGET_OS_EMBEDDED else if (CFEqual(typeID, kIOHIDServicePlugInTypeID)) return (void *) IOHIDEventServiceClass::alloc(); #endif else if (CFEqual(typeID, kIOUPSPlugInTypeID)) return (void *) IOHIDUPSClass::alloc(); else return NULL; } void IOHIDIUnknown::factoryAddRef() { if (0 == factoryRefCount++) { CFUUIDRef factoryId = kIOHIDDeviceFactoryID; CFRetain(factoryId); CFPlugInAddInstanceForFactory(factoryId); } } void IOHIDIUnknown::factoryRelease() { if (1 == factoryRefCount--) { CFUUIDRef factoryId = kIOHIDDeviceFactoryID; CFPlugInRemoveInstanceForFactory(factoryId); CFRelease(factoryId); } else if (factoryRefCount < 0) factoryRefCount = 0; } IOHIDIUnknown::IOHIDIUnknown(void *unknownVTable) : refCount(1) { iunknown.pseudoVTable = (IUnknownVTbl *) unknownVTable; iunknown.obj = this; factoryAddRef(); }; IOHIDIUnknown::~IOHIDIUnknown() { factoryRelease(); } UInt32 IOHIDIUnknown::addRef() { refCount += 1; return refCount; } UInt32 IOHIDIUnknown::release() { UInt32 retVal = refCount - 1; if (retVal > 0) refCount = retVal; else if (retVal == 0) { refCount = retVal; delete this; } else retVal = 0; return retVal; } HRESULT IOHIDIUnknown:: genericQueryInterface(void *self, REFIID iid, void **ppv) { IOHIDIUnknown *me = ((InterfaceMap *) self)->obj; return me->queryInterface(iid, ppv); } UInt32 IOHIDIUnknown::genericAddRef(void *self) { IOHIDIUnknown *me = ((InterfaceMap *) self)->obj; return me->addRef(); } UInt32 IOHIDIUnknown::genericRelease(void *self) { IOHIDIUnknown *me = ((InterfaceMap *) self)->obj; return me->release(); }
d57dd4d01a91801114a8615f43756e013259014f
ba9322f7db02d797f6984298d892f74768193dcf
/mts/src/model/QueryMediaWorkflowExecutionListResult.cc
c79ac0e89f5d8856c372f52d31031ba12349ebc7
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
4,873
cc
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/mts/model/QueryMediaWorkflowExecutionListResult.h> #include <json/json.h> using namespace AlibabaCloud::Mts; using namespace AlibabaCloud::Mts::Model; QueryMediaWorkflowExecutionListResult::QueryMediaWorkflowExecutionListResult() : ServiceResult() {} QueryMediaWorkflowExecutionListResult::QueryMediaWorkflowExecutionListResult(const std::string &payload) : ServiceResult() { parse(payload); } QueryMediaWorkflowExecutionListResult::~QueryMediaWorkflowExecutionListResult() {} void QueryMediaWorkflowExecutionListResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allMediaWorkflowExecutionList = value["MediaWorkflowExecutionList"]["MediaWorkflowExecution"]; for (auto value : allMediaWorkflowExecutionList) { MediaWorkflowExecution mediaWorkflowExecutionListObject; if(!value["RunId"].isNull()) mediaWorkflowExecutionListObject.runId = value["RunId"].asString(); if(!value["MediaWorkflowId"].isNull()) mediaWorkflowExecutionListObject.mediaWorkflowId = value["MediaWorkflowId"].asString(); if(!value["Name"].isNull()) mediaWorkflowExecutionListObject.name = value["Name"].asString(); if(!value["State"].isNull()) mediaWorkflowExecutionListObject.state = value["State"].asString(); if(!value["MediaId"].isNull()) mediaWorkflowExecutionListObject.mediaId = value["MediaId"].asString(); if(!value["CreationTime"].isNull()) mediaWorkflowExecutionListObject.creationTime = value["CreationTime"].asString(); auto allActivityList = value["ActivityList"]["Activity"]; for (auto value : allActivityList) { MediaWorkflowExecution::Activity activityListObject; if(!value["Name"].isNull()) activityListObject.name = value["Name"].asString(); if(!value["Type"].isNull()) activityListObject.type = value["Type"].asString(); if(!value["JobId"].isNull()) activityListObject.jobId = value["JobId"].asString(); if(!value["State"].isNull()) activityListObject.state = value["State"].asString(); if(!value["Code"].isNull()) activityListObject.code = value["Code"].asString(); if(!value["Message"].isNull()) activityListObject.message = value["Message"].asString(); if(!value["StartTime"].isNull()) activityListObject.startTime = value["StartTime"].asString(); if(!value["EndTime"].isNull()) activityListObject.endTime = value["EndTime"].asString(); auto mNSMessageResultNode = value["MNSMessageResult"]; if(!mNSMessageResultNode["MessageId"].isNull()) activityListObject.mNSMessageResult.messageId = mNSMessageResultNode["MessageId"].asString(); if(!mNSMessageResultNode["ErrorMessage"].isNull()) activityListObject.mNSMessageResult.errorMessage = mNSMessageResultNode["ErrorMessage"].asString(); if(!mNSMessageResultNode["ErrorCode"].isNull()) activityListObject.mNSMessageResult.errorCode = mNSMessageResultNode["ErrorCode"].asString(); mediaWorkflowExecutionListObject.activityList.push_back(activityListObject); } auto inputNode = value["Input"]; if(!inputNode["UserData"].isNull()) mediaWorkflowExecutionListObject.input.userData = inputNode["UserData"].asString(); auto inputFileNode = inputNode["InputFile"]; if(!inputFileNode["Bucket"].isNull()) mediaWorkflowExecutionListObject.input.inputFile.bucket = inputFileNode["Bucket"].asString(); if(!inputFileNode["Location"].isNull()) mediaWorkflowExecutionListObject.input.inputFile.location = inputFileNode["Location"].asString(); if(!inputFileNode["Object"].isNull()) mediaWorkflowExecutionListObject.input.inputFile.object = inputFileNode["Object"].asString(); mediaWorkflowExecutionList_.push_back(mediaWorkflowExecutionListObject); } auto allNonExistRunIds = value["NonExistRunIds"]["RunId"]; for (const auto &item : allNonExistRunIds) nonExistRunIds_.push_back(item.asString()); } std::vector<std::string> QueryMediaWorkflowExecutionListResult::getNonExistRunIds()const { return nonExistRunIds_; } std::vector<QueryMediaWorkflowExecutionListResult::MediaWorkflowExecution> QueryMediaWorkflowExecutionListResult::getMediaWorkflowExecutionList()const { return mediaWorkflowExecutionList_; }
c6c504a967859832698f51949996d684d0f4a7db
306165cfe0649c719b27a386b786cc200abdc2f8
/Advanced Recursion/Merge Sort Code.cpp
57856dd3e9031b264d8865f8a38fa1e440e1846d
[]
no_license
EkanshMangal/Coding-Ninjas
3af046f237983bcaebabdaebe8664eb00e5f3b43
baeb58e6c8071c37ebca6957e5d7b9e92f9f83d1
refs/heads/master
2021-01-16T14:41:39.302884
2020-08-12T04:32:49
2020-08-12T04:32:49
243,156,722
0
0
null
null
null
null
UTF-8
C++
false
false
1,646
cpp
/* Merge Sort Code Sort an array A using Merge Sort. Change in the input array itself. So no need to return or print anything. Input format : Line 1 : Integer n i.e. Array size Line 2 : Array elements (separated by space) Output format : Array elements in increasing order (separated by space) Constraints : 1 <= n <= 10^3 Sample Input 1 : 6 2 6 8 5 4 3 Sample Output 1 : 2 3 4 5 6 8 Sample Input 2 : 5 2 1 5 2 3 Sample Output 2 : 1 2 2 3 5 */ #include<bits/stdc++.h> using namespace std; void merge(int input[], int start, int mid, int end) { int i=start,j=mid,k=0; int temp[end-start+1]; while(i<mid && j<=end) { if(input[i]<=input[j]) { temp[k++]=input[i++]; } if(input[j]<input[i]) { temp[k++]=input[j++]; } } while(i<mid) { temp[k++]=input[i++]; } while(j<=end) { temp[k++]=input[j++]; } for(i=start,k=0;i<=end;i++,k++) { input[i]=temp[k]; } return; } void mergesort1(int input[],int start, int end) { if(end>start) { int mid=(start+end)/2; mergesort1(input,start,mid); mergesort1(input,mid+1,end); merge(input,start,mid+1,end); } else { return; } } void mergeSort(int input[], int size){ // Write your code here return mergesort1(input,0,size-1); } // int main() // { // int size; // cin>>size; // int arr[size]; // for(int i=0;i<size;i++) // { // cin>>arr[i]; // } // mergeSort(arr,size); // for(int i=0;i<size;i++) // { // cout<<arr[i]; // } // }
4494cccf32db79f01ac357285fb15b9d8ec1e5ce
43298fdf216663512904fe6a1d6894bf14907fb8
/HolyEditor/main.cpp
fde1fe02eef8959c4688758c93bb4577c978c56e
[]
no_license
q4a/holyspirit-trunk
06daf0cf7ad015c77ee901e39c9bf3c738a19933
b43da88736d375357027468216920cbb671765ba
refs/heads/master
2021-01-13T06:08:23.951764
2013-03-05T14:57:21
2013-03-05T14:57:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,918
cpp
//////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "MainWindow.h" #include "MainWindow.moc" #include <QApplication> #include <QVBoxLayout> #include <QFrame> #include <QLabel> #include "Moteurs/moteurGraphique.h" #include "Moteurs/moteurSons.h" #include "Moteurs/eventManager.h" #include "configuration.h" Configuration *configuration; Console *console; MoteurGraphique *moteurGraphique; MoteurSons *moteurSons; EventManager *eventManager; #include "Map/map.h" Map *map; //////////////////////////////////////////////////////////// /// Entry point of application /// /// \return Application exit code /// //////////////////////////////////////////////////////////// int main(int argc, char **argv) { // moteurGraphique->CreateNewWindow(); map = NULL; QApplication application(argc, argv); configuration=Configuration::GetInstance(); console=Console::GetInstance(); console->Ajouter("--------------------------------------------------------------------------------"); console->Ajouter("Demarrage du jeu",0); console->Ajouter("--------------------------------------------------------------------------------"); console->Ajouter(""); console->Ajouter("Initialisation du moteur graphique"); moteurGraphique = MoteurGraphique::GetInstance(); eventManager=EventManager::GetInstance(); MainWindow mainWindow; mainWindow.showMaximized(); console->Ajouter("Initialisation du moteur sonore"); moteurSons = MoteurSons::GetInstance(); console->Ajouter(""); srand(time(NULL)); configuration->Charger(); // if (!sf::PostFX::CanUsePostFX()) // configuration->postFX = false; moteurGraphique->Charger(); return application.exec(); //return true; }
[ "ig0rk0@02226d48-ee4e-0410-85af-ca5f3f0fcfbc" ]
ig0rk0@02226d48-ee4e-0410-85af-ca5f3f0fcfbc
3effcfdea6a42651513b5a07a8c28ad209007b1a
d0b9a07078c61942e4286e5eea68223a7a2649e9
/16708.cpp
d177e867810428559e7bb98cdabf52ea2366cd6a
[]
no_license
qjatn0120/BOJ_algorithm
3b82e030bc56fdbcf68c726e1fb4764e8e1218cd
ab3c03342a206c1c2d89561fe9bb885ed98b1a4f
refs/heads/master
2023-07-15T21:42:12.997079
2021-09-04T02:23:33
2021-09-04T02:23:33
287,887,189
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
cpp
#include <bits/stdc++.h> using namespace std; int ans, init, board, n, m; vector <int> target; string str; bool visited[1 << 28]; void getAns(int state); int main(){ cin.tie(nullptr), ios::sync_with_stdio(false); for(int i = 0; i < 7; i++){ int tmp = 0; for(int j = 0; j < 4; j++) tmp |= (1 << j * 7 + i); target.push_back(tmp); for(int j = 0; j < 4; j++) target.push_back(tmp ^ (1 << j * 7 + i)); } for(int i = 0; i < 4; i++) for(int s = 0; s < 7; s++) for(int e = s + 2; e < 7; e++){ int tmp = 0; for(int j = s; j <= e; j++) tmp |= (1 << i * 7 + j); target.push_back(tmp); } cin >> n; for(int i = 0; i < n; i++){ cin >> str; int num = str.back() - '1', color = str.size() - 4; init |= (1 << color * 7 + num); } cin >> m; for(int i = 0; i < m; i++){ cin >> str; int num = str.back() - '1', color = str.size() - 4; board |= (1 << color * 7 + num); } ans = n; getAns(init | board); cout << n - ans; } void getAns(int state){ if(visited[state]) return; visited[state] = true; if(!(state & board)) ans = min(ans, __builtin_popcount(state)); for(int tar : target) if(!((state & tar) ^ tar)) getAns(state ^ tar); }
1237d39312f050cf4d0e192cca9701c840f14829
167378226f891e834b5b7e61ead1d4146662e777
/include/suicore/uicontentcontrol.h
91f18419d28a707231e7710976419a8bd12ddeb9
[]
no_license
tfzxyinhao/sharpui
1017502dcb3afc985e2c057b7bb4243af82677fe
1d7a340192f89c9a7cf6dacfec2f1d38d6f2ea11
refs/heads/master
2021-01-18T11:12:43.149136
2012-10-12T16:44:44
2012-10-12T16:44:44
6,212,902
1
0
null
null
null
null
GB18030
C++
false
false
2,077
h
// 华勤科技版权所有 2010-2011 // // 文件名:uicontentcontrol.h // 功 能:实现窗口的基本操作,包括窗口属性的存取。 // // 作 者:汪荣 // 时 间:2010-07-02 // // ============================================================================ # ifndef _UICONTENTCONTROL_H_ # define _UICONTENTCONTROL_H_ #include <suicore/uicontrol.h> namespace suic { /// <summary> /// 内容界面元素类的基类,仅包含一个子元素,可以设置Padding. /// 对其进行边距控制,有内容时,默认内容元素铺满整个区域 /// </summary> class SUICORE_API ContentControl : public Control { public: ContentControl(); virtual ~ContentControl(); /// <summary> /// 获取内容对象 /// </summary> /// <remarks> /// 内容对象必须派生至FrameworkElement /// </remarks> /// <returns>内容对象</returns> ObjectPtr GetContent(); void SetContent(ObjectPtr contentPtr); /// <summary> /// 设置内容文本 /// </summary> /// <remarks> /// 纯文本并不创建内容对象,而是采用自身作为容器 /// </remarks> /// <param name="text">文本</param> /// <returns>内容对象</returns> void SetText(const String & text); public: virtual suic::Size MeasureOverride(const suic::Size& size); virtual suic::Size ArrangeOverride(const suic::Size& size); virtual void OnInitialized(); virtual void OnSetterChanged(SetterChangedEventArg& e); virtual void OnRender(DrawingContext * drawing); virtual void OnMouseLeftButtonDown(MouseEventArg& e); virtual void OnMouseLeftButtonDbclk(MouseEventArg& e); virtual void OnContentChanged(suic::ObjectPtr oldContent, suic::ObjectPtr newContent); virtual void AddLogicalChild(suic::Element* child); virtual suic::Element* GetLogicalChild(int index); virtual Int32 GetLogicalChildrenCount(); protected: // 元素内容对象 ElementPtr _content; }; typedef shared<ContentControl> ContentControlPtr; }; # endif
41882d7f7f570499566d33f09284f8582c211e66
31b68b1851c12b48e1e83a16a572b57af8197153
/Dynamic_Programming_2/maximum_sum_rectangle.cpp
c5911d80c2358bb9f11da72f406bdf07a8229102
[]
no_license
Rohan7546/Coding_Ninjas_Competitive_Programming
40e77fba03e6cbb20e8d0679cb00a033bb839aaf
2506a9b8c32629b7610c66a32446e255a42e9e20
refs/heads/main
2023-06-27T02:36:59.564187
2021-07-21T08:45:25
2021-07-21T08:45:25
383,400,568
5
1
null
null
null
null
UTF-8
C++
false
false
1,400
cpp
/* Maximum Sum Rectangle Send Feedback Given a 2D array, find the maximum sum rectangle in it. In other words find maximum sum over all rectangles in the matrix. Input Format: First line of input will contain T(number of test case), each test case follows as. First line contains 2 numbers n and m denoting number of rows and number of columns. Next n lines contain m space separated integers denoting elements of matrix nxm. Output Format: Output a single integer, maximum sum rectangle for each test case in a newline. Constraints 1 <= T <= 50 1<=n,m<=100 -10^5 <= mat[i][j] <= 10^5 Sample Input 1 4 5 1 2 -1 -4 -20 -8 -3 4 2 1 3 8 10 1 3 -4 -1 1 7 -6 Sample Output 29 */ #include<bits/stdc++.h> using namespace std; int kadane(int *a, int c) { int sum = 0, best = 0; for (int i = 0; i < c; i++) { sum = max(a[i], sum + a[i]); best = max(best, sum); } return best; } int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; int a[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a[i][j]; } } int maxm = INT_MIN; for (int i = 0; i < n; i++) { int temp[m]; memset(temp, 0, sizeof(temp)); for (int j = i; j < n; j++) { for (int k = 0; k < m; k++) { temp[k] += a[j][k]; } maxm = max(maxm, kadane(temp, m)); } } cout << maxm << endl; } }
4f9725071c77fd8f0c4cb7364b7f08e996b7b22b
2f1a092537d8650cacbd274a3bd600e87a627e90
/thrift/compiler/test/fixtures/lazy_deserialization/gen-cpp2/terse_writes_data.h
4510cd04d91114ffdefbad281c45e80f7e69961e
[ "Apache-2.0" ]
permissive
ConnectionMaster/fbthrift
3aa7d095c00b04030fddbabffbf09a5adca29d42
d5d0fa3f72ee0eb4c7b955e9e04a25052678d740
refs/heads/master
2023-04-10T17:49:05.409858
2021-08-03T02:32:49
2021-08-03T02:33:57
187,603,239
1
1
Apache-2.0
2023-04-03T23:15:28
2019-05-20T08:49:29
C++
UTF-8
C++
false
false
1,728
h
/** * Autogenerated by Thrift for src/terse_writes.thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #pragma once #include <thrift/lib/cpp2/gen/module_data_h.h> #include "thrift/compiler/test/fixtures/lazy_deserialization/gen-cpp2/terse_writes_types.h" namespace apache { namespace thrift { template <> struct TStructDataStorage<::apache::thrift::test::TerseFoo> { static constexpr const std::size_t fields_size = 4; static const std::array<folly::StringPiece, fields_size> fields_names; static const std::array<int16_t, fields_size> fields_ids; static const std::array<protocol::TType, fields_size> fields_types; }; template <> struct TStructDataStorage<::apache::thrift::test::TerseLazyFoo> { static constexpr const std::size_t fields_size = 4; static const std::array<folly::StringPiece, fields_size> fields_names; static const std::array<int16_t, fields_size> fields_ids; static const std::array<protocol::TType, fields_size> fields_types; }; template <> struct TStructDataStorage<::apache::thrift::test::TerseOptionalFoo> { static constexpr const std::size_t fields_size = 4; static const std::array<folly::StringPiece, fields_size> fields_names; static const std::array<int16_t, fields_size> fields_ids; static const std::array<protocol::TType, fields_size> fields_types; }; template <> struct TStructDataStorage<::apache::thrift::test::TerseOptionalLazyFoo> { static constexpr const std::size_t fields_size = 4; static const std::array<folly::StringPiece, fields_size> fields_names; static const std::array<int16_t, fields_size> fields_ids; static const std::array<protocol::TType, fields_size> fields_types; }; }} // apache::thrift
d706bdd8c2fadf4b166e87acd26fa77706a188cd
9fad4848e43f4487730185e4f50e05a044f865ab
/src/content/shell/browser/shell_network_delegate.cc
db264abfa4786732098f53c27c00b87bb54de03f
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
3,901
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/shell/browser/shell_network_delegate.h" #include "base/command_line.h" #include "base/strings/string_util.h" #include "content/public/common/content_switches.h" #include "net/base/net_errors.h" #include "net/base/static_cookie_policy.h" #include "net/url_request/url_request.h" namespace content { namespace { bool g_accept_all_cookies = true; } ShellNetworkDelegate::ShellNetworkDelegate() { } ShellNetworkDelegate::~ShellNetworkDelegate() { } void ShellNetworkDelegate::SetAcceptAllCookies(bool accept) { g_accept_all_cookies = accept; } int ShellNetworkDelegate::OnBeforeURLRequest( net::URLRequest* request, const net::CompletionCallback& callback, GURL* new_url) { return net::OK; } int ShellNetworkDelegate::OnBeforeSendHeaders( net::URLRequest* request, const net::CompletionCallback& callback, net::HttpRequestHeaders* headers) { return net::OK; } void ShellNetworkDelegate::OnSendHeaders( net::URLRequest* request, const net::HttpRequestHeaders& headers) { } int ShellNetworkDelegate::OnHeadersReceived( net::URLRequest* request, const net::CompletionCallback& callback, const net::HttpResponseHeaders* original_response_headers, scoped_refptr<net::HttpResponseHeaders>* override_response_headers, GURL* allowed_unsafe_redirect_url) { return net::OK; } void ShellNetworkDelegate::OnBeforeRedirect(net::URLRequest* request, const GURL& new_location) { } void ShellNetworkDelegate::OnResponseStarted(net::URLRequest* request) { } void ShellNetworkDelegate::OnCompleted(net::URLRequest* request, bool started) { } void ShellNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) { } void ShellNetworkDelegate::OnPACScriptError(int line_number, const base::string16& error) { } ShellNetworkDelegate::AuthRequiredResponse ShellNetworkDelegate::OnAuthRequired( net::URLRequest* request, const net::AuthChallengeInfo& auth_info, const AuthCallback& callback, net::AuthCredentials* credentials) { return AUTH_REQUIRED_RESPONSE_NO_ACTION; } bool ShellNetworkDelegate::OnCanGetCookies(const net::URLRequest& request, const net::CookieList& cookie_list) { net::StaticCookiePolicy::Type policy_type = g_accept_all_cookies ? net::StaticCookiePolicy::ALLOW_ALL_COOKIES : net::StaticCookiePolicy::BLOCK_ALL_THIRD_PARTY_COOKIES; net::StaticCookiePolicy policy(policy_type); int rv = policy.CanGetCookies( request.url(), request.first_party_for_cookies()); return rv == net::OK; } bool ShellNetworkDelegate::OnCanSetCookie(const net::URLRequest& request, const std::string& cookie_line, net::CookieOptions* options) { net::StaticCookiePolicy::Type policy_type = g_accept_all_cookies ? net::StaticCookiePolicy::ALLOW_ALL_COOKIES : net::StaticCookiePolicy::BLOCK_ALL_THIRD_PARTY_COOKIES; net::StaticCookiePolicy policy(policy_type); int rv = policy.CanSetCookie( request.url(), request.first_party_for_cookies()); return rv == net::OK; } bool ShellNetworkDelegate::OnCanAccessFile(const net::URLRequest& request, const base::FilePath& path) const { return true; } bool ShellNetworkDelegate::OnAreExperimentalCookieFeaturesEnabled() const { return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalWebPlatformFeatures); } bool ShellNetworkDelegate::OnAreStrictSecureCookiesEnabled() const { return OnAreExperimentalCookieFeaturesEnabled(); } } // namespace content
7ad2667bbc1a897d642790c0de5ce3e33024baeb
58c5614f48b226f2f12e95bf5a9a85055d0bcae7
/src/TestBeamTransform.h
4fc9ff242ad28d8351ec7e2e2efb7da0b0bfd1e7
[]
no_license
StevenGreen1/CLICpix_TestBeamCode
e9911c7999bda94a6a9d01d5cc448b128253580e
1f1f7e99b9da37ff38ae9525be9ea144e7aca346
refs/heads/master
2018-01-08T08:23:55.849640
2015-09-24T12:52:41
2015-09-24T12:52:41
43,066,113
0
0
null
null
null
null
UTF-8
C++
false
false
3,036
h
// $Id: TestBeamTransform.h,v 1.2 2009-07-17 15:56:21 gligorov Exp $ #ifndef TESTBEAMTRANSFORM_H #define TESTBEAMTRANSFORM_H 1 // Include files #include "TestBeamObject.h" #include "Parameters.h" #include "TestBeamEventElement.h" #include "TMatrixD.h" #include "TVectorD.h" #include "TMath.h" #include "Math/Point3D.h" #include "Math/Vector3D.h" #include "Math/Vector4D.h" #include "Math/Rotation3D.h" #include "Math/EulerAngles.h" #include "Math/AxisAngle.h" #include "Math/Quaternion.h" #include "Math/RotationX.h" #include "Math/RotationY.h" #include "Math/RotationZ.h" #include "Math/RotationZYX.h" #include "Math/LorentzRotation.h" #include "Math/Boost.h" #include "Math/BoostX.h" #include "Math/BoostY.h" #include "Math/BoostZ.h" #include "Math/Transform3D.h" #include "Math/Plane3D.h" #include "Math/VectorUtil.h" #include "Math/Translation3D.h" #include "Math/PositionVector3D.h" using namespace ROOT::Math; using namespace std; /** @class TestBeamTransform TestBeamTransform.h * * * @author Malcolm John * @date 2009-07-01 */ class TestBeamTransform : public TestBeamObject { public: TestBeamTransform(float,float,float,float,float,float); TestBeamTransform(Parameters*, std::string); TestBeamTransform(TestBeamTransform&,bool=COPY); ~TestBeamTransform(){delete m_transform;} Transform3D localToGlobalTransform(){return *m_transform;}; Transform3D globalToLocalTransform(){return m_transform->Inverse();}; protected: private: Transform3D* m_transform; }; inline TestBeamTransform::TestBeamTransform(Parameters* parameters, std::string dID) : m_transform(0) { // Constructor from a pointer to parameters and the ID of the chip being transformed const float tx = parameters->alignment[dID]->displacementX(); const float ty = parameters->alignment[dID]->displacementY(); const float tz = parameters->alignment[dID]->displacementZ(); const float rx = parameters->alignment[dID]->rotationX(); const float ry = parameters->alignment[dID]->rotationY(); const float rz = parameters->alignment[dID]->rotationZ(); Translation3D move(tx, ty, tz); RotationZYX twist(rz, ry, rx); Rotation3D twister(twist); m_transform = new Transform3D(twister, move); } inline TestBeamTransform::TestBeamTransform(float translationX, float translationY, float translationZ, float rotationX, float rotationY, float rotationZ) { //The constructor defines the transform, which for us is from the local to the global coordinate system //and will be read from the alignment file. To transform from the global to the local, we simply //get the inverse later on. m_transform = NULL; Translation3D move(translationX, translationY, translationZ); RotationZYX twist(rotationZ, rotationY, rotationX); Rotation3D twister(twist); m_transform = new Transform3D(twister,move); } inline TestBeamTransform::TestBeamTransform(TestBeamTransform& c,bool action) : TestBeamObject() { if (action == COPY) return; m_transform = c.m_transform; } #endif // TESTBEAMTRANSFORM_H
342c871468aefa0afdc7dee38a92b0c2c0b3bdf5
c08c0f95066f596a2e4db54e2a037e9b48fda643
/Source/Code/Triangulation/main.cpp
5325c369f28ecf2b80e0e72efdf9038de5de4212
[]
no_license
retallickj/flight-suite-alpha
6b69d089e03c0f6fa384b826f28bceaf37f49619
c7c2853ccb2ac7ebc21c5be0683660eaf96beb3f
refs/heads/master
2021-01-23T07:20:44.827477
2013-04-29T08:06:44
2013-04-29T08:06:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,727
cpp
// multicamera vision.cpp : Defines the entry point for the console application. // #include "multicameratriangulator.h" #include <iostream> #include <fstream> #define EPSILON 0.1 #define ITERATIONS 10 #define FEED_ARG_OFFSET 2 #define POINTS_ARG 2 #define PARAM_ARG 3 #define WRITE_ARG 1 #define LARGE_NUMBER 99999999999999999999999.0 using namespace cv; using namespace std; int strToInt(string myString) { stringstream ss(myString); int myInt; ss >> myInt; return myInt; } template <class TYPE> string toStr(TYPE in) { stringstream ss; ss << in; return ss.str(); } int main(int argc, char** argv) { if(argc < PARAM_ARG+1) return -1; vector<string> pointFiles; vector<string> paramFiles; string pnt_path = argv[POINTS_ARG]; string param_path = argv[PARAM_ARG]; // load handlers FileStorage fs1(pnt_path,FileStorage::READ); FileStorage fs2(param_path,FileStorage::READ); if(!fs1.isOpened()) { cerr << "Failed to open file..." << pnt_path; return -1; } if(!fs2.isOpened()) { cerr << "Failed to open file..." << param_path; return -1; } // load points int numFeeds; int numPoints; int numParams; fs1["num_feeds"] >> numFeeds; fs1["num_points"] >> numPoints; fs2["num_params"] >> numParams; if(numParams != numFeeds - 1) { cerr << "Incorrect number of parameter files..."; return -1; } string name, path; for(int i=0; i < numFeeds; i++) { name = "feed_path_" + toStr(i); fs1[name] >> path; pointFiles.push_back(path); } for(int i=0; i < numParams; i++) { name = "param_path_" + toStr(i); fs2[name] >> path; paramFiles.push_back(path); } // handle write filename string write_path = argv[WRITE_ARG]; // release handlers fs1.release(); fs2.release(); multiCameraTriangulator triangulator(numFeeds,paramFiles); vector<FileStorage> feeds(numFeeds); vector<FileStorage> points(numPoints); vector<vector<vector<Point3f> > > inPoints; vector<vector<vector<Point3f> > > inPointsUndist; vector<vector<Point3f> > outPoints; vector<Point3f> triangulatePoints; vector<vector<float> > timeStamps; vector<vector<unsigned int> > indexes; string fileName; string pointName; inPoints.resize(numFeeds); inPointsUndist.resize(numFeeds); indexes.resize(numFeeds); triangulatePoints.resize(numFeeds); outPoints.resize(numPoints); timeStamps.resize(numPoints); for(int i = 0; i < numFeeds; i++) { fileName = pointFiles[i]; //bool temp =feeds[i].open(fileName,FileStorage::READ); feeds[i].open(fileName,FileStorage::READ); inPoints[i].resize(numPoints); indexes[i].resize(numPoints); for(int j = 0; j < numPoints; j++) { pointName = "points_" + format("%d",j); feeds[i][pointName] >> inPoints[i][j]; indexes[i][j] = 1; } } bool loop = true; //loop which interpolates between points and triangulates positions while(loop) { float minTime = LARGE_NUMBER; int feedNum; //loop through feeds and determine which feed has its second point at the earliest time for(int j = 0; j < numFeeds; j++) { for(int k = 0; k < numPoints; k++) { if(inPoints[j][k][indexes[j][k]].z < minTime) { minTime = inPoints[j][k][indexes[j][k]].z; feedNum = j; } } } //loop through points and interpolate at the 2nd point of the earliest feed between the 1st and 2nd points of all other feeds for(int k = 0; k < numPoints; k++) { bool triangulate = true; //loop through feeds for given point for(int j = 0; j < numFeeds; j++) { //if the 1st point of any other feed is after the second point of the earliest feed dont triangulate if(inPoints[j][k][indexes[j][k]-1].z > inPoints[j][k][indexes[feedNum][k]].z) { triangulate = false; } else { vector<Point2f> undistortMat; undistortMat.resize(1); vector<Point2f> outMat; outMat.resize(1); //if the feed is the one with the earliest 2nd point no interpolation necessary if(feedNum == j) { undistortMat[0].x = inPoints[j][k][indexes[j][k]].x; undistortMat[0].y = inPoints[j][k][indexes[j][k]].y; } //for all other feeds interpolate between 1st and 2nd points else { double interpFact = (minTime - inPoints[j][k][indexes[j][k]-1].z)/(inPoints[j][k][indexes[j][k]].z - inPoints[j][k][indexes[j][k]-1].z); undistortMat[0].x = inPoints[j][k][indexes[j][k]-1].x + (inPoints[j][k][indexes[j][k]].x - inPoints[j][k][indexes[j][k]-1].x)*interpFact; undistortMat[0].y = inPoints[j][k][indexes[j][k]-1].y + (inPoints[j][k][indexes[j][k]].y - inPoints[j][k][indexes[j][k]-1].y)*interpFact; } //undistort the interpolated point undistortPoints(undistortMat,outMat,triangulator.cameras[j],triangulator.distCoefs[j]); //undistort normalizes the points, so we have to multiply by the camera matrix to return it to pixel coordinates, haven't found a way to avoid this triangulatePoints[j].x = outMat[0].x*triangulator.cameras[j].at<double>(0,0)+triangulator.cameras[j].at<double>(0,2); triangulatePoints[j].y = outMat[0].y*triangulator.cameras[j].at<double>(1,1)+triangulator.cameras[j].at<double>(1,2); triangulatePoints[j].z = 1; } } //triangulate 3d point if(triangulate) { outPoints[k].push_back(triangulator.iterativeLinearLSTriangulation(triangulatePoints,EPSILON,ITERATIONS)); timeStamps[k].push_back(minTime); } //increase index of the earliest feed indexes[feedNum][k] ++; } //check and see if the end of any feed has been reached for(int j = 0; j < numFeeds; j++) { for(int k = 0; k < numPoints; k++) { if(inPoints[j][k].size() <= indexes[j][k]) { loop = false; } } } } //output data to xml and tab seperated files string fileFolder = write_path; for(int i = 0; i < numPoints; i++) { //bool temp = points[i].open(fileFolder + "point" + format("%d.xml",i),FileStorage::WRITE); points[i].open(fileFolder + "point" + format("%d.xml",i),FileStorage::WRITE); points[i] << "point" << outPoints[i]; points[i] << "timeStamps" << timeStamps[i]; ofstream myfile; string filename = fileFolder + "point" + format("%d.txt",i); myfile.open(filename.c_str()); for(unsigned int j = 0; j < outPoints[0].size();j++) { myfile << outPoints[i][j].x << "\t" << outPoints[i][j].y << "\t" << outPoints[i][j].z <<"\n"; } myfile.close(); } return 0; }
ea7d9e548e4fdb97e0fd514152f01e9ac9101ecc
6a99fda0515cbaafbc840d4f38207758c65b24ad
/test/unit/IRTypeCheckerTest.cpp
36582f591f45068f86ec25c431d606a119c23312
[ "MIT" ]
permissive
CrackerCat/redex
58850cbb87df7bdf4b795dcfb55482bb106957a5
df5a2ba9b6942465e66dd141556b2ff0e828bc47
refs/heads/master
2022-01-23T19:26:27.434480
2022-01-03T19:23:06
2022-01-03T19:24:09
142,514,440
0
0
null
2018-07-27T01:53:26
2018-07-27T01:53:26
null
UTF-8
C++
false
false
86,328
cpp
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gmock/gmock.h> #include <gtest/gtest.h> #include <limits> #include <sstream> #include <string> #include <unordered_set> #include "Creators.h" #include "DexAsm.h" #include "DexClass.h" #include "DexUtil.h" #include "IRAssembler.h" #include "IRCode.h" #include "IROpcode.h" #include "IRTypeChecker.h" #include "LocalDce.h" #include "RedexTest.h" using namespace testing; /** * This enum is used in the iput/iget test * helper functions to check the suffix of the * IR operand. e.g iget-boolean vs iget-wide. * SHORT includes boolean, byte, char, short. */ enum OperandType { WIDE, SHORT, REF }; /** * This struct is used to describe the type of * the value in the iput/iget IR. It is used as * the argument for test helper functions. * * param value_type: the DexType of this type; * param value_super_type: super type; * param ctor_str: string to create ctor for type; * param field_str: string to create field for type; */ struct TestValueType { TestValueType(DexType* value_type, DexType* value_super_type, const std::string& ctor_str, const std::string& field_str) { this->value_type = value_type; this->value_super_type = value_super_type; this->ctor = DexMethod::make_method(ctor_str)->make_concrete(ACC_PUBLIC, false); this->field = DexField::make_field(field_str)->make_concrete(ACC_PUBLIC); // create class ClassCreator cls_creator(value_type); cls_creator.set_super(value_super_type); cls_creator.add_method(ctor); cls_creator.add_field(field); cls_creator.create(); } DexType* value_type = nullptr; DexType* value_super_type = nullptr; DexMethod* ctor = nullptr; DexField* field = nullptr; }; /** * Helper function for input-* / iget-* IR * Used for the failed tests * * param a_type: struct instance to describe type a; * param b_type: struct instance to describe type b; * param exp_fail_str: the expected output for failed tests; * param opcode_to_test: specify the instruction to test; * param is_put: flag to tell whether it's a put IR * param ir_suffix: suffix of the iget/iput IR * options: WIDE, REF, SHORT SHORT (byte, boolean, short, char) * param method: pointer to DexMethod from IRTypeChecker; * * skeleton: * (const v3, 1) / (const-wide v3, 1) * (new-instance "LA;") * (move-result-pseudo-object v1) * (new-instance "LB;") * (move-result-pseudo-object v2) * (invoke-direct (v1) a_ctor) * (invoke-direct (v2) b_ctor) * (iput/iget [v0] v1 b_f) * [For iget] (move-result-pseudo v0) / (move-result-pseudo-wide v0) * (return-void) */ void field_incompatible_fail_helper(const TestValueType& a_type, const TestValueType& b_type, const internal::string& exp_fail_str, IROpcode opcode_to_test, bool is_put, OperandType ir_suffix, DexMethod* method) { using namespace dex_asm; // these instructions differ from each IR // const initialize IRInstruction* init_literal = nullptr; // invoke type a IRInstruction* a_invoke_insn = nullptr; // target IR to test IRInstruction* ir_to_test = nullptr; // move result pseudo for iget-* IRInstruction* extra_insn = nullptr; if (is_put) { // put-* IR a_invoke_insn = dasm(OPCODE_INVOKE_DIRECT, a_type.ctor, {1_v}); switch (ir_suffix) { case SHORT: { // short, byte, boolean, char init_literal = dasm(OPCODE_CONST, {3_v, 1_L}); break; } case WIDE: { init_literal = dasm(OPCODE_CONST_WIDE, {3_v, 1_L}); break; } case REF: not_reached(); } ir_to_test = dasm(opcode_to_test, b_type.field, {3_v, 1_v}); } else { // get-* IR a_invoke_insn = dasm(OPCODE_INVOKE_DIRECT, a_type.ctor, {1_v, 3_v}); switch (ir_suffix) { case SHORT: { // short, byte, boolean, char init_literal = dasm(OPCODE_CONST, {3_v, 1_L}); extra_insn = dasm(IOPCODE_MOVE_RESULT_PSEUDO, {0_v}); break; } case WIDE: { init_literal = dasm(OPCODE_CONST_WIDE, {3_v, 1_L}); extra_insn = dasm(IOPCODE_MOVE_RESULT_PSEUDO_WIDE, {5_v}); break; } case REF: not_reached(); } ir_to_test = dasm(opcode_to_test, b_type.field, {1_v}); } // alternative to add_code // to avoid using function pointer // to a member of an abstract class IRCode* code = method->get_code(); code->push_back(init_literal); // type a code->push_back(dasm(OPCODE_NEW_INSTANCE, a_type.value_type)); code->push_back(dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v})); code->push_back(a_invoke_insn); // type b code->push_back(dasm(OPCODE_NEW_INSTANCE, b_type.value_type)); code->push_back(dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {2_v})); code->push_back(dasm(OPCODE_INVOKE_DIRECT, b_type.ctor, {2_v})); // test ir code->push_back(ir_to_test); // MOVE_RESULT_PSEUDO if (extra_insn) { code->push_back(extra_insn); } // return code->push_back(dasm(OPCODE_RETURN_VOID)); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT(checker.what(), MatchesRegex(exp_fail_str)); } /** * Helper function for input-* / iget-* IR * Used for the success tests * * param a_type: struct instance to describe type a; * param b_type: struct instance to describe type b; * param opcode_to_test: specify the instruction to run; * param is_put: flag to tell whether it's a put IR * param ir_suffix: suffix of the iget/iput IR * options: WIDE, REF, SHORT * param method: pointer to DexMethod from IRTypeChecker; * * skeleton: * (const v0, 1) / (const-wide v0, 1) * (new-instance "LA;") * (move-result-pseudo-object v1) * (new-instance "LAsub;") * (move-result-pseudo-object v2) * (invoke-direct (v1) a_ctor) * (invoke-direct (v2) sub_ctor) * (iput/iget [v0] v1 a_f) * [For iget] (move-result-pseudo v0) / (move-result-pseudo-wide v5) * (return-void) */ void field_compatible_success_helper(const TestValueType& a_type, const TestValueType& b_type, IROpcode opcode_to_test, bool is_put, OperandType ir_suffix, DexMethod* method) { using namespace dex_asm; // these instructions differ from each IR // const initialize IRInstruction* init_literal = nullptr; // invoke type a IRInstruction* a_invoke_insn = nullptr; // invoke type sub a IRInstruction* asub_invoke_insn = nullptr; // target IR to test IRInstruction* ir_to_test = nullptr; // move result pseudo for iget-* IRInstruction* extra_insn = nullptr; if (is_put) { // put-* IR a_invoke_insn = dasm(OPCODE_INVOKE_DIRECT, a_type.ctor, {1_v}); asub_invoke_insn = dasm(OPCODE_INVOKE_DIRECT, b_type.ctor, {2_v}); switch (ir_suffix) { case SHORT: { // short, byte, boolean, char init_literal = dasm(OPCODE_CONST, {3_v, 1_L}); break; } case WIDE: { init_literal = dasm(OPCODE_CONST_WIDE, {3_v, 1_L}); break; } case REF: not_reached(); } ir_to_test = dasm(opcode_to_test, a_type.field, {3_v, 2_v}); } else { // get-* IR a_invoke_insn = dasm(OPCODE_INVOKE_DIRECT, a_type.ctor, {1_v, 3_v}); asub_invoke_insn = dasm(OPCODE_INVOKE_DIRECT, b_type.ctor, {2_v, 3_v}); switch (ir_suffix) { case SHORT: { // short, byte, boolean, char init_literal = dasm(OPCODE_CONST, {3_v, 1_L}); extra_insn = dasm(IOPCODE_MOVE_RESULT_PSEUDO, {0_v}); break; } case WIDE: { init_literal = dasm(OPCODE_CONST_WIDE, {3_v, 1_L}); extra_insn = dasm(IOPCODE_MOVE_RESULT_PSEUDO_WIDE, {5_v}); break; } case REF: not_reached(); } ir_to_test = dasm(opcode_to_test, a_type.field, {2_v}); } IRCode* code = method->get_code(); code->push_back(init_literal); // type a code->push_back(dasm(OPCODE_NEW_INSTANCE, a_type.value_type)); code->push_back(dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v})); code->push_back(a_invoke_insn); // type asub code->push_back(dasm(OPCODE_NEW_INSTANCE, b_type.value_type)); code->push_back(dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {2_v})); code->push_back(asub_invoke_insn); // test ir code->push_back(ir_to_test); // MOVE_RESULT_PSEUDO if (extra_insn) { code->push_back(extra_insn); } // return code->push_back(dasm(OPCODE_RETURN_VOID)); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.good()); } class IRTypeCheckerTest : public RedexTest { public: ~IRTypeCheckerTest() {} IRTypeCheckerTest() { auto args = DexTypeList::make_type_list({ DexType::make_type("I"), // v5 DexType::make_type("B"), // v6 DexType::make_type("J"), // v7/v8 DexType::make_type("Z"), // v9 DexType::make_type("D"), // v10/v11 DexType::make_type("S"), // v12 DexType::make_type("F"), // v13 type::java_lang_Object() // v14 }); ClassCreator cc(type::java_lang_Object()); cc.set_access(ACC_PUBLIC); cc.set_external(); auto object_class = cc.create(); auto proto = DexProto::make_proto(type::_boolean(), args); m_method = DexMethod::make_method(DexType::make_type("Lbar;"), DexString::make_string("testMethod"), proto) ->make_concrete(ACC_PUBLIC | ACC_STATIC, /* is_virtual */ false); m_method->set_deobfuscated_name("testMethod"); m_method->set_code(std::make_unique<IRCode>(m_method, /* temp_regs */ 5)); proto = DexProto::make_proto(type::java_lang_Object(), args); m_method_ret_obj = DexMethod::make_method(DexType::make_type("Lbar;"), DexString::make_string("testMethodRetObj"), proto) ->make_concrete(ACC_PUBLIC | ACC_STATIC, /* is_virtual */ false); m_method_ret_obj->set_deobfuscated_name("testMethodRetObj"); m_method_ret_obj->set_code( std::make_unique<IRCode>(m_method_ret_obj, /* temp_regs */ 5)); m_virtual_method = DexMethod::make_method(DexType::make_type("Lbar;"), DexString::make_string("testVirtualMethod"), proto) ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); m_virtual_method->set_deobfuscated_name("testVirtualMethod"); m_virtual_method->set_code( std::make_unique<IRCode>(m_virtual_method, /* temp_regs */ 5)); } void add_code(const std::vector<IRInstruction*>& insns) { add_code(m_method, insns); } void add_code(const std::unique_ptr<IRCode>& insns) { add_code(m_method, insns); } void add_code_ret_obj(const std::vector<IRInstruction*>& insns) { add_code(m_method_ret_obj, insns); } void add_code_ret_obj(const std::unique_ptr<IRCode>& insns) { add_code(m_method_ret_obj, insns); } void add_code(DexMethod* m, const std::vector<IRInstruction*>& insns) { IRCode* code = m->get_code(); for (const auto& insn : insns) { code->push_back(insn); } } void add_code(DexMethod* m, const std::unique_ptr<IRCode>& insns) { IRCode* code = m->get_code(); for (const auto& insn : *insns) { code->push_back(insn); } } protected: DexMethod* m_method; DexMethod* m_method_ret_obj; DexMethod* m_virtual_method; }; TEST_F(IRTypeCheckerTest, load_param) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_ADD_INT, {5_v, 5_v, 6_v}), dasm(IOPCODE_LOAD_PARAM, {5_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT(checker.what(), MatchesRegex("^Encountered [0x[0-9a-f]+] OPCODE: " "IOPCODE_LOAD_PARAM v5 not at the start " "of the method$")); } TEST_F(IRTypeCheckerTest, move_result) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_FILLED_NEW_ARRAY, DexType::make_type("I")) ->set_srcs_size(1) ->set_src(0, 5), dasm(OPCODE_ADD_INT, {5_v, 5_v, 5_v}), dasm(OPCODE_MOVE_RESULT, {0_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT(checker.what(), MatchesRegex("^Encountered [0x[0-9a-f]+] OPCODE: MOVE_RESULT v0 " "without appropriate prefix instruction. Expected " "invoke or filled-new-array, got " "ADD_INT v5, v5, v5$")); } TEST_F(IRTypeCheckerTest, move_result_at_start) { using namespace dex_asm; // Construct a new method because we don't want any load-param opcodes in // this one auto args = DexTypeList::make_type_list({}); auto proto = DexProto::make_proto(type::_boolean(), args); auto method = DexMethod::make_method(DexType::make_type("Lbar;"), DexString::make_string("testMethod2"), proto) ->make_concrete(ACC_PUBLIC | ACC_STATIC, /* is_virtual */ false); method->set_deobfuscated_name("testMethod2"); method->set_code(std::make_unique<IRCode>(method, 0)); IRCode* code = method->get_code(); code->push_back(dasm(OPCODE_MOVE_RESULT, {0_v})); code->push_back(dasm(OPCODE_ADD_INT, {5_v, 5_v, 5_v})); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT(checker.what(), MatchesRegex("^Encountered [0x[0-9a-f]+] OPCODE: MOVE_RESULT v0 " "at start of the method$")); } TEST_F(IRTypeCheckerTest, move_result_pseudo_no_prefix) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(IOPCODE_MOVE_RESULT_PSEUDO, {0_v}), dasm(OPCODE_ADD_INT, {5_v, 5_v, 5_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Encountered [0x[0-9a-f]+] OPCODE: IOPCODE_MOVE_RESULT_PSEUDO v0 " "without appropriate prefix instruction$")); } TEST_F(IRTypeCheckerTest, move_result_pseudo_no_suffix) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_CHECK_CAST, type::java_lang_Object(), {14_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT(checker.what(), ContainsRegex("^Did not find move-result-pseudo after " "[0x[0-9a-f]+] OPCODE: CHECK_CAST v14, " "Ljava/lang/Object;")); } TEST_F(IRTypeCheckerTest, arrayRead) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_CHECK_CAST, DexType::make_type("[I"), {14_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_AGET, {0_v, 5_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO, {1_v}), dasm(OPCODE_ADD_INT, {2_v, 1_v, 5_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ("OK", checker.what()); EXPECT_EQ(SCALAR, checker.get_type(insns[4], 1)); EXPECT_EQ(INT, checker.get_type(insns[5], 1)); } TEST_F(IRTypeCheckerTest, arrayReadWide) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_CHECK_CAST, DexType::make_type("[D"), {14_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_AGET_WIDE, {0_v, 5_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_WIDE, {1_v}), dasm(OPCODE_ADD_DOUBLE, {3_v, 1_v, 10_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ(SCALAR1, checker.get_type(insns[4], 1)); EXPECT_EQ(SCALAR2, checker.get_type(insns[4], 2)); EXPECT_EQ(DOUBLE1, checker.get_type(insns[5], 3)); EXPECT_EQ(DOUBLE2, checker.get_type(insns[5], 4)); } TEST_F(IRTypeCheckerTest, multipleDefinitions) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_CHECK_CAST, DexType::make_type("[I"), {14_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_AGET, {0_v, 5_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO, {0_v}), dasm(OPCODE_INT_TO_FLOAT, {0_v, 0_v}), dasm(OPCODE_NEG_FLOAT, {0_v, 0_v}), dasm(OPCODE_MOVE_OBJECT, {0_v, 14_v}), dasm(OPCODE_CHECK_CAST, DexType::make_type("Lfoo;"), {0_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, DexMethod::make_method("LFoo;", "bar", "J", {"S"}), {0_v, 12_v}), dasm(OPCODE_MOVE_RESULT_WIDE, {0_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ(REFERENCE, checker.get_type(insns[2], 0)); EXPECT_EQ(SCALAR, checker.get_type(insns[4], 0)); EXPECT_EQ(FLOAT, checker.get_type(insns[5], 0)); EXPECT_EQ(FLOAT, checker.get_type(insns[6], 0)); EXPECT_EQ(REFERENCE, checker.get_type(insns[7], 0)); EXPECT_EQ(REFERENCE, checker.get_type(insns[9], 0)); EXPECT_EQ(LONG1, checker.get_type(insns[11], 0)); EXPECT_EQ(LONG2, checker.get_type(insns[11], 1)); } TEST_F(IRTypeCheckerTest, referenceFromInteger) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_MOVE, {0_v, 5_v}), dasm(OPCODE_AGET, {0_v, 5_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO, {0_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Type error in method testMethod at instruction 'AGET v0, v5' " "@ 0x[0-9a-f]+ for register v0: expected type REF, but found " "INT instead")); } TEST_F(IRTypeCheckerTest, misalignedLong) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_MOVE_WIDE, {0_v, 7_v}), dasm(OPCODE_NEG_LONG, {1_v, 1_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Type error in method testMethod at instruction 'NEG_LONG v1, v1' " "@ 0x[0-9a-f]+ for register v1: expected type \\(LONG1, LONG2\\), " "but found \\(LONG2, TOP\\) instead")); } TEST_F(IRTypeCheckerTest, uninitializedRegister) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_INVOKE_VIRTUAL, DexMethod::make_method("Lbar;", "foo", "V", {}), {0_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Type error in method testMethod at instruction 'INVOKE_VIRTUAL v0, " "Lbar;\\.foo:\\(\\)V' @ 0x[0-9a-f]+ for register v0: expected " "type REF, but found TOP instead")); } TEST_F(IRTypeCheckerTest, undefinedRegister) { using namespace dex_asm; auto if_mie = new MethodItemEntry(dasm(OPCODE_IF_EQZ, {9_v})); auto goto_mie = new MethodItemEntry(dasm(OPCODE_GOTO, {})); auto target1 = new BranchTarget(if_mie); auto target2 = new BranchTarget(goto_mie); IRCode* code = m_method->get_code(); code->push_back(*if_mie); // branch to target1 code->push_back(dasm(OPCODE_MOVE_OBJECT, {0_v, 14_v})); code->push_back(dasm(OPCODE_CHECK_CAST, DexType::make_type("Lbar;"), {0_v})); code->push_back(dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v})); code->push_back(*goto_mie); // branch to target2 code->push_back(target1); code->push_back(dasm(OPCODE_MOVE, {0_v, 12_v})); code->push_back(target2); // Coming out of one branch, v0 is a reference and coming out of the other, // it's an integer. code->push_back(dasm(OPCODE_INVOKE_VIRTUAL, DexMethod::make_method("Lbar;", "foo", "V", {}), {0_v})); code->push_back(dasm(OPCODE_RETURN, {9_v})); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Type error in method testMethod at instruction 'INVOKE_VIRTUAL v0, " "Lbar;\\.foo:\\(\\)V' @ 0x[0-9a-f]+ for register v0: expected " "type REF, but found TOP instead")); } TEST_F(IRTypeCheckerTest, signatureMismatch) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_CHECK_CAST, DexType::make_type("Lbar;"), {14_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, DexMethod::make_method("Lbar;", "foo", "V", {"I", "J", "Z"}), {0_v, 5_v, 7_v, 13_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Type error in method testMethod at instruction 'INVOKE_VIRTUAL v0, " "v5, v7, v13, Lbar;\\.foo:\\(IJZ\\)V' @ 0x[0-9a-f]+ for register " "v13: expected type INT, but found FLOAT instead")); } TEST_F(IRTypeCheckerTest, longInvoke) { using namespace dex_asm; IRInstruction* invoke = new IRInstruction(OPCODE_INVOKE_STATIC); invoke->set_srcs_size(7); invoke->set_method(DexMethod::make_method( "Lbar;", "foo", "V", {"I", "B", "J", "Z", "D", "S", "F"})); invoke->set_src(0, 5); invoke->set_src(1, 6); invoke->set_src(2, 7); invoke->set_src(3, 9); invoke->set_src(4, 10); invoke->set_src(5, 12); invoke->set_src(6, 13); std::vector<IRInstruction*> insns = {invoke, dasm(OPCODE_RETURN, {9_v})}; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); } TEST_F(IRTypeCheckerTest, longSignatureMismatch) { using namespace dex_asm; IRInstruction* invoke = new IRInstruction(OPCODE_INVOKE_STATIC); invoke->set_srcs_size(7); invoke->set_method(DexMethod::make_method( "Lbar;", "foo", "V", {"I", "B", "J", "Z", "S", "D", "F"})); invoke->set_src(0, 5); invoke->set_src(1, 6); invoke->set_src(2, 7); invoke->set_src(3, 9); invoke->set_src(4, 10); invoke->set_src(5, 11); invoke->set_src(6, 13); std::vector<IRInstruction*> insns = {invoke, dasm(OPCODE_RETURN, {9_v})}; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Type error in method testMethod at instruction 'INVOKE_STATIC " "v5, v6, v7, v9, v10, v11, v13, Lbar;\\.foo:\\(IBJZSDF\\)V' " "@ 0x[0-9a-f]+ for register v10: expected type INT, but found " "DOUBLE1 " "instead")); } TEST_F(IRTypeCheckerTest, comparisonOperation) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_MOVE_WIDE, {0_v, 10_v}), dasm(OPCODE_CMP_LONG, {0_v, 7_v, 0_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex( "^Type error in method testMethod at instruction 'CMP_LONG v0, v7, " "v0' @ 0x[0-9a-f]+ for register v0: expected type \\(LONG1, " "LONG2\\), but found \\(DOUBLE1, DOUBLE2\\) instead")); } TEST_F(IRTypeCheckerTest, verifyMoves) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_MOVE_OBJECT, {1_v, 0_v}), dasm(OPCODE_MOVE, {1_v, 9_v}), dasm(OPCODE_RETURN, {1_v}), }; add_code(insns); IRTypeChecker lax_checker(m_method); lax_checker.run(); EXPECT_TRUE(lax_checker.good()) << lax_checker.what(); IRTypeChecker strict_checker(m_method); strict_checker.verify_moves(); strict_checker.run(); EXPECT_TRUE(strict_checker.fail()); EXPECT_THAT( strict_checker.what(), MatchesRegex( "^Type error in method testMethod at instruction " "'MOVE_OBJECT v1, v0' @ 0x[0-9a-f]+ for register v0: expected type " "REF, but found TOP instead")); } TEST_F(IRTypeCheckerTest, exceptionHandler) { using namespace dex_asm; auto exception_type = DexType::make_type("Ljava/lang/Exception;"); auto catch_start = new MethodItemEntry(exception_type); IRCode* code = m_method->get_code(); IRInstruction* noexc_return = dasm(OPCODE_RETURN, {1_v}); IRInstruction* exc_return = dasm(OPCODE_RETURN, {0_v}); code->push_back(dasm(OPCODE_MOVE, {0_v, 9_v})); code->push_back(dasm(OPCODE_CONST, {1_v, 0_L})); code->push_back(dasm(OPCODE_CONST, {2_v, 12_L})); code->push_back(TRY_START, catch_start); code->push_back(dasm(OPCODE_DIV_INT, {5_v, 5_v})); // Can throw code->push_back(dasm(IOPCODE_MOVE_RESULT_PSEUDO, {2_v})); code->push_back(dasm(OPCODE_CONST, {1_v, 1_L})); code->push_back(dasm(OPCODE_MOVE, {3_v, 1_v})); code->push_back(TRY_END, catch_start); code->push_back(noexc_return); code->push_back(*catch_start); code->push_back(exc_return); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ(INT, checker.get_type(noexc_return, 0)); EXPECT_EQ(CONST, checker.get_type(noexc_return, 1)); EXPECT_EQ(INT, checker.get_type(noexc_return, 2)); EXPECT_EQ(CONST, checker.get_type(noexc_return, 3)); // The exception is thrown by DIV_INT before v2 is modified. EXPECT_EQ(INT, checker.get_type(exc_return, 0)); EXPECT_EQ(ZERO, checker.get_type(exc_return, 1)); EXPECT_EQ(CONST, checker.get_type(exc_return, 2)); EXPECT_EQ(TOP, checker.get_type(exc_return, 3)); EXPECT_EQ(INT, checker.get_type(exc_return, 5)); // The rest of the type environment, like method parameters, should be // left unchanged in the exception handler. EXPECT_EQ(REFERENCE, checker.get_type(exc_return, 14)); } TEST_F(IRTypeCheckerTest, overlappingMoveWide) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_MOVE_WIDE, {1_v, 7_v}), dasm(OPCODE_MOVE_WIDE, {0_v, 1_v}), dasm(OPCODE_MOVE_WIDE, {0_v, 10_v}), dasm(OPCODE_MOVE_WIDE, {1_v, 0_v}), dasm(OPCODE_RETURN, {9_v}), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ("OK", checker.what()); EXPECT_EQ(LONG1, checker.get_type(insns[1], 1)); EXPECT_EQ(LONG2, checker.get_type(insns[1], 2)); EXPECT_EQ(LONG1, checker.get_type(insns[2], 0)); EXPECT_EQ(LONG2, checker.get_type(insns[2], 1)); EXPECT_EQ(DOUBLE1, checker.get_type(insns[3], 0)); EXPECT_EQ(DOUBLE2, checker.get_type(insns[3], 1)); EXPECT_EQ(DOUBLE1, checker.get_type(insns[4], 1)); EXPECT_EQ(DOUBLE2, checker.get_type(insns[4], 2)); } TEST_F(IRTypeCheckerTest, filledNewArray) { auto insns = assembler::ircode_from_string(R"( ( (const-string "S1") (move-result-pseudo-object v1) (const-string "S2") (move-result-pseudo-object v2) (const-string "S3") (move-result-pseudo-object v3) (filled-new-array (v1 v2 v3) "[Ljava/lang/String;") (move-result-object v0) (return v9) ) )"); add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ("OK", checker.what()); } TEST_F(IRTypeCheckerTest, zeroOrReference) { using namespace dex_asm; std::vector<IRInstruction*> insns = { dasm(OPCODE_CONST_CLASS, DexType::make_type("Lbar;")), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_MONITOR_ENTER, {0_v}), dasm(OPCODE_CONST, {1_v, 0_L}), dasm(OPCODE_MONITOR_EXIT, {0_v}), dasm(OPCODE_RETURN_OBJECT, {0_v}), dasm(OPCODE_MOVE_EXCEPTION, {1_v}), dasm(OPCODE_MONITOR_EXIT, {0_v}), dasm(OPCODE_THROW, {1_v}), }; add_code_ret_obj(insns); IRTypeChecker checker(m_method_ret_obj); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ("OK", checker.what()); EXPECT_EQ(REFERENCE, checker.get_type(insns[2], 0)); EXPECT_EQ(REFERENCE, checker.get_type(insns[3], 0)); EXPECT_EQ(REFERENCE, checker.get_type(insns[4], 0)); EXPECT_EQ(ZERO, checker.get_type(insns[4], 1)); EXPECT_EQ(REFERENCE, checker.get_type(insns[5], 0)); EXPECT_EQ(ZERO, checker.get_type(insns[5], 1)); EXPECT_EQ(BOTTOM, checker.get_type(insns[6], 0)); EXPECT_EQ(BOTTOM, checker.get_type(insns[6], 1)); EXPECT_EQ(BOTTOM, checker.get_type(insns[7], 1)); EXPECT_EQ(BOTTOM, checker.get_type(insns[8], 1)); } /** * The bytecode stream of the following Java code. * A simple branch join scenario on a reference type. * * Base base = null; * if (condition) { * base = new A(); * base.foo(); * } else { * base = new B(); * base.foo(); * } * base.foo(); */ TEST_F(IRTypeCheckerTest, joinDexTypesSharingCommonBaseSimple) { // Construct type hierarchy. const auto type_base = DexType::make_type("LBase;"); const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); ClassCreator cls_base_creator(type_base); cls_base_creator.set_super(type::java_lang_Object()); auto base_foo = DexMethod::make_method("LBase;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_base_creator.add_method(base_foo); cls_base_creator.create(); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type_base); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_foo = DexMethod::make_method("LA;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_a_creator.add_method(a_foo); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type_base); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); auto b_foo = DexMethod::make_method("LB;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_b_creator.add_method(b_foo); cls_b_creator.create(); // Construct code that references the above hierarchy. using namespace dex_asm; auto if_mie = new MethodItemEntry(dasm(OPCODE_IF_EQZ, {5_v})); auto goto_mie = new MethodItemEntry(dasm(OPCODE_GOTO, {})); auto target1 = new BranchTarget(if_mie); auto target2 = new BranchTarget(goto_mie); std::vector<IRInstruction*> insns = { // B0 // *if_mie, // branch to target1 // B1 dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, a_foo, {0_v}), // *goto_mie, // branch to target2 // B2 // target1, dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, b_foo, {0_v}), // target2, // B3 // Coming out of one branch, v0 is a reference and coming out of the // other, // it's an integer. dasm(OPCODE_INVOKE_VIRTUAL, base_foo, {0_v}), dasm(OPCODE_RETURN, {9_v}), }; IRCode* code = m_method->get_code(); code->push_back(*if_mie); code->push_back(insns[0]); code->push_back(insns[1]); code->push_back(insns[2]); code->push_back(insns[3]); code->push_back(*goto_mie); code->push_back(target1); code->push_back(insns[4]); code->push_back(insns[5]); code->push_back(insns[6]); code->push_back(insns[7]); code->push_back(target2); code->push_back(insns[8]); code->push_back(insns[9]); IRTypeChecker checker(m_method); checker.run(); // Checks EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ("OK", checker.what()); EXPECT_EQ(type_a, *checker.get_dex_type(insns[2], 0)); EXPECT_EQ(type_a, *checker.get_dex_type(insns[3], 0)); EXPECT_EQ(type_b, *checker.get_dex_type(insns[6], 0)); EXPECT_EQ(type_b, *checker.get_dex_type(insns[7], 0)); EXPECT_EQ(type_base, *checker.get_dex_type(insns[8], 0)); EXPECT_EQ(type_base, *checker.get_dex_type(insns[9], 0)); } /** * The bytecode stream of the following Java code. * A simple branch join scenario on a reference type. * * Base base = null; * if (condition) { * base = new A(); * base.foo(); * } else { * base = new B(); * base.foo(); * } * base.foo(); */ TEST_F(IRTypeCheckerTest, joinCommonBaseWithConflictingInterface) { // Construct type hierarchy. const auto type_base = DexType::make_type("LBase;"); const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); const auto type_i = DexType::make_type("LI;"); ClassCreator cls_base_creator(type_base); cls_base_creator.set_super(type::java_lang_Object()); auto base_foo = DexMethod::make_method("LBase;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_base_creator.add_method(base_foo); cls_base_creator.create(); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type_base); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_foo = DexMethod::make_method("LA;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_a_creator.add_method(a_foo); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type_base); cls_b_creator.add_interface(type_i); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); auto b_foo = DexMethod::make_method("LB;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_b_creator.add_method(b_foo); cls_b_creator.create(); // Construct code that references the above hierarchy. using namespace dex_asm; auto if_mie = new MethodItemEntry(dasm(OPCODE_IF_EQZ, {5_v})); auto goto_mie = new MethodItemEntry(dasm(OPCODE_GOTO, {})); auto target1 = new BranchTarget(if_mie); auto target2 = new BranchTarget(goto_mie); std::vector<IRInstruction*> insns = { // B0 // *if_mie, // branch to target1 // B1 dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, a_foo, {0_v}), // *goto_mie, // branch to target2 // B2 // target1, dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, b_foo, {0_v}), // target2, // B3 // Coming out of one branch, v0 is a reference and coming out of the // other, // it's an integer. dasm(OPCODE_INVOKE_VIRTUAL, base_foo, {0_v}), dasm(OPCODE_RETURN, {9_v}), }; IRCode* code = m_method->get_code(); code->push_back(*if_mie); code->push_back(insns[0]); code->push_back(insns[1]); code->push_back(insns[2]); code->push_back(insns[3]); code->push_back(*goto_mie); code->push_back(target1); code->push_back(insns[4]); code->push_back(insns[5]); code->push_back(insns[6]); code->push_back(insns[7]); code->push_back(target2); code->push_back(insns[8]); code->push_back(insns[9]); IRTypeChecker checker(m_method); checker.run(); // Checks EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ("OK", checker.what()); EXPECT_EQ(type_a, *checker.get_dex_type(insns[2], 0)); EXPECT_EQ(type_a, *checker.get_dex_type(insns[3], 0)); EXPECT_EQ(type_b, *checker.get_dex_type(insns[6], 0)); EXPECT_EQ(type_b, *checker.get_dex_type(insns[7], 0)); EXPECT_EQ(boost::none, checker.get_dex_type(insns[8], 0)); EXPECT_EQ(boost::none, checker.get_dex_type(insns[9], 0)); } /** * The bytecode stream of the following Java code. * A simple branch join scenario on a reference type. * * Base base = null; * if (condition) { * base = new A(); * base.foo(); * } else { * base = new B(); * base.foo(); * } * base.foo(); */ TEST_F(IRTypeCheckerTest, joinCommonBaseWithMergableInterface) { // Construct type hierarchy. const auto type_base = DexType::make_type("LBase;"); const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); const auto type_i = DexType::make_type("LI;"); ClassCreator cls_base_creator(type_base); cls_base_creator.set_super(type::java_lang_Object()); cls_base_creator.add_interface(type_i); auto base_foo = DexMethod::make_method("LBase;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_base_creator.add_method(base_foo); cls_base_creator.create(); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type_base); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_foo = DexMethod::make_method("LA;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_a_creator.add_method(a_foo); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type_base); cls_b_creator.add_interface(type_i); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); auto b_foo = DexMethod::make_method("LB;.foo:()I")->make_concrete(ACC_PUBLIC, true); cls_b_creator.add_method(b_foo); cls_b_creator.create(); // Construct code that references the above hierarchy. using namespace dex_asm; auto if_mie = new MethodItemEntry(dasm(OPCODE_IF_EQZ, {5_v})); auto goto_mie = new MethodItemEntry(dasm(OPCODE_GOTO, {})); auto target1 = new BranchTarget(if_mie); auto target2 = new BranchTarget(goto_mie); std::vector<IRInstruction*> insns = { // B0 // *if_mie, // branch to target1 // B1 dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, a_foo, {0_v}), // *goto_mie, // branch to target2 // B2 // target1, dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {0_v}), dasm(OPCODE_INVOKE_VIRTUAL, b_foo, {0_v}), // target2, // B3 // Coming out of one branch, v0 is a reference and coming out of the // other, // it's an integer. dasm(OPCODE_INVOKE_VIRTUAL, base_foo, {0_v}), dasm(OPCODE_RETURN, {9_v}), }; IRCode* code = m_method->get_code(); code->push_back(*if_mie); code->push_back(insns[0]); code->push_back(insns[1]); code->push_back(insns[2]); code->push_back(insns[3]); code->push_back(*goto_mie); code->push_back(target1); code->push_back(insns[4]); code->push_back(insns[5]); code->push_back(insns[6]); code->push_back(insns[7]); code->push_back(target2); code->push_back(insns[8]); code->push_back(insns[9]); IRTypeChecker checker(m_method); checker.run(); // Checks EXPECT_TRUE(checker.good()) << checker.what(); EXPECT_EQ("OK", checker.what()); EXPECT_EQ(type_a, *checker.get_dex_type(insns[2], 0)); EXPECT_EQ(type_a, *checker.get_dex_type(insns[3], 0)); EXPECT_EQ(type_b, *checker.get_dex_type(insns[6], 0)); EXPECT_EQ(type_b, *checker.get_dex_type(insns[7], 0)); EXPECT_EQ(type_base, *checker.get_dex_type(insns[8], 0)); EXPECT_EQ(type_base, *checker.get_dex_type(insns[9], 0)); } /** * The bytecode stream of the following Java code. * * Base base; * if (condition) { * base = null; * } else { * base = new Object(); * } * base.foo(); */ TEST_F(IRTypeCheckerTest, invokeInvalidObjectType) { // Construct type hierarchy. const auto type_base = DexType::make_type("LBase;"); ClassCreator cls_base_creator(type_base); cls_base_creator.set_super(type::java_lang_Object()); auto base_foobar = DexMethod::make_method("LBase;.foobar:()I") ->make_concrete(ACC_PUBLIC, true); cls_base_creator.add_method(base_foobar); cls_base_creator.create(); auto object_ctor = DexMethod::make_method("Ljava/lang/Object;.<init>:()V"); EXPECT_TRUE(object_ctor != nullptr); // Construct code that references the above hierarchy. using namespace dex_asm; auto if_mie = new MethodItemEntry(dasm(OPCODE_IF_EQZ, {5_v})); auto goto_mie = new MethodItemEntry(dasm(OPCODE_GOTO, {})); auto target1 = new BranchTarget(if_mie); auto target2 = new BranchTarget(goto_mie); std::vector<IRInstruction*> insns = { // B0 // *if_mie, // branch to target1 // B1 dasm(OPCODE_CONST, {0_v, 0_L}), // *goto_mie, // branch to target2 // B2 // target1, dasm(OPCODE_NEW_INSTANCE, type::java_lang_Object()), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, object_ctor, {0_v}), // target2, // B3 // Coming out of one branch, v0 is null and coming out of the // other, it's an Object, but not (necessarily) a Base dasm(OPCODE_INVOKE_VIRTUAL, base_foobar, {0_v}), dasm(OPCODE_RETURN, {9_v}), }; IRCode* code = m_method->get_code(); code->push_back(*if_mie); code->push_back(insns[0]); code->push_back(*goto_mie); code->push_back(target1); code->push_back(insns[1]); code->push_back(insns[2]); code->push_back(insns[3]); code->push_back(target2); code->push_back(insns[4]); code->push_back(insns[5]); IRTypeChecker checker(m_method); checker.run(); // This should NOT type check successfully due to invoking Base.foobar against // an Object EXPECT_FALSE(checker.good()) << checker.what(); EXPECT_NE("OK", checker.what()); } TEST_F(IRTypeCheckerTest, invokeInitAfterNewInstance) { { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (new-instance "LFoo;") (move-result-pseudo-object v0) (invoke-direct (v0) "LFoo;.<init>:()V") ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); } { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (new-instance "LFoo;") (move-result-pseudo-object v0) ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); } { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (new-instance "LFoo;") (move-result-pseudo-object v0) (move-object v1 v0) (return-object v1) ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_FALSE(checker.good()); EXPECT_THAT(checker.what(), MatchesRegex("^Use of uninitialized variable.*")); } { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (new-instance "LFoo;") (move-result-pseudo-object v0) (move-object v1 v0) (invoke-direct (v0) "LFoo;.<init>:()V") (return-object v1) ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); } { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (new-instance "LFoo;") (move-result-pseudo-object v0) (move-object v1 v0) (return-object v1) ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_FALSE(checker.good()); EXPECT_THAT(checker.what(), MatchesRegex("^Use of uninitialized variable.*")); } { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (new-instance "LFoo;") (move-result-pseudo-object v0) (new-instance "LFoo;") (move-result-pseudo-object v5) (invoke-direct (v5) "LFoo;.<init>:()V") (return-object v5) (return-object v0) ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); } } TEST_F(IRTypeCheckerTest, checkNoOverwriteThis) { // Good { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (const v1 0) (return-object v0) ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.good()) << checker.what(); } // Bad: virtual method { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (const v0 0) ; overwrites `this` register (return-object v0) ) )")); IRTypeChecker checker(method); checker.check_no_overwrite_this(); checker.run(); EXPECT_FALSE(checker.good()); EXPECT_EQ(checker.what(), "Encountered overwrite of `this` register by CONST v0, 0"); } // Bad: non-static (private) direct method { auto method = DexMethod::make_method("LFoo;.bar:(LBar;)LFoo;") ->make_concrete(ACC_PRIVATE, /* is_virtual */ false); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param-object v1) (const v0 0) ; overwrites `this` register (return-object v0) ) )")); IRTypeChecker checker(method); checker.check_no_overwrite_this(); checker.run(); EXPECT_FALSE(checker.good()); EXPECT_EQ(checker.what(), "Encountered overwrite of `this` register by CONST v0, 0"); } } TEST_F(IRTypeCheckerTest, loadParamVirtualFail) { m_virtual_method->set_code(assembler::ircode_from_string(R"( ( (load-param v0) (const v1 0) (return-object v1) ) )")); IRTypeChecker checker(m_virtual_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT(checker.what(), MatchesRegex("^First parameter must be loaded with " "load-param-object: IOPCODE_LOAD_PARAM v0$")); } TEST_F(IRTypeCheckerTest, loadParamVirtualSuccess) { m_virtual_method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param v1) (load-param v2) (load-param-wide v3) (load-param v4) (load-param-wide v5) (load-param v6) (load-param v7) (load-param-object v8) (return-object v8) ) )")); IRTypeChecker checker(m_virtual_method); checker.run(); EXPECT_FALSE(checker.fail()); } TEST_F(IRTypeCheckerTest, loadParamStaticCountSuccess) { m_method->set_code(assembler::ircode_from_string(R"( ( (load-param v0) (load-param v1) (load-param-wide v2) (load-param v3) (load-param-wide v4) (load-param v5) (load-param v6) (load-param-object v7) (const v7 0) (return-object v7) ) )")); IRTypeChecker checker(m_method); checker.run(); EXPECT_FALSE(checker.fail()); } TEST_F(IRTypeCheckerTest, loadParamStaticCountLessFail) { m_method->set_code(assembler::ircode_from_string(R"( ( (load-param v0) (load-param v1) (load-param-wide v2) (const v3 0) (return-object v3) ) )")); IRTypeChecker checker(m_method); checker.run(); EXPECT_EQ(checker.what(), "Number of existing load-param instructions (3) is lower than " "expected (8)"); } TEST_F(IRTypeCheckerTest, loadParamInstanceCountLessFail) { m_virtual_method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (const v3 0) (return-object v3) ) )")); IRTypeChecker checker(m_virtual_method); checker.run(); EXPECT_EQ(checker.what(), "Number of existing load-param instructions (1) is lower than " "expected (9)"); } TEST_F(IRTypeCheckerTest, loadParamInstanceCountMoreFail) { m_virtual_method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (load-param v1) (load-param v2) (load-param-wide v3) (load-param v4) (load-param-wide v5) (load-param v6) (load-param v7) (load-param-object v8) (load-param v9) (const v7 0) (return-object v7) ) )")); IRTypeChecker checker(m_virtual_method); checker.run(); EXPECT_EQ(checker.what(), "Not enough argument types for IOPCODE_LOAD_PARAM v9"); } TEST_F(IRTypeCheckerTest, loadParamStaticCountMoreFail) { m_method->set_code(assembler::ircode_from_string(R"( ( (load-param v0) (load-param v1) (load-param-wide v2) (load-param v3) (load-param-wide v4) (load-param v5) (load-param v6) (load-param-object v7) (load-param v8) (return-object v7) ) )")); IRTypeChecker checker(m_method); checker.run(); EXPECT_EQ(checker.what(), "Not enough argument types for IOPCODE_LOAD_PARAM v8"); } /** * v0 not compatible with field type * * class A { B f; } -> v1 * class B {} * class C {} -> v0 * * iput-object C (v0), A (v1), "LA;.f:LB;" * */ TEST_F(IRTypeCheckerTest, putObjectFieldIncompatibleTypeFail) { const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); const auto type_c = DexType::make_type("LC;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:LB;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type::java_lang_Object()); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); cls_b_creator.create(); ClassCreator cls_c_creator(type_c); cls_c_creator.set_super(type::java_lang_Object()); auto c_ctor = DexMethod::make_method("LC;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_c_creator.add_method(c_ctor); cls_c_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // type c dasm(OPCODE_NEW_INSTANCE, type_c), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, c_ctor, {0_v}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v}), // type b dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {2_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {2_v}), dasm(OPCODE_IPUT_OBJECT, a_f, {0_v, 1_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex("^Type error in method testMethod at instruction " "'IPUT_OBJECT v0, v1, LA;.f:LB;' " "@ 0x[0-9a-f]+ for : LC; is not assignable to LB;\n")); } /** * v1 not compatible with field class * * class A { B f; } -> v1 * class B {} -> v0 * class C { B f; } * * iput-object B (v0), A (v1), "LC;.f:LB;" * */ TEST_F(IRTypeCheckerTest, putObjectFieldIncompatibleClassFail) { const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); const auto type_c = DexType::make_type("LC;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:LB;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type::java_lang_Object()); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); cls_b_creator.create(); ClassCreator cls_c_creator(type_c); cls_c_creator.set_super(type::java_lang_Object()); auto c_ctor = DexMethod::make_method("LC;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); auto c_f = DexField::make_field("LC;.f:LB;")->make_concrete(ACC_PUBLIC); cls_c_creator.add_field(c_f); cls_c_creator.add_method(c_ctor); cls_c_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // type b dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {0_v}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v}), // type c dasm(OPCODE_NEW_INSTANCE, type_c), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {2_v}), dasm(OPCODE_INVOKE_DIRECT, c_ctor, {2_v}), dasm(OPCODE_IPUT_OBJECT, c_f, {0_v, 1_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex("^Type error in method testMethod at instruction " "'IPUT_OBJECT v0, v1, LC;.f:LB;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LC;\n")); } /** * iput-object success * * class A { B f; } -> v1 * class B {} -> v0 * * iput-object B (v0), A (v1), "LA;.f:LB;" * */ TEST_F(IRTypeCheckerTest, putObjectSuccess) { const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:LB;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type::java_lang_Object()); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); cls_b_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // type b dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {0_v}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v}), dasm(OPCODE_IPUT_OBJECT, a_f, {0_v, 1_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()); } /** * v1 not compatible with field class * * class A { B f; } -> v1 * class B {} -> v0 * class C { B f; } * * iget-object B (v0), A (v1), "LC;.f:LB;" * */ TEST_F(IRTypeCheckerTest, getObjectFieldIncompatibleClassFail) { const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); const auto type_c = DexType::make_type("LC;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:LB;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type::java_lang_Object()); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); cls_b_creator.create(); ClassCreator cls_c_creator(type_c); cls_c_creator.set_super(type::java_lang_Object()); auto c_ctor = DexMethod::make_method("LC;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); auto c_f = DexField::make_field("LC;.f:LB;")->make_concrete(ACC_PUBLIC); cls_c_creator.add_field(c_f); cls_c_creator.add_method(c_ctor); cls_c_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // type b dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {0_v}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v}), // type c dasm(OPCODE_NEW_INSTANCE, type_c), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {2_v}), dasm(OPCODE_INVOKE_DIRECT, c_ctor, {2_v}), dasm(OPCODE_IGET_OBJECT, c_f, {1_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex("^Type error in method testMethod at instruction " "'IGET_OBJECT v1, LC;.f:LB;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LC;\n")); } /** * iget-object success * * class A { B f; } -> v1 * class B {} -> v0 * * iget-object B (v0), A (v1), "LA;.f:LB;" * */ TEST_F(IRTypeCheckerTest, getObjectSuccess) { const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:LB;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type::java_lang_Object()); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); cls_b_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // type b dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {0_v}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v}), dasm(OPCODE_IGET_OBJECT, a_f, {1_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {0_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()); } /** * v1 not compatible with field class * * class A { int f; } -> v1 * int 2 -> v0 * class B { int f; } * * iput 2 (v0), A (v1), "LB;.f:I;" * */ TEST_F(IRTypeCheckerTest, putInstanceFieldIncompatibleClassFail) { const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:I;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type::java_lang_Object()); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); auto b_f = DexField::make_field("LB;.f:I;")->make_concrete(ACC_PUBLIC); cls_b_creator.add_field(b_f); cls_b_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // literal 2 dasm(OPCODE_CONST, {0_v, 2_L}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v}), // type b dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {2_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {2_v}), dasm(OPCODE_IPUT, b_f, {0_v, 1_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex("^Type error in method testMethod at instruction " "'IPUT v0, v1, LB;.f:I;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n")); } /** * iput success * * class A { int f; } -> v1 * int 2 -> v0 * * iput 2 (v0), A (v1), "LA;.f:I;" * */ TEST_F(IRTypeCheckerTest, putInstanceSuccess) { const auto type_a = DexType::make_type("LA;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:I;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // literal 2 dasm(OPCODE_CONST, {0_v, 2_L}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v}), dasm(OPCODE_IPUT, a_f, {0_v, 1_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()); } /** * v1 not compatible with field class * * class A { int f = 2; } -> v1 * * class B { int f; } * * iget v0, A (v1), "LB;.f:I;" * */ TEST_F(IRTypeCheckerTest, getInstanceFieldIncompatibleClassFail) { const auto type_a = DexType::make_type("LA;"); const auto type_b = DexType::make_type("LB;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:(I)V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:I;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); ClassCreator cls_b_creator(type_b); cls_b_creator.set_super(type::java_lang_Object()); auto b_ctor = DexMethod::make_method("LB;.<init>:()V") ->make_concrete(ACC_PUBLIC, false); cls_b_creator.add_method(b_ctor); auto b_f = DexField::make_field("LB;.f:I;")->make_concrete(ACC_PUBLIC); cls_b_creator.add_field(b_f); cls_b_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // literal 2 dasm(OPCODE_CONST, {3_v, 2_L}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v, 3_v}), // type b dasm(OPCODE_NEW_INSTANCE, type_b), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {2_v}), dasm(OPCODE_INVOKE_DIRECT, b_ctor, {2_v}), dasm(OPCODE_IGET, b_f, {1_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO, {0_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.fail()); EXPECT_THAT( checker.what(), MatchesRegex("^Type error in method testMethod at instruction " "'IGET v1, LB;.f:I;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n")); } /** * iget success * * class A { int f = 2; } -> v1 * * iget v0, A (v1), "LA;.f:I;" * */ TEST_F(IRTypeCheckerTest, getInstanceSuccess) { const auto type_a = DexType::make_type("LA;"); ClassCreator cls_a_creator(type_a); cls_a_creator.set_super(type::java_lang_Object()); auto a_ctor = DexMethod::make_method("LA;.<init>:(I)V") ->make_concrete(ACC_PUBLIC, false); cls_a_creator.add_method(a_ctor); auto a_f = DexField::make_field("LA;.f:I;")->make_concrete(ACC_PUBLIC); cls_a_creator.add_field(a_f); cls_a_creator.create(); using namespace dex_asm; std::vector<IRInstruction*> insns = { // literal 2 dasm(OPCODE_CONST, {3_v, 2_L}), // type a dasm(OPCODE_NEW_INSTANCE, type_a), dasm(IOPCODE_MOVE_RESULT_PSEUDO_OBJECT, {1_v}), dasm(OPCODE_INVOKE_DIRECT, a_ctor, {1_v, 3_v}), dasm(OPCODE_IGET, a_f, {1_v}), dasm(IOPCODE_MOVE_RESULT_PSEUDO, {0_v}), dasm(OPCODE_RETURN_VOID), }; add_code(insns); IRTypeChecker checker(m_method); checker.run(); EXPECT_TRUE(checker.good()); } /** * v1 not compatible with field class * * class A { short f; } -> v1 * short 1 -> v3 * class B { short f; } * * iput-short 1 (v3), A (v1), "LB;.f:S;" * */ TEST_F(IRTypeCheckerTest, putShortFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IPUT_SHORT v3, v1, LB;.f:S;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IPUT_SHORT; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:S;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:S;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, true, SHORT, m_method); } /** * iput-short success * * class A { short f; } -> v1 * short 1 -> v3 * * iput-short 1 (v3), A (v1), "LA;.f:S;" * */ TEST_F(IRTypeCheckerTest, putShortSuccess) { IROpcode op = OPCODE_IPUT_SHORT; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:S;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:()V", "LAsub;.f:S;"); field_compatible_success_helper(a_type, sub_type, op, true, SHORT, m_method); } /** * v1 not compatible with field class * * class A { short f = 1; } -> v1 * * class B { short f; } * * iget-short v3, A (v1), "LB;.f:S;" * */ TEST_F(IRTypeCheckerTest, getShortFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IGET_SHORT v1, LB;.f:S;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IGET_SHORT; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(S)V", "LA;.f:S;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:S;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, false, SHORT, m_method); } /** * iget-short success * * class A { short f = 1; } -> v1 * * iget-short v3, A (v1), "LA;.f:S;" * */ TEST_F(IRTypeCheckerTest, getShortSuccess) { IROpcode op = OPCODE_IGET_SHORT; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(S)V", "LA;.f:S;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:(S)V", "LAsub;.f:S;"); field_compatible_success_helper(a_type, sub_type, op, false, SHORT, m_method); } /** * v1 not compatible with field class * * class A { boolean f; } -> v1 * boolean true -> v3 * class B { boolean f; } * * iput-boolean true (v3), A (v1), "LB;.f:Z;" * */ TEST_F(IRTypeCheckerTest, putBoolFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IPUT_BOOLEAN v3, v1, LB;.f:Z;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IPUT_BOOLEAN; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:Z;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:Z;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, true, SHORT, m_method); } /** * iput-boolean success * * class A { boolean f; } -> v1 * boolean true -> v3 * class Asub extends A {}; -> v2 * * iput-boolean true (v3), Asub (v2), "LA;.f:Z;" * */ TEST_F(IRTypeCheckerTest, putBoolSuccess) { IROpcode op = OPCODE_IPUT_BOOLEAN; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:Z;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:()V", "LAsub;.f:Z;"); field_compatible_success_helper(a_type, sub_type, op, true, SHORT, m_method); } /** * v1 not compatible with field class * * class A { boolean f = true; } -> v1 * * class B { boolean f; } * * iget-boolean v0, A (v1), "LB;.f:Z;" * */ TEST_F(IRTypeCheckerTest, getBoolFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IGET_BOOLEAN v1, LB;.f:Z;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IGET_BOOLEAN; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(Z)V", "LA;.f:Z;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:Z;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, false, SHORT, m_method); } /** * iget-boolean success * * class A {boolean f = true} -> v1 * * class Asub extends A {boolean f = true;}; -> v2 * * iget-boolean v0, Asub (v2), "LA;.f:Z;" * */ TEST_F(IRTypeCheckerTest, getBoolSuccess) { IROpcode op = OPCODE_IGET_BOOLEAN; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(Z)V", "LA;.f:Z;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:(Z)V", "LAsub;.f:Z;"); field_compatible_success_helper(a_type, sub_type, op, false, SHORT, m_method); } /** * v1 not compatible with field class * * class A { long f; } -> v1 * long 1L -> v3 * class B { long f; } -> v2 * * iput-wide 1L (v3), A (v1), "LB;.f:J;" * */ TEST_F(IRTypeCheckerTest, putWideFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IPUT_WIDE v3, v1, LB;.f:J;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IPUT_WIDE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:J;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:J;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, true, WIDE, m_method); } /** * iput-wide success * * class A { long f; } -> v1 * long 1L -> v3 * class Asub extends A {}; -> v2 * * iput-wide 1L (v3), Asub (v2), "LA;.f:J;" * */ TEST_F(IRTypeCheckerTest, putWideSuccess) { IROpcode op = OPCODE_IPUT_WIDE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:J;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:()V", "LAsub;.f:J;"); field_compatible_success_helper(a_type, sub_type, op, true, WIDE, m_method); } /** * v1 not compatible with field class * * class A { long f = 1L; } -> v1 * * class B { long f; } * * iget-wide v5, A (v1), "LB;.f:J;" * */ TEST_F(IRTypeCheckerTest, getWideFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IGET_WIDE v1, LB;.f:J;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IGET_WIDE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(J)V", "LA;.f:J;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:J;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, false, WIDE, m_method); } /** * iget-wide success * * class A {long f = 1L} -> v1 * * class Asub extends A {long f = 1L;}; -> v2 * * iget-wide v5, Asub (v2), "LA;.f:J;" * */ TEST_F(IRTypeCheckerTest, getWideSuccess) { IROpcode op = OPCODE_IGET_WIDE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(J)V", "LA;.f:J;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:(J)V", "LAsub;.f:J;"); field_compatible_success_helper(a_type, sub_type, op, false, WIDE, m_method); } /** * v1 not compatible with field class * * class A { byte f; } -> v1 * byte 1 -> v3 * class B { byte f; } -> v2 * * iput-byte 1 (v3), A (v1), "LB;.f:B;" * */ TEST_F(IRTypeCheckerTest, putByteFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IPUT_BYTE v3, v1, LB;.f:B;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IPUT_BYTE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:B;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:B;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, true, SHORT, m_method); } /** * iput-byte success * * class A { byte f; } -> v1 * byte 1 -> v3 * class Asub extends A {}; -> v2 * * iput-byte 1 (v3), Asub (v2), "LA;.f:B;" * */ TEST_F(IRTypeCheckerTest, putByteSuccess) { IROpcode op = OPCODE_IPUT_BYTE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:B;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:()V", "LAsub;.f:B;"); field_compatible_success_helper(a_type, sub_type, op, true, SHORT, m_method); } /** * v1 not compatible with field class * * class A { byte f = 1; } -> v1 * * class B { byte f; } * * iget-byte v0, A (v1), "LB;.f:B;" * */ TEST_F(IRTypeCheckerTest, getByteFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IGET_BYTE v1, LB;.f:B;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IGET_BYTE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(B)V", "LA;.f:B;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:B;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, false, SHORT, m_method); } /** * iget-byte success * * class A {byte f = 1} -> v1 * * class Asub extends A {byte f = 1;}; -> v2 * * iget-byte v0, Asub (v2), "LA;.f:B;" * */ TEST_F(IRTypeCheckerTest, getByteSuccess) { IROpcode op = OPCODE_IGET_BYTE; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(B)V", "LA;.f:B;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:(B)V", "LAsub;.f:B;"); field_compatible_success_helper(a_type, sub_type, op, false, SHORT, m_method); } /** * v1 not compatible with field class * * class A { char f; } -> v1 * char 1 -> v3 * class B { char f; } -> v2 * * iput-char 1 (v3), A (v1), "LB;.f:C;" * */ TEST_F(IRTypeCheckerTest, putCharFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IPUT_CHAR v3, v1, LB;.f:C;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IPUT_CHAR; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:C;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:C;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, true, SHORT, m_method); } /** * iput-char success * * class A { char f; } -> v1 * char 1 -> v3 * class Asub extends A {}; -> v2 * * iput-char 1 (v3), Asub (v2), "LA;.f:C;" * */ TEST_F(IRTypeCheckerTest, putCharSuccess) { IROpcode op = OPCODE_IPUT_CHAR; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:()V", "LA;.f:C;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:()V", "LAsub;.f:C;"); field_compatible_success_helper(a_type, sub_type, op, true, SHORT, m_method); } /** * v1 not compatible with field class * * class A { char f = 1; } -> v1 * * class B { char f; } * * iget-char v0, A (v1), "LB;.f:C;" * */ TEST_F(IRTypeCheckerTest, getCharFieldIncompatibleClassFail) { const std::string exp_fail_str = "^Type error in method testMethod at instruction " "'IGET_CHAR v1, LB;.f:C;' " "@ 0x[0-9a-f]+ for : LA; is not assignable to LB;\n"; IROpcode op = OPCODE_IGET_CHAR; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_b = DexType::make_type("LB;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(C)V", "LA;.f:C;"); TestValueType b_type(dex_type_b, type::java_lang_Object(), "LB;.<init>:()V", "LB;.f:C;"); field_incompatible_fail_helper(a_type, b_type, exp_fail_str, op, false, SHORT, m_method); } /** * iget-char success * * class A {char f = 1} -> v1 * * class Asub extends A {char f = 1}; -> v2 * * iget-char v0, Asub (v2), "LA;.f:C;" * */ TEST_F(IRTypeCheckerTest, getCharSuccess) { IROpcode op = OPCODE_IGET_CHAR; const auto dex_type_a = DexType::make_type("LA;"); const auto dex_type_asub = DexType::make_type("LAsub;"); TestValueType a_type(dex_type_a, type::java_lang_Object(), "LA;.<init>:(C)V", "LA;.f:C;"); TestValueType sub_type(dex_type_asub, dex_type_a, "LAsub;.<init>:(C)V", "LAsub;.f:C;"); field_compatible_success_helper(a_type, sub_type, op, false, SHORT, m_method); } template <bool kVirtual> class LoadParamMutationTest : public IRTypeCheckerTest { public: void run() { IRCode* code = (kVirtual ? m_virtual_method : m_method)->get_code(); recurse(code, code->begin()); } void recurse(IRCode* code, IRList::iterator it) { if (it == code->end()) { return; } if (it->type == MFLOW_OPCODE && opcode::is_a_load_param(it->insn->opcode())) { auto real_op = it->insn->opcode(); for (auto op = IOPCODE_LOAD_PARAM; op <= IOPCODE_LOAD_PARAM_WIDE; op = static_cast<IROpcode>(static_cast<uint16_t>(op) + 1)) { if (op == real_op) { continue; } it->insn->set_opcode(op); check_fail(); } it->insn->set_opcode(real_op); } ++it; recurse(code, it); } void check_fail() { IRTypeChecker checker(kVirtual ? m_virtual_method : m_method); checker.run(); EXPECT_TRUE(checker.fail()); } }; using LoadParamMutationStaticTest = LoadParamMutationTest<false>; using LoadParamMutationVirtualTest = LoadParamMutationTest<true>; TEST_F(LoadParamMutationStaticTest, mutate) { run(); } TEST_F(LoadParamMutationVirtualTest, mutate) { run(); } TEST_F(IRTypeCheckerTest, invokeSuperInterfaceMethod) { // Construct type hierarchy. const auto interface_type = DexType::make_type("LI;"); ClassCreator interface_type_creator(interface_type); interface_type_creator.set_super(type::java_lang_Object()); interface_type_creator.set_access(ACC_INTERFACE); auto foo_method = DexMethod::make_method("LI;.foo:()V")->make_concrete(ACC_PUBLIC, true); interface_type_creator.add_method(foo_method); interface_type_creator.create(); // Construct code that references the above hierarchy. using namespace dex_asm; IRCode* code = m_method->get_code(); code->push_back(dasm(OPCODE_CONST, {0_v, 0_L})); code->push_back(dasm(OPCODE_INVOKE_SUPER, foo_method, {0_v})); code->push_back(dasm(OPCODE_RETURN_VOID)); IRTypeChecker checker(m_method); checker.run(); // Checks EXPECT_FALSE(checker.good()); EXPECT_THAT(checker.what(), MatchesRegex(".*\nillegal invoke-super to interface method.*")); } TEST_F(IRTypeCheckerTest, synchronizedThrowOutsideCatchAllInTry) { auto method = DexMethod::make_method("LFoo;.bar:()V;") ->make_concrete(ACC_PUBLIC, /* is_virtual */ true); method->set_code(assembler::ircode_from_string(R"( ( (load-param-object v0) (monitor-enter v0) (.try_start a) (check-cast v0 "LFoo;") (move-result-pseudo-object v1) (.try_end a) (.catch (a) "LMyThrowable;") (monitor-exit v0) (return-void) ) )")); IRTypeChecker checker(method); checker.run(); EXPECT_TRUE(checker.fail()); }
98f47f4fb6eaa41a98ce54724f1152af5179ad9d
c51febc209233a9160f41913d895415704d2391f
/library/ATF/LPD3DTRANSFORMDATA.hpp
5b51c15ad0dad904f97c8ae48309d4bc22c8affc
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
274
hpp
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_D3DTRANSFORMDATA.hpp> START_ATF_NAMESPACE typedef _D3DTRANSFORMDATA *LPD3DTRANSFORMDATA; END_ATF_NAMESPACE
7d841f22b649f10b52f7fcb124c4da5c8d81389f
4af9bc5520bc6d52102a36db9cf7b594459d5fc3
/Demo/Intermediate/Build/Mac/UE4Editor/Inc/EpochDemo/EpochDemo.init.gen.cpp
0cfd7b3062d952bd428a6ead8eff15128f7ef16a
[]
no_license
Srose0712/Demos
13979df6bd48505f7e083728272929e9a86cfbe1
32e1b9cc18204981da3539f94448f648ccd67f7a
refs/heads/master
2020-06-28T16:57:09.375814
2019-08-16T16:27:26
2019-08-16T16:27:26
200,288,266
0
0
null
null
null
null
UTF-8
C++
false
false
1,100
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeEpochDemo_init() {} UPackage* Z_Construct_UPackage__Script_EpochDemo() { static UPackage* ReturnPackage = nullptr; if (!ReturnPackage) { static const UE4CodeGen_Private::FPackageParams PackageParams = { "/Script/EpochDemo", nullptr, 0, PKG_CompiledIn | 0x00000000, 0xAB43577F, 0x07ED099F, METADATA_PARAMS(nullptr, 0) }; UE4CodeGen_Private::ConstructUPackage(ReturnPackage, PackageParams); } return ReturnPackage; } PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
44a007a3359d4bc6037712059f72d69b85724d9f
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_mpl_aux__numeric_op.hpp
cc5c173b7e23addafec78181a35caea08a80e216
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
41
hpp
#include <boost/mpl/aux_/numeric_op.hpp>
0512ffdca7ca2c4a3816b44b1f7fe5320ee0a65c
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1483488_0/C++/fz1989/2012_q_C.cpp
fd6aae460ea20c066e65f54f3edbadc5e86b634f
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; const int maxn = 2000001; int parent[maxn], rank[maxn]; int T,A,B; int digs[10]; int findset(int now) { if (parent[now] != now) { parent[now] = findset(parent[now]); } return parent[now]; } void unionset(int x ,int y){ int rx = findset(x); int ry = findset(y); if (rx == ry) return; if (rank[rx] < rank[ry]) { rank[ry] += rank[rx]; parent[rx] = ry; } else { rank[rx] += rank[ry]; parent[ry] = rx; } } int solve(int num) { int len = 0; int top = 1; int prenum = num ,sum = num; while (num) { digs[len++] = num % 10; num /= 10; if (num) top *= 10; } for (int i = 0; i < len; i++) { int nextnum = (prenum - digs[len - 1 - i] * top) * 10 + digs[len - 1 - i]; if (nextnum >= A && nextnum <= B) { unionset(sum, nextnum); } prenum = nextnum; } } int main() { freopen("test.out","w",stdout); scanf("%d",&T); for (int cas = 1; cas <= T; cas++) { scanf("%d%d",&A, &B); long long ret = 0; for (int i = A; i <= B; i++) { parent[i] = i; rank[i] = 1; } for (int i = A; i <= B; i++) { if (parent[i] == i) { solve(i); } } for (int i = A; i <= B; i++) { if (parent[i] == i && rank[i] > 1) { ret += (long long)(rank[i] - 1) * (rank[i]) / 2; } } printf("Case #%d: ", cas); cout << ret << endl; } }
a46b82342297c9db7a1ff1a18a1c1cd4d3f5278c
5bfaffd283b998ab89132f0a98879b12c29b290d
/lib/animations/graceful-enable-data.h
6f78350c19e6b8d68d93424dcbc3f1f2c4bfc5b5
[ "MIT" ]
permissive
dingjingmaster/platform-theme
a76ef4ed0a68831acf803ba070b7e37f4b909e71
ad597690284fee806cd0303c319c194711fc2551
refs/heads/main
2023-02-08T17:00:45.504743
2021-01-03T09:33:29
2021-01-03T09:33:29
320,217,306
0
0
null
null
null
null
UTF-8
C++
false
false
585
h
#ifndef GRACEFUL_ENABLE_DATA_H #define GRACEFUL_ENABLE_DATA_H #include "graceful-export.h" #include "graceful-widget-state-data.h" namespace Graceful { //* Enable data class GRACEFUL_EXPORT EnableData : public WidgetStateData { Q_OBJECT public: EnableData(QObject *parent, QWidget *target, int duration, bool state = true) : WidgetStateData(parent, target, duration, state) { target->installEventFilter(this); } //* destructor virtual ~EnableData() { } //* event filter virtual bool eventFilter(QObject *, QEvent *); }; } #endif
6282ba7a7f437dbe6f92e367b54448aefc8d956f
87d4f0499a8d792446d10753c088cb635188f47c
/PRO1/X01385_ca/S001-AC.cc
15a87e21a425c0db7155f7f645a60df494ea1f09
[]
no_license
lladruc/FIB
e08265cc6231aab8983ee0ff1343ac2266237427
da03b6aa0acce04fa61d52a51f3c7934b2d84820
refs/heads/master
2022-05-03T04:02:08.073880
2022-04-11T12:03:31
2022-04-11T12:03:31
33,666,272
0
2
null
null
null
null
UTF-8
C++
false
false
451
cc
#include <iostream> #include <vector> using namespace std; int ndiferents(const vector<int>& v){ int r=0; for(int i=0;i<v.size();++i){ bool unic = true; int j=i-1; while( j >= 0 and unic){ if(v[i] == v[j]) unic = false; --j; } if(unic) ++r; } return r; } int main(){ int n; while(cin >> n){ vector<int> v(n); while(n>0){ --n; cin >> v[n]; } cout << ndiferents(v) << endl; } }
43f2d70ae70efef3cae962ee248315f939c68de4
4bb3b35e054643be978d66f10fbaf1b1ad6d0060
/src/routines/level1/xaxpy.hpp
caac871e888d57e51546a8068b89b2423291637b
[ "Apache-2.0" ]
permissive
lijian8/CLBlast
e2b4fefa39e127529c585848702929c6e9516bb8
115af8c78ed93894b1e3021d9612df89d2cef3d4
refs/heads/master
2020-12-24T09:52:37.511421
2016-09-25T08:44:31
2016-09-25T08:44:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
hpp
// ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // This file implements the Xaxpy routine. The precision is implemented using a template argument. // // ================================================================================================= #ifndef CLBLAST_ROUTINES_XAXPY_H_ #define CLBLAST_ROUTINES_XAXPY_H_ #include "routine.hpp" namespace clblast { // ================================================================================================= // See comment at top of file for a description of the class template <typename T> class Xaxpy: public Routine { public: // Constructor Xaxpy(Queue &queue, EventPointer event, const std::string &name = "AXPY"); // Templated-precision implementation of the routine StatusCode DoAxpy(const size_t n, const T alpha, const Buffer<T> &x_buffer, const size_t x_offset, const size_t x_inc, const Buffer<T> &y_buffer, const size_t y_offset, const size_t y_inc); }; // ================================================================================================= } // namespace clblast // CLBLAST_ROUTINES_XAXPY_H_ #endif
b42329c81c0a182fb6547596090a143702f1c223
d9a972a5e0e84f08d63113df382fcf4c6a455a81
/examples/ESP32_MultiTask/AsyncMT_ESP32WM_Config/AsyncMT_ESP32WM_Config.ino
f2d405f0eca62bec2cf2df3a285c7cdc8027ab8d
[ "MIT" ]
permissive
Pongsatorn-Tot/Blynk_Async_WM
5ae3d86844648d0c02a1181c692c91c70ea2ecb0
4180d269d21792f2d403577dbcc286a38b50e85b
refs/heads/master
2023-02-09T02:24:21.616370
2021-01-02T08:44:14
2021-01-02T08:44:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,330
ino
/**************************************************************************************************************************** Async_ESP32WM_Config.ino For ESP32 boards Blynk_Async_WM is a library, using AsyncWebServer instead of (ESP8266)WebServer for the ESP8266/ESP32 to enable easy configuration/reconfiguration and autoconnect/autoreconnect of WiFi/Blynk. Based on and modified from Blynk library v0.6.1 (https://github.com/blynkkk/blynk-library/releases) Built by Khoi Hoang (https://github.com/khoih-prog/Blynk_Async_WM) Licensed under MIT license Version: 1.2.0 Version Modified By Date Comments ------- ----------- ---------- ----------- 1.0.16 K Hoang 25/08/2020 Initial coding to use (ESP)AsyncWebServer instead of (ESP8266)WebServer. Bump up to v1.0.16 to sync with Blynk_WM v1.0.16 1.1.0 K Hoang 26/11/2020 Add examples using RTOS MultiTask to avoid blocking in operation. 1.2.0 K Hoang 01/01/2021 Add support to ESP32 LittleFS. Remove possible compiler warnings. Update examples. Add MRD ********************************************************************************************************************************/ #include "defines.h" #include <Ticker.h> #include <DHT.h> DHT dht(DHT_PIN, DHT_TYPE); #define DHT11_DEBUG 1 Ticker led_ticker; volatile bool blynkConnected = false; #if USE_DYNAMIC_PARAMETERS void displayCredentials(void) { Serial.println("\nYour stored Credentials :"); for (int i = 0; i < NUM_MENU_ITEMS; i++) { Serial.println(String(myMenuItems[i].displayName) + " = " + myMenuItems[i].pdata); } } void checkAndDisplayCredentials(void) { static bool displayedCredentials = false; if (!displayedCredentials) { for (int i = 0; i < NUM_MENU_ITEMS; i++) { if (!strlen(myMenuItems[i].pdata)) { break; } if ( i == (NUM_MENU_ITEMS - 1) ) { displayedCredentials = true; displayCredentials(); } } } } #endif void readAndSendData() { float temperature = dht.readTemperature(); float humidity = dht.readHumidity(); if (!isnan(temperature) && !isnan(humidity)) { #if (DHT11_DEBUG > 0) Serial.println("Temp *C: " + String(temperature)); Serial.println("Humid %: " + String(humidity)); #endif if (blynkConnected) { Blynk.virtualWrite(V17, String(temperature, 1)); Blynk.virtualWrite(V18, String(humidity, 1)); } } else { #if (DHT11_DEBUG > 1) Serial.println(F("\nTemp *C: Error")); Serial.println(F("Humid %: Error")); #endif if (blynkConnected) { Blynk.virtualWrite(V17, "NAN"); Blynk.virtualWrite(V18, "NAN"); } } Serial.print("R"); } void set_led(byte status) { digitalWrite(LED_BUILTIN, status); } void checkBlynk(void) { static int num = 1; if (blynkConnected) { set_led(HIGH); led_ticker.once_ms(111, set_led, (byte) LOW); Serial.print(F("B")); } else { Serial.print(F("F")); } if (num == 80) { Serial.println(); num = 1; } else if (num++ % 10 == 0) { Serial.print(F(" ")); } } ////////////////// Start Free-RTOS related code ////////////////// void SensorReadEveryNSec( void * pvParameters ) { #define SENSOR_READ_INTERVAL_MS 10000L for (;;) { readAndSendData(); vTaskDelay(SENSOR_READ_INTERVAL_MS / portTICK_PERIOD_MS); } } void InternetBlynkStatus( void * pvParameters ) { // Check Internet connection every PING_INTERVAL_MS if already Online #define CHECK_BLYNK_INTERVAL_MS 10000L for (;;) { checkBlynk(); vTaskDelay(CHECK_BLYNK_INTERVAL_MS / portTICK_PERIOD_MS); } } void BlynkRun( void * pvParameters ) { #define BLYNK_RUN_INTERVAL_MS 250L for (;;) { Blynk.run(); #if USE_DYNAMIC_PARAMETERS checkAndDisplayCredentials(); #endif vTaskDelay(BLYNK_RUN_INTERVAL_MS / portTICK_PERIOD_MS); } } void BlynkCheck( void * pvParameters ) { #define BLYNK_CHECK_INTERVAL_MS 5000L bool wifiConnected = false; for (;;) { wifiConnected = (WiFi.status() == WL_CONNECTED); if ( wifiConnected && Blynk.connected() ) { blynkConnected = true; } else { blynkConnected = false; if (wifiConnected) Serial.println(F("\nBlynk Disconnected")); else Serial.println(F("\nWiFi Disconnected")); } vTaskDelay(BLYNK_CHECK_INTERVAL_MS / portTICK_PERIOD_MS); } } /////////// Set Core and Priority. Be careful here /////////// #define USING_CORE_1 0 #define USING_CORE_2 1 //Low priority numbers denote low priority tasks. The idle task has priority 0 (tskIDLE_PRIORITY). //MAX_PRIORITIES = 25 => Can use priority from 0-24 #define SensorReadEveryNSec_Priority ( 4 | portPRIVILEGE_BIT ) #define InternetBlynkStatus_Priority ( 3 | portPRIVILEGE_BIT ) // Don't use BlynkRun_Priority too low, can drop Blynk connection, especially in SSL #define BlynkRun_Priority ( 15 | portPRIVILEGE_BIT ) #define BlynkCheck_Priority ( BlynkRun_Priority ) ////////////////// End Free-RTOS related code ////////////////// void setup() { pinMode(LED_BUILTIN, OUTPUT); // Debug console Serial.begin(115200); while (!Serial); delay(200); #if ( USE_LITTLEFS || USE_SPIFFS) Serial.print(F("\nStarting Async_ESP32_WM_Config using ")); Serial.print(CurrentFileFS); #else Serial.print(F("\nStarting Async_ESP32_WM_Config using EEPROM")); #endif #if USE_SSL Serial.print(F(" with SSL on ")); Serial.println(ARDUINO_BOARD); #else Serial.print(F(" without SSL on ")); Serial.println(ARDUINO_BOARD); #endif #if USE_BLYNK_WM Serial.println(BLYNK_ASYNC_WM_VERSION); Serial.println(ESP_DOUBLE_RESET_DETECTOR_VERSION); #endif dht.begin(); // Set config portal SSID and Password Blynk.setConfigPortal("TestPortal-ESP32", "TestPortalPass"); // Set config portal IP address Blynk.setConfigPortalIP(IPAddress(192, 168, 220, 1)); // Set config portal channel, default = 1. Use 0 => random channel from 1-13 to avoid conflict Blynk.setConfigPortalChannel(0); // From v1.0.5, select either one of these to set static IP + DNS Blynk.setSTAStaticIPConfig(IPAddress(192, 168, 2, 230), IPAddress(192, 168, 2, 1), IPAddress(255, 255, 255, 0)); //Blynk.setSTAStaticIPConfig(IPAddress(192, 168, 2, 220), IPAddress(192, 168, 2, 1), IPAddress(255, 255, 255, 0), // IPAddress(192, 168, 2, 1), IPAddress(8, 8, 8, 8)); //Blynk.setSTAStaticIPConfig(IPAddress(192, 168, 2, 220), IPAddress(192, 168, 2, 1), IPAddress(255, 255, 255, 0), // IPAddress(4, 4, 4, 4), IPAddress(8, 8, 8, 8)); // Use this to default DHCP hostname to ESP8266-XXXXXX or ESP32-XXXXXX //Blynk.begin(); // Use this to personalize DHCP hostname (RFC952 conformed) // 24 chars max,- only a..z A..Z 0..9 '-' and no '-' as last char //Blynk.begin("ESP32-WM-Config"); Blynk.begin(HOST_NAME); if (Blynk.connected()) { #if ( USE_LITTLEFS || USE_SPIFFS) Serial.print(F("\nBlynk ESP32 using ")); Serial.print(CurrentFileFS); Serial.println(F(" connected.")); #else Serial.println(F("\nBlynk ESP32 using EEPROM connected.")); Serial.printf("EEPROM size = %d bytes, EEPROM start address = %d / 0x%X\n", EEPROM_SIZE, EEPROM_START, EEPROM_START); #endif Serial.print(F("Board Name : ")); Serial.println(Blynk.getBoardName()); } ////////////////// Tasks creation ////////////////// #if (BLYNK_WM_RTOS_DEBUG > 0) Serial.println(F("*********************************************************")); Serial.printf("configUSE_PORT_OPTIMISED_TASK_SELECTION = %s\n", configUSE_PORT_OPTIMISED_TASK_SELECTION ? "true" : "false"); Serial.printf("configUSE_TIME_SLICING = %s\n", configUSE_TIME_SLICING ? "true" : "false"); Serial.printf("configMAX_PRIORITIES = %d, portPRIVILEGE_BIT = %d\n", configMAX_PRIORITIES, portPRIVILEGE_BIT); Serial.printf("Task Priority : InternetBlynkStatus = %d, BlynkRun = %d\n", InternetBlynkStatus_Priority, BlynkRun_Priority); Serial.printf("Task Priority : SensorReadEveryNSec = %d, BlynkCheck = %d\n", SensorReadEveryNSec_Priority, BlynkCheck_Priority); Serial.println(F("*********************************************************")); #endif // RTOS function prototype //BaseType_t xTaskCreatePinnedToCore(TaskFunction_t pvTaskCode, const char *constpcName, const uint32_t STACK_SIZE, // void *constpvParameters, UBaseType_t IDLE_PRIORITY, TaskHandle_t *constpvCreatedTask, const BaseType_t xCoreID) xTaskCreatePinnedToCore( BlynkRun, "BlynkRun", 50000, NULL, BlynkRun_Priority, NULL, USING_CORE_2); xTaskCreatePinnedToCore( BlynkCheck, "BlynkCheck", 5000, NULL, BlynkCheck_Priority, NULL, USING_CORE_2); xTaskCreatePinnedToCore( SensorReadEveryNSec, "SensorReadEveryNSec", 20000, NULL, SensorReadEveryNSec_Priority, NULL, USING_CORE_2); xTaskCreatePinnedToCore( InternetBlynkStatus, "InternetBlynkStatus", 5000, NULL, InternetBlynkStatus_Priority, NULL, USING_CORE_2); ////////////////// End Tasks creation ////////////////// } void loop() { // No more Blynk.run() and timer.run() here. All is tasks }
67fad154615cc1911e27dc506f3c1b8d483ab21d
207c6d618e70a7249f911cd43a58a5459afd9f96
/MyLogging/ThreadLoggerStream.cpp
8a034c70b95e2d843e0e2f08cd9533419dfb76ed
[]
no_license
dickyPro/MLogger
b9466c7d63c21f0bfe5c6fde482fd2692d366878
44745745fd8526605d52ccacb25c31d214623c9e
refs/heads/master
2021-07-25T02:51:49.673213
2017-11-06T14:29:34
2017-11-06T14:29:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
684
cpp
#include "ThreadLoggerStream.h" #include "LogItemQueue.h" #include "LogItem.h" using namespace logging; using namespace std; namespace logging { ThreadLoggerStream::ThreadLoggerStream(Priority pri): LoggerStream(pri),_isSubmitted(false) { } //当流结束之时,则将内容压缩到安全队列 ThreadLoggerStream::~ThreadLoggerStream() { Submit(); } void ThreadLoggerStream::Output(const string& message) { _buffer+=message; } //判断是否已经提交到任务队列中 void ThreadLoggerStream::Submit() { if(!_isSubmitted) { LogItem logItem(GetPriority(),_buffer); LogItemQueue::GetInstance().Push(logItem); _isSubmitted=true; } } }
4e2a5073f8d139f910a21fe56f931549d0a7ba40
23d01d942c97a31e46529c4371e98aa0c757ecd1
/hll/legion-realm/patch/runtime/legion/legion_types.h
6728c3cb871cab1e00fb89768142e272eb763e6c
[]
no_license
ModeladoFoundation/ocr-apps
f538bc31282f56d43a952610a8f4ec6bacd88e67
c0179d63574e7bb01f940aceaa7fe1c85fea5902
refs/heads/master
2021-09-02T23:41:54.190248
2017-08-30T01:48:39
2017-08-30T01:49:30
116,198,341
1
0
null
null
null
null
UTF-8
C++
false
false
76,605
h
/* Copyright 2017 Stanford University, NVIDIA Corporation * Portions Copyright 2017 Rice University, 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. */ #ifndef __LEGION_TYPES_H__ #define __LEGION_TYPES_H__ /** * \file legion_types.h */ #include <cstdio> #include <cstdlib> #include <cassert> #include <cstring> #include <stdint.h> #include "limits.h" #include <map> #include <set> #include <list> #include <deque> #include <vector> #include "legion_config.h" #include "legion_template_help.h" // Make sure we have the appropriate defines in place for including realm #define REALM_USE_LEGION_LAYOUT_CONSTRAINTS #include "realm.h" namespace BindingLib { class Utility; } // BindingLib namespace namespace Legion { typedef ::legion_error_t LegionErrorType; typedef ::legion_privilege_mode_t PrivilegeMode; typedef ::legion_allocate_mode_t AllocateMode; typedef ::legion_coherence_property_t CoherenceProperty; typedef ::legion_region_flags_t RegionFlags; typedef ::legion_projection_type_t ProjectionType; typedef ::legion_partition_kind_t PartitionKind; typedef ::legion_external_resource_t ExternalResource; typedef ::legion_timing_measurement_t TimingMeasurement; typedef ::legion_dependence_type_t DependenceType; typedef ::legion_index_space_kind_t IndexSpaceKind; typedef ::legion_file_mode_t LegionFileMode; typedef ::legion_execution_constraint_t ExecutionConstraintKind; typedef ::legion_layout_constraint_t LayoutConstraintKind; typedef ::legion_equality_kind_t EqualityKind; typedef ::legion_dimension_kind_t DimensionKind; typedef ::legion_isa_kind_t ISAKind; typedef ::legion_resource_constraint_t ResourceKind; typedef ::legion_launch_constraint_t LaunchKind; typedef ::legion_specialized_constraint_t SpecializedKind; // Forward declarations for user level objects // legion.h class IndexSpace; class IndexPartition; class FieldSpace; class LogicalRegion; class LogicalPartition; class IndexAllocator; class FieldAllocator; class TaskArgument; class ArgumentMap; class Lock; struct LockRequest; class Grant; class PhaseBarrier; struct RegionRequirement; struct IndexSpaceRequirement; struct FieldSpaceRequirement; struct TaskLauncher; struct IndexTaskLauncher; typedef IndexTaskLauncher IndexLauncher; // for backwards compatibility struct InlineLauncher; struct CopyLauncher; struct AcquireLauncher; struct ReleaseLauncher; struct FillLauncher; struct LayoutConstraintRegistrar; struct TaskVariantRegistrar; struct TaskGeneratorArguments; class Future; class FutureMap; class Predicate; class PhysicalRegion; class IndexIterator; template<typename T> struct ColoredPoints; struct InputArgs; class ProjectionFunctor; class Task; class Copy; class InlineMapping; class Acquire; class Release; class Close; class Fill; class Runtime; class MPILegionHandshake; // For backwards compatibility typedef Runtime HighLevelRuntime; // Helper for saving instantiated template functions struct SerdezRedopFns; // Forward declarations for compiler level objects // legion.h class ColoringSerializer; class DomainColoringSerializer; // Forward declarations for wrapper tasks // legion.h class LegionTaskWrapper; class LegionSerialization; // Forward declarations for C wrapper objects // legion_c_util.h class TaskResult; class CObjectWrapper; // legion_utilities.h struct RegionUsage; class AutoLock; class ImmovableAutoLock; class ColorPoint; class Serializer; class Deserializer; class LgEvent; // base event type for legion class ApEvent; // application event class ApUserEvent; // application user event class ApBarrier; // application barrier class RtEvent; // runtime event class RtUserEvent; // runtime user event class RtBarrier; template<typename T> class Fraction; template<typename T, unsigned int MAX, unsigned SHIFT, unsigned MASK> class BitMask; template<typename T, unsigned int MAX, unsigned SHIFT, unsigned MASK> class TLBitMask; #ifdef __SSE2__ template<unsigned int MAX> class SSEBitMask; template<unsigned int MAX> class SSETLBitMask; #endif #ifdef __AVX__ template<unsigned int MAX> class AVXBitMask; template<unsigned int MAX> class AVXTLBitMask; #endif template<typename T, unsigned LOG2MAX> class BitPermutation; template<typename IT, typename DT, bool BIDIR = false> class IntegerSet; // legion_constraint.h class ISAConstraint; class ProcessorConstraint; class ResourceConstraint; class LaunchConstraint; class ColocationConstraint; class ExecutionConstraintSet; class SpecializedConstraint; class MemoryConstraint; class FieldConstraint; class OrderingConstraint; class SplittingConstraint; class DimensionConstraint; class AlignmentConstraint; class OffsetConstraint; class PointerConstraint; class LayoutConstraintSet; class TaskLayoutConstraintSet; namespace Mapping { class PhysicalInstance; class MapperEvent; class ProfilingRequestSet; class Mapper; class MapperRuntime; class DefaultMapper; class ShimMapper; class TestMapper; class DebugMapper; class ReplayMapper; // The following types are effectively overlaid on the Realm versions // to allow for Legion-specific profiling measurements enum ProfilingMeasurementID { PMID_LEGION_FIRST = Realm::PMID_REALM_LAST, PMID_RUNTIME_OVERHEAD, }; }; namespace Internal { enum OpenState { NOT_OPEN = 0, OPEN_READ_ONLY = 1, OPEN_READ_WRITE = 2, // unknown dirty information below OPEN_SINGLE_REDUCE = 3, // only one open child with reductions below OPEN_MULTI_REDUCE = 4, // multiple open children with same reduction // Only projection states below here OPEN_READ_ONLY_PROJ = 5, // read-only projection OPEN_READ_WRITE_PROJ = 6, // read-write projection OPEN_READ_WRITE_PROJ_DISJOINT_SHALLOW = 7, // depth=0, children disjoint OPEN_REDUCE_PROJ = 8, // reduction-only projection OPEN_REDUCE_PROJ_DIRTY = 9, // same as above but already open dirty }; // redop IDs - none used in HLR right now, but 0 isn't allowed enum { REDOP_ID_AVAILABLE = 1, }; // Runtime task numbering enum { INIT_TASK_ID = Realm::Processor::TASK_ID_PROCESSOR_INIT, SHUTDOWN_TASK_ID = Realm::Processor::TASK_ID_PROCESSOR_SHUTDOWN, LG_TASK_ID = Realm::Processor::TASK_ID_FIRST_AVAILABLE, LG_LEGION_PROFILING_ID = Realm::Processor::TASK_ID_FIRST_AVAILABLE+1, LG_MAPPER_PROFILING_ID = Realm::Processor::TASK_ID_FIRST_AVAILABLE+2, LG_LAUNCH_TOP_LEVEL_ID = Realm::Processor::TASK_ID_FIRST_AVAILABLE+3, LG_MPI_INTEROP_ID = Realm::Processor::TASK_ID_FIRST_AVAILABLE+4, LG_MPI_SYNC_ID = Realm::Processor::TASK_ID_FIRST_AVAILABLE+5, TASK_ID_AVAILABLE = Realm::Processor::TASK_ID_FIRST_AVAILABLE+6, }; // Enumeration of Legion runtime tasks enum LgTaskID { LG_SCHEDULER_ID, LG_POST_END_ID, LG_DEFERRED_READY_TRIGGER_ID, LG_DEFERRED_EXECUTION_TRIGGER_ID, LG_DEFERRED_RESOLUTION_TRIGGER_ID, LG_DEFERRED_COMMIT_TRIGGER_ID, LG_DEFERRED_POST_MAPPED_ID, LG_DEFERRED_EXECUTE_ID, LG_DEFERRED_COMPLETE_ID, LG_DEFERRED_COMMIT_ID, LG_RECLAIM_LOCAL_FIELD_ID, LG_DEFERRED_COLLECT_ID, LG_PRE_PIPELINE_ID, LG_TRIGGER_DEPENDENCE_ID, LG_TRIGGER_COMPLETE_ID, LG_TRIGGER_OP_ID, LG_TRIGGER_TASK_ID, LG_DEFERRED_RECYCLE_ID, LG_DEFERRED_SLICE_ID, LG_MUST_INDIV_ID, LG_MUST_INDEX_ID, LG_MUST_MAP_ID, LG_MUST_DIST_ID, LG_MUST_LAUNCH_ID, LG_DEFERRED_FUTURE_SET_ID, LG_DEFERRED_FUTURE_MAP_SET_ID, LG_RESOLVE_FUTURE_PRED_ID, LG_CONTRIBUTE_COLLECTIVE_ID, LG_TOP_FINISH_TASK_ID, LG_MAPPER_TASK_ID, LG_DISJOINTNESS_TASK_ID, LG_PART_INDEPENDENCE_TASK_ID, LG_SPACE_INDEPENDENCE_TASK_ID, LG_PENDING_CHILD_TASK_ID, LG_DECREMENT_PENDING_TASK_ID, LG_SEND_VERSION_STATE_UPDATE_TASK_ID, LG_UPDATE_VERSION_STATE_REDUCE_TASK_ID, LG_ADD_TO_DEP_QUEUE_TASK_ID, LG_WINDOW_WAIT_TASK_ID, LG_ISSUE_FRAME_TASK_ID, LG_CONTINUATION_TASK_ID, LG_MAPPER_CONTINUATION_TASK_ID, LG_FINISH_MAPPER_CONTINUATION_TASK_ID, LG_TASK_IMPL_SEMANTIC_INFO_REQ_TASK_ID, LG_INDEX_SPACE_SEMANTIC_INFO_REQ_TASK_ID, LG_INDEX_PART_SEMANTIC_INFO_REQ_TASK_ID, LG_FIELD_SPACE_SEMANTIC_INFO_REQ_TASK_ID, LG_FIELD_SEMANTIC_INFO_REQ_TASK_ID, LG_REGION_SEMANTIC_INFO_REQ_TASK_ID, LG_PARTITION_SEMANTIC_INFO_REQ_TASK_ID, LG_SELECT_TUNABLE_TASK_ID, LG_DEFERRED_ENQUEUE_OP_ID, LG_DEFERRED_ENQUEUE_TASK_ID, LG_DEFER_MAPPER_MESSAGE_TASK_ID, LG_DEFER_COMPOSITE_VIEW_REF_TASK_ID, LG_DEFER_COMPOSITE_VIEW_REGISTRATION_TASK_ID, LG_DEFER_COMPOSITE_NODE_REF_TASK_ID, LG_DEFER_COMPOSITE_NODE_CAPTURE_TASK_ID, LG_CONVERT_VIEW_TASK_ID, LG_UPDATE_VIEW_REFERENCES_TASK_ID, LG_REMOVE_VERSION_STATE_REF_TASK_ID, LG_DEFER_RESTRICTED_MANAGER_TASK_ID, LG_REMOTE_VIEW_CREATION_TASK_ID, LG_DEFER_DISTRIBUTE_TASK_ID, LG_DEFER_PERFORM_MAPPING_TASK_ID, LG_DEFER_LAUNCH_TASK_ID, LG_DEFER_MAP_AND_LAUNCH_TASK_ID, LG_ADD_VERSIONING_SET_REF_TASK_ID, LG_VERSION_STATE_CAPTURE_DIRTY_TASK_ID, LG_DISJOINT_CLOSE_TASK_ID, LG_DEFER_MATERIALIZED_VIEW_TASK_ID, LG_MISSPECULATE_TASK_ID, LG_DEFER_PHI_VIEW_REF_TASK_ID, LG_DEFER_PHI_VIEW_REGISTRATION_TASK_ID, LG_MESSAGE_ID, // These two must be the last two LG_RETRY_SHUTDOWN_TASK_ID, LG_LAST_TASK_ID, // This one should always be last }; /** * \class LgTaskArgs * The base class for all Legion Task arguments */ template<typename T> struct LgTaskArgs { public: LgTaskArgs(void) : lg_task_id(T::TASK_ID) { } public: const LgTaskID lg_task_id; }; // Make this a macro so we can keep it close to // declaration of the task IDs themselves #define LG_TASK_DESCRIPTIONS(name) \ const char *name[LG_LAST_TASK_ID] = { \ "Scheduler", \ "Post-Task Execution", \ "Deferred Ready Trigger", \ "Deferred Execution Trigger", \ "Deferred Resolution Trigger", \ "Deferred Commit Trigger", \ "Deferred Post Mapped", \ "Deferred Execute", \ "Deferred Complete", \ "Deferred Commit", \ "Reclaim Local Field", \ "Garbage Collection", \ "Prepipeline Stage", \ "Logical Dependence Analysis", \ "Trigger Complete", \ "Operation Physical Dependence Analysis", \ "Task Physical Dependence Analysis", \ "Deferred Recycle", \ "Deferred Slice", \ "Must Individual Task Dependence Analysis", \ "Must Index Task Dependence Analysis", \ "Must Task Physical Dependence Analysis", \ "Must Task Distribution", \ "Must Task Launch", \ "Deferred Future Set", \ "Deferred Future Map Set", \ "Resolve Future Predicate", \ "Contribute Collective", \ "Top Finish", \ "Mapper Task", \ "Disjointness Test", \ "Partition Independence Test", \ "Index Space Independence Test", \ "Remove Pending Child", \ "Decrement Pending Task", \ "Send Version State Update", \ "Update Version State Reduce", \ "Add to Dependence Queue", \ "Window Wait", \ "Issue Frame", \ "Legion Continuation", \ "Mapper Continuation", \ "Finish Mapper Continuation", \ "Task Impl Semantic Request", \ "Index Space Semantic Request", \ "Index Partition Semantic Request", \ "Field Space Semantic Request", \ "Field Semantic Request", \ "Region Semantic Request", \ "Partition Semantic Request", \ "Select Tunable", \ "Deferred Enqueue Op", \ "Deferred Enqueue Task", \ "Deferred Mapper Message", \ "Deferred Composite View Ref", \ "Deferred Composite View Registration", \ "Deferred Composite Node Ref", \ "Deferred Composite Node Capture", \ "Convert View for Version State", \ "Update View References for Version State", \ "Deferred Remove Version State Valid Ref", \ "Deferred Restricted Manager GC Ref", \ "Remote View Creation", \ "Defer Task Distribution", \ "Defer Task Perform Mapping", \ "Defer Task Launch", \ "Defer Task Map and Launch", \ "Defer Versioning Set Reference", \ "Version State Capture Dirty", \ "Disjoint Close", \ "Defer Materialized View Creation", \ "Handle Mapping Misspeculation", \ "Defer Phi View Reference", \ "Defer Phi View Registration", \ "Remote Message", \ "Retry Shutdown", \ }; enum MappingCallKind { GET_MAPPER_NAME_CALL, GET_MAPER_SYNC_MODEL_CALL, SELECT_TASK_OPTIONS_CALL, PREMAP_TASK_CALL, SLICE_TASK_CALL, MAP_TASK_CALL, SELECT_VARIANT_CALL, POSTMAP_TASK_CALL, TASK_SELECT_SOURCES_CALL, TASK_CREATE_TEMPORARY_CALL, TASK_SPECULATE_CALL, TASK_REPORT_PROFILING_CALL, MAP_INLINE_CALL, INLINE_SELECT_SOURCES_CALL, INLINE_CREATE_TEMPORARY_CALL, INLINE_REPORT_PROFILING_CALL, MAP_COPY_CALL, COPY_SELECT_SOURCES_CALL, COPY_CREATE_TEMPORARY_CALL, COPY_SPECULATE_CALL, COPY_REPORT_PROFILING_CALL, MAP_CLOSE_CALL, CLOSE_SELECT_SOURCES_CALL, CLOSE_CREATE_TEMPORARY_CALL, CLOSE_REPORT_PROFILING_CALL, MAP_ACQUIRE_CALL, ACQUIRE_SPECULATE_CALL, ACQUIRE_REPORT_PROFILING_CALL, MAP_RELEASE_CALL, RELEASE_SELECT_SOURCES_CALL, RELEASE_CREATE_TEMPORARY_CALL, RELEASE_SPECULATE_CALL, RELEASE_REPORT_PROFILING_CALL, CONFIGURE_CONTEXT_CALL, SELECT_TUNABLE_VALUE_CALL, MAP_MUST_EPOCH_CALL, MAP_DATAFLOW_GRAPH_CALL, SELECT_TASKS_TO_MAP_CALL, SELECT_STEAL_TARGETS_CALL, PERMIT_STEAL_REQUEST_CALL, HANDLE_MESSAGE_CALL, HANDLE_TASK_RESULT_CALL, LAST_MAPPER_CALL, }; #define MAPPER_CALL_NAMES(name) \ const char *name[LAST_MAPPER_CALL] = { \ "get_mapper_name", \ "get_mapper_sync_model", \ "select_task_options", \ "premap_task", \ "slice_task", \ "map_task", \ "select_task_variant", \ "postmap_task", \ "select_task_sources", \ "create task temporary", \ "speculate (for task)", \ "report profiling (for task)", \ "map_inline", \ "select_inline_sources", \ "inline create temporary", \ "report profiling (for inline)", \ "map_copy", \ "select_copy_sources", \ "copy create temporary", \ "speculate (for copy)", \ "report_profiling (for copy)", \ "map_close", \ "select_close_sources", \ "close create temporary", \ "report_profiling (for close)", \ "map_acquire", \ "speculate (for acquire)", \ "report_profiling (for acquire)", \ "map_release", \ "select_release_sources", \ "release create temporary", \ "speculate (for release)", \ "report_profiling (for release)", \ "configure_context", \ "select_tunable_value", \ "map_must_epoch", \ "map_dataflow_graph", \ "select_tasks_to_map", \ "select_steal_targets", \ "permit_steal_request", \ "handle_message", \ "handle_task_result", \ } // Methodology for assigning priorities to meta-tasks // The lowest priority is for the heavy lifting meta // tasks, so they go through the queue at low priority. // The deferred-throughput priority is for tasks that // have already gone through the queue once with // throughput priority, but had to be deferred for // some reason and therefore shouldn't get stuck at // the back of the throughput queue again. Latency // priority is for very small tasks which take a // minimal amount of time to perform and therefore // shouldn't get stuck behind the heavy meta-tasks. // Resource priority means that this task holds a // Realm resource (e.g. reservation) and therefore // shouldn't be stuck behind anything. enum LgPriority { LG_THROUGHPUT_PRIORITY = 0, LG_DEFERRED_THROUGHPUT_PRIORITY = 1, LG_LATENCY_PRIORITY = 2, LG_RESOURCE_PRIORITY = 3, }; enum VirtualChannelKind { DEFAULT_VIRTUAL_CHANNEL = 0, INDEX_SPACE_VIRTUAL_CHANNEL = 1, FIELD_SPACE_VIRTUAL_CHANNEL = 2, LOGICAL_TREE_VIRTUAL_CHANNEL = 3, MAPPER_VIRTUAL_CHANNEL = 4, SEMANTIC_INFO_VIRTUAL_CHANNEL = 5, LAYOUT_CONSTRAINT_VIRTUAL_CHANNEL = 6, CONTEXT_VIRTUAL_CHANNEL = 7, MANAGER_VIRTUAL_CHANNEL = 8, VIEW_VIRTUAL_CHANNEL = 9, UPDATE_VIRTUAL_CHANNEL = 10, VARIANT_VIRTUAL_CHANNEL = 11, VERSION_VIRTUAL_CHANNEL = 12, VERSION_MANAGER_VIRTUAL_CHANNEL = 13, ANALYSIS_VIRTUAL_CHANNEL = 14, MAX_NUM_VIRTUAL_CHANNELS = 15, // this one must be last }; enum MessageKind { TASK_MESSAGE, STEAL_MESSAGE, ADVERTISEMENT_MESSAGE, SEND_INDEX_SPACE_NODE, SEND_INDEX_SPACE_REQUEST, SEND_INDEX_SPACE_RETURN, SEND_INDEX_SPACE_CHILD_REQUEST, SEND_INDEX_SPACE_CHILD_RESPONSE, SEND_INDEX_SPACE_COLORS_REQUEST, SEND_INDEX_SPACE_COLORS_RESPONSE, SEND_INDEX_PARTITION_NOTIFICATION, SEND_INDEX_PARTITION_NODE, SEND_INDEX_PARTITION_REQUEST, SEND_INDEX_PARTITION_RETURN, SEND_INDEX_PARTITION_CHILD_REQUEST, SEND_INDEX_PARTITION_CHILD_RESPONSE, SEND_INDEX_PARTITION_CHILDREN_REQUEST, SEND_INDEX_PARTITION_CHILDREN_RESPONSE, SEND_FIELD_SPACE_NODE, SEND_FIELD_SPACE_REQUEST, SEND_FIELD_SPACE_RETURN, SEND_FIELD_ALLOC_REQUEST, SEND_FIELD_ALLOC_NOTIFICATION, SEND_FIELD_SPACE_TOP_ALLOC, SEND_FIELD_FREE, SEND_TOP_LEVEL_REGION_REQUEST, SEND_TOP_LEVEL_REGION_RETURN, SEND_LOGICAL_REGION_NODE, INDEX_SPACE_DESTRUCTION_MESSAGE, INDEX_PARTITION_DESTRUCTION_MESSAGE, FIELD_SPACE_DESTRUCTION_MESSAGE, LOGICAL_REGION_DESTRUCTION_MESSAGE, LOGICAL_PARTITION_DESTRUCTION_MESSAGE, INDIVIDUAL_REMOTE_MAPPED, INDIVIDUAL_REMOTE_COMPLETE, INDIVIDUAL_REMOTE_COMMIT, SLICE_REMOTE_MAPPED, SLICE_REMOTE_COMPLETE, SLICE_REMOTE_COMMIT, DISTRIBUTED_REMOTE_REGISTRATION, DISTRIBUTED_VALID_UPDATE, DISTRIBUTED_GC_UPDATE, DISTRIBUTED_RESOURCE_UPDATE, DISTRIBUTED_CREATE_ADD, DISTRIBUTED_CREATE_REMOVE, DISTRIBUTED_UNREGISTER, SEND_ATOMIC_RESERVATION_REQUEST, SEND_ATOMIC_RESERVATION_RESPONSE, SEND_BACK_LOGICAL_STATE, SEND_MATERIALIZED_VIEW, SEND_COMPOSITE_VIEW, SEND_FILL_VIEW, SEND_PHI_VIEW, SEND_REDUCTION_VIEW, SEND_INSTANCE_MANAGER, SEND_REDUCTION_MANAGER, SEND_CREATE_TOP_VIEW_REQUEST, SEND_CREATE_TOP_VIEW_RESPONSE, SEND_SUBVIEW_DID_REQUEST, SEND_SUBVIEW_DID_RESPONSE, SEND_VIEW_REQUEST, SEND_VIEW_UPDATE_REQUEST, SEND_VIEW_UPDATE_RESPONSE, SEND_VIEW_REMOTE_UPDATE, SEND_VIEW_REMOTE_INVALIDATE, SEND_MANAGER_REQUEST, SEND_FUTURE_RESULT, SEND_FUTURE_SUBSCRIPTION, SEND_MAPPER_MESSAGE, SEND_MAPPER_BROADCAST, SEND_TASK_IMPL_SEMANTIC_REQ, SEND_INDEX_SPACE_SEMANTIC_REQ, SEND_INDEX_PARTITION_SEMANTIC_REQ, SEND_FIELD_SPACE_SEMANTIC_REQ, SEND_FIELD_SEMANTIC_REQ, SEND_LOGICAL_REGION_SEMANTIC_REQ, SEND_LOGICAL_PARTITION_SEMANTIC_REQ, SEND_TASK_IMPL_SEMANTIC_INFO, SEND_INDEX_SPACE_SEMANTIC_INFO, SEND_INDEX_PARTITION_SEMANTIC_INFO, SEND_FIELD_SPACE_SEMANTIC_INFO, SEND_FIELD_SEMANTIC_INFO, SEND_LOGICAL_REGION_SEMANTIC_INFO, SEND_LOGICAL_PARTITION_SEMANTIC_INFO, SEND_REMOTE_CONTEXT_REQUEST, SEND_REMOTE_CONTEXT_RESPONSE, SEND_REMOTE_CONTEXT_FREE, SEND_VERSION_OWNER_REQUEST, SEND_VERSION_OWNER_RESPONSE, SEND_VERSION_STATE_REQUEST, SEND_VERSION_STATE_RESPONSE, SEND_VERSION_STATE_UPDATE_REQUEST, SEND_VERSION_STATE_UPDATE_RESPONSE, SEND_VERSION_STATE_VALID_NOTIFICATION, SEND_VERSION_MANAGER_ADVANCE, SEND_VERSION_MANAGER_INVALIDATE, SEND_VERSION_MANAGER_REQUEST, SEND_VERSION_MANAGER_RESPONSE, SEND_INSTANCE_REQUEST, SEND_INSTANCE_RESPONSE, SEND_GC_PRIORITY_UPDATE, SEND_NEVER_GC_RESPONSE, SEND_ACQUIRE_REQUEST, SEND_ACQUIRE_RESPONSE, SEND_VARIANT_REQUEST, SEND_VARIANT_RESPONSE, SEND_VARIANT_BROADCAST, SEND_CONSTRAINT_REQUEST, SEND_CONSTRAINT_RESPONSE, SEND_CONSTRAINT_RELEASE, SEND_CONSTRAINT_REMOVAL, SEND_TOP_LEVEL_TASK_REQUEST, SEND_TOP_LEVEL_TASK_COMPLETE, SEND_MPI_RANK_EXCHANGE, SEND_SHUTDOWN_NOTIFICATION, SEND_SHUTDOWN_RESPONSE, LAST_SEND_KIND, // This one must be last }; #define LG_MESSAGE_DESCRIPTIONS(name) \ const char *name[LAST_SEND_KIND] = { \ "Task Message", \ "Steal Message", \ "Advertisement Message", \ "Send Index Space Node", \ "Send Index Space Request", \ "Send Index Space Return", \ "Send Index Space Child Request", \ "Send Index Space Child Response", \ "Send Index Space Colors Request", \ "Send Index Space Colors Response", \ "Send Index Partition Notification", \ "Send Index Partition Node", \ "Send Index Partition Request", \ "Send Index Partition Return", \ "Send Index Partition Child Request", \ "Send Index Partition Child Response", \ "Send Index Partition Children Request", \ "Send Index Partition Children Response", \ "Send Field Space Node", \ "Send Field Space Request", \ "Send Field Space Return", \ "Send Field Alloc Request", \ "Send Field Alloc Notification", \ "Send Field Space Top Alloc", \ "Send Field Free", \ "Send Top Level Region Request", \ "Send Top Level Region Return", \ "Send Logical Region Node", \ "Index Space Destruction", \ "Index Partition Destruction", \ "Field Space Destruction", \ "Logical Region Destruction", \ "Logical Partition Destruction", \ "Individual Remote Mapped", \ "Individual Remote Complete", \ "Individual Remote Commit", \ "Slice Remote Mapped", \ "Slice Remote Complete", \ "Slice Remote Commit", \ "Distributed Remote Registration", \ "Distributed Valid Update", \ "Distributed GC Update", \ "Distributed Resource Update", \ "Distributed Create Add", \ "Distributed Create Remove", \ "Distributed Unregister", \ "Send Atomic Reservation Request", \ "Send Atomic Reservation Response", \ "Send Back Logical State", \ "Send Materialized View", \ "Send Composite View", \ "Send Fill View", \ "Send Phi View", \ "Send Reduction View", \ "Send Instance Manager", \ "Send Reduction Manager", \ "Send Create Top View Request", \ "Send Create Top View Response", \ "Send Subview DID Request", \ "Send Subview DID Response", \ "Send View Request", \ "Send View Update Request", \ "Send View Update Response", \ "Send View Remote Update", \ "Send View Remote Invalidate", \ "Send Manager Request", \ "Send Future Result", \ "Send Future Subscription", \ "Send Mapper Message", \ "Send Mapper Broadcast", \ "Send Task Impl Semantic Req", \ "Send Index Space Semantic Req", \ "Send Index Partition Semantic Req", \ "Send Field Space Semantic Req", \ "Send Field Semantic Req", \ "Send Logical Region Semantic Req", \ "Send Logical Partition Semantic Req", \ "Send Task Impl Semantic Info", \ "Send Index Space Semantic Info", \ "Send Index Partition Semantic Info", \ "Send Field Space Semantic Info", \ "Send Field Semantic Info", \ "Send Logical Region Semantic Info", \ "Send Logical Partition Semantic Info", \ "Send Remote Context Request", \ "Send Remote Context Response", \ "Send Remote Context Free", \ "Send Version Owner Request", \ "Send Version Owner Response", \ "Send Version State Request", \ "Send Version State Response", \ "Send Version State Update Request", \ "Send Version State Update Response", \ "Send Version State Valid Notification", \ "Send Version Manager Advance", \ "Send Version Manager Invalidate", \ "Send Version Manager Request", \ "Send Version Manager Response", \ "Send Instance Request", \ "Send Instance Response", \ "Send GC Priority Update", \ "Send Never GC Response", \ "Send Acquire Request", \ "Send Acquire Response", \ "Send Task Variant Request", \ "Send Task Variant Response", \ "Send Task Variant Broadcast", \ "Send Constraint Request", \ "Send Constraint Response", \ "Send Constraint Release", \ "Send Constraint Removal", \ "Top Level Task Request", \ "Top Level Task Complete", \ "Send MPI Rank Exchange", \ "Send Shutdown Notification", \ "Send Shutdown Response", \ }; enum RuntimeCallKind { PACK_BASE_TASK_CALL, UNPACK_BASE_TASK_CALL, TASK_PRIVILEGE_CHECK_CALL, CLONE_TASK_CALL, COMPUTE_POINT_REQUIREMENTS_CALL, EARLY_MAP_REGIONS_CALL, INTRA_TASK_ALIASING_CALL, ACTIVATE_SINGLE_CALL, DEACTIVATE_SINGLE_CALL, SELECT_INLINE_VARIANT_CALL, INLINE_CHILD_TASK_CALL, PACK_SINGLE_TASK_CALL, UNPACK_SINGLE_TASK_CALL, PACK_REMOTE_CONTEXT_CALL, HAS_CONFLICTING_INTERNAL_CALL, FIND_CONFLICTING_CALL, FIND_CONFLICTING_INTERNAL_CALL, CHECK_REGION_DEPENDENCE_CALL, FIND_PARENT_REGION_REQ_CALL, FIND_PARENT_REGION_CALL, CHECK_PRIVILEGE_CALL, TRIGGER_SINGLE_CALL, INITIALIZE_MAP_TASK_CALL, FINALIZE_MAP_TASK_CALL, VALIDATE_VARIANT_SELECTION_CALL, MAP_ALL_REGIONS_CALL, INITIALIZE_REGION_TREE_CONTEXTS_CALL, INVALIDATE_REGION_TREE_CONTEXTS_CALL, CREATE_INSTANCE_TOP_VIEW_CALL, LAUNCH_TASK_CALL, ACTIVATE_MULTI_CALL, DEACTIVATE_MULTI_CALL, SLICE_INDEX_SPACE_CALL, CLONE_MULTI_CALL, MULTI_TRIGGER_EXECUTION_CALL, PACK_MULTI_CALL, UNPACK_MULTI_CALL, ACTIVATE_INDIVIDUAL_CALL, DEACTIVATE_INDIVIDUAL_CALL, INDIVIDUAL_PERFORM_MAPPING_CALL, INDIVIDUAL_RETURN_VIRTUAL_CALL, INDIVIDUAL_TRIGGER_COMPLETE_CALL, INDIVIDUAL_TRIGGER_COMMIT_CALL, INDIVIDUAL_POST_MAPPED_CALL, INDIVIDUAL_PACK_TASK_CALL, INDIVIDUAL_UNPACK_TASK_CALL, INDIVIDUAL_PACK_REMOTE_COMPLETE_CALL, INDIVIDUAL_UNPACK_REMOTE_COMPLETE_CALL, POINT_ACTIVATE_CALL, POINT_DEACTIVATE_CALL, POINT_TASK_COMPLETE_CALL, POINT_TASK_COMMIT_CALL, POINT_PACK_TASK_CALL, POINT_UNPACK_TASK_CALL, POINT_TASK_POST_MAPPED_CALL, REMOTE_TASK_ACTIVATE_CALL, REMOTE_TASK_DEACTIVATE_CALL, REMOTE_UNPACK_CONTEXT_CALL, INDEX_ACTIVATE_CALL, INDEX_DEACTIVATE_CALL, INDEX_COMPUTE_FAT_PATH_CALL, INDEX_EARLY_MAP_TASK_CALL, INDEX_DISTRIBUTE_CALL, INDEX_PERFORM_MAPPING_CALL, INDEX_COMPLETE_CALL, INDEX_COMMIT_CALL, INDEX_PERFORM_INLINING_CALL, INDEX_CLONE_AS_SLICE_CALL, INDEX_HANDLE_FUTURE, INDEX_RETURN_SLICE_MAPPED_CALL, INDEX_RETURN_SLICE_COMPLETE_CALL, INDEX_RETURN_SLICE_COMMIT_CALL, SLICE_ACTIVATE_CALL, SLICE_DEACTIVATE_CALL, SLICE_APPLY_VERSION_INFO_CALL, SLICE_DISTRIBUTE_CALL, SLICE_PERFORM_MAPPING_CALL, SLICE_LAUNCH_CALL, SLICE_MAP_AND_LAUNCH_CALL, SLICE_PACK_TASK_CALL, SLICE_UNPACK_TASK_CALL, SLICE_CLONE_AS_SLICE_CALL, SLICE_HANDLE_FUTURE_CALL, SLICE_CLONE_AS_POINT_CALL, SLICE_ENUMERATE_POINTS_CALL, SLICE_MAPPED_CALL, SLICE_COMPLETE_CALL, SLICE_COMMIT_CALL, REALM_SPAWN_META_CALL, REALM_SPAWN_TASK_CALL, REALM_CREATE_INSTANCE_CALL, REALM_ISSUE_COPY_CALL, REALM_ISSUE_FILL_CALL, REGION_TREE_LOGICAL_ANALYSIS_CALL, REGION_TREE_LOGICAL_FENCE_CALL, REGION_TREE_VERSIONING_ANALYSIS_CALL, REGION_TREE_ADVANCE_VERSION_NUMBERS_CALL, REGION_TREE_INITIALIZE_CONTEXT_CALL, REGION_TREE_INVALIDATE_CONTEXT_CALL, REGION_TREE_PREMAP_ONLY_CALL, REGION_TREE_PHYSICAL_REGISTER_ONLY_CALL, REGION_TREE_PHYSICAL_REGISTER_USERS_CALL, REGION_TREE_PHYSICAL_PERFORM_CLOSE_CALL, REGION_TREE_PHYSICAL_CLOSE_CONTEXT_CALL, REGION_TREE_PHYSICAL_COPY_ACROSS_CALL, REGION_TREE_PHYSICAL_REDUCE_ACROSS_CALL, REGION_TREE_PHYSICAL_CONVERT_MAPPING_CALL, REGION_TREE_PHYSICAL_FILL_FIELDS_CALL, REGION_TREE_PHYSICAL_ATTACH_FILE_CALL, REGION_TREE_PHYSICAL_DETACH_FILE_CALL, REGION_NODE_REGISTER_LOGICAL_USER_CALL, REGION_NODE_CLOSE_LOGICAL_NODE_CALL, REGION_NODE_SIPHON_LOGICAL_CHILDREN_CALL, REGION_NODE_SIPHON_LOGICAL_PROJECTION_CALL, REGION_NODE_PERFORM_LOGICAL_CLOSES_CALL, REGION_NODE_FIND_VALID_INSTANCE_VIEWS_CALL, REGION_NODE_FIND_VALID_REDUCTION_VIEWS_CALL, REGION_NODE_ISSUE_UPDATE_COPIES_CALL, REGION_NODE_SORT_COPY_INSTANCES_CALL, REGION_NODE_ISSUE_GROUPED_COPIES_CALL, REGION_NODE_ISSUE_UPDATE_REDUCTIONS_CALL, REGION_NODE_PREMAP_REGION_CALL, REGION_NODE_REGISTER_REGION_CALL, REGION_NODE_CLOSE_STATE_CALL, CURRENT_STATE_RECORD_VERSION_NUMBERS_CALL, CURRENT_STATE_ADVANCE_VERSION_NUMBERS_CALL, PHYSICAL_STATE_CAPTURE_STATE_CALL, PHYSICAL_STATE_APPLY_PATH_ONLY_CALL, PHYSICAL_STATE_APPLY_STATE_CALL, PHYSICAL_STATE_MAKE_LOCAL_CALL, VERSION_STATE_UPDATE_PATH_ONLY_CALL, VERSION_STATE_MERGE_PHYSICAL_STATE_CALL, VERSION_STATE_REQUEST_CHILDREN_CALL, VERSION_STATE_REQUEST_INITIAL_CALL, VERSION_STATE_REQUEST_FINAL_CALL, VERSION_STATE_SEND_STATE_CALL, VERSION_STATE_HANDLE_REQUEST_CALL, VERSION_STATE_HANDLE_RESPONSE_CALL, MATERIALIZED_VIEW_FIND_LOCAL_PRECONDITIONS_CALL, MATERIALIZED_VIEW_FIND_LOCAL_COPY_PRECONDITIONS_CALL, MATERIALIZED_VIEW_FILTER_PREVIOUS_USERS_CALL, MATERIALIZED_VIEW_FILTER_CURRENT_USERS_CALL, MATERIALIZED_VIEW_FILTER_LOCAL_USERS_CALL, COMPOSITE_VIEW_SIMPLIFY_CALL, COMPOSITE_VIEW_ISSUE_DEFERRED_COPIES_CALL, COMPOSITE_NODE_CAPTURE_PHYSICAL_STATE_CALL, COMPOSITE_NODE_SIMPLIFY_CALL, REDUCTION_VIEW_PERFORM_REDUCTION_CALL, REDUCTION_VIEW_PERFORM_DEFERRED_REDUCTION_CALL, REDUCTION_VIEW_PERFORM_DEFERRED_REDUCTION_ACROSS_CALL, REDUCTION_VIEW_FIND_COPY_PRECONDITIONS_CALL, REDUCTION_VIEW_FIND_USER_PRECONDITIONS_CALL, REDUCTION_VIEW_FILTER_LOCAL_USERS_CALL, LAST_RUNTIME_CALL_KIND, // This one must be last }; #define RUNTIME_CALL_DESCRIPTIONS(name) \ const char *name[LAST_RUNTIME_CALL_KIND] = { \ "Pack Base Task", \ "Unpack Base Task", \ "Task Privilege Check", \ "Clone Base Task", \ "Compute Point Requirements", \ "Early Map Regions", \ "Intra-Task Aliasing", \ "Activate Single", \ "Deactivate Single", \ "Select Inline Variant", \ "Inline Child Task", \ "Pack Single Task", \ "Unpack Single Task", \ "Pack Remote Context", \ "Has Conflicting Internal", \ "Find Conflicting", \ "Find Conflicting Internal", \ "Check Region Dependence", \ "Find Parent Region Requirement", \ "Find Parent Region", \ "Check Privilege", \ "Trigger Single", \ "Initialize Map Task", \ "Finalized Map Task", \ "Validate Variant Selection", \ "Map All Regions", \ "Initialize Region Tree Contexts", \ "Invalidate Region Tree Contexts", \ "Create Instance Top View", \ "Launch Task", \ "Activate Multi", \ "Deactivate Multi", \ "Slice Index Space", \ "Clone Multi Call", \ "Multi Trigger Execution", \ "Pack Multi", \ "Unpack Multi", \ "Activate Individual", \ "Deactivate Individual", \ "Individual Perform Mapping", \ "Individual Return Virtual", \ "Individual Trigger Complete", \ "Individual Trigger Commit", \ "Individual Post Mapped", \ "Individual Pack Task", \ "Individual Unpack Task", \ "Individual Pack Remote Complete", \ "Individual Unpack Remote Complete", \ "Activate Point", \ "Deactivate Point", \ "Point Task Complete", \ "Point Task Commit", \ "Point Task Pack", \ "Point Task Unpack", \ "Point Task Post Mapped", \ "Remote Task Activate", \ "Remote Task Deactivate", \ "Remote Unpack Context", \ "Index Activate", \ "Index Deactivate", \ "Index Compute Fat Path", \ "Index Early Map Task", \ "Index Distribute", \ "Index Perform Mapping", \ "Index Complete", \ "Index Commit", \ "Index Perform Inlining", \ "Index Clone As Slice", \ "Index Handle Future", \ "Index Return Slice Mapped", \ "Index Return Slice Complete", \ "Index Return Slice Commit", \ "Slice Activate", \ "Slice Deactivate", \ "Slice Apply Version Info", \ "Slice Distribute", \ "Slice Perform Mapping", \ "Slice Launch", \ "Slice Map and Launch", \ "Slice Pack Task", \ "Slice Unpack Task", \ "Slice Clone As Slice", \ "Slice Handle Future", \ "Slice Cone as Point", \ "Slice Enumerate Points", \ "Slice Mapped", \ "Slice Complete", \ "Slice Commit", \ "Realm Spawn Meta", \ "Realm Spawn Task", \ "Realm Create Instance", \ "Realm Issue Copy", \ "Realm Issue Fill", \ "Region Tree Logical Analysis", \ "Region Tree Logical Fence", \ "Region Tree Versioning Analysis", \ "Region Tree Advance Version Numbers", \ "Region Tree Initialize Context", \ "Region Tree Invalidate Context", \ "Region Tree Premap Only", \ "Region Tree Physical Register Only", \ "Region Tree Physical Register Users", \ "Region Tree Physical Perform Close", \ "Region Tree Physical Close Context", \ "Region Tree Physical Copy Across", \ "Region Tree Physical Reduce Across", \ "Region Tree Physical Convert Mapping", \ "Region Tree Physical Fill Fields", \ "Region Tree Physical Attach File", \ "Region Tree Physical Detach File", \ "Region Node Register Logical User", \ "Region Node Close Logical Node", \ "Region Node Siphon Logical Children", \ "Region Node Siphon Logical Projection", \ "Region Node Perform Logical Closes", \ "Region Node Find Valid Instance Views", \ "Region Node Find Valid Reduction Views", \ "Region Node Issue Update Copies", \ "Region Node Sort Copy Instances", \ "Region Node Issue Grouped Copies", \ "Region Node Issue Update Reductions", \ "Region Node Premap Region", \ "Region Node Register Region", \ "Region Node Close State", \ "Logical State Record Verison Numbers", \ "Logical State Advance Version Numbers", \ "Physical State Capture State", \ "Physical State Apply Path Only", \ "Physical State Apply State", \ "Physical State Make Local", \ "Version State Update Path Only", \ "Version State Merge Physical State", \ "Version State Request Children", \ "Version State Request Initial", \ "Version State Request Final", \ "Version State Send State", \ "Version State Handle Request", \ "Version State Handle Response", \ "Materialized View Find Local Preconditions", \ "Materialized View Find Local Copy Preconditions", \ "Materialized View Filter Previous Users", \ "Materialized View Filter Current Users", \ "Materialized View Filter Local Users", \ "Composite View Simplify", \ "Composite View Issue Deferred Copies", \ "Composite Node Capture Physical State", \ "Composite Node Simplify", \ "Reduction View Perform Reduction", \ "Reduction View Perform Deferred Reduction", \ "Reduction View Perform Deferred Reduction Across", \ "Reduction View Find Copy Preconditions", \ "Reduction View Find User Preconditions", \ "Reduction View Filter Local Users", \ }; enum SemanticInfoKind { INDEX_SPACE_SEMANTIC, INDEX_PARTITION_SEMANTIC, FIELD_SPACE_SEMANTIC, FIELD_SEMANTIC, LOGICAL_REGION_SEMANTIC, LOGICAL_PARTITION_SEMANTIC, TASK_SEMANTIC, }; // Forward declarations for runtime level objects // runtime.h class Collectable; class ArgumentMapImpl; class ArgumentMapStore; class FutureImpl; class FutureMapImpl; class PhysicalRegionImpl; class GrantImpl; class PredicateImpl; class MPILegionHandshakeImpl; class ProcessorManager; class MemoryManager; class VirtualChannel; class MessageManager; class ShutdownManager; class GarbageCollectionEpoch; class TaskImpl; class VariantImpl; class LayoutConstraints; class GeneratorImpl; class ProjectionFunction; class Runtime; // legion_ops.h class Operation; class SpeculativeOp; class MapOp; class CopyOp; class IndexCopyOp; class PointCopyOp; class FenceOp; class FrameOp; class DeletionOp; class InternalOp; class OpenOp; class AdvanceOp; class CloseOp; class InterCloseOp; class ReadCloseOp; class PostCloseOp; class VirtualCloseOp; class AcquireOp; class ReleaseOp; class DynamicCollectiveOp; class FuturePredOp; class NotPredOp; class AndPredOp; class OrPredOp; class MustEpochOp; class PendingPartitionOp; class DependentPartitionOp; class FillOp; class IndexFillOp; class PointFillOp; class AttachOp; class DetachOp; class TimingOp; class TaskOp; // legion_tasks.h class ExternalTask; class SingleTask; class MultiTask; class IndividualTask; class PointTask; class IndexTask; class SliceTask; class RemoteTask; class MinimalPoint; // legion_context.h /** * \class ContextInterface * This is a pure virtual class so users don't try to use it. * It defines the context interface that the task wrappers use * for getting access to context data when running a task. */ class TaskContext; class InnerContext;; class TopLevelContext; class RemoteContext; class LeafContext; class InlineContext; class ContextInterface { public: virtual Task* get_task(void) = 0; virtual const std::vector<PhysicalRegion>& begin_task(void) = 0; virtual void end_task(const void *result, size_t result_size, bool owned) = 0; // This is safe because we see in legion_context.h that // TaskContext implements this interface and no one else // does. If only C++ implemented forward declarations of // inheritence then we wouldn't have this dumb problem // (mixin classes anyone?). inline TaskContext* as_context(void) { return reinterpret_cast<TaskContext*>(this); } }; // legion_trace.h class LegionTrace; class StaticTrace; class DynamicTrace; class TraceCaptureOp; class TraceCompleteOp; // region_tree.h class RegionTreeForest; class IndexTreeNode; class IndexSpaceNode; class IndexPartNode; class FieldSpaceNode; class RegionTreeNode; class RegionNode; class PartitionNode; class RegionTreeContext; class RegionTreePath; class PathTraverser; class NodeTraverser; class ProjectionEpoch; class LogicalState; class PhysicalState; class VersionState; class VersionInfo; class RestrictInfo; class Restriction; class Acquisition; class Collectable; class Notifiable; class ReferenceMutator; class LocalReferenceMutator; class NeverReferenceMutator; class DistributedCollectable; class LayoutDescription; class PhysicalManager; // base class for instance and reduction class CopyAcrossHelper; class LogicalView; // base class for instance and reduction class InstanceManager; class InstanceKey; class InstanceView; class DeferredView; class MaterializedView; class CompositeBase; class CompositeView; class CompositeVersionInfo; class CompositeNode; class FillView; class PhiView; class MappingRef; class InstanceRef; class InstanceSet; class InnerTaskView; class ReductionManager; class ListReductionManager; class FoldReductionManager; class VirtualManager; class ReductionView; class InstanceBuilder; class RegionAnalyzer; class RegionMapper; struct EscapedUser; struct EscapedCopy; struct GenericUser; struct LogicalUser; struct PhysicalUser; struct TraceInfo; class ClosedNode; class LogicalCloser; class TreeCloseImpl; class TreeClose; struct CloseInfo; // legion_spy.h class TreeStateLogger; // legion_profiling.h class LegionProfiler; class LegionProfInstance; // mapper_manager.h class MappingCallInfo; class MapperManager; class SerializingManager; class ConcurrentManager; typedef Mapping::MapperEvent MapperEvent; typedef Mapping::ProfilingMeasurementID ProfilingMeasurementID; #define FRIEND_ALL_RUNTIME_CLASSES \ friend class Legion::Runtime; \ friend class Internal::Runtime; \ friend class Internal::PhysicalRegionImpl; \ friend class Internal::TaskImpl; \ friend class Internal::ProcessorManager; \ friend class Internal::MemoryManager; \ friend class Internal::Operation; \ friend class Internal::SpeculativeOp; \ friend class Internal::MapOp; \ friend class Internal::CopyOp; \ friend class Internal::IndexCopyOp; \ friend class Internal::PointCopyOp; \ friend class Internal::FenceOp; \ friend class Internal::DynamicCollectiveOp; \ friend class Internal::FuturePredOp; \ friend class Internal::DeletionOp; \ friend class Internal::OpenOp; \ friend class Internal::AdvanceOp; \ friend class Internal::CloseOp; \ friend class Internal::InterCloseOp; \ friend class Internal::ReadCloseOp; \ friend class Internal::PostCloseOp; \ friend class Internal::VirtualCloseOp; \ friend class Internal::AcquireOp; \ friend class Internal::ReleaseOp; \ friend class Internal::PredicateImpl; \ friend class Internal::NotPredOp; \ friend class Internal::AndPredOp; \ friend class Internal::OrPredOp; \ friend class Internal::MustEpochOp; \ friend class Internal::PendingPartitionOp; \ friend class Internal::DependentPartitionOp; \ friend class Internal::FillOp; \ friend class Internal::IndexFillOp; \ friend class Internal::PointFillOp; \ friend class Internal::AttachOp; \ friend class Internal::DetachOp; \ friend class Internal::TimingOp; \ friend class Internal::ExternalTask; \ friend class Internal::TaskOp; \ friend class Internal::SingleTask; \ friend class Internal::MultiTask; \ friend class Internal::IndividualTask; \ friend class Internal::PointTask; \ friend class Internal::IndexTask; \ friend class Internal::SliceTask; \ friend class Internal::RegionTreeForest; \ friend class Internal::IndexSpaceNode; \ friend class Internal::IndexPartNode; \ friend class Internal::FieldSpaceNode; \ friend class Internal::RegionTreeNode; \ friend class Internal::RegionNode; \ friend class Internal::PartitionNode; \ friend class Internal::LogicalView; \ friend class Internal::InstanceView; \ friend class Internal::DeferredView; \ friend class Internal::ReductionView; \ friend class Internal::MaterializedView; \ friend class Internal::CompositeView; \ friend class Internal::CompositeNode; \ friend class Internal::FillView; \ friend class Internal::LayoutDescription; \ friend class Internal::PhysicalManager; \ friend class Internal::InstanceManager; \ friend class Internal::ReductionManager; \ friend class Internal::ListReductionManager; \ friend class Internal::FoldReductionManager; \ friend class Internal::TreeStateLogger; \ friend class Internal::MapperManager; \ friend class Internal::InstanceRef; \ friend class Internal::MPILegionHandshakeImpl; \ friend class Internal::FutureMapImpl; \ friend class Internal::TaskContext; \ friend class Internal::InnerContext; \ friend class Internal::TopLevelContext; \ friend class Internal::RemoteContext; \ friend class Internal::LeafContext; \ friend class Internal::InlineContext; \ friend class BindingLib::Utility; \ friend class CObjectWrapper; #define LEGION_EXTERN_LOGGER_DECLARATIONS \ extern LegionRuntime::Logger::Category log_run; \ extern LegionRuntime::Logger::Category log_task; \ extern LegionRuntime::Logger::Category log_index; \ extern LegionRuntime::Logger::Category log_field; \ extern LegionRuntime::Logger::Category log_region; \ extern LegionRuntime::Logger::Category log_inst; \ extern LegionRuntime::Logger::Category log_variant; \ extern LegionRuntime::Logger::Category log_allocation; \ extern LegionRuntime::Logger::Category log_prof; \ extern LegionRuntime::Logger::Category log_garbage; \ extern LegionRuntime::Logger::Category log_spy; \ extern LegionRuntime::Logger::Category log_shutdown; }; // Internal namespace // Typedefs that are needed everywhere typedef LegionRuntime::Accessor::ByteOffset ByteOffset; typedef Realm::Runtime RealmRuntime; typedef Realm::Machine Machine; typedef Realm::Domain Domain; typedef Realm::DomainPoint DomainPoint; typedef Realm::IndexSpaceAllocator IndexSpaceAllocator; typedef Realm::Memory Memory; typedef Realm::Processor Processor; typedef Realm::CodeDescriptor CodeDescriptor; typedef Realm::Reservation Reservation; typedef ::legion_reduction_op_id_t ReductionOpID; typedef Realm::ReductionOpUntyped ReductionOp; typedef ::legion_custom_serdez_id_t CustomSerdezID; typedef Realm::CustomSerdezUntyped SerdezOp; typedef Realm::Machine::ProcessorMemoryAffinity ProcessorMemoryAffinity; typedef Realm::Machine::MemoryMemoryAffinity MemoryMemoryAffinity; typedef Realm::ElementMask::Enumerator Enumerator; typedef ::legion_lowlevel_coord_t coord_t; typedef Realm::IndexSpace::FieldDataDescriptor FieldDataDescriptor; typedef std::map<CustomSerdezID, const Realm::CustomSerdezUntyped *> SerdezOpTable; typedef std::map<Realm::ReductionOpID, const Realm::ReductionOpUntyped *> ReductionOpTable; typedef void (*SerdezInitFnptr)(const ReductionOp*, void *&, size_t&); typedef void (*SerdezFoldFnptr)(const ReductionOp*, void *&, size_t&, const void*); typedef std::map<Realm::ReductionOpID, SerdezRedopFns> SerdezRedopTable; typedef ::legion_projection_type_t HandleType; typedef ::legion_address_space_t AddressSpace; typedef ::legion_task_priority_t TaskPriority; typedef ::legion_garbage_collection_priority_t GCPriority; typedef ::legion_color_t Color; typedef ::legion_field_id_t FieldID; typedef ::legion_trace_id_t TraceID; typedef ::legion_mapper_id_t MapperID; typedef ::legion_context_id_t ContextID; typedef ::legion_instance_id_t InstanceID; typedef ::legion_index_space_id_t IndexSpaceID; typedef ::legion_index_partition_id_t IndexPartitionID; typedef ::legion_index_tree_id_t IndexTreeID; typedef ::legion_field_space_id_t FieldSpaceID; typedef ::legion_generation_id_t GenerationID; typedef ::legion_type_handle TypeHandle; typedef ::legion_projection_id_t ProjectionID; typedef ::legion_region_tree_id_t RegionTreeID; typedef ::legion_distributed_id_t DistributedID; typedef ::legion_address_space_id_t AddressSpaceID; typedef ::legion_tunable_id_t TunableID; typedef ::legion_generator_id_t GeneratorID; typedef ::legion_mapping_tag_id_t MappingTagID; typedef ::legion_semantic_tag_t SemanticTag; typedef ::legion_variant_id_t VariantID; typedef ::legion_unique_id_t UniqueID; typedef ::legion_version_id_t VersionID; typedef ::legion_projection_epoch_id_t ProjectionEpochID; typedef ::legion_task_id_t TaskID; typedef ::legion_layout_constraint_id_t LayoutConstraintID; typedef std::map<Color,ColoredPoints<ptr_t> > Coloring; typedef std::map<Color,Domain> DomainColoring; typedef std::map<Color,std::set<Domain> > MultiDomainColoring; typedef std::map<DomainPoint,ColoredPoints<ptr_t> > PointColoring; typedef std::map<DomainPoint,Domain> DomainPointColoring; typedef std::map<DomainPoint,std::set<Domain> > MultiDomainPointColoring; typedef void (*RegistrationCallbackFnptr)(Machine machine, Runtime *rt, const std::set<Processor> &local_procs); typedef LogicalRegion (*RegionProjectionFnptr)(LogicalRegion parent, const DomainPoint&, Runtime *rt); typedef LogicalRegion (*PartitionProjectionFnptr)(LogicalPartition parent, const DomainPoint&, Runtime *rt); typedef bool (*PredicateFnptr)(const void*, size_t, const std::vector<Future> futures); typedef void (*RealmFnptr)(const void*,size_t, const void*,size_t,Processor); // Magical typedefs // (don't forget to update ones in old HighLevel namespace in legion.inl) typedef Internal::TaskContext* Context; typedef Internal::ContextInterface* InternalContext; typedef Internal::GeneratorImpl* GeneratorContext; typedef void (*GeneratorFnptr)(GeneratorContext, const TaskGeneratorArguments&, Runtime*); // Anothing magical typedef namespace Mapping { typedef Internal::MappingCallInfo* MapperContext; typedef Internal::PhysicalManager* PhysicalInstanceImpl; }; namespace Internal { // This is only needed internally typedef Realm::RegionInstance PhysicalInstance; // Pull some of the mapper types into the internal space typedef Mapping::Mapper Mapper; typedef Mapping::PhysicalInstance MappingInstance; // A little bit of logic here to figure out the // kind of bit mask to use for FieldMask // The folowing macros are used in the FieldMask instantiation of BitMask // If you change one you probably have to change the others too #define LEGION_FIELD_MASK_FIELD_TYPE uint64_t #define LEGION_FIELD_MASK_FIELD_SHIFT 6 #define LEGION_FIELD_MASK_FIELD_MASK 0x3F #define LEGION_FIELD_MASK_FIELD_ALL_ONES 0xFFFFFFFFFFFFFFFF #if defined(__AVX__) #if (MAX_FIELDS > 256) typedef AVXTLBitMask<MAX_FIELDS> FieldMask; #elif (MAX_FIELDS > 128) typedef AVXBitMask<MAX_FIELDS> FieldMask; #elif (MAX_FIELDS > 64) typedef SSEBitMask<MAX_FIELDS> FieldMask; #else typedef BitMask<LEGION_FIELD_MASK_FIELD_TYPE,MAX_FIELDS, LEGION_FIELD_MASK_FIELD_SHIFT, LEGION_FIELD_MASK_FIELD_MASK> FieldMask; #endif #elif defined(__SSE2__) #if (MAX_FIELDS > 128) typedef SSETLBitMask<MAX_FIELDS> FieldMask; #elif (MAX_FIELDS > 64) typedef SSEBitMask<MAX_FIELDS> FieldMask; #else typedef BitMask<LEGION_FIELD_MASK_FIELD_TYPE,MAX_FIELDS, LEGION_FIELD_MASK_FIELD_SHIFT, LEGION_FIELD_MASK_FIELD_MASK> FieldMask; #endif #else #if (MAX_FIELDS > 64) typedef TLBitMask<LEGION_FIELD_MASK_FIELD_TYPE,MAX_FIELDS, LEGION_FIELD_MASK_FIELD_SHIFT, LEGION_FIELD_MASK_FIELD_MASK> FieldMask; #else typedef BitMask<LEGION_FIELD_MASK_FIELD_TYPE,MAX_FIELDS, LEGION_FIELD_MASK_FIELD_SHIFT, LEGION_FIELD_MASK_FIELD_MASK> FieldMask; #endif #endif typedef BitPermutation<FieldMask,LEGION_FIELD_LOG2> FieldPermutation; typedef Fraction<unsigned long> InstFrac; #undef LEGION_FIELD_MASK_FIELD_SHIFT #undef LEGION_FIELD_MASK_FIELD_MASK // Similar logic as field masks for node masks // The following macros are used in the NodeMask instantiation of BitMask // If you change one you probably have to change the others too #define LEGION_NODE_MASK_NODE_TYPE uint64_t #define LEGION_NODE_MASK_NODE_SHIFT 6 #define LEGION_NODE_MASK_NODE_MASK 0x3F #define LEGION_NODE_MASK_NODE_ALL_ONES 0xFFFFFFFFFFFFFFFF #if defined(__AVX__) #if (MAX_NUM_NODES > 256) typedef AVXTLBitMask<MAX_NUM_NODES> NodeMask; #elif (MAX_NUM_NODES > 128) typedef AVXBitMask<MAX_NUM_NODES> NodeMask; #elif (MAX_NUM_NODES > 64) typedef SSEBitMask<MAX_NUM_NODES> NodeMask; #else typedef BitMask<LEGION_NODE_MASK_NODE_TYPE,MAX_NUM_NODES, LEGION_NODE_MASK_NODE_SHIFT, LEGION_NODE_MASK_NODE_MASK> NodeMask; #endif #elif defined(__SSE2__) #if (MAX_NUM_NODES > 128) typedef SSETLBitMask<MAX_NUM_NODES> NodeMask; #elif (MAX_NUM_NODES > 64) typedef SSEBitMask<MAX_NUM_NODES> NodeMask; #else typedef BitMask<LEGION_NODE_MASK_NODE_TYPE,MAX_NUM_NODES, LEGION_NODE_MASK_NODE_SHIFT, LEGION_NODE_MASK_NODE_MASK> NodeMask; #endif #else #if (MAX_NUM_NODES > 64) typedef TLBitMask<LEGION_NODE_MASK_NODE_TYPE,MAX_NUM_NODES, LEGION_NODE_MASK_NODE_SHIFT, LEGION_NODE_MASK_NODE_MASK> NodeMask; #else typedef BitMask<LEGION_NODE_MASK_NODE_TYPE,MAX_NUM_NODES, LEGION_NODE_MASK_NODE_SHIFT, LEGION_NODE_MASK_NODE_MASK> NodeMask; #endif #endif typedef IntegerSet<AddressSpaceID,NodeMask> NodeSet; #undef LEGION_NODE_MASK_NODE_SHIFT #undef LEGION_NODE_MASK_NODE_MASK // The following macros are used in the ProcessorMask instantiation of BitMask // If you change one you probably have to change the others too #define LEGION_PROC_MASK_PROC_TYPE uint64_t #define LEGION_PROC_MASK_PROC_SHIFT 6 #define LEGION_PROC_MASK_PROC_MASK 0x3F #define LEGION_PROC_MASK_PROC_ALL_ONES 0xFFFFFFFFFFFFFFFF #if defined(__AVX__) #if (MAX_NUM_PROCS > 256) typedef AVXTLBitMask<MAX_NUM_PROCS> ProcessorMask; #elif (MAX_NUM_PROCS > 128) typedef AVXBitMask<MAX_NUM_PROCS> ProcessorMask; #elif (MAX_NUM_PROCS > 64) typedef SSEBitMask<MAX_NUM_PROCS> ProcessorMask; #else typedef BitMask<LEGION_PROC_MASK_PROC_TYPE,MAX_NUM_PROCS, LEGION_PROC_MASK_PROC_SHIFT, LEGION_PROC_MASK_PROC_MASK> ProcessorMask; #endif #elif defined(__SSE2__) #if (MAX_NUM_PROCS > 128) typedef SSETLBitMask<MAX_NUM_PROCS> ProcessorMask; #elif (MAX_NUM_PROCS > 64) typedef SSEBitMask<MAX_NUM_PROCS> ProcessorMask; #else typedef BitMask<LEGION_PROC_MASK_PROC_TYPE,MAX_NUM_PROCS, LEGION_PROC_MASK_PROC_SHIFT, LEGION_PROC_MASK_PROC_MASK> ProcessorMask; #endif #else #if (MAX_NUM_PROCS > 64) typedef TLBitMask<LEGION_PROC_MASK_PROC_TYPE,MAX_NUM_PROCS, LEGION_PROC_MASK_PROC_SHIFT, LEGION_PROC_MASK_PROC_MASK> ProcessorMask; #else typedef BitMask<LEGION_PROC_MASK_PROC_TYPE,MAX_NUM_PROCS, LEGION_PROC_MASK_PROC_SHIFT, LEGION_PROC_MASK_PROC_MASK> ProcessorMask; #endif #endif #undef PROC_SHIFT #undef PROC_MASK }; // namespace Internal //http://stackoverflow.com/questions/154136 #if USE_OCR_LAYER #define COPY_OCR_EVT_FROM(e) do { this->evt_guid = e.evt_guid;} while(0) #define COPY_OCR_EVT_TO(e) do { e.evt_guid = this->evt_guid;} while(0) #else // USE_OCR_LAYER #define COPY_OCR_EVT_FROM(e) do {} while(0) #define COPY_OCR_EVT_TO(e) do {} while(0) #endif // USE_OCR_LAYER // Legion derived event types class LgEvent : public Realm::Event { public: static const LgEvent NO_LG_EVENT; public: LgEvent(void) { id = 0; #if USE_OCR_LAYER evt_guid = NULL_GUID; #endif // USE_OCR_LAYER } LgEvent(const LgEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs);} explicit LgEvent(const Realm::Event e) { id = e.id; COPY_OCR_EVT_FROM(e);} public: inline LgEvent& operator=(const LgEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs); return *this; } }; class PredEvent : public LgEvent { public: static const PredEvent NO_PRED_EVENT; public: PredEvent(void) : LgEvent() { } PredEvent(const PredEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs);} explicit PredEvent(const Realm::UserEvent &e) : LgEvent(e) { } public: inline PredEvent& operator=(const PredEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs); return *this; } inline operator Realm::UserEvent() const { Realm::UserEvent e; e.id = id; COPY_OCR_EVT_TO(e); return e; } }; class ApEvent : public LgEvent { public: static const ApEvent NO_AP_EVENT; public: ApEvent(void) : LgEvent() { } ApEvent(const ApEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs);} explicit ApEvent(const Realm::Event &e) : LgEvent(e) { } explicit ApEvent(const PredEvent &e) { id = e.id; COPY_OCR_EVT_FROM(e);} public: inline ApEvent& operator=(const ApEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs); return *this; } inline bool has_triggered_faultignorant(void) const { bool poisoned; return has_triggered_faultaware(poisoned); } }; class ApUserEvent : public ApEvent { public: static const ApUserEvent NO_AP_USER_EVENT; public: ApUserEvent(void) : ApEvent() { } ApUserEvent(const ApUserEvent &rhs) : ApEvent(rhs) { } explicit ApUserEvent(const Realm::UserEvent &e) : ApEvent(e) { } public: inline ApUserEvent& operator=(const ApUserEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs); return *this; } inline operator Realm::UserEvent() const { Realm::UserEvent e; e.id = id; COPY_OCR_EVT_TO(e); return e; } }; class ApBarrier : public ApEvent { public: static const ApBarrier NO_AP_BARRIER; public: ApBarrier(void) : ApEvent(), timestamp(0) { } ApBarrier(const ApBarrier &rhs) : ApEvent(rhs), timestamp(rhs.timestamp) { } explicit ApBarrier(const Realm::Barrier &b) : ApEvent(b), timestamp(b.timestamp) { } public: inline ApBarrier& operator=(const ApBarrier &rhs) { id = rhs.id; timestamp = rhs.timestamp; return *this; } inline operator Realm::Barrier() const { Realm::Barrier b; b.id = id; b.timestamp = timestamp; return b; } public: Realm::Barrier::timestamp_t timestamp; }; class RtEvent : public LgEvent { public: static const RtEvent NO_RT_EVENT; public: RtEvent(void) : LgEvent() { } RtEvent(const RtEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs);} explicit RtEvent(const Realm::Event &e) : LgEvent(e) { } explicit RtEvent(const PredEvent &e) { id = e.id; COPY_OCR_EVT_FROM(e);} public: inline RtEvent& operator=(const RtEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs); return *this; } }; class RtUserEvent : public RtEvent { public: static const RtUserEvent NO_RT_USER_EVENT; public: RtUserEvent(void) : RtEvent() { } RtUserEvent(const RtUserEvent &rhs) : RtEvent(rhs) { } explicit RtUserEvent(const Realm::UserEvent &e) : RtEvent(e) { } public: inline RtUserEvent& operator=(const RtUserEvent &rhs) { id = rhs.id; COPY_OCR_EVT_FROM(rhs); return *this; } inline operator Realm::UserEvent() const { Realm::UserEvent e; e.id = id; COPY_OCR_EVT_TO(e); return e; } }; class RtBarrier : public RtEvent { public: static const RtBarrier NO_RT_BARRIER; public: RtBarrier(void) : RtEvent(), timestamp(0) { } RtBarrier(const RtBarrier &rhs) : RtEvent(rhs), timestamp(rhs.timestamp) { } explicit RtBarrier(const Realm::Barrier &b) : RtEvent(b), timestamp(b.timestamp) { } public: inline RtBarrier& operator=(const RtBarrier &rhs) { id = rhs.id; timestamp = rhs.timestamp; return *this; } inline operator Realm::Barrier() const { Realm::Barrier b; b.id = id; b.timestamp = timestamp; return b; } public: Realm::Barrier::timestamp_t timestamp; }; }; // Legion namespace #endif // __LEGION_TYPES_H__
c961c3b323b8464068d3b96a1fecb3713202a368
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_3081_squid-3.5.27.cpp
c52222ae41bae665a0354f5ab82fb1ee9006bcf2
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
bool StoreEntry::memoryCachable() { if (!checkCachable()) return 0; if (mem_obj == NULL) return 0; if (mem_obj->data_hdr.size() == 0) return 0; if (mem_obj->inmem_lo != 0) return 0; if (!Config.onoff.memory_cache_first && swap_status == SWAPOUT_DONE && refcount == 1) return 0; return 1; }
dedf9bc5a625dc30af4546217dd8f9b3ff2b96ff
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-medialive/include/aws/medialive/model/ImmediateModeScheduleActionStartSettings.h
95daa8e9a5d33d537801d915c843b6d546c7b167
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
1,497
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/medialive/MediaLive_EXPORTS.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace MediaLive { namespace Model { /** * Settings to configure an action so that it occurs as soon as possible.<p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/ImmediateModeScheduleActionStartSettings">AWS * API Reference</a></p> */ class AWS_MEDIALIVE_API ImmediateModeScheduleActionStartSettings { public: ImmediateModeScheduleActionStartSettings(); ImmediateModeScheduleActionStartSettings(Aws::Utils::Json::JsonView jsonValue); ImmediateModeScheduleActionStartSettings& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; }; } // namespace Model } // namespace MediaLive } // namespace Aws
fada5a6b5c394df4567a22b8f292b05bc462dbe0
2ef3fa4b5d053f42dde1f0db8e9a7773418b08f3
/Engine/Timer.h
990ca36f8a8503edd0d59f69d4a421b323a7c211
[ "MIT" ]
permissive
GuillemArman/Project_Engine
1ee1d3e047f07bb5d73d0e4520b38ac4e9248b45
ddb376996818f07e7a34958f00a27501c2e4ff6c
refs/heads/master
2020-03-28T17:15:52.013198
2018-09-18T12:39:04
2018-09-18T12:39:04
148,773,026
0
0
null
null
null
null
UTF-8
C++
false
false
312
h
#ifndef __TIMER_H__ #define __TIMER_H__ #include "Globals.h" #include "SDL\include\SDL.h" class Timer { public: // Constructor Timer(); void Start(); void Stop(); Uint32 Read(); float ReadSec(); void Reset(); bool running; private: Uint32 started_at; Uint32 stopped_at; }; #endif //__TIMER_H__
18bc9d6a841a91dd55ce4e8163336b34f8477d39
c2d270aff0a4d939f43b6359ac2c564b2565be76
/src/ui/app_list/search/history.cc
0e432570be37823fc0aa63ea386c75518b9c2e34
[ "BSD-3-Clause" ]
permissive
bopopescu/QuicDep
dfa5c2b6aa29eb6f52b12486ff7f3757c808808d
bc86b705a6cf02d2eade4f3ea8cf5fe73ef52aa0
refs/heads/master
2022-04-26T04:36:55.675836
2020-04-29T21:29:26
2020-04-29T21:29:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/app_list/search/history.h" #include <stddef.h> #include "ash/app_list/model/search/tokenized_string.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "ui/app_list/search/history_data.h" #include "ui/app_list/search/history_data_store.h" namespace app_list { namespace { // Normalize the given string by joining all its tokens with a space. std::string NormalizeString(const std::string& utf8) { TokenizedString tokenized(base::UTF8ToUTF16(utf8)); return base::UTF16ToUTF8( base::JoinString(tokenized.tokens(), base::ASCIIToUTF16(" "))); } } // namespace History::History(scoped_refptr<HistoryDataStore> store) : store_(store), data_loaded_(false) { const size_t kMaxQueryEntries = 1000; const size_t kMaxSecondaryQueries = 5; data_.reset( new HistoryData(store_.get(), kMaxQueryEntries, kMaxSecondaryQueries)); data_->AddObserver(this); } History::~History() { data_->RemoveObserver(this); } bool History::IsReady() const { return data_loaded_; } void History::AddLaunchEvent(const std::string& query, const std::string& result_id) { DCHECK(IsReady()); data_->Add(NormalizeString(query), result_id); } std::unique_ptr<KnownResults> History::GetKnownResults( const std::string& query) const { DCHECK(IsReady()); return data_->GetKnownResults(NormalizeString(query)); } void History::OnHistoryDataLoadedFromStore() { data_loaded_ = true; } } // namespace app_list
4d1bff65ed98f466dd976e166079041d57620a40
d8de0ad96cd86caa0c62362961007b7ba74025eb
/合并表记录.cpp
fa1d422ff307795a65daf328d22d5c2de6bb0247
[]
no_license
Giho-Lee/nowcoder-homework
e28f9bdd6e5e4a289059c13013b08d5dbe8eb2b7
dc57167d53f6619cc2adfc50550ae91ddcdc572e
refs/heads/main
2023-03-12T15:45:51.698525
2021-03-07T06:29:34
2021-03-07T06:29:34
344,794,797
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
/* 题目:https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201 */ #include <iostream> #include <map> using namespace std; int main (int argc, char **argv) { int rows; cin >> rows; map<int, int> m; for (int i = 0; i < rows; i++) { int index, value; cin >> index >> value; if (m.end() != m.find(index)) { m[index] += value; } else { m[index] = value; } } map<int, int>::iterator it; for (it = m.begin(); it != m.end(); it++) { cout << it->first << " " << it->second << endl; } return 0; }
14fdd24802ed4eae8673957aa8a8011ed66f1008
5307d5d3d3760240358ad73529723fe9c7411b07
/src/pubkey.h
1be0edd18495b40123107d499db768afa5322b45
[ "MIT" ]
permissive
cruro/cruro
b75d4900c760c40d9641c3355350e9ed56723f84
80aa93365db5e6653bb8235fb61914ee4aa087e8
refs/heads/master
2020-06-18T10:31:58.958195
2019-07-12T14:39:43
2019-07-12T14:39:43
196,270,857
0
0
null
null
null
null
UTF-8
C++
false
false
7,637
h
// Copyright (c) 2009-2010 crury Nakamoto // Copyright (c) 2009-2018 The Cruro Core developers // Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_PUBKEY_H #define BITCOIN_PUBKEY_H #include <hash.h> #include <serialize.h> #include <uint256.h> #include <stdexcept> #include <vector> const unsigned int BIP32_EXTKEY_SIZE = 74; /** A reference to a CKey: the Hash160 of its serialized public key */ class CKeyID : public uint160 { public: CKeyID() : uint160() {} explicit CKeyID(const uint160& in) : uint160(in) {} }; typedef uint256 ChainCode; /** An encapsulated public key. */ class CPubKey { public: /** * secp256k1: */ static constexpr unsigned int PUBLIC_KEY_SIZE = 65; static constexpr unsigned int COMPRESSED_PUBLIC_KEY_SIZE = 33; static constexpr unsigned int SIGNATURE_SIZE = 72; static constexpr unsigned int COMPACT_SIGNATURE_SIZE = 65; /** * see www.keylength.com * script supports up to 75 for single byte push */ static_assert( PUBLIC_KEY_SIZE >= COMPRESSED_PUBLIC_KEY_SIZE, "COMPRESSED_PUBLIC_KEY_SIZE is larger than PUBLIC_KEY_SIZE"); private: /** * Just store the serialized data. * Its length can very cheaply be computed from the first byte. */ unsigned char vch[PUBLIC_KEY_SIZE]; //! Compute the length of a pubkey with a given first byte. unsigned int static GetLen(unsigned char chHeader) { if (chHeader == 2 || chHeader == 3) return COMPRESSED_PUBLIC_KEY_SIZE; if (chHeader == 4 || chHeader == 6 || chHeader == 7) return PUBLIC_KEY_SIZE; return 0; } //! Set this key data to be invalid void Invalidate() { vch[0] = 0xFF; } public: bool static ValidSize(const std::vector<unsigned char> &vch) { return vch.size() > 0 && GetLen(vch[0]) == vch.size(); } //! Construct an invalid public key. CPubKey() { Invalidate(); } //! Initialize a public key using begin/end iterators to byte data. template <typename T> void Set(const T pbegin, const T pend) { int len = pend == pbegin ? 0 : GetLen(pbegin[0]); if (len && len == (pend - pbegin)) memcpy(vch, (unsigned char*)&pbegin[0], len); else Invalidate(); } //! Construct a public key using begin/end iterators to byte data. template <typename T> CPubKey(const T pbegin, const T pend) { Set(pbegin, pend); } //! Construct a public key from a byte vector. explicit CPubKey(const std::vector<unsigned char>& _vch) { Set(_vch.begin(), _vch.end()); } //! Simple read-only vector-like interface to the pubkey data. unsigned int size() const { return GetLen(vch[0]); } const unsigned char* data() const { return vch; } const unsigned char* begin() const { return vch; } const unsigned char* end() const { return vch + size(); } const unsigned char& operator[](unsigned int pos) const { return vch[pos]; } //! Comparator implementation. friend bool operator==(const CPubKey& a, const CPubKey& b) { return a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) == 0; } friend bool operator!=(const CPubKey& a, const CPubKey& b) { return !(a == b); } friend bool operator<(const CPubKey& a, const CPubKey& b) { return a.vch[0] < b.vch[0] || (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0); } //! Implement serialization, as if this was a byte vector. template <typename Stream> void Serialize(Stream& s) const { unsigned int len = size(); ::WriteCompactSize(s, len); s.write((char*)vch, len); } template <typename Stream> void Unserialize(Stream& s) { unsigned int len = ::ReadCompactSize(s); if (len <= PUBLIC_KEY_SIZE) { s.read((char*)vch, len); } else { // invalid pubkey, skip available data char dummy; while (len--) s.read(&dummy, 1); Invalidate(); } } //! Get the KeyID of this public key (hash of its serialization) CKeyID GetID() const { return CKeyID(Hash160(vch, vch + size())); } //! Get the 256-bit hash of this public key. uint256 GetHash() const { return Hash(vch, vch + size()); } /* * Check syntactic correctness. * * Note that this is consensus critical as CheckSig() calls it! */ bool IsValid() const { return size() > 0; } //! fully validate whether this is a valid public key (more expensive than IsValid()) bool IsFullyValid() const; //! Check whether this is a compressed public key. bool IsCompressed() const { return size() == COMPRESSED_PUBLIC_KEY_SIZE; } /** * Verify a DER signature (~72 bytes). * If this public key is not fully valid, the return value will be false. */ bool Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const; /** * Check whether a signature is normalized (lower-S). */ static bool CheckLowS(const std::vector<unsigned char>& vchSig); //! Recover a public key from a compact signature. bool RecoverCompact(const uint256& hash, const std::vector<unsigned char>& vchSig); //! Turn this public key into an uncompressed public key. bool Decompress(); //! Derive BIP32 child pubkey. bool Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const; }; struct CExtPubKey { unsigned char nDepth; unsigned char vchFingerprint[4]; unsigned int nChild; ChainCode chaincode; CPubKey pubkey; friend bool operator==(const CExtPubKey &a, const CExtPubKey &b) { return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], sizeof(vchFingerprint)) == 0 && a.nChild == b.nChild && a.chaincode == b.chaincode && a.pubkey == b.pubkey; } void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const; void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]); bool Derive(CExtPubKey& out, unsigned int nChild) const; void Serialize(CSizeComputer& s) const { // Optimized implementation for ::GetSerializeSize that avoids copying. s.seek(BIP32_EXTKEY_SIZE + 1); // add one byte for the size (compact int) } template <typename Stream> void Serialize(Stream& s) const { unsigned int len = BIP32_EXTKEY_SIZE; ::WriteCompactSize(s, len); unsigned char code[BIP32_EXTKEY_SIZE]; Encode(code); s.write((const char *)&code[0], len); } template <typename Stream> void Unserialize(Stream& s) { unsigned int len = ::ReadCompactSize(s); unsigned char code[BIP32_EXTKEY_SIZE]; if (len != BIP32_EXTKEY_SIZE) throw std::runtime_error("Invalid extended key size\n"); s.read((char *)&code[0], len); Decode(code); } }; /** Users of this module must hold an ECCVerifyHandle. The constructor and * destructor of these are not allowed to run in parallel, though. */ class ECCVerifyHandle { static int refcount; public: ECCVerifyHandle(); ~ECCVerifyHandle(); }; #endif // BITCOIN_PUBKEY_H
[ "“[email protected]”" ]
55218b9ad4b57575a6e731c0f35ccc3649b4dfaa
9554a5ea57823a76c25132fcfdfd20de324d9bd8
/includes/common/windows/MutexWindows.h
5dbbb4763498574fdfa7b499c76757ef2f9924cc
[]
no_license
suchet-q/epic_win
23b33fc7042ec1b02cd8245e7926178bec0a9957
f35756d3566af30215005873f4a3de6996464658
refs/heads/master
2021-01-23T21:35:04.696611
2013-11-24T22:23:08
2013-11-24T22:23:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
258
h
#pragma once #include "windows/WindowsInclude.h" class MutexWindows { CRITICAL_SECTION _mutex; bool _init; public: MutexWindows(void); ~MutexWindows(void); bool initMutex(); bool Lock(); bool Unlock(); bool destroyMutex(); };
576de9dbd50b8c8ba85867df15df9bf0edc31013
14be5228d52d9a7e9db16de48d4b262ce33d6257
/Anno_2016_2017/Esercizi_2016_11_24/Esercizio_1.cpp
87d559974126b2f6c192de7694cc5e8618d73883
[]
no_license
a-pucci/GameDev-1anno-2016-2017
d7625be64b1878ab4e2155aea35c2f141265190a
0b1298c4524864db30f62c7a6483554786a64fe8
refs/heads/master
2021-06-20T13:36:53.455226
2019-02-26T20:33:21
2021-04-02T18:03:00
74,010,542
0
0
null
null
null
null
UTF-8
C++
false
false
844
cpp
#include <iostream> #include <string> using namespace std; int main() { int playerScore[10]; cout << "\t\tLEADERBOARD\n"; for(int i = 0; i < 10; i++) { cout << "\nInserire punteggio ottenuto dal Giocatore " << i+1 << ": "; cin >> playerScore[i]; } cout << "\n\n\tLISTA PUNTEGGI: " << endl; for(int i = 0; i < 10; i++) { cout << "\n Giocatore " << i+1 << " - " << playerScore[i] << endl; } cout << "\n\n\tLISTA PUNTEGGI INVERSI: " << endl; for(int i = 9; i >= 0; i--) { cout << "\n Giocatore " << i+1 << " - " << playerScore[i]; } int sum; cout << "\n\n\tMEDIA PUNTEGGI: " << endl; for(int i = 0; i < 10; i++) { sum += playerScore[i]; } int media = sum/10; cout << "\nLa media dei punteggi e': " << media << endl; }