blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
95bb0bc2d84a200b21ba306fa9f4efa55e647b44
408886ea75550f3c7c7ef807255d1209f1f12e15
/Reader.h
aef1c802c252c1e15bf5329cdb3ea9f7b15f9150
[]
no_license
Etav99/SBD1
38fe7a1635100502d64a687ccd40ed7a34de894f
e1aa0adfb38c8e510ec20fb56589c7afeed1ca5c
refs/heads/main
2023-04-29T06:29:42.378694
2021-05-17T16:40:20
2021-05-17T16:40:20
368,253,397
0
0
null
null
null
null
UTF-8
C++
false
false
482
h
#pragma once #include "Record.h" #include <fstream> #include <iostream> #include <string> using namespace std; struct Reader { string fileName; int blockStartIndex; int blockEndIndex; int bufferSize; int lastRecordIndex; bool bufferEmpty; int *readNo; Record* buffer; Reader(string fileName, int bufferSize); Reader(string fileName, int bufferSize, int* readNo); void updateSize(); bool loadBlock(int blockIndex); Record* readRecord(int recordNumber); ~Reader(); };
[ "etavpl@gmail.com" ]
etavpl@gmail.com
c6b76a8b44a20ed0560c5e713c6f9b802de6ed68
fb108bb00285ad633d074479d6e4cb5d3ee087a7
/Source/Stub.cpp
2b5c87019c26ae925a0afe9e1da75c61f0791ffd
[]
no_license
roushk/Brimstone-Game-Engine
2ace63d7f494d4942706f23e63cb463586192ff5
e2463a58082cd6a4a824b9b90a5c21647ebcecec
refs/heads/main
2023-08-04T21:36:15.696338
2023-08-04T20:13:50
2023-08-04T20:13:50
160,778,525
1
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
//*************************************************************************** // Filename: Stub.cpp // Author : Coleman Jonas // Description: Use this as a basic layout for all c++ files in the proj. //***************************************************************************
[ "coleman.jonas@gmail.com" ]
coleman.jonas@gmail.com
14b973f2ad741405fe301e9b39a007bf37b51825
d4c720f93631097ee048940d669e0859e85eabcf
/chrome/browser/ui/webui/signin/turn_sync_on_helper_browsertest.cc
f8342e10a795dee77cdd1d9516de91ea74328b8d
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
3b920d87437d9293f654de1f22d3ea341e7a8b55
refs/heads/webnn
2023-03-21T03:20:15.377034
2023-01-25T21:19:44
2023-01-25T21:19:44
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
9,288
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 <memory> #include <vector> #include "base/callback_forward.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "build/buildflag.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_browser_test_base.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/webui/signin/turn_sync_on_helper.h" #include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace { class Delegate : public TurnSyncOnHelper::Delegate { public: enum class BlockingStep { kNone, kMergeData, kEnterpriseManagement, kSyncConfirmation, kSyncDisabled, }; struct Choices { absl::optional<signin::SigninChoice> merge_data_choice = signin::SIGNIN_CHOICE_CONTINUE; absl::optional<signin::SigninChoice> enterprise_management_choice = signin::SIGNIN_CHOICE_CONTINUE; absl::optional<LoginUIService::SyncConfirmationUIClosedResult> sync_optin_choice = LoginUIService::SYNC_WITH_DEFAULT_SETTINGS; absl::optional<LoginUIService::SyncConfirmationUIClosedResult> sync_disabled_choice = absl::nullopt; }; using SyncConfirmationCallback = base::OnceCallback<void(LoginUIService::SyncConfirmationUIClosedResult)>; using CallbackVariant = absl::variant<signin::SigninChoiceCallback, SyncConfirmationCallback>; explicit Delegate(Choices choices) : choices_(choices), run_loop_(std::make_unique<base::RunLoop>()) {} ~Delegate() override = default; // TurnSyncOnHelper::Delegate: void ShowLoginError(const SigninUIError& error) override { NOTREACHED(); } void ShowMergeSyncDataConfirmation( const std::string& previous_email, const std::string& new_email, signin::SigninChoiceCallback callback) override { AdvanceFlowOrCapture(BlockingStep::kMergeData, std::move(callback)); } void ShowEnterpriseAccountConfirmation( const AccountInfo& account_info, signin::SigninChoiceCallback callback) override { AdvanceFlowOrCapture(BlockingStep::kEnterpriseManagement, std::move(callback)); } void ShowSyncConfirmation(SyncConfirmationCallback callback) override { AdvanceFlowOrCapture(BlockingStep::kSyncConfirmation, std::move(callback)); } void ShowSyncDisabledConfirmation( bool is_managed_account, SyncConfirmationCallback callback) override { AdvanceFlowOrCapture(BlockingStep::kSyncDisabled, std::move(callback)); } void ShowSyncSettings() override { NOTREACHED(); } void SwitchToProfile(Profile* new_profile) override { NOTREACHED(); } BlockingStep blocking_step() const { return blocking_step_; } base::WeakPtr<Delegate> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } void WaitUntilBlock() { DCHECK(run_loop_); run_loop_->Run(); // After the wait ends, reset the `run_loop_` to wait for the next choice. run_loop_.reset(); run_loop_ = std::make_unique<base::RunLoop>(); } // Call this function when the delegate is blocked, with new `choices` that // should now unblock it. void UpdateChoicesAndAdvanceFlow(Choices choices) { auto blocking_step = blocking_step_; ASSERT_NE(BlockingStep::kNone, blocking_step) << "UpdateChoicesAndAdvanceFlow() expects to be called while the " "delegate is blocked."; choices_ = choices; blocking_step_ = BlockingStep::kNone; switch (blocking_step) { case BlockingStep::kNone: NOTREACHED(); break; case BlockingStep::kMergeData: ASSERT_TRUE(choices_.merge_data_choice.has_value()); std::move(absl::get<signin::SigninChoiceCallback>(blocking_callback_)) .Run(*choices_.merge_data_choice); break; case BlockingStep::kEnterpriseManagement: ASSERT_TRUE(choices_.enterprise_management_choice.has_value()); std::move(absl::get<signin::SigninChoiceCallback>(blocking_callback_)) .Run(*choices_.enterprise_management_choice); break; case BlockingStep::kSyncConfirmation: ASSERT_TRUE(choices_.sync_optin_choice.has_value()); std::move(absl::get<SyncConfirmationCallback>(blocking_callback_)) .Run(*choices_.sync_optin_choice); break; case BlockingStep::kSyncDisabled: ASSERT_TRUE(choices_.sync_disabled_choice.has_value()); std::move(absl::get<SyncConfirmationCallback>(blocking_callback_)) .Run(*choices_.sync_disabled_choice); break; } } private: void AdvanceFlowOrCapture(BlockingStep step, CallbackVariant callback) { switch (step) { case BlockingStep::kNone: NOTREACHED(); break; case BlockingStep::kMergeData: if (!choices_.merge_data_choice.has_value()) break; std::move(absl::get<signin::SigninChoiceCallback>(callback)) .Run(*choices_.merge_data_choice); return; case BlockingStep::kEnterpriseManagement: if (!choices_.enterprise_management_choice.has_value()) break; std::move(absl::get<signin::SigninChoiceCallback>(callback)) .Run(*choices_.enterprise_management_choice); return; case BlockingStep::kSyncConfirmation: if (!choices_.sync_optin_choice.has_value()) break; std::move(absl::get<SyncConfirmationCallback>(callback)) .Run(*choices_.sync_optin_choice); return; case BlockingStep::kSyncDisabled: if (!choices_.sync_disabled_choice.has_value()) break; std::move(absl::get<SyncConfirmationCallback>(callback)) .Run(*choices_.sync_disabled_choice); return; } blocking_step_ = step; blocking_callback_ = std::move(callback); DCHECK(run_loop_); run_loop_->Quit(); } Choices choices_; BlockingStep blocking_step_ = BlockingStep::kNone; CallbackVariant blocking_callback_; std::unique_ptr<base::RunLoop> run_loop_; base::WeakPtrFactory<Delegate> weak_ptr_factory_{this}; }; } // namespace class TurnSyncOnHelperBrowserTest : public SigninBrowserTestBase {}; #if BUILDFLAG(IS_CHROMEOS_LACROS) // TODO(https://crbug.com/1344165): Support resetting the primary account. #define MAYBE_PrimaryAccountResetAfterSyncOptInFlowAborted \ DISABLED_PrimaryAccountResetAfterSyncOptInFlowAborted #else #define MAYBE_PrimaryAccountResetAfterSyncOptInFlowAborted \ PrimaryAccountResetAfterSyncOptInFlowAborted #endif // Tests that aborting a Sync opt-in flow started with a secondary account // reverts the primary account to the initial one. IN_PROC_BROWSER_TEST_F(TurnSyncOnHelperBrowserTest, MAYBE_PrimaryAccountResetAfterSyncOptInFlowAborted) { Profile* profile = browser()->profile(); auto accounts_info = SetAccounts({"primary@gmail.com", "secondary@gmail.com"}); auto primary_account_id = accounts_info[0].account_id; auto secondary_account_id = accounts_info[1].account_id; ASSERT_EQ(signin::ConsentLevel::kSignin, signin::GetPrimaryAccountConsentLevel(identity_manager())); ASSERT_EQ(primary_account_id, identity_manager()->GetPrimaryAccountId( signin::ConsentLevel::kSignin)); base::RunLoop run_loop; Delegate::Choices choices = {.sync_optin_choice = absl::nullopt}; auto owned_delegate = std::make_unique<Delegate>(choices); base::WeakPtr<Delegate> delegate = owned_delegate->GetWeakPtr(); new TurnSyncOnHelper( profile, signin_metrics::AccessPoint::ACCESS_POINT_UNKNOWN, signin_metrics::PromoAction::PROMO_ACTION_NO_SIGNIN_PROMO, signin_metrics::Reason::kUnknownReason, secondary_account_id, TurnSyncOnHelper::SigninAbortedMode::KEEP_ACCOUNT, std::move(owned_delegate), run_loop.QuitClosure()); delegate->WaitUntilBlock(); EXPECT_EQ(Delegate::BlockingStep::kSyncConfirmation, delegate->blocking_step()); EXPECT_EQ(signin::ConsentLevel::kSignin, signin::GetPrimaryAccountConsentLevel(identity_manager())); EXPECT_EQ(secondary_account_id, identity_manager()->GetPrimaryAccountId( signin::ConsentLevel::kSignin)); choices.sync_optin_choice = LoginUIService::ABORT_SYNC; delegate->UpdateChoicesAndAdvanceFlow(choices); // The flow should complete and destroy the delegate and TurnSyncOnHelper. run_loop.Run(); EXPECT_FALSE(delegate); // Account consistency (via `SigninManager`) should kick in via a posted task // and reset the PrimaryAccount. base::RunLoop().RunUntilIdle(); EXPECT_EQ(signin::ConsentLevel::kSignin, signin::GetPrimaryAccountConsentLevel(identity_manager())); EXPECT_EQ(primary_account_id, identity_manager()->GetPrimaryAccountId( signin::ConsentLevel::kSignin)); }
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
0be4c096ae5acf01e389936881d9f71196aaf33a
2e8c1b6f181c8ea440107ca82156ba38fd239037
/hello-world/build/libxpcc/generated_platform/driver/adc/stm32/adc_interrupt_2.cpp
40820ec845a1fefb874c8f68f26a3944704d65a7
[]
no_license
zzzdeb/roboter
5b4082fc28565c7b8f90493431c6899fc6c054aa
ee1d9001b892cd53386a6266b82b3c86f04fdd62
refs/heads/master
2020-06-10T09:31:21.246821
2016-12-08T21:08:41
2016-12-08T21:08:41
75,973,908
0
0
null
null
null
null
UTF-8
C++
false
false
530
cpp
// coding: utf-8 /* Copyright (c) 2011, Roboterclub Aachen e.V. * All Rights Reserved. * * The file is part of the xpcc library and is released under the 3-clause BSD * license. See the file `LICENSE` for the full license governing this code. */ // ---------------------------------------------------------------------------- #include "adc_interrupt_2.hpp" // ---------------------------------------------------------------------------- xpcc::stm32::AdcInterrupt2::Handler xpcc::stm32::AdcInterrupt2::handler(xpcc::dummy);
[ "zolboo.deb@gmail.com" ]
zolboo.deb@gmail.com
25e86077259d9073627abab55c8acefd5ed0e411
a62342d6359a88b0aee911e549a4973fa38de9ea
/0.6.0.3/Internal/SDK/ST_QuestReward_Generator_structs.h
78ddb28ccaf0bbbe528340178e932e97a8d1294f
[]
no_license
zanzo420/Medieval-Dynasty-SDK
d020ad634328ee8ee612ba4bd7e36b36dab740ce
d720e49ae1505e087790b2743506921afb28fc18
refs/heads/main
2023-06-20T03:00:17.986041
2021-07-15T04:51:34
2021-07-15T04:51:34
386,165,085
0
0
null
null
null
null
UTF-8
C++
false
false
1,864
h
#pragma once // Name: Medieval Dynasty, Version: 0.6.0.3 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Script Structs //--------------------------------------------------------------------------- // UserDefinedStruct ST_QuestReward_Generator.ST_QuestReward_Generator // 0x00C8 struct FST_QuestReward_Generator { struct FST_GenerateItemsForQuest_Generator Items_61_0EF38CEA4E8D860F984909914B92866D; // 0x0000(0x0018) (Edit, BlueprintVisible, HasGetValueTypeHash) int Liking_45_6F7DB08B49144B1A745A5E8BCBCC35D1; // 0x0018(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int Affection_46_50E0E2134B0085B095732FB24137EF9E; // 0x001C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int DynastyReputation_48_5D55F5544DF91AF2E861C49243525A08; // 0x0020(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) unsigned char UnknownData_K683[0x4]; // 0x0024(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY) TMap<TEnumAsByte<E_Skills_E_Skills>, int> SkillExperience_43_1A39A82F454A6F275541FD9BD5545D5D; // 0x0028(0x0050) (Edit, BlueprintVisible) TMap<TEnumAsByte<E_TechnologyTypes_E_TechnologyTypes>, int> TechnologyPoints_56_48AC28C745ED750A805FDEAF45E7B6AF; // 0x0078(0x0050) (Edit, BlueprintVisible) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
c93ef7ebf7dad7b05b29dfaffaf72f4161013faf
d6d13467f1591d510c9f3f18bffefad250980195
/Source.cpp
0ea8a21b3ce515635dce4fbd0339c767aed566db
[]
no_license
polinafr/CExam
b591dd5e5e1e69e3c507812fecb67b52b021a19c
ec56f963d28b355a0c253d8950b05496fc554b85
refs/heads/master
2023-06-09T03:42:34.814692
2021-06-28T08:44:30
2021-06-28T08:44:30
380,830,468
0
0
null
null
null
null
UTF-8
C++
false
false
915
cpp
#include "OurString.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #define FirstTestString "Gaudeamus igitur, Iuvenes dum sumus" #define EmptyString "" #define SECOND_TEST_STRING "Draco dormiens nunquam tititlandus" void main() { char* str1 = (char*)malloc(strlen(FirstTestString)); strcpy_s(str1, strlen(FirstTestString), FirstTestString); String* FString = CreateString(str1); printf(FString->text); printf("%d", FString->len); String* SecondTestString = CreateString(SECOND_TEST_STRING); String* ErrorString = CreateString(EmptyString); printf("%d", ErrorString->len); printf("%d", IsEmpty(ErrorString)); printf("%d", IsEmpty(FString)); printf("%d", IsEmpty(NULL)); printf("%d", GetStringLength(ErrorString)); printf("%d", GetStringLength(FString)); //printf("%d", CompareString(NULL, )); printf("%d", DeleteString(FString)); printf("%d", DeleteString(ErrorString)); }
[ "Zapadniki1836" ]
Zapadniki1836
df67bd89fc870f5e72311209e0934acd9aafd4ec
4f8f944062e3841892c19e5baef16a50ffd88834
/srm444/RotatingTriganles.cpp
3514cd382794248fe0c7d711336a76ffdb94e2ab
[]
no_license
triplekiller/mytopcoder
2e56628c8cf185f7737a5b7d010f510e3945c2f8
09d9a3b0aee24ee2fab2fce089fd6a6c13b81d6d
refs/heads/master
2021-01-17T12:34:59.386276
2013-08-10T03:19:44
2013-08-10T03:19:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,561
cpp
class RatatingTriangles { char m[51][51]; int N,M; void rot() { char t[51][51]; memset(t,' ',sizof(t)); int i,j; for( i=0;i<N;i++) for( j=0;j<M;j++) t[j][N-i-1]=m[i][j]; swap(N,M); memcpy(m,t,sizeof(m)); } int getOne(int i, int j) { int ret=0; int len; for( len=1;;len++) { int bi=i,bj=j-len+1,ti=i-len+1,tj=j; if(bj<0 || ti<0) return ret; if(bi !=N-1 && m[bi+1][bj]=='#') return ret; if(tj !=M-1 && m[ti][tj+1]=='#') return ret;; int k,sum=0; for( k=0;k<len;k++) { if(m[bi][bj]=='.') return ret; if(m[bi][bj]=='/') sum++; bi--; bj++; } if(sum==len) ret++; } return ret; } int getTwo(int i,int j) { int ret=0; int len; for(len=1;;len++) { int li=i, lj=j-len+1, ri=i, rj=j+len, bi=i-len+1; if( lj<0 || rj >= M || bi<0) return ret; if( i!=N-1 && (m[i+1][lj]=='#' || m[i+1][rj]=='#')) return ret; int k,sum=0; for( k=0;k<len;k++) { if(m[li][lj]=='.' || m[ri][rj]=='.') return ret; if(m[li][lj]=='/' && m[ri][rj]=='/') sum++; li--, ri--, lj++, rj--; } if( sum==len ) ret++; } return ret; } public: int count(vector<string> grid) { int i,j; N=grid.size(); M=grid[0].size(); memset(m,' ',sizeof(mm)); for( i=0;i<N;i++) for(j=0;j<M;j++) m[i][j]=grid[i][j]; int k; int sum=0; for(k=0;k<4;k++) { rot(); for(i=0;i<N;i++) { for(j=0;j<M;j++) { sum+=getOne(i,j); sum+=getTwo(i,j); } } } return sum; } };
[ "yinyinbigdata@gmail.com" ]
yinyinbigdata@gmail.com
2c633bfde7215a3045ee30ed75a1b9e8aee6d998
15a8062b4c0d60b6ff2edceaad20cd065ba94e3e
/homeworks/04-vectors/vectors.h
0dceefb990c7f47085b4d4880f0fa39959edc3ce
[]
no_license
acc-cosc-1337-fall-2018/acc-cosc-1337-fall-2018-NigelChilders
545c630b6a4af042ba1e4d0c68026857a59c2c5d
6d3ade3a578ceae3bfc69681431b7abf0b269ff8
refs/heads/master
2021-08-18T05:39:00.988026
2018-12-13T01:35:53
2018-12-13T01:35:53
147,739,946
0
0
null
null
null
null
UTF-8
C++
false
false
2,128
h
#include <string> #include <vector> #include <algorithm> using std::vector; using std::string; /* Write a value return function with a vector of ints list reference parameter that returns the maximum value of the list @param numbers is a reference to a vector of integers @return the max value in the vector */ int get_max_from_vector(vector<int>& numbers); /* Write a value function sum_of_squares with a vector of ints list reference parameter that computes the sum of the squares of the numbers in the vector. For example, a vector of ints with values 2, 3, 4 should return 4+9+16 which is 29. WRITE THE PARAM AND RETURN COMMENTS BELOW(SEE MY EXAMPLE ABOVE) */ //write function prototype int get_sum_of_squares(vector<int>& numbers); /* Write a value-return function replace with parameters reference to vector of strings , old string, and new_val string that replaces all occurences of old string with new_val string in a vector of strings @param strings reference to a vector of strings (read/write) @param old reference to a string read only @param new_val reference to a string read only */ void replace(vector<string>& strings, const string& old, const string& new_val); /* Write a function named is_prime with an integer parameter that given a number returns true if prime or false if not prime @param number: Any whole number @return: bool if prime False if not */ //write prototype here bool is_prime(int number); /* Write a a function named vector_of_primes with an integer parameter that Given a number returns all the prime numbers up to the number Example given number 10 returns '2,3,5,7,' @param int integer value @return vector of ints containing prime values up to a value Psuedocode: Create a variable vector of ints named primes loop from 1 to the value of n in the loop call is_prime function you created with an argument of the current vector value at the current loop index if the return value of is_prime is true add the value to the primes vector make sure to return vector of ints primes after loop exits */ //write function prototype here vector<int> vector_of_primes(int n);
[ "nigel.childers@g.austincc.edu" ]
nigel.childers@g.austincc.edu
c4d534a055813b557d0a0738ba41566497a5624f
cb5df704f9468c656b369389240c80d23e9a5d1e
/MatlabDemo/MatlabDemo/Sourcecpp.cpp
d0bb703546a7b712be9b4f51ea992d0baa0c22a5
[]
no_license
acdobdler/Programming-Finance
83ce91b8496a9c265bbb535b5870f401db230000
05fc4267e968d6fdf5ba515332723609409d20b2
refs/heads/master
2021-11-24T17:44:01.941251
2017-12-12T02:11:57
2017-12-12T02:11:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
988
cpp
#include<yvals.h> #if(_MSC_VER>=1600) #define _STDC_utf_16__ #endif #include"mex.h" #include<engine.h> #include<iostream> #pragma comment(lib,"libmx.lib") #pragma comment(lib,"libmex.lib") #pragma comment(lib,"libeng.lib") using namespace std; int main() { Engine *ep; ep = engOpen(NULL); if (ep == NULL) { cout << "ERROR:engine open failed" << endl; exit(1); } int size1 = 100; double *step = new double[size1]; int size2 = 100; double *value = new double[size2]; for (int i = 0; i < 100; i++) { step[i] = i; value[i] = sin(i); } mxArray *A; A = mxCreateDoubleMatrix(1, 100, mxREAL); memcpy((void*)mxGetPr(A), (void *)step, sizeof(double) * 100); mxArray *B; B = mxCreateDoubleMatrix(1, 100, mxREAL); memcpy((void*)mxGetPr(B), (void *)value, sizeof(double) * 100); engPutVariable(ep, "x", A); engPutVariable(ep, "y", B); engEvalString(ep, "plot(x,y)"); system("pause"); mxDestroyArray(A); engEvalString(ep, "close;"); engClose(ep); return 0; }
[ "jiahaotang1994@gmail.com" ]
jiahaotang1994@gmail.com
979da486cf43565a7f2de7be4f52f30b0507513f
87a600d36a5757969ead7e235c93e3530d72b43a
/abm_product/public/SHMData_A.h
657957ad49362b79ae5b4c505fce493f562b604f
[]
no_license
xkmld419/learning
3c3cad407d03bf693bcd863794cca7fb8a5df99a
128ffa1496c43c36b83f266522bd49b28184499f
refs/heads/master
2023-07-12T16:54:50.647834
2021-08-21T15:41:42
2021-08-21T15:41:42
45,075,836
1
0
null
null
null
null
GB18030
C++
false
false
21,392
h
/*VER: 1*/ // Copyright (c) 2005,联创科技股份有限公司电信事业部 // All rights reserved. #ifndef SHMDATA_A_H_HEADER_INCLUDED_BDBB63C4 #define SHMDATA_A_H_HEADER_INCLUDED_BDBB63C4 ////说明:可按条重用的内存分配 //// 使用一个数组记录删除的项,分配时先分配空闲的,再分配原来删除的项 ////优点:分配快,且分配时不会影响删除,只要分配做到单入,删除做到单入,分配和删除操作可以同时进行,不需要锁。 ////不足:返回总条数以及对在用数据项导出时需要进行复杂的运算才能得到结果。 ////zhangap ////最后修改时间:2010-01-29 //unsigned int i = (* m_piUsedSE ); //if(i!=0 && 0== m_pIArray[i]){ // ////判断到还没分配满过 // //} //if( 0== m_pIArray[(* m_piTotalSE)] ){ // ////判断到还没有删除满过 // //} //if( 0 == (*m_piDelOver) ){ // ////也是判断到还没有删除满过 //} #include "HashList.h" #include "SHMAccess.h" #include <iostream> #include <unistd.h> using namespace std; #define ATTACH_DATA_A(X, Y, Z) \ X = new SHMData_A<Y> (Z); \ if (!(X)) { \ freeAll (); \ THROW(MBC_UserInfo+1); \ } \ if (!(X->exist())) { \ m_bAttached = false; \ } //## 共享内存数据区模板类,要求存放的数据的 //## 每个元素的大小不小于32个字节,如果元素的 //## 大小小于32个字节,会出现问题 template <class T> class SHMData_A : public SHMAccess { public: typedef T value_type; class Iteration { private: unsigned int m_iCurOffset; SHMData_A<T> * m_pDataA; unsigned char *pData; unsigned int m_iStateCnt; private: unsigned int getInfo() { /// '0'表示数据项, '1'表示空闲项 ////返回里面有状态的总条数 unsigned int uiTemp = (*(m_pDataA->m_piTotalSE)); pData = new unsigned char[uiTemp]; memset(pData, '0', sizeof(unsigned char)*uiTemp ); unsigned int i = (*(m_pDataA->m_piUsedSE)); unsigned int j =0; if(i!=0 && 0==m_pDataA->m_pIArray[i]){ ////还没分配满过,删除项直接从0开始,返回值返回实际最大分配项所在的偏移 uiTemp = i; i=0; for(; i != (*(m_pDataA->m_piDeledSE)); i++){ if( i>= uiTemp ){ ////可能在这个中间其他进程进行了大量数据的分配和释放操作 break; } j = m_pDataA->m_pIArray[i]; if( 0== j){ j = i; } pData[j]++; } return uiTemp; } for(; i != (*(m_pDataA->m_piDeledSE)); i++){ if( i>= uiTemp ){ i = 0; } j = m_pDataA->m_pIArray[i]; if( 0== j){ j = i; } if( '0' == pData[j] ){ ////此条记录置成空闲 pData[j] = '1'; }else{ ////此条记录出现多次删除 pData[j]++; } } return uiTemp; } public: void close(){ if(pData){ delete [] pData; pData =0;} m_iCurOffset = 1; m_iStateCnt = 0; } bool next(T & tOut, unsigned int &uiOffsetOut) { if(!pData){ m_iStateCnt = getInfo(); } if(pData && m_iCurOffset>0){ while( m_iCurOffset< m_iStateCnt ){ if('0' == pData[m_iCurOffset] ){ uiOffsetOut = m_iCurOffset; tOut = m_pDataA->m_pPointer[ m_iCurOffset ]; m_iCurOffset++; return true; } m_iCurOffset++; } return false; } return false; } bool nextBatch(unsigned int uiMax, T tOut[], unsigned int &iOutCnt) { if(!pData){ m_iStateCnt = getInfo(); } unsigned int iTotal = (*(m_pDataA->m_piTotalSE)); unsigned int iCnt=0; if(pData && m_iCurOffset>0 && uiMax){ while(iCnt<uiMax && m_iCurOffset < m_iStateCnt ){ if('0' == pData[m_iCurOffset] ){ tOut[iCnt] = m_pDataA->m_pPointer[ m_iCurOffset ]; iCnt++; } m_iCurOffset++; } if(iCnt){ iOutCnt = iCnt; return true; } iOutCnt = 0; return false; } return false; } Iteration ( unsigned int iCur, SHMData_A<T> * pSHMDataA): m_iCurOffset(iCur), m_pDataA(pSHMDataA),pData(0),m_iStateCnt(0) {} Iteration (const Iteration & right) { m_iCurOffset = right.m_iCurOffset; m_pDataA = right.m_pDataA; pData = 0; m_iStateCnt = 0; } ~Iteration () { if(pData) { delete [] pData; pData =0;} } }; Iteration getIteration () { return Iteration ( 1, this); } public: friend class Iteration; SHMData_A(char *shmname, bool bShm = true); SHMData_A(long shmkey); ~SHMData_A(); operator T *(); void create( unsigned int itemnumber) ; void reset(); bool revoke( unsigned int uiOffset); void showDetail(); bool checkHealth(); unsigned int kick(unsigned int uiBeginOff, int iNxtOffset, int iExpOffset, const char * sDate, unsigned int * o_uiKickSelf, bool * o_bKickSelf ); unsigned int kickAndRevoke(unsigned int uiBeginOff, int iNxtOffset, int iExpOffset, const char * sDate, int iChkOffset1, int iChkOffset2, unsigned int * o_uiKickSelf , bool * o_bKickSelf); unsigned int malloc(); unsigned int getCount(); unsigned int getTotal(); unsigned long getDelTotal(); unsigned int getDelFree (); time_t getLoadTime(); unsigned int getMemSize(); unsigned int getUsedSize(); unsigned long getMemAdress(); unsigned long getRealSize(); inline void checkSafe(){ if(0 == *m_piFlag) return; while(*m_piFlag){ usleep(102400); } }; bool setRevokeFlag( unsigned int iFlag){ if(m_poSHM && m_piFlag){ *m_piFlag = iFlag; return true; } return false; }; bool ifSetRevokeFlag(){ if( *m_piFlag ) return true; return false; }; private: void open(); protected : unsigned int *m_piTotal; unsigned int *m_piUsed; T *m_pPointer; ///内存结构模式ID,用作兼容性,老版本是0,第2版有1(按行)和2(按块) 等取值。 unsigned int *m_piVersion; unsigned int *m_piTotalSE; unsigned int *m_piUsedSE; unsigned int *m_piDeledSE; unsigned int *m_piFlag; ///如果置位,表示在做内存清理操作,此时所有其他操作要暂停 unsigned int *m_piDelOver; ///记录删除个数达到total的次数 unsigned int *m_pIArray; }; template <class T> SHMData_A<T>::SHMData_A(char *shmname, bool bShm) : SHMAccess (shmname, bShm) { if (m_poSHM){ open (); if( 1 != *m_piVersion ) THROW(MBC_SHMData+1); } } template <class T> SHMData_A<T>::SHMData_A(long shmkey) : SHMAccess (shmkey) { if (m_poSHM){ open (); if( 1 != *m_piVersion ) THROW(MBC_SHMData+1); } } //##ModelId=42441AD801E8 template <class T> SHMData_A<T>::~SHMData_A() { } template <class T> SHMData_A<T>::operator T *() { return m_pPointer; } template <class T> void SHMData_A<T>::create(unsigned int itemnumber) { if( sizeof(T)< 16 ) THROW(MBC_SHMData+2); SHMAccess::create((itemnumber+2)* (sizeof(T)+sizeof(int)) ); open (); ////老程序连上新内存让其无法分配空间 *m_piTotal = 2; *m_piUsed = 2; *m_piVersion = 1; *m_piTotalSE = itemnumber + 1 ; m_pIArray =(unsigned int *) &m_pPointer[(*m_piTotalSE)+1]; *m_piUsedSE = 1; *m_piDeledSE= 0; if( sizeof(T)< 32 ){ ///1个结构体放不下控制信息,此时让下标从2开始,到itemnumber+1结束 ///平时下标是从1到itemnumber结束 *m_piUsedSE = 2; *m_piDeledSE = 1; m_pIArray[0] = itemnumber+1; } } template <class T> void SHMData_A<T>::reset() { *m_piUsedSE = 1; *m_piDeledSE= 0; memset( m_pIArray, 0, (*m_piTotalSE) * sizeof(int) ); *m_piDelOver =0; if( sizeof(T)< 32 ){ ///1个结构体放不下控制信息,此时让下标从2开始,到itemnumber+1结束 ///平时下标是从1到itemnumber结束 *m_piUsedSE = 2; *m_piDeledSE = 1; m_pIArray[0] = *m_piTotalSE;///itemnumber+1; } } template <class T> unsigned int SHMData_A<T>::malloc() { if (*m_piDeledSE == *m_piUsedSE) return 0; unsigned int uiRet = m_pIArray[(*m_piUsedSE)]; if(!uiRet) uiRet = (*m_piUsedSE); (*m_piUsedSE)++; if( (*m_piUsedSE) >= (*m_piTotalSE) ) (*m_piUsedSE) = 0 ; return uiRet; } template <class T> void SHMData_A<T>::open() { m_piTotal = (unsigned *)((char *)(*m_poSHM)) + 1; m_piUsed = m_piTotal + 1; m_pPointer = (T *)( (char *)(*m_poSHM)); m_piVersion = m_piTotal - 1; m_piTotalSE = m_piTotal + 2; m_piFlag = m_piTotal + 3; m_piUsedSE = m_piTotal + 4; m_piDeledSE = m_piTotal + 5; m_piDelOver = m_piTotal + 6; if( (*m_piTotalSE) ) { m_pIArray =(unsigned int *) &m_pPointer[(*m_piTotalSE)+1]; }else{ m_pIArray = 0; } } template <class T> unsigned int SHMData_A<T>::getCount() { unsigned int iCnt = 0; if( (*m_piUsedSE) > (*m_piDeledSE) ){ iCnt = ( (*m_piUsedSE) - (*m_piDeledSE) -1 ); }else{ iCnt = (*m_piTotalSE)- 1 - ( (*m_piDeledSE) - (*m_piUsedSE) ); } return iCnt; } template <class T> unsigned int SHMData_A<T>::getTotal() { if (*m_piTotalSE) return (*m_piTotalSE)-1; return 0; } ///需要在程序外面防止同一个uiOffset调用revoke两次,一旦调用两次就会乱掉内存了 template <class T> bool SHMData_A<T>::revoke( unsigned int uiOffset) { if(!m_poSHM) return false; if( ((*m_piDeledSE)+1 )%(*m_piTotalSE) == (*m_piUsedSE) ) return false; T oTemp; memset(&oTemp, 0, sizeof(T) ); if(memcmp(& m_pPointer[uiOffset], &oTemp, sizeof(T)) ==0){ ////可能是重复删除,除非是一个数据项分配了但是没进行任何赋值马上就被删除 return false; } m_pIArray[(*m_piDeledSE)] = uiOffset; memset( & m_pPointer[uiOffset], 0, sizeof(T) ); ///不能直接先 ++再判断回0,防止此时正好在分配空间 if( (*m_piDeledSE)+1 >= (*m_piTotalSE) ){ (*m_piDeledSE) = 0; (*m_piDelOver)++; }else{ (*m_piDeledSE)++; } return true; } ////获取自创建以来所删除的总条数 template <class T> unsigned long SHMData_A<T>::getDelTotal( ) { if( sizeof(T) <32 ) return ( (*m_piTotalSE) * (*m_piDelOver) + (*m_piDeledSE) ) - 1; return ( (*m_piTotalSE) * (*m_piDelOver) + (*m_piDeledSE) ); } ////获取 目前处于删除状态但还未被重新分配出去的条数 template <class T> unsigned int SHMData_A<T>::getDelFree( ) { if( (*m_piDelOver) ){ ////已经全部删除过,那么所有空闲状态的都是先前删除得到的位置 return getTotal()-getCount(); }else{ if( (*m_piUsedSE) > (*m_piDeledSE) ){ if( sizeof(T) <32 ) return (*m_piDeledSE)-1; else return (*m_piDeledSE) ; }else{ return (*m_piDeledSE)-(*m_piUsedSE); } } } ////检查重复删除 ////返回是否健康 template <class T> bool SHMData_A<T>::checkHealth() { unsigned char * pData = new unsigned char[(*m_piTotalSE)]; memset(pData, '0', sizeof(char)*(*m_piTotalSE) ); unsigned int i = (* m_piUsedSE ); unsigned int j =0; bool bRet = true; for(; i != (* m_piDeledSE ); i++){ if( i>= (* m_piTotalSE ) ){ i = 0; } j = m_pIArray[i]; if( 0== j){ j = i; } if( '0' == pData[j] ){ ////此条记录空闲 pData[j] = '1'; }else{ ////此条记录出现多次删除 pData[j]++; bRet = false; cout<< pData[j]<<"次删除记录:"<< j<<","; } cout<<endl; } delete []pData; if( 0== m_pIArray[(* m_piTotalSE)] ){ ////还没有删除满过 if((*m_piDelOver)!=0 ){ bRet = false; cout<<"删除记录的内存校验1失败."; } } if( 0!= m_pIArray[(* m_piTotalSE)] ){ ////已经删除满过 if( 0 == (*m_piDelOver) ){ bRet = false; cout<<"删除记录的内存校验2失败."; } unsigned int i = (* m_piUsedSE ); if( i!=0 && 0== m_pIArray[i] ){ bRet = false; cout<<"删除记录的内存校验3失败."; } ////如果删除满过,就必须分配满过 ////以上判断基于一个数据项只有先分配了他才可能存在删除他 } return bRet; } template <class T> void SHMData_A<T>::showDetail() { if(!m_poSHM) return ; // cout<<"内存模式:"<< (*m_piVersion)<<", 单条结构体大小:"<< sizeof(T) << endl; // cout<<"内存容量:"<< getTotal() <<", 已使用条数:"<< getCount() << endl; // cout<<"自创建以来删除的总条数:"<< getDelTotal() << endl; // cout<<"空闲可用数量:"<< getTotal()-getCount() << ", 其中来自删除的数量为:"<< getDelFree() << endl; char sText[256]; char keys[64]; if(m_sSHMName) { strncpy(keys, m_sSHMName, sizeof(keys)); }else{ sprintf(keys, "%ld", m_lSHMKey); } if( !m_poSHM ){ snprintf(sText, sizeof(sText), "%-10s 0x%-10lx %2u %-12s %-9d %-10u %-10u %4d%%", keys, 0,(*m_piVersion), "DATA_A", sizeof(T), 0, 0, 0 ); }else{ char * pp = (char * )(*m_poSHM); unsigned int uiTotal = getTotal(); unsigned int uiCount = getCount(); int percent = 100*uiCount/uiTotal; if( (100*uiCount)%uiTotal ) percent++; snprintf(sText, sizeof(sText), "%-10s 0x%-10lx %2u %-12s %-9d %-10u %-10u %4u%% %-9u %-10lu", keys, pp,(*m_piVersion), "DATA_A", sizeof(T), uiTotal, uiCount, percent, getDelFree(), getDelTotal() ); } cout<< sText<<endl; } ////如果更新掉了第1个节点,则更新输出o_uiKickSelf ////返回脱链的个数 template <class T> unsigned int SHMData_A<T>::kick(unsigned int uiBeginOff, int iNxtOffset, int iExpOffset, const char * sDate, unsigned int * o_uiKickSelf, bool * o_bKickSelf ) { if(!sDate || iNxtOffset<0 || iExpOffset<0 ) return 0 ; unsigned int uiDataOff = uiBeginOff; unsigned int iCnt=0; *o_bKickSelf=false; if( uiDataOff ){ unsigned int uiDataNext = *(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset); unsigned int uiSelf= uiDataOff; while(uiDataNext){ char * pExp = ( ( (char *)&m_pPointer[uiDataNext] ) + iExpOffset); if( strncmp(pExp, sDate, 8)<0 ){ ///过期的数据 *(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset) = *(unsigned int *)( ( (char *)&m_pPointer[uiDataNext])+ iNxtOffset); *(unsigned int *)( ( (char *)&m_pPointer[uiDataNext])+ iNxtOffset)=0; iCnt++; uiDataNext=*(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset); continue; } uiDataOff = uiDataNext; uiDataNext=*(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset); } char * pExp = ( ( (char *)&m_pPointer[uiSelf] ) + iExpOffset); if( strncmp(pExp, sDate, 8)<0 ){ *o_uiKickSelf = *(unsigned int *)( ( (char *)&m_pPointer[uiSelf])+ iNxtOffset); *(unsigned int *)( ( (char *)&m_pPointer[uiSelf])+ iNxtOffset)=0; iCnt++; *o_bKickSelf = true; } } return iCnt; } ////如果更新掉了第1个节点,则更新输出o_uiKickSelf ////返回删掉的个数 template <class T> unsigned int SHMData_A<T>::kickAndRevoke(unsigned int uiBeginOff, int iNxtOffset, int iExpOffset, const char * sDate, int iChkOffset1, int iChkOffset2 , unsigned int *o_uiKickSelf, bool * o_bKickSelf) { if(!sDate || iNxtOffset<0 || iExpOffset<0 ) return 0 ; unsigned int uiDataOff = uiBeginOff; unsigned int iCnt=0; *o_bKickSelf=false; if( uiDataOff ){ unsigned int uiDataNext = *(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset); unsigned int uiSelf= uiDataOff; while(uiDataNext){ char * pExp = ( ( (char *)&m_pPointer[uiDataNext] ) + iExpOffset); if( strncmp(pExp, sDate, 8)<0 && ( iChkOffset1<0 || 0 == *(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iChkOffset1) ) && ( iChkOffset2<0 || 0 == *(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iChkOffset2) ) ){ ///过期的数据且check的数据已经清空 *(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset) = *(unsigned int *)( ( (char *)&m_pPointer[uiDataNext])+ iNxtOffset); *(unsigned int *)( ( (char *)&m_pPointer[uiDataNext])+ iNxtOffset)=0; revoke(uiDataNext); iCnt++; uiDataNext=*(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset); continue; } uiDataOff = uiDataNext; uiDataNext=*(unsigned int *)( ( (char *)&m_pPointer[uiDataOff] )+ iNxtOffset); } char * pExp = ( ( (char *)&m_pPointer[uiSelf] ) + iExpOffset); if( strncmp(pExp, sDate, 8)<0 && ( iChkOffset1<0 || 0 == *(unsigned int *)( ( (char *)&m_pPointer[uiSelf] )+ iChkOffset1) ) && ( iChkOffset2<0 || 0 == *(unsigned int *)( ( (char *)&m_pPointer[uiSelf] )+ iChkOffset2) ) ){ *o_uiKickSelf = *(unsigned int *)( ( (char *)&m_pPointer[uiSelf])+ iNxtOffset); *(unsigned int *)( ( (char *)&m_pPointer[uiSelf])+ iNxtOffset)=0; iCnt++; revoke(uiSelf); *o_bKickSelf = true; } } return iCnt; } template <class T> unsigned int SHMData_A<T>::getMemSize() { unsigned int size = 0; if (*m_piTotalSE) { size = (*m_piTotalSE)* sizeof(T); } if (size) return size ; return 0; } template <class T> unsigned int SHMData_A<T>::getUsedSize() { unsigned int size = 0; if (*m_piUsedSE) { size = (*m_piUsedSE)* sizeof(T); } if (size) return size ; return 0; } template <class T> unsigned long SHMData_A<T>::getMemAdress() { if (m_poSHM) { return (unsigned long)m_poSHM; } return 0; } template <class T> unsigned long SHMData_A<T>::getRealSize() { unsigned long size = m_poSHM->size(); return size; } template <class T> time_t SHMData_A<T>::getLoadTime() { time_t shm_ctime; if (m_poSHM) { shm_ctime = m_poSHM->getShmTime(); return shm_ctime; } return 0; } //////返回基本信息 //template <class T> //int SHMData_A<T>::getInfo(char * sOut, int iMax ) //{ // char keys[64]; // if(m_sSHMName) { // strncpy(keys, m_sSHMName, sizeof(name)); // }else{ // sprintf(keys, "%ld", m_lSHMKey); // } // int i = snprintf(sOut, iMax, "%10s 0x%10x %12s %9d %10u %10u %4d%%", // keys, (*m_poSHM), "DATA_A", sizeof(T), getTotal(), getCount(), 100L*getCount()/getTotal() ); // // return i; //} #endif
[ "xkmld419@126.com" ]
xkmld419@126.com
21b9cdbdb0c8bef523e7309c63a82c70a3b0ffff
c816d974ff77f0cc2a0853e870c2348e68bdc445
/trabalho2/createrascunho.cpp
6f3367c0e9364516523297d33b7d6ccec29283ca
[]
no_license
bragalucas1/ED
01529803f093815fb4e233809e7196c895521d09
a91e0a86acd063be7e2990395516a2a09dd2178b
refs/heads/main
2023-08-29T10:44:54.353074
2021-10-19T22:25:29
2021-10-19T22:25:29
388,488,840
1
0
null
null
null
null
UTF-8
C++
false
false
12,522
cpp
switch (id){ case 'I': if(rot == 0 || rot == 180){//mesmo caso de rotação levando em conta os 2 graus de rotação char **I = new char*[4]; //cria-se a peça for(int i = 0; i < 4; i++){ I[i] = new char[1]; } for(int i = 0; i < 4; i++){ for(int j = 0; j < 1; j++){ //formatação da peça I[i][j] = 'I'; //peça recebe o caractere I em todas dimensoes } } altp = 4; //altura e largura para o tipo de rotação especifica largp = 1; return I; break; } if(rot == 90 || rot == 270){ char **I = new char*[1]; I[0] = new char[4]; for(int j = 0; j < 4;j++){ //recebe apenas uma dimensão I[0][j] = 'I'; } altp = 1;//altura e largura para o tipo de rotação especifica largp = 4; return I; break; } case 'J': if(rot == 0){ char **J = new char*[2]; for(int i = 0; i < 2 ; i++){ J[i] = new char[4]; } for(int i = 0; i< 2; i++){ for(int j = 0;j < 4; j++){ if((i == 1 && j == 0) || (i == 1 && j == 1) || (i == 1 && j == 2)){ //formatação da peça J[i][j] = ' '; } else{ J[i][j] = 'J'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 4; return J; break; } if(rot == 90){ char **J = new char*[4]; for(int i = 0; i < 4;i++){ J[i] = new char[2]; } for(int i = 0; i < 4; i++){ for(int j = 0; j < 2; j++){ if((i == 0 && j == 0) || (i == 1 && j == 0) || (i == 2 && j == 0)){ //formatação da peça J[i][j] = ' '; } else{ J[i][j] = 'J'; } } } altp = 4;//altura e largura para o tipo de rotação especifica largp = 2; return J; break; } if(rot == 180){ char **J = new char*[2]; for(int i = 0; i < 2; i++){ J[i] = new char[4]; } for(int i = 0; i < 2; i++){ for(int j = 0;j < 4; j++){ if((i == 0 && j == 1) || (i == 0 && j == 2) || (i == 0 && j == 3)){ //formatação da peça J[i][j] = ' '; } else{ J[i][j] = 'J'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 4; return J; break; } if(rot == 270){ char **J = new char*[4]; for(int i = 0; i < 4; i++){ J[i] = new char[2]; } for(int i = 0; i < 4; i++){ for(int j = 0; j < 2; j++){ if((i == 1 && j == 1) || (i == 2 && j == 1) || (i == 3 && j == 1)){ //formatação da peça J[i][j] = ' '; } else{ J[i][j] = 'J'; } } } altp = 4;//altura e largura para o tipo de rotação especifica largp = 2; return J; break; } case 'L': if(rot == 0){ char **L = new char*[2]; for(int i = 0; i < 2; i++){ L[i] = new char[4]; } for(int i = 0; i < 2 ; i++){ for(int j = 0; j < 4; j++){ if((i == 1 && j == 1) || (i == 1 && j == 2) || (i == 1 && j == 3)){ //formatação da peça L[i][j] = ' '; } else{ L[i][j] = 'L'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 4; return L; break; } if(rot == 90){ char **L = new char*[4]; for(int i = 0; i < 4; i++){ L[i] = new char[2]; } for(int i = 0; i < 4; i++){ for(int j = 0; j < 2; j++){ if((i == 1 && j == 0) || (i == 2 && j == 0) || (i == 3 && j == 0)){ //formatação da peça L[i][j] = ' '; } else{ L[i][j] = 'L'; } } } altp = 4;//altura e largura para o tipo de rotação especifica largp = 2; return L; break; } if(rot == 180){ char **L = new char*[2]; for(int i = 0; i < 2; i++){ L[i] = new char[4]; } for(int i = 0; i < 2; i++){ for(int j = 0; j < 4; j++){ if((i == 0 && j == 0) || (i == 0 && j == 1) || (i == 0 && j == 2)){ //formatação da peça L[i][j] = ' '; } else{ L[i][j] = 'L'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 4; return L; break; } if(rot == 270){ char **L = new char*[4]; for(int i = 0; i < 4; i++){ L[i] = new char[2]; } for(int i = 0; i < 4; i++){ for(int j = 0; j < 2; j++){ if((i == 0 && j == 1) || (i == 1 && j == 1) || (i == 2 && j == 1)){ //formatação da peça L[i][j] = ' '; } else{ L[i][j] = 'L'; } } } altp = 4;//altura e largura para o tipo de rotação especifica largp = 2; return L; break; } case 'O': //Todos os casos de rotação da peça dão origem á mesma. { char **o = new char*[2]; for(int i = 0; i < 2; i++){ o[i] = new char[2]; } for(int i = 0; i < 2; i++){ for(int j = 0; j < 2;j++){ o[i][j] = 'O'; } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 2; return o; break; } case 'S': if(rot == 0 || rot == 180){ char **S = new char*[2]; for(int i = 0; i < 2; i++){ S[i] = new char[3]; } for(int i = 0; i < 2; i++){ for(int j = 0; j < 3; j++){ if((i == 0 && j == 0) || (i == 1 && j == 2)){ //formatação da peça S[i][j] = ' '; } else{ S[i][j] = 'S'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 3; return S; break; } if(rot == 90 || rot == 270){ char **S = new char*[3]; for(int i = 0; i < 3; i++){ S[i] = new char[2]; } for(int i = 0; i < 3; i++){ for(int j = 0; j < 2; j++){ if((i == 0 && j == 1) || (i == 2 && j==0)){//formatação da peça S[i][j] = ' '; } else{ S[i][j] = 'S'; } } } altp = 3;//altura e largura para o tipo de rotação especifica largp = 2; return S; break; } case 'T': if(rot == 0){ char **T = new char*[2]; for(int i = 0; i < 2; i++){ T[i] = new char[3]; } for(int i = 0; i < 2; i++){ for(int j = 0; j < 3; j++){ if((i == 1 && j == 0) || (i == 1 && j == 2)){ //formatação da peça T[i][j] = ' '; } else{ T[i][j] = 'T'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 3; return T; break; } if(rot == 90){ char **T = new char*[3]; for(int i = 0; i < 3; i++){ T[i] = new char[2]; } for(int i = 0; i < 3; i++){ for(int j = 0; j < 2; j++){ if((i == 0 && j == 0) || (i == 2 && j == 0 )){ //formatação da peça T[i][j] = ' '; } else{ T[i][j] = 'T'; } } } altp = 3;//altura e largura para o tipo de rotação especifica largp = 2; return T; break; } if(rot == 180){ char **T = new char*[2]; for(int i = 0; i < 2; i++){ T[i] = new char[3]; } for(int i = 0; i < 2; i++){ for(int j = 0; j < 3; j++){ if((i == 0 && j==0) || (i ==0 && j==2)){ //formatação da peça T[i][j] = ' '; } else{ T[i][j] = 'T'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 3; return T; break; } if(rot == 270){ char **T = new char*[3]; for(int i = 0;i < 3; i++){ T[i] = new char[2]; } for(int i = 0; i < 3; i++){ for(int j =0;j < 2; j++){ if((i == 0 && j == 1) || (i == 2 && j == 1)){//formatação da peça T[i][j] = ' '; } else{ T[i][j] = 'T'; } } } altp = 3;//altura e largura para o tipo de rotação especifica largp = 2; return T; break; } case 'Z': if(rot ==0 || rot == 180){ char **Z = new char*[2]; for(int i = 0; i < 2 ;i++){ Z[i] = new char[3]; } for(int i = 0; i < 2; i++){ for(int j = 0; j < 3; j++){ if((i == 0 && j == 2) || (i == 1 && j == 0)){ //formatação da peça Z[i][j] = ' '; } else{ Z[i][j] = 'Z'; } } } altp = 2;//altura e largura para o tipo de rotação especifica largp = 3; return Z; break; } if(rot == 90 || rot == 270){ char **Z = new char*[3]; for(int i = 0; i < 3; i++){ Z[i] = new char[2]; } for(int i = 0; i < 3; i++){ for(int j =0;j < 2;j++){ if((i == 0 && j == 0) || (i == 2 && j == 1)){ //formatação da peça Z[i][j] = ' '; } else{ Z[i][j] = 'Z'; } } } altp = 3;//altura e largura para o tipo de rotação especifica largp = 2; return Z; break; } default: break; } }
[ "lucas.b.moura@ufv.br" ]
lucas.b.moura@ufv.br
7ea0e071519370395feb261bc7e144bd57a1f431
c37aa1e5eb0990dae9b5c71891fda4d8e48ed4aa
/LeetCode/consecutive_characters.cpp
cd207e23e8d4d974be6daf8240a24b6b2179a929
[]
no_license
aladenisun/LeetCode
84915a86d045027f1bed2c5db6d76639f61c34a4
1040a4eb7d9dfef87179c7f7b84e3497b68cbc51
refs/heads/master
2023-02-16T04:25:53.686053
2021-01-10T21:25:23
2021-01-10T21:25:23
284,111,057
0
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxPower(string s) { int freq = 1; int power = 1; int current; /* if current == prev current ++; if current == prev then freq++; if not the same: then freq = 1 and power = freq; then start again :) l e e t c o d e */ if (s.size() == 0) return 0; for(current=1; current<s.size(); current++){ printf("current = %i\n", current); if (s[current] == s[current-1] ) freq++; // freq = 2 else{ freq = 1; } power = max(power, freq); } return power; } }; int main(){ printf("Hello World"); string s = "leeeeeetccooooooodde"; int ret; Solution Example; ret = Example.maxPower(s); printf("power = %i\n", ret); }
[ "nisunalade13@gmail.com" ]
nisunalade13@gmail.com
bed88a168d86aabecb35e41804ac64819d857759
771b8c57e855d7e7595ec3b8d644ed05640962c4
/week1/triangle2/src/ofApp.h
56cad6d857457cd4fdf072eda20b06b27c74c822
[]
no_license
ailadi/ofApps
56896dc1c562e4e9aef0a030508c3b849955f902
1b06e3903694e61d6eb3f045ecb4d8b8cdabea33
refs/heads/master
2021-04-29T17:45:14.760029
2018-04-14T02:36:20
2018-04-14T02:36:20
121,677,241
0
0
null
null
null
null
UTF-8
C++
false
false
721
h
#pragma once #include "ofMain.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); void tri(float x, float y, float r, float angle); float xcenter = 400; float ycenter = 400; float ptx; float pty; };
[ "ailadi@Ailadi.home" ]
ailadi@Ailadi.home
3856a463ef1fe9e18b8982949ec63872cb6ebfa8
59b751330bb04796fd1f0efdd341afca3d639927
/Connectors/IB/SampleCode/cpp/Shared/HScrollListBox.h
e743bcd428c672cffa992583722972f0e17a2ad5
[]
no_license
chinux23/TickDatabase
54d923e8457e1992be1878cf37365ba79cc2cad5
b8993b550f7c7ce80c2a9c5bb1e9172fcfbd93d2
refs/heads/master
2021-01-19T11:39:59.556777
2012-07-25T06:40:08
2012-07-25T06:40:08
2,785,228
6
3
null
null
null
null
UTF-8
C++
false
false
1,314
h
#if !defined(CHSCROLLLISTBOX_H) #define CHSCROLLLISTBOX_H ///////////////////////////////////////////////////////////////////////////// // CHScrollListBox window ///////////////////////////////////////////////////////////////////////////// class CHScrollListBox : public CListBox { // Construction public: CHScrollListBox(); public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CHScrollListBox) //}}AFX_VIRTUAL // Implementation public: virtual ~CHScrollListBox(); // Generated message map functions protected: //{{AFX_MSG(CHScrollListBox) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG afx_msg LRESULT OnAddString(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnInsertString(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnDeleteString(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnResetContent(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() private: void ResetHExtent(); void SetNewHExtent(LPCTSTR lpszNewString); int GetTextLen(LPCTSTR lpszText); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(CHSCROLLLISTBOX_H)
[ "chinux@gmail.com" ]
chinux@gmail.com
f6157613bf0836b2bd2645fa860a9b0ef58826d0
ee6ff3af175a37c2b2377c5ed5f184609e134755
/oshgui/Dependencies/Source/GLM/glm/core/intrinsic_geometric.inl
aaaeb3667a492fc5f18a7361c7d7170287eede7f
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
EternityX/DEADCELL-CSGO
c1363ecf5a62941954514d946137a4b791da3b36
7b873216637977d914b2eeb6893cb0cc4708aff2
refs/heads/master
2023-08-28T07:09:39.914038
2021-11-30T12:27:01
2021-11-30T12:27:01
175,938,531
597
233
MIT
2020-09-27T02:29:08
2019-03-16T07:07:59
C++
UTF-8
C++
false
false
4,471
inl
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2012 G-Truc Creation (www.g-truc.net) /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// /// @ref core /// @file glm/core/intrinsic_geometric.inl /// @date 2009-05-08 / 2011-06-15 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// namespace glm{ namespace detail{ //length GLM_FUNC_QUALIFIER __m128 sse_len_ps(__m128 x) { __m128 dot0 = sse_dot_ps(x, x); __m128 sqt0 = _mm_sqrt_ps(dot0); return sqt0; } //distance GLM_FUNC_QUALIFIER __m128 sse_dst_ps(__m128 p0, __m128 p1) { __m128 sub0 = _mm_sub_ps(p0, p1); __m128 len0 = sse_len_ps(sub0); return len0; } //dot GLM_FUNC_QUALIFIER __m128 sse_dot_ps(__m128 v1, __m128 v2) { __m128 mul0 = _mm_mul_ps(v1, v2); __m128 swp0 = _mm_shuffle_ps(mul0, mul0, _MM_SHUFFLE(2, 3, 0, 1)); __m128 add0 = _mm_add_ps(mul0, swp0); __m128 swp1 = _mm_shuffle_ps(add0, add0, _MM_SHUFFLE(0, 1, 2, 3)); __m128 add1 = _mm_add_ps(add0, swp1); return add1; } // SSE1 GLM_FUNC_QUALIFIER __m128 sse_dot_ss(__m128 v1, __m128 v2) { __m128 mul0 = _mm_mul_ps(v1, v2); __m128 mov0 = _mm_movehl_ps(mul0, mul0); __m128 add0 = _mm_add_ps(mov0, mul0); __m128 swp1 = _mm_shuffle_ps(add0, add0, 1); __m128 add1 = _mm_add_ss(add0, swp1); return add1; } //cross GLM_FUNC_QUALIFIER __m128 sse_xpd_ps(__m128 v1, __m128 v2) { __m128 swp0 = _mm_shuffle_ps(v1, v1, _MM_SHUFFLE(3, 0, 2, 1)); __m128 swp1 = _mm_shuffle_ps(v1, v1, _MM_SHUFFLE(3, 1, 0, 2)); __m128 swp2 = _mm_shuffle_ps(v2, v2, _MM_SHUFFLE(3, 0, 2, 1)); __m128 swp3 = _mm_shuffle_ps(v2, v2, _MM_SHUFFLE(3, 1, 0, 2)); __m128 mul0 = _mm_mul_ps(swp0, swp3); __m128 mul1 = _mm_mul_ps(swp1, swp2); __m128 sub0 = _mm_sub_ps(mul0, mul1); return sub0; } //normalize GLM_FUNC_QUALIFIER __m128 sse_nrm_ps(__m128 v) { __m128 dot0 = sse_dot_ps(v, v); __m128 isr0 = _mm_rsqrt_ps(dot0); __m128 mul0 = _mm_mul_ps(v, isr0); return mul0; } //faceforward GLM_FUNC_QUALIFIER __m128 sse_ffd_ps(__m128 N, __m128 I, __m128 Nref) { //__m128 dot0 = _mm_dot_ps(v, v); //__m128 neg0 = _mm_neg_ps(N); //__m128 sgn0 = _mm_sgn_ps(dot0); //__m128 mix0 = _mm_mix_ps(N, neg0, sgn0); //return mix0; __m128 dot0 = sse_dot_ps(Nref, I); __m128 sgn0 = sse_sgn_ps(dot0); __m128 mul0 = _mm_mul_ps(sgn0, glm::detail::minus_one); __m128 mul1 = _mm_mul_ps(N, mul0); return mul1; } //reflect GLM_FUNC_QUALIFIER __m128 sse_rfe_ps(__m128 I, __m128 N) { __m128 dot0 = sse_dot_ps(N, I); __m128 mul0 = _mm_mul_ps(N, dot0); __m128 mul1 = _mm_mul_ps(mul0, glm::detail::two); __m128 sub0 = _mm_sub_ps(I, mul1); return sub0; } //refract GLM_FUNC_QUALIFIER __m128 sse_rfa_ps(__m128 I, __m128 N, __m128 eta) { __m128 dot0 = sse_dot_ps(N, I); __m128 mul0 = _mm_mul_ps(eta, eta); __m128 mul1 = _mm_mul_ps(dot0, dot0); __m128 sub0 = _mm_sub_ps(glm::detail::one, mul0); __m128 sub1 = _mm_sub_ps(glm::detail::one, mul1); __m128 mul2 = _mm_mul_ps(sub0, sub1); if(_mm_movemask_ps(_mm_cmplt_ss(mul2, glm::detail::zero)) == 0) return glm::detail::zero; __m128 sqt0 = _mm_sqrt_ps(mul2); __m128 mul3 = _mm_mul_ps(eta, dot0); __m128 add0 = _mm_add_ps(mul3, sqt0); __m128 mul4 = _mm_mul_ps(add0, N); __m128 mul5 = _mm_mul_ps(eta, I); __m128 sub2 = _mm_sub_ps(mul5, mul4); return sub2; } }//namespace detail }//namespace glm
[ "jeramie@protonmail.com" ]
jeramie@protonmail.com
7306382e551b3314599a6d9889a928741265675d
553366bef70aedae6414579fc5d9c2db46f72bf3
/main/HAP/plugins/InfluxDB/HAPPluginInfluxDB.hpp
0670f7678597696a98899c95efa67ba7caaaef09
[ "Apache-2.0" ]
permissive
planetk/Homekit
e047870628f7ab3f016e101a22e65f36eac537b3
836cc84f2741caaa5bf31f58be1037f301ea9c70
refs/heads/master
2020-09-26T04:13:35.074470
2019-12-01T06:41:55
2019-12-01T06:41:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
hpp
// // HAPPluginInfluxDB.hpp // Homekit // // Created on: 29.04.2018 // Author: michael // #ifndef HAPPLUGININFLUXDB_HPP_ #define HAPPLUGININFLUXDB_HPP_ #include <Arduino.h> #include "HAPPlugins.hpp" #include "HAPLogger.hpp" #include "HAPAccessory.hpp" #include "Influxdb.h" #define HAP_PLUGIN_INFLUXDB_INTERVAL 60 * 1000 // 60 sec #define HAP_INFLUXDB_TIMEOUT 10 * 1000 // 10 sec -> unused class HAPPluginInfluxDB: public HAPPlugin { public: HAPPluginInfluxDB(); HAPAccessory* initAccessory() override; bool begin(); void setValue(String oldValue, String newValue){}; String getValue(int iid) { return ""; }; void handleImpl(bool forced = false); void handleEvents(int eventCode, struct HAPEvent eventParam); HAPConfigValidationResult validateConfig(JsonObject object); JsonObject getConfigImpl(); void setConfigImpl(JsonObject root); void addEventListener(EventManager* eventManager); private: Influxdb* _influxdb; String _username; String _password; String _hostname; String _database; uint16_t _port; uint16_t _usedSize; // bool shouldHandle(); }; REGISTER_PLUGIN(HAPPluginInfluxDB) #endif /* HAPPLUGININFLUXDB_HPP_ */
[ "michael@macbookpro.local" ]
michael@macbookpro.local
cdd865cc98e5a044cb94e712ba3c9cb5a69bb949
bfb05cd47add77df4bac22db8b9ea7d89a1fa95a
/src/base/interpreter/Interpreter.hpp
9f140abd4ba5990ae715d81a691bc4ce3f5c041e
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xyh-cosmo/GMAT
a7662f3a5abeb747dd0d14c96185ee40211d4cc9
00b6b61a40560c095da3d83dab4ab1e9157f01c7
refs/heads/master
2021-12-07T22:41:30.436316
2016-01-11T21:33:08
2016-01-11T21:33:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,174
hpp
//$Id$ //------------------------------------------------------------------------------ // Interpreter //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Author: Darrel J. Conway // Created: 2003/08/28 // Rework: 2006/09/27 by Linda Jun (NASA/GSFC) // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // /** * Class definition for the Interpreter base class */ //------------------------------------------------------------------------------ #ifndef Interpreter_hpp #define Interpreter_hpp #include "gmatdefs.hpp" #include "InterpreterException.hpp" #include "GmatBase.hpp" #include "TextParser.hpp" #include "ScriptReadWriter.hpp" #include "ElementWrapper.hpp" // Forward references for GMAT core objects class Spacecraft; class Formation; class Hardware; class Propagator; class ODEModel; class PropSetup; class PhysicalModel; class SolarSystem; class CelestialBody; class Parameter; class GmatCommand; class CoordinateSystem; class AxisSystem; class Subscriber; class Burn; class Function; class Moderator; class Validator; class Interface; /** * Interpreter is the base class for the GMAT Interpreter subsystem. * * Interpreter defines the interfaces used to parse the text files that control * execution in GMAT. It also provides the interfaces to write text files out, * either to the file system, the screen, or the GUI. */ class GMAT_API Interpreter { public: Interpreter(SolarSystem *ss = NULL, ObjectMap *objMap = NULL); virtual ~Interpreter(); //------------------------------------------------------------------------------ // bool Interpret() //------------------------------------------------------------------------------ /** * Retrieves text input from a stream and translate it into GMAT objects and * actions. * * This method gets overridden by derived classes. * * @return true on success, false on failure. */ //------------------------------------------------------------------------------ virtual bool Interpret() = 0; //------------------------------------------------------------------------------ // bool Build() //------------------------------------------------------------------------------ /** * Accesses GMAT objects and actions and writes them to a stream. * * This method gets overridden by derived classes. * * @return true on success, false on failure. */ //------------------------------------------------------------------------------ virtual bool Build(Gmat::WriteMode mode) = 0; virtual Parameter* CreateSystemParameter(const std::string &str); virtual Parameter* CreateParameter(const std::string &type, const std::string &name, const std::string &ownerName = "", const std::string &depName = ""); const StringArray& GetListOfObjects(Gmat::ObjectType type); const StringArray& GetListOfObjects(const char *typeName); const StringArray& GetListOfObjects(const std::string &typeName); const StringArray& GetListOfViewableSubtypesOf(Gmat::ObjectType type); const StringArray& GetListOfViewableCommands(); GmatBase* GetConfiguredObject(const char *name); GmatBase* GetConfiguredObject(const std::string &name); GmatBase* FindObject(const char *name, const std::string &ofType = ""); GmatBase* FindObject(const std::string &name, const std::string &ofType = ""); GmatBase* CreateObject(const std::string &type, const std::string &name, Integer manage = 1, bool createDefault = false, bool includeLineOnError = true, bool showWarning = true); void SetConfiguredObjectMap(); void SetSolarSystemInUse(SolarSystem *ss); SolarSystem* GetSolarSystemInUse(); void SetObjectMap(ObjectMap *objMap, bool forFunction = false); ObjectMap* GetObjectMap(); void SetFunction(Function *func); Function* GetFunction(); void SetContinueOnError(bool flag); bool GetContinueOnError(); bool IsInCommandMode(); bool FoundBeginMissionSequence(); const StringArray& GetErrorList() { return errorList; } void SetHeaderComment(const std::string &comment){headerComment = comment;} void SetFooterComment(const std::string &comment){footerComment = comment;} bool IsObjectType(const char *type); bool IsObjectType(const std::string &type); bool IsCommandType(const char *type); bool IsCommandType(const std::string &type); Gmat::ObjectType GetObjectType(const std::string &type); // to check commands bool ValidateCommand(GmatCommand *cmd); // to create subscriber wrappers bool ValidateSubscriber(GmatBase *obj); bool SetForceModelProperty(GmatBase *obj, const std::string &prop, const std::string &value, GmatBase *fromObj); bool SetDragForceProperty(GmatBase *obj, const std::string &pmType, const std::string &pmField, const std::string &value); bool SetMeasurementModelProperty(GmatBase *obj, const std::string &prop, const std::string &value); bool SetTrackingDataProperty(GmatBase *obj, const std::string &prop, const std::string &value); bool SetTrackingSystemProperty(GmatBase *obj, const std::string &prop, const std::string &value); bool SetDataStreamProperty(GmatBase *obj, const std::string &property, const std::string &value); bool FindOwnedObject(GmatBase *owner, const std::string toProp, GmatBase **ownedObj, Integer &id, Gmat::ParameterType &type); bool FindPropertyID(GmatBase *obj, const std::string &chunk, GmatBase **owner, Integer &id, Gmat::ParameterType &type); void BuildCreatableObjectMaps(); StringArray GetCreatableList(Gmat::ObjectType type, const std::string subType = ""); virtual void SetInputFocus(); virtual void NotifyRunCompleted(); virtual void UpdateView(Integer type = 7); virtual void CloseCurrentProject(); virtual void StartMatlabServer(); virtual void ResetIconFile(); Interface* GetMatlabInterface(); bool OpenMatlabEngine(); bool CloseMatlabEngine(); protected: Moderator *theModerator; SolarSystem *theSolarSystem; Validator *theValidator; // Object map to be used for finding objects ObjectMap *theObjectMap; // String array to be used for finding temporary object names StringArray tempObjectNames; /// A pointer to the ScriptReadWriter used when reading or writing script. ScriptReadWriter *theReadWriter; TextParser theTextParser; bool inCommandMode; bool inRealCommandMode; bool beginMissionSeqFound; bool initialized; bool parsingDelayedBlock; bool ignoreError; bool inScriptEvent; /// For handling GmatFunction bool gmatFunctionsAvailable; bool inFunctionMode; bool hasFunctionDefinition; Function *currentFunction; /// Flag used to handle Python function call detection bool isPythonFunction; /// For handling delayed blocks StringArray delayedBlocks; StringArray delayedBlockLineNumbers; /// Block type and comments std::string headerComment; std::string footerComment; std::string currentBlock; std::string currentLine; std::string lineNumber; Gmat::BlockType currentBlockType; /// Error handling data bool continueOnError; std::string errorMsg1; std::string errorMsg2; std::string debugMsg; StringArray errorList; void Initialize(); void RegisterAliases(); Parameter* GetArrayIndex(const std::string &arrayStr, Integer &row, Integer &col); AxisSystem* CreateAxisSystem(std::string type, GmatBase *owner); // for commands bool ParseAndSetCommandName(GmatCommand *cmd, const std::string &cmdType, const std::string &desc, std::string &newDesc); GmatCommand* CreateCommand(const std::string &type, const std::string &desc, bool &retFlag, GmatCommand *inCmd = NULL); GmatCommand* AppendCommand(const std::string &type, bool &retFlag, GmatCommand *inCmd = NULL); GmatCommand* CreateAssignmentCommand(const std::string &lhs, const std::string &rhs, bool &retFlag, GmatCommand *inCmd = NULL); bool AssembleCommand(GmatCommand *cmd, const std::string &desc); bool AssembleCallFunctionCommand(GmatCommand *cmd, const std::string &desc); bool AssembleConditionalCommand(GmatCommand *cmd, const std::string &desc); bool AssembleForCommand(GmatCommand *cmd, const std::string &desc); bool AssembleGeneralCommand(GmatCommand *cmd, const std::string &desc); bool AssembleTargetCommand(GmatCommand *cmd, const std::string &desc); bool AssembleOptimizeCommand(GmatCommand *cmd, const std::string &desc); bool AssembleFiniteBurnCommand(GmatCommand *cmd, const std::string &desc); bool AssembleReportCommand(GmatCommand *cmd, const std::string &desc); bool AssembleCreateCommand(GmatCommand *cmd, const std::string &desc); bool SetCommandRefObjects(GmatCommand *cmd, const std::string &desc); // for assignment GmatBase* MakeAssignment(const std::string &lhs, const std::string &rhs); // for setting whole object bool SetObjectToObject(GmatBase *toObj, GmatBase *fromObj, const std::string &rhs); bool SetObjectToProperty(GmatBase *toObj, GmatBase *fromOwner, const std::string &fromProp); bool SetObjectToArray(GmatBase *toObj, const std::string &fromArray); bool SetObjectToValue(GmatBase *toObj, const std::string &value); // for setting property bool SetPropertyToObject(GmatBase *toOwner, const std::string &toProp, GmatBase *fromObj); bool SetPropertyToProperty(GmatBase *toOwner, const std::string &toProp, GmatBase *fromOwner, const std::string &fromProp); bool SetPropertyToArray(GmatBase *toOwner, const std::string &toProp, const std::string &fromArray); bool SetPropertyToValue(GmatBase *toOwner, const std::string &toProp, const std::string &value); // for setting array bool SetArrayToObject(GmatBase *toArrObj, const std::string &toArray, GmatBase *fromObj); bool SetArrayToProperty(GmatBase *toArrObj, const std::string &toArray, GmatBase *fromOwner, const std::string &fromProp); bool SetArrayToArray(GmatBase *toArrObj, const std::string &toArray, GmatBase *fromArrObj, const std::string &fromArray); bool SetArrayToValue(GmatBase *toArrObj, const std::string &toArray, const std::string &value); // for setting/getting property value bool SetPropertyValue(GmatBase *obj, const Integer id, const Gmat::ParameterType type, const std::string &value, const Integer index = -1, const Integer colIndex = -1); bool SetPropertyObjectValue(GmatBase *obj, const Integer id, const Gmat::ParameterType type, const std::string &value, const Integer index = -1); bool SetPropertyStringValue(GmatBase *obj, const Integer id, const Gmat::ParameterType type, const std::string &value, const Integer index = -1); std::string GetPropertyValue(GmatBase *obj, const Integer id); bool SetProperty(GmatBase *obj, const Integer id, const Gmat::ParameterType type, const std::string &value); bool SetComplexProperty(GmatBase *obj, const std::string &prop, const std::string &value); bool SetSolarSystemProperty(GmatBase *obj, const std::string &prop, const std::string &value); // for setting/getting array value Real GetArrayValue(const std::string &arrayStr, Integer &row, Integer &col); bool IsArrayElement(const std::string &str); // for Variable expression bool ParseVariableExpression(Parameter *var, const std::string &exp); // for error handling void HandleError(const BaseException &e, bool writeLine = true, bool isWarning = false, bool showWarning = true); void HandleErrorMessage(const BaseException &e, const std::string &lineNumber, const std::string &line, bool writeLine = true, bool isWarning = false, bool showWarning = true); // for branch command checking bool IsBranchCommand(const std::string &str); bool CheckBranchCommands(const IntegerArray &lineNumbers, const StringArray &lines); // for setting object inside branch command void SetObjectInBranchCommand(GmatCommand *brCmd, const std::string &branchType, const std::string &childType, const std::string &objName); // Final setting of reference object pointers needed by the GUI and validation bool FinalPass(); bool FinalPassSubscribers(); // for GamtFunction handling bool CheckFunctionDefinition(const std::string &funcPathAndName, GmatBase *function, bool fullCheck = true); bool BuildFunctionDefinition(const std::string &str); void ClearTempObjectNames(); bool ValidateMcsCommands(GmatCommand *first, GmatCommand *parent = NULL, StringArray *missingObjects = NULL, std::string *accumulatedErrors = NULL); bool ValidateSolverCmdLevels(GmatCommand *bc, Integer cmdLevel); // for debug void WriteStringArray(const std::string &title1, const std::string &title2, const StringArray &parts); void WriteForceModel(GmatBase *obj); void ShowObjectMap(const std::string &title, ObjectMap *objMap = NULL); private: StringArray commandList; StringArray atmosphereList; StringArray attitudeList; StringArray axisSystemList; StringArray burnList; StringArray calculatedPointList; StringArray dataFileList; StringArray ephemFileList; StringArray functionList; StringArray hardwareList; StringArray measurementList; StringArray trackingSystemList; StringArray obtypeList; StringArray odeModelList; StringArray parameterList; StringArray physicalModelList; StringArray propagatorList; StringArray solverList; StringArray stopcondList; StringArray subscriberList; StringArray spacePointList; StringArray celestialBodyList; StringArray eventLocatorList; StringArray interfaceList; StringArray matlabFunctionNames; static StringArray allObjectTypeList; static StringArray viewableCommandList; static std::map<std::string, Gmat::ObjectType> objectTypeMap; bool IsParameterType(const std::string &desc); bool CheckForSpecialCase(GmatBase *obj, Integer id, std::string &value); bool CheckUndefinedReference(GmatBase *obj, bool writeLine = true); bool HandleMathTree(GmatCommand *cmd); bool HasFilenameTypeParameter(GmatCommand *cmd); static const std::string defaultIndicator; }; #endif // INTERPRETER_HPP
[ "rockstorm@gmx.com" ]
rockstorm@gmx.com
4d0e1c374d563c29b5face40f4de4352d7551805
815e2e1e8e27c76159f2e0e1a5bb3ae6074901df
/SM_DM_DFT_W10_32/ImageProc.cpp
67b9599d813d379da8b34071c43edfb0ad1a8232
[]
no_license
isliulin/DM_DFT
a038bc7eaec1fb2b53e6d323182f99edaff3a8be
e60665c91c081779c4963e8236150092dacaf0b4
refs/heads/master
2023-07-06T17:12:56.657888
2021-08-09T11:26:49
2021-08-09T11:26:49
null
0
0
null
null
null
null
UHC
C++
false
false
142,823
cpp
// ImageProc.cpp: implementation of the CImageProc class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ImageProc.h" #include "Global.h" #include <Math.h> #include <malloc.h> #define MAX_MASK_SIZE 9 #define DEFAULT_POSITION_MARGIN 10 #define MAX_NO_IMAGE_TO_MAKE_AVERAGE_IMAGE 10 //+add 090219(Modification No2) //extern CStdioFile g_LogFile; //extern BOOL g_LogFileOpen; //============= // Filter Mask //============= int Mask3x3_a[3*3] = { 114,114,114, 114,112,114, 114,114,114 }; int Mask5x5_a[5*5] = { 41,41,41,41,41, 41,41,41,41,41, 41,41,40,41,41, 41,41,41,41,41, 41,41,41,41,41 }; int Mask5x5_b[5*5] = { 0,-41, -41,-41, 0, -41, 41, 41, 41,-41, -41, 41, 164, 41,-41, -41, 41, 41, 41,-41, 0,-41, -41,-41, 0 }; int Mask7x7_a[7*7] = { 0,-1534,-1535,-1535,-1535,-1534,0, -1534,-205,103,205,103,-205,-1534, -1535,103,2867,3268,2867,103,-1535, -1535,205,3268,5328,3268,205,-1535, -1535,103,2867,3268,2867,103,-1535, -1534,-205,103,205,103,-205,-1534, 0,-1534,-1535,-1535,-1535,-1534,0 }; extern CDATsysView* g_pView; extern BOOL RefImage_DirectLoad(CString szRefFileName,int nUseMaskImage); //======================== // Temporary Image Buffer //======================== #define FULL_HD_IMAGE_SIZE 6220800 // 1920*1080*3 = 6220800 BYTE g_ImageBuffer1[6220800]; BYTE g_ImageBuffer2[6220800]; BYTE g_ImageBuffer3[6220800]; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CImageProc::CImageProc() { m_nColorMarginLevel = 0; m_nBrightMarginLevel = 0; m_nNoUsedColorHighBits = 0; m_nNoUsedBrightHighBits = 0; m_fTargetMatchRate = 99.5f; m_ptPositionShift.x = 0; m_ptPositionShift.y = 0; m_ptRoiPosition.x = 0; m_ptRoiPosition.y = 0; m_nRoiWidth = 0; m_nRoiHeight = 0; m_nAvgMaskWidth = 0; m_nAvgMaskHeight = 0; m_nNoRepeat = 0; m_fLowerLimit = 0.0; m_fUpperLimit = 0.0; for(int i=0; i<3; i++) { for(int j=0; j<NO_DIFFERENT_POINT_BLOCK; j++) { m_aNoDifferentPoint[i][j] = 0; } } m_nSecondDifferentPointFreePercent = -1; //+del kwmoon 080715 // m_fAllowedErrorPixelPercentage = 0; m_nCaptionWidth = 0; m_nCaptionHeight = 0; //+del kwmoon 080715 // m_fAllowedErrorPixelPercentageForOsdTest = 0; //+add kwmoon 071224 m_nCaptionKeyDelay = 0; m_nCaptionEnterKeyDelay = 0; m_nCaptionCheckTime = 0; //+change kwmoon 080124 //+add kwmoon 080110 // m_nNoKeyPress = 0; m_nNoOnKeyPress = 0; m_nNoOffKeyPress = 0; //+add kwmoon 071127 m_nDigitalEyeDelay = 0; //+add kwmoon 080121 m_ptOsdPosition.x = 0; m_ptOsdPosition.y = 0; //+add kwmoon 080121 m_nOsdWidth = 0; m_nOsdHeight = 0; //+add kwmoon 080828 m_ptInvalidPosition.x = 0; m_ptInvalidPosition.y = 0; m_nInvalidWidth = 0; m_nInvalidHeight = 0; //+add kwmoon 080228 for(int i=0; i<3; i++) { m_nNoPixelInMiddleRange[i] = 0; m_nNoNonBlackPixel[i] = 0; } //+add kwmoon 080715 for(int i=0; i<5;i++) { m_nNoBandErrorPixel[i] = 0; m_nNoAllowedBandErrorPixel[i] = 0; m_fBandErrorPixelPercentage[i] = 0.0f; m_fAllowedBandErrorPixelPercentage[i] = 0.0f; } //+add kwmoon 080715 m_nNoRoiPixel = 0; m_nNoTargetPixel = 0; m_nNoGoodPixel = 0; m_fGoodPixelPercentage = 0.0f; //+add kwmoon 080828 m_bInvalidateInvalidRegion = FALSE; m_nDiff_LowerLimit = -20; m_nDiff_UpperLimit = 20; m_fMovingPicTest_Limit = 0.2; } CImageProc::~CImageProc() { } // Set Position Margin void CImageProc::SetMatchRate(float fMatchRate) { m_fTargetMatchRate = fMatchRate; } // Set Color Margin void CImageProc::SetColorMargin(int nColorMargin) { m_nColorMarginLevel = nColorMargin; } // Set Color Limit void CImageProc::SetColorLimit(float fLowerLimit, float fUpperLimit) { m_fLowerLimit = fLowerLimit; m_fUpperLimit = fUpperLimit; } // Set Bright Margin void CImageProc::SetBrightMargin(int nBrightMargin) { m_nBrightMarginLevel = nBrightMargin; } void CImageProc::SetUsedNoColorHighBits(int nNoUsedColorHighBits) { m_nNoUsedColorHighBits = nNoUsedColorHighBits; } void CImageProc::SetUsedNoBrightHighBits(int nNoUsedBrightHighBits) { m_nNoUsedBrightHighBits = nNoUsedBrightHighBits; } void CImageProc::SetCaptionSize(int nWidth, int nHeight) { m_nCaptionWidth = nWidth; m_nCaptionHeight = nHeight; } void CImageProc::SetCaptionKey(int nCaptionKeyDelay, int nCaptionEnterKeyDelay, int nNoOnKeyPress, int nNoOffKeyPress) { m_nCaptionKeyDelay = nCaptionKeyDelay; m_nCaptionEnterKeyDelay = nCaptionEnterKeyDelay; //+change kwmoon 080124 m_nNoOnKeyPress = nNoOnKeyPress; m_nNoOffKeyPress = nNoOffKeyPress; } //+add kwmoon 071224 void CImageProc::SetCaptionCheckTime(int nCaptionCheckTime) { m_nCaptionCheckTime = nCaptionCheckTime; } //+add kwmoon 071112 void CImageProc::SetDigitalEyeDelay(int nDelay) { m_nDigitalEyeDelay = nDelay; } // Set Region of Interest (ROI) void CImageProc::SetRoi(POINT ptRoi1Position,POINT ptRoi2Position) { m_ptRoiPosition.x = ptRoi1Position.x; m_ptRoiPosition.y = ptRoi1Position.y; m_nRoiWidth = ptRoi2Position.x - ptRoi1Position.x; m_nRoiHeight = ptRoi2Position.y - ptRoi1Position.y; } // Set Position Shift void CImageProc::SetPositionShift(CPoint ptPositionShift) { m_ptPositionShift.x = ptPositionShift.x; m_ptPositionShift.y = ptPositionShift.y; } void CImageProc::CalcTestRange(CBaseImage& SnapImage, int& nStartXposition, int& nEndXposition, int& nStartYposition, int& nEndYposition) { CString szString = _T(""); int nSnapWidth = SnapImage.m_InfoHeader.biWidth; int nSnapHeight = SnapImage.m_InfoHeader.biHeight; if((m_nRoiHeight > 0) && (m_nRoiWidth > 0)) // In case of applying ROI { // Set start position & end position if(m_ptPositionShift.x >= 0) { nStartXposition = m_ptRoiPosition.x; nEndXposition = nStartXposition + m_nRoiWidth; if((nEndXposition + m_ptPositionShift.x) > nSnapWidth) { nEndXposition = nEndXposition - m_ptPositionShift.x; } } else { nStartXposition = m_ptRoiPosition.x; nEndXposition = nStartXposition + m_nRoiWidth; if((nStartXposition - abs(m_ptPositionShift.x)) < 0) { nStartXposition = nStartXposition + abs(m_ptPositionShift.x); //+change kwmoon 080819 // nEndXposition = nStartXposition - abs(m_ptPositionShift.x); nEndXposition = nEndXposition - abs(m_ptPositionShift.x); } } if(m_ptPositionShift.y >= 0) { nStartYposition = GetOppositeStartYposition(m_ptRoiPosition.y,m_nRoiHeight,nSnapHeight); nEndYposition = nStartYposition + m_nRoiHeight; if((nStartYposition - abs(m_ptPositionShift.y)) < 0) { nStartYposition = nStartYposition + abs(m_ptPositionShift.y); nEndYposition = nEndYposition - abs(m_ptPositionShift.y); } } else { nStartYposition = GetOppositeStartYposition(m_ptRoiPosition.y,m_nRoiHeight,nSnapHeight); nEndYposition = nStartYposition + m_nRoiHeight; if((nEndYposition + abs(m_ptPositionShift.y)) > nSnapHeight) { nEndYposition = nEndYposition - abs(m_ptPositionShift.y); } } } else // In case of full size test { // Set start position & end position if(m_ptPositionShift.x >= 0) { //+change kwmoon 080618 // nStartXposition = 0; nStartXposition = m_ptPositionShift.x; //+change kwmoon 080618 // nEndXposition = (RefImage.m_InfoHeader.biWidth-1)-m_ptPositionShift.x; nEndXposition = (nSnapWidth-1)-m_ptPositionShift.x; } else { nStartXposition = abs(m_ptPositionShift.x); //+change kwmoon 080618 // nEndXposition = (RefImage.m_InfoHeader.biWidth-1)-abs(m_ptPositionShift.x); nEndXposition = (nSnapWidth-1)-abs(m_ptPositionShift.x); } if(m_ptPositionShift.y >= 0) { //+change kwmoon 080618 // nStartYposition = 0; nStartYposition = m_ptPositionShift.y; //+change kwmoon 080618 // nEndXposition = (RefImage.m_InfoHeader.biWidth-1)-abs(m_ptPositionShift.x); nEndYposition = (nSnapHeight-1)-m_ptPositionShift.y; } else { nStartYposition = 0; //+change kwmoon 080618 // nEndXposition = (RefImage.m_InfoHeader.biWidth-1)-abs(m_ptPositionShift.x); nEndYposition = (nSnapHeight-1)-abs(m_ptPositionShift.y); } } } /*----------------------------------------------------------------------------------------- 함수명 : RGBTest 기 능 : - Grab한 이미지와 Reference 이미지를 비교하여 Spec In/Out을 판정함 - Mask 이미지를 참조하여 Black 영역만을 검사함 - 각 Pixel을 1:1로 비교하는 방식과 칼라값의 상위 몇 Bit를 비교하는 2가지 방식이 있음 - 각 Pixel을 1:1로 비교하는 방식의 경우, 가장 큰 차이를 갖는 칼라값 정보를 제공함 입력파라미터 : - int nType : OSD_IMAGE_TEST - OSD 검사, Grab이미지와 Ref이미지의 ROI영역에 대해 Avg-Filter 적용함 NORMAL_IMAGE_TEST - COLOR 검사, Ref이미지는 이미 Avg-Filter(3x3) 적용해 두었으므로, Grab에만 Avg-Filter(3x3) 적용함 - CBaseImage& SnapImage : Grab한 이미지가 저장되어 있는 Object - CBaseImage& RefImage : Reference 이미지가 저장되어 있는 Object - CBaseImage& MaskImage : Mask 이미지가 저장되어 있는 Object - POINT& ptResultPosition : 가장 큰 칼라값 차이가 발견된 좌표 - float& fMaxDifference : 가장 큰 칼라값 차이 - int& nTotalNoErrorPixel : SpecOut인 Pixel의 총 개수 - BOOL bUseMaskImage : 칼라값 비교시, Mask 이미지를 참조할지의 여부 Return 값 : - TEST_PASS, TEST_FAIL 또는 TEST_ABORT -----------------------------------------------------------------------------------------*/ int CImageProc::RGBTest(int nType, CBaseImage& SnapImage, CBaseImage& RefImage, CBaseImage& MaskImage, POINT& ptResultPosition,float& fMaxDifference,int& nTotalNoErrorPixel, BOOL bUseMaskImage,CProgressCtrl& Progress) { int nProgress = 0; int nTestResult = TEST_PASS; //================================== // Dimension of the Reference Image //================================== int nRefWidth = RefImage.m_InfoHeader.biWidth; int nRefHeight = RefImage.m_InfoHeader.biHeight; int nMaskWidth = 0; int nMaskHeight = 0; if(MaskImage.m_bImageLoaded) { nMaskWidth = MaskImage.m_InfoHeader.biWidth; nMaskHeight = MaskImage.m_InfoHeader.biHeight; } //============================= // Dimension of the Snap Image //============================= int nSnapWidth = SnapImage.m_InfoHeader.biWidth; int nSnapHeight = SnapImage.m_InfoHeader.biHeight; int nSnapBitCount = SnapImage.m_InfoHeader.biBitCount; //================= // Local Variables //================= int nDifference = 0; int nGrabRcolor = 0,nGrabGcolor = 0,nGrabBcolor = 0; int nRefRcolor = 0,nRefGcolor = 0,nRefBcolor = 0; int nShiftedDiff = 0; int nColorMargin = 0; int nLowerLimit = 0,nUpperLimit = 0; int nRefRGBvaule = 0,nSnapRGBvalue = 0; int nNoShift = 0; int nStartXposition = 0,nStartYposition = 0; int nEndXposition = 0,nEndYposition = 0; int nColorDepth = RefImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*RefImage.m_InfoHeader.biWidth); int nNoLevel = (int)pow(2,(nColorDepth/3))-1; BYTE* SnapImageBackup = NULL; BYTE* RefImageBackup = NULL; POINT ptPassPlusResultPosition = {0,0}; POINT ptPassMinusResultPosition = {0,0}; POINT ptNgPlusResultPosition = {0,0}; POINT ptNgMinusResultPosition = {0,0}; int nPassPlusMaxDifference = 0; int nNgPlusMaxDifference = 0; int nPassMinusMaxDifference = 0; int nNgMinusMaxDifference = 0; int nImageBufferSize = 0; int nImageSize = 0; int nTestRetryFlag = 0; int nPlusMaxDifference = 0; int nMinusMaxDifference = 0; POINT ptPlusResultPosition; POINT ptMinusResultPosition; int nAvgMaskWidth = 3; int nAvgMaskHeight = 3; DWORD dwFuncTickCount = 0; DWORD dwFuncElapsedTime = 0; CString szFuncElapsedTime = _T(""); CString szErrMsg = _T(""); START_TEST : //======================= // Check Image Attribute //======================= if(CheckImageAttribute(SnapImage,RefImage,MaskImage) == TEST_ABORT) { return TEST_ABORT; } nTotalNoErrorPixel = 0; m_nNoErrorInfo = 0; m_nNoGoodPixel = 0; m_fGoodPixelPercentage = 0.0f; //============ // Init array //============ if(CurrentSet->bSaveReviewData || CurrentSet->bSaveDetailResultData || g_pView->m_bAdjSpecMode) { for(int i=0; i<3; i++) { for(int j=0; j<NO_DIFFERENT_POINT_BLOCK; j++) m_aNoDifferentPoint[i][j] = 0; } m_nSecondDifferentPointFreePercent = -1; } for(int i=0; i<5;i++) { m_nNoBandErrorPixel[i] = 0; m_nNoAllowedBandErrorPixel[i] = 0; m_fBandErrorPixelPercentage[i] = 0.0f; } Progress.SetPos(10); //========================================= // Allocate memory for the processed image //========================================= nImageSize = SnapImage.m_InfoHeader.biSizeImage; if(SnapImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(SnapImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(SnapImage.m_pProcessedImageData); SnapImage.m_pProcessedImageData = NULL; SnapImage.m_pProcessedImageData = (BYTE *)malloc(SnapImage.m_BmInfo->bmiHeader.biSizeImage); } } else { SnapImage.m_pProcessedImageData = (BYTE *)malloc(SnapImage.m_BmInfo->bmiHeader.biSizeImage); } memset(SnapImage.m_pProcessedImageData,0,SnapImage.m_BmInfo->bmiHeader.biSizeImage); //============================================ // Allocate memory for temporary image buffer //============================================ //+change kwmoon 080820 // BYTE* pProcessedImageData = (BYTE *)malloc(SnapImage.m_InfoHeader.biSizeImage); // memset(pProcessedImageData,0,SnapImage.m_InfoHeader.biSizeImage); BYTE* pProcessedImageData = g_ImageBuffer1; memset(g_ImageBuffer1,0,FULL_HD_IMAGE_SIZE); Progress.SetPos(20); nLowerLimit = Percentage2Level(m_fLowerLimit,nNoLevel); nUpperLimit = Percentage2Level(m_fUpperLimit,nNoLevel); if(m_nNoUsedColorHighBits > 0) { nNoShift = SnapImage.m_InfoHeader.biBitCount/3 - m_nNoUsedColorHighBits; } //======================= // Calculate Coordinates //======================= CalcTestRange(SnapImage,nStartXposition,nEndXposition,nStartYposition,nEndYposition); //====================== // Apply Average Filter //====================== if(nType == OSD_IMAGE_TEST) { if(Average(nAvgMaskWidth,nAvgMaskHeight,nStartXposition,nEndXposition, nStartYposition,nEndYposition,SnapImage,FALSE) == TEST_FAIL) { AfxMessageBox("Failed to run average-filter"); return TEST_ABORT; } if(Average(nAvgMaskWidth,nAvgMaskHeight,nStartXposition,nEndXposition, nStartYposition,nEndYposition,RefImage,FALSE) == TEST_FAIL) { AfxMessageBox("Failed to run average-filter"); return TEST_ABORT; } } /* else { if(Average(nAvgMaskWidth,nAvgMaskHeight,nStartXposition,nEndXposition, nStartYposition,nEndYposition,SnapImage,FALSE) == TEST_FAIL) { AfxMessageBox("Failed to run average-filter"); return TEST_ABORT; } if(RefImage.m_pProcessedImageData == NULL) { RefImage.m_pProcessedImageData = (BYTE *)malloc(RefImage.m_BmInfo->bmiHeader.biSizeImage); } memcpy((BYTE*)RefImage.m_pProcessedImageData,(BYTE*)RefImage.m_pImageData,(int)RefImage.m_InfoHeader.biSizeImage); } */ SnapImage.m_bProcessedImageLoaded = FALSE; int nX = 0,nY = 0; int nColorChannel = 0; int nLastErrorXpos = -1,nLastErrorYpos = -1; int nSnapImageIndex = 0, nRefImageIndex = 0; int nBlockIndex = 0, nMaskValue = 0; int nDifferenceR = 0, nDifferenceG = 0, nDifferenceB = 0; int nMaxDifference = 0, nMinDifference = 0; BOOL bInvalidMask = TRUE; m_nNoTargetPixel = 0; //20101207 Change :m_pImageData -> m_pProcessedImageData //===================== // Compare each pixels //===================== for(int nRow = nStartYposition; nRow <= nEndYposition; nRow++) { for(int nColumn = nStartXposition; nColumn <= nEndXposition; nColumn++) { nRefImageIndex = (nRow)*nBytesInRow+3*(nColumn); nSnapImageIndex = (nRow-m_ptPositionShift.y)*nBytesInRow+3*(nColumn+m_ptPositionShift.x); if(MaskImage.m_bImageLoaded && bUseMaskImage) { nMaskValue = MaskImage.m_pImageData[nRefImageIndex] | MaskImage.m_pImageData[nRefImageIndex+1] | MaskImage.m_pImageData[nRefImageIndex+2]; } if(nMaskValue == 0) // Inspection Region { m_nNoTargetPixel++; bInvalidMask = FALSE; if(nType == OSD_IMAGE_TEST) { nRefBcolor = RefImage.m_pProcessedImageData[nRefImageIndex]; nGrabBcolor = SnapImage.m_pProcessedImageData[nSnapImageIndex]; nRefGcolor = RefImage.m_pProcessedImageData[nRefImageIndex+1]; nGrabGcolor = SnapImage.m_pProcessedImageData[nSnapImageIndex+1]; nRefRcolor = RefImage.m_pProcessedImageData[nRefImageIndex+2]; nGrabRcolor = SnapImage.m_pProcessedImageData[nSnapImageIndex+2]; } else{ nRefBcolor = RefImage.m_pImageData[nRefImageIndex]; nGrabBcolor = SnapImage.m_pImageData[nSnapImageIndex]; nRefGcolor = RefImage.m_pImageData[nRefImageIndex+1]; nGrabGcolor = SnapImage.m_pImageData[nSnapImageIndex+1]; nRefRcolor = RefImage.m_pImageData[nRefImageIndex+2]; nGrabRcolor = SnapImage.m_pImageData[nSnapImageIndex+2]; } //=================== // Color Difference //=================== if(m_nNoUsedColorHighBits > 0) { nDifferenceB = ((nGrabBcolor>>nNoShift) - (nRefBcolor>>nNoShift)); nDifferenceG = ((nGrabGcolor>>nNoShift) - (nRefGcolor>>nNoShift)); nDifferenceR = ((nGrabRcolor>>nNoShift) - (nRefRcolor>>nNoShift)); } else { nDifferenceB = (nGrabBcolor - nRefBcolor); nDifferenceG = (nGrabGcolor - nRefGcolor); nDifferenceR = (nGrabRcolor - nRefRcolor); } //=================== // Difference Image //=================== //+change kwmoon 080820 // pProcessedImageData[nRefImageIndex] = abs(nDifferenceB); // pProcessedImageData[nRefImageIndex+1] = abs(nDifferenceG); // pProcessedImageData[nRefImageIndex+2] = abs(nDifferenceR); if((abs(nDifferenceG) <= nUpperLimit) && (abs(nDifferenceG) >= nLowerLimit) // R && (abs(nDifferenceG) <= nUpperLimit) && (abs(nDifferenceG) >= nLowerLimit) // G && (abs(nDifferenceB) <= nUpperLimit) && (abs(nDifferenceB) >= nLowerLimit)) // B { // Spec In pProcessedImageData[nRefImageIndex+2] = 0; pProcessedImageData[nRefImageIndex+1] = 0; pProcessedImageData[nRefImageIndex ] = 0; } else { // Spec Out pProcessedImageData[nRefImageIndex+2] = 255; pProcessedImageData[nRefImageIndex+1] = 255; pProcessedImageData[nRefImageIndex ] = 255; } //- nMaxDifference = GetMaxValue(nDifferenceB,nDifferenceG,nDifferenceR); nMinDifference = GetMinValue(nDifferenceB,nDifferenceG,nDifferenceR); nDifference = abs(nMaxDifference) >= abs(nMinDifference) ? nMaxDifference : nMinDifference; //============ // Error Pixel //============ if(((m_nNoUsedColorHighBits > 0) && (abs(nDifference) > 0)) || ((m_nNoUsedColorHighBits == 0) && ((nMaxDifference > nUpperLimit) || (nMinDifference < nLowerLimit)))) { if(m_nNoUsedColorHighBits > 0) { nDifference = nDifference<<nNoShift; } if((nColumn != nLastErrorXpos) || (nRow != nLastErrorYpos)) { nTotalNoErrorPixel++; float fDifferenePercentage = 0; if(nDifference >= 0) // nDifference > nUpperLimit { fDifferenePercentage = Level2Percentage(abs(nDifference-nUpperLimit),nNoLevel); if(fDifferenePercentage < 2) m_nNoBandErrorPixel[0]++; if((fDifferenePercentage >= 2) && (fDifferenePercentage < 4)) m_nNoBandErrorPixel[1]++; if((fDifferenePercentage >= 4) && (fDifferenePercentage < 6)) m_nNoBandErrorPixel[2]++; if((fDifferenePercentage >= 6) && (fDifferenePercentage < 8)) m_nNoBandErrorPixel[3]++; if(fDifferenePercentage >= 8) m_nNoBandErrorPixel[4]++; } else // nDifference < nLowerLimit { fDifferenePercentage = Level2Percentage(abs(nDifference-nLowerLimit),nNoLevel); if(fDifferenePercentage < 2) m_nNoBandErrorPixel[0]++; if((fDifferenePercentage >= 2) && (fDifferenePercentage < 4)) m_nNoBandErrorPixel[1]++; if((fDifferenePercentage >= 4) && (fDifferenePercentage < 6)) m_nNoBandErrorPixel[2]++; if((fDifferenePercentage >= 6) && (fDifferenePercentage < 8)) m_nNoBandErrorPixel[3]++; if(fDifferenePercentage >= 8) m_nNoBandErrorPixel[4]++; } nLastErrorXpos = nColumn; nLastErrorYpos = nRow; } if((nDifference <0) && (nDifference < nNgMinusMaxDifference)) { nNgMinusMaxDifference = nDifference; ptNgMinusResultPosition.x = nColumn; ptNgMinusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } if((nDifference >=0) && (nDifference >= nNgPlusMaxDifference)) { nNgPlusMaxDifference = nDifference; ptNgPlusResultPosition.x = nColumn; ptNgPlusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } } //============ // Good Pixel //============ else { m_nNoGoodPixel++; if((nDifference <0) && (nDifference < nPassMinusMaxDifference)) { nPassMinusMaxDifference = nDifference; ptPassMinusResultPosition.x = nColumn; ptPassMinusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } if((nDifference >=0) && (nDifference >= nPassPlusMaxDifference)) { nPassPlusMaxDifference = nDifference; ptPassPlusResultPosition.x = nColumn; ptPassPlusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } } if(CurrentSet->bSaveReviewData || CurrentSet->bSaveDetailResultData || g_pView->m_bAdjSpecMode) { nBlockIndex = (int)Level2Percentage(abs(nDifferenceB),nNoLevel); m_aNoDifferentPoint[0][nBlockIndex]++; nBlockIndex = (int)Level2Percentage(abs(nDifferenceG),nNoLevel); m_aNoDifferentPoint[1][nBlockIndex]++; nBlockIndex = (int)Level2Percentage(abs(nDifferenceR),nNoLevel); m_aNoDifferentPoint[2][nBlockIndex]++; } } } } //============================ // Store data for spec-adjust //============================ if(CurrentSet->bSaveReviewData || CurrentSet->bSaveDetailResultData || g_pView->m_bAdjSpecMode) { int nDifferentPointFreePercentNo = 0; for(int j=0; j<NO_DIFFERENT_POINT_BLOCK; j++) { if((m_aNoDifferentPoint[0][j] == 0) && (m_aNoDifferentPoint[1][j] == 0) && (m_aNoDifferentPoint[2][j] == 0)) { nDifferentPointFreePercentNo++; if(nDifferentPointFreePercentNo == 2) { m_nSecondDifferentPointFreePercent = j; break; } } } } //============== // Invalid Mask //============== if(bInvalidMask) { CString szMsg = _T(""); CString szFileName = _T(""); if(nType == GRAB_CHECK_TEST) { szMsg.Format("[Grab_Image_Check] No test was performed because of a mask image values. check mask image! (%d,%d)",m_nRoiWidth,m_nRoiHeight); } else { szMsg.Format("[Color Test] No test was performed because of a mask image values. check mask image!"); } if(nTestRetryFlag == 0) { if(RefImage.m_szFilePath != _T("")) { szFileName = RefImage.m_szFilePath.Right(RefImage.m_szFilePath.GetLength()-RefImage.m_szFilePath.ReverseFind('\\')-1); if(!RefImage_DirectLoad(szFileName,1)) { AfxMessageBox(szMsg); return TEST_ABORT; } else { nTestRetryFlag = 1; goto START_TEST; } } } AfxMessageBox(szMsg); return TEST_ABORT; } SnapImage.m_bProcessedImageLoaded = TRUE; Progress.SetPos(100); //========================================================== // Copy temoporary image to SnapImage.m_pProcessedImageData //========================================================== memcpy((BYTE*)SnapImage.m_pProcessedImageData,(BYTE*)pProcessedImageData,(int)SnapImage.m_InfoHeader.biSizeImage); //======================================= // Deallocate memory for temporary image //======================================= //+change kwmoon 080820 /* if(pProcessedImageData != NULL) { free(pProcessedImageData); pProcessedImageData = NULL; } */ pProcessedImageData = NULL; //======================= // Make Difference Image //======================= //+del kwmoon 080820 // BinaryForDiffImage(NORMAL_BINARY,SnapImage,nLowerLimit,nUpperLimit); //============================= // Store data for error pixels //============================= for(int i=0; i<5; i++) { if(m_nNoBandErrorPixel[i] == 0) { m_fBandErrorPixelPercentage[i] = 0; } else { m_fBandErrorPixelPercentage[i] = (float)m_nNoBandErrorPixel[i] * 100 / (float)m_nNoTargetPixel; } m_nNoAllowedBandErrorPixel[i] = (int)((float)m_fAllowedBandErrorPixelPercentage[i] * 0.01 * (float)m_nNoTargetPixel); } m_fGoodPixelPercentage =(float)m_nNoGoodPixel * 100 / (float)m_nNoTargetPixel; //=========================== // Find Max Difference Value //=========================== if(nTotalNoErrorPixel == 0) { nTestResult = TEST_PASS; nPlusMaxDifference = nPassPlusMaxDifference; nMinusMaxDifference = nPassMinusMaxDifference; ptPlusResultPosition = ptPassPlusResultPosition; ptMinusResultPosition = ptPassMinusResultPosition; } else { if((m_fBandErrorPixelPercentage[0] < CurrentSet->fAllowedBandErrorPixelPercentage[0]) && (m_fBandErrorPixelPercentage[1] < CurrentSet->fAllowedBandErrorPixelPercentage[1]) && (m_fBandErrorPixelPercentage[2] < CurrentSet->fAllowedBandErrorPixelPercentage[2]) && (m_fBandErrorPixelPercentage[3] < CurrentSet->fAllowedBandErrorPixelPercentage[3]) && (m_fBandErrorPixelPercentage[4] < CurrentSet->fAllowedBandErrorPixelPercentage[4])) { nTestResult = TEST_PASS; nPlusMaxDifference = nPassPlusMaxDifference; nMinusMaxDifference = nPassMinusMaxDifference; ptPlusResultPosition = ptPassPlusResultPosition; ptMinusResultPosition = ptPassMinusResultPosition; } else { nTestResult = TEST_FAIL; nPlusMaxDifference = nNgPlusMaxDifference; nMinusMaxDifference = nNgMinusMaxDifference; ptPlusResultPosition = ptNgPlusResultPosition; ptMinusResultPosition = ptNgMinusResultPosition; } } if(nPlusMaxDifference >= abs(nMinusMaxDifference)) { nMaxDifference = nPlusMaxDifference; ptResultPosition.x = ptPlusResultPosition.x; ptResultPosition.y = ptPlusResultPosition.y; } else { nMaxDifference = nMinusMaxDifference; ptResultPosition.x = ptMinusResultPosition.x; ptResultPosition.y = ptMinusResultPosition.y; } fMaxDifference = Level2Percentage(nMaxDifference,nNoLevel); return nTestResult; } //+add kwmoon 080124 int CImageProc::GetMaxValue(int nDifferenceB,int nDifferenceG,int nDifferenceR) { int nDifference = 0; int nMaxDifference = 0; nDifference = nDifferenceB >= nDifferenceG ? nDifferenceB : nDifferenceG; nMaxDifference = nDifference >= nDifferenceR ? nDifference : nDifferenceR; return nMaxDifference; } //+add kwmoon 080124 int CImageProc::GetMinValue(int nDifferenceB,int nDifferenceG,int nDifferenceR) { int nDifference = 0; int nMinDifference = 0; nDifference = nDifferenceB <= nDifferenceG ? nDifferenceB : nDifferenceG; nMinDifference = nDifference <= nDifferenceR ? nDifference : nDifferenceR; return nMinDifference; } int CImageProc::BrightnessTest(CBaseImage& SnapImage, CBaseImage& RefImage, CBaseImage& MaskImage, POINT& ptResultPosition,int& nMaxDifference,CProgressCtrl& Progress) { // If it's not a true color image, return false if((SnapImage.m_InfoHeader.biBitCount < 24) || (RefImage.m_InfoHeader.biBitCount < 24)) { AfxMessageBox("Only true color image is supported!"); return TEST_ABORT; } int nProgress = 0; int nTestResult = TEST_PASS; // Dimension of the Reference Image int nRefWidth = RefImage.m_InfoHeader.biWidth; int nRefHeight = RefImage.m_InfoHeader.biHeight; // Dimension of the Snap Image int nSnapWidth = SnapImage.m_InfoHeader.biWidth; int nSnapHeight = SnapImage.m_InfoHeader.biHeight; int nSnapBitCount = SnapImage.m_InfoHeader.biBitCount; int nDifference = 0; int nMaxPassDifference = 0; int nMaxFailDifference = 0; int nGrabRcolor = 0; int nGrabGcolor = 0; int nGrabBcolor = 0; int nRefRcolor = 0; int nRefGcolor = 0; int nRefBcolor = 0; int nGrabYcolor = 0; int nGrabCbcolor = 0; int nGrabCrcolor = 0; int nRefYcolor = 0; int nRefCbcolor = 0; int nRefCrcolor = 0; int nShiftedDiff = 0; int nColorMargin = 0; int nRefBrightValue = 0; int nSnapBrightValue = 0; int nNoShift = 0; int nStartXposition = 0; int nStartYposition = 0; int nEndXposition = 0; int nEndYposition = 0; int nColorDepth = RefImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*RefImage.m_InfoHeader.biWidth); BYTE* SnapImageBackup = NULL; BYTE* RefImageBackup = NULL; int nImageBufferSize = 0; int nImageSize = 0; CString szErrMsg = _T(""); if(SnapImage.m_bImageLoaded == FALSE) { AfxMessageBox("Snap Image is not loaded!"); return TEST_ABORT; } if(RefImage.m_bImageLoaded == FALSE) { AfxMessageBox("Ref Image is not loaded!"); return TEST_ABORT; } if(MaskImage.m_bImageLoaded == FALSE) { AfxMessageBox("Mask Image is not loaded!"); return TEST_ABORT; } // Compare the size and color depth of images if((nRefWidth != nSnapWidth) || (nRefHeight != nSnapHeight)) { AfxMessageBox("The size of two images is different!"); return TEST_ABORT; } if(RefImage.m_InfoHeader.biBitCount != SnapImage.m_InfoHeader.biBitCount) { AfxMessageBox("The color depth of two images is different!"); return TEST_ABORT; } if((m_nRoiWidth >= nSnapWidth) || (m_nRoiHeight >= nSnapHeight)) { szErrMsg.Format("[ROI Error] Roi with & height should be less than witdh & height of image! (W:%d_%d,H:%d_%d)" ,m_nRoiWidth,nSnapWidth,m_nRoiHeight,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if((m_ptRoiPosition.x >= (nSnapWidth-1)) || (m_ptRoiPosition.y >= (nSnapHeight-1))) { szErrMsg.Format("[ROI Error] Roi (x,y) should be less than witdh & height of image! (X:%d,Y:%d,W:%d,H:%d)" ,m_ptRoiPosition.x,m_ptRoiPosition.y,nSnapWidth,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } m_nNoErrorInfo = 0; Progress.SetPos(10); // Allocate memory (store the processed image into a snapImage object) nImageSize = SnapImage.m_InfoHeader.biSizeImage; if(SnapImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(SnapImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(SnapImage.m_pProcessedImageData); SnapImage.m_pProcessedImageData = NULL; SnapImage.m_pProcessedImageData = (BYTE *)malloc(SnapImage.m_BmInfo->bmiHeader.biSizeImage); } } else { SnapImage.m_pProcessedImageData = (BYTE *)malloc(SnapImage.m_BmInfo->bmiHeader.biSizeImage); } memset(SnapImage.m_pProcessedImageData,0,SnapImage.m_BmInfo->bmiHeader.biSizeImage); Progress.SetPos(20); nColorMargin = m_nBrightMarginLevel; if(m_nNoUsedBrightHighBits > 0) { nNoShift = SnapImage.m_InfoHeader.biBitCount/3 - m_nNoUsedBrightHighBits; } //+change kwmoon 080618 CalcTestRange(SnapImage,nStartXposition,nEndXposition,nStartYposition,nEndYposition); SnapImage.m_bProcessedImageLoaded = FALSE; int nX = 0; int nY = 0; int nColorChannel = 0; int nLastErrorXpos = -1; int nLastErrorYpos = -1; int nSnapImageIndex = 0; int nRefImageIndex = 0; int nMaskValue = 0; if(RefImage.m_InfoHeader.biBitCount==24) // If the color depth of image is 24 bits { for(int nRow=nStartYposition; nRow<=nEndYposition; nRow++) { for(int nColumn=nStartXposition; nColumn<=nEndXposition; nColumn++) { nRefImageIndex = (nRow)*nBytesInRow+3*(nColumn); nSnapImageIndex = (nRow-m_ptPositionShift.y)*nBytesInRow+3*(nColumn+m_ptPositionShift.x); nMaskValue = MaskImage.m_pImageData[nRefImageIndex] | MaskImage.m_pImageData[nRefImageIndex+1] | MaskImage.m_pImageData[nRefImageIndex+2]; if(nMaskValue == 0) { nGrabRcolor = SnapImage.m_pImageData[nSnapImageIndex+2]; nGrabGcolor = SnapImage.m_pImageData[nSnapImageIndex+1]; nGrabBcolor = SnapImage.m_pImageData[nSnapImageIndex]; nRefRcolor = RefImage.m_pImageData[nRefImageIndex+2]; nRefGcolor = RefImage.m_pImageData[nRefImageIndex+1]; nRefBcolor = RefImage.m_pImageData[nRefImageIndex]; nGrabYcolor = (int)(0.29900*nGrabRcolor + 0.58700*nGrabGcolor + 0.11400*nGrabBcolor); nGrabCbcolor = (int)(-0.16874*nGrabRcolor - 0.33126*nGrabGcolor + 0.50000*nGrabBcolor); nGrabCrcolor = (int)(0.50000*nGrabRcolor - 0.41869*nGrabGcolor - 0.08131*nGrabBcolor); nRefYcolor = (int)(0.29900*nRefRcolor + 0.58700*nRefGcolor + 0.11400*nRefBcolor); nRefCbcolor = (int)(-0.16874*nRefRcolor - 0.33126*nRefGcolor + 0.50000*nRefBcolor); nRefCrcolor = (int)(0.50000*nRefRcolor - 0.41869*nRefGcolor - 0.08131*nRefBcolor); nRefBrightValue = nRefYcolor; nSnapBrightValue = nGrabYcolor; if(m_nNoUsedColorHighBits > 0) { nDifference = (abs)((nRefBrightValue>>nNoShift) - (nSnapBrightValue>>nNoShift)); } else { nDifference = (abs)(nRefBrightValue - nSnapBrightValue); } SnapImage.m_pProcessedImageData[nRefImageIndex+2] = nDifference; SnapImage.m_pProcessedImageData[nRefImageIndex+1] = nDifference; SnapImage.m_pProcessedImageData[nRefImageIndex] = nDifference; if(((m_nNoUsedColorHighBits > 0) && (nDifference > 0)) ||((m_nNoUsedColorHighBits == 0) && (nDifference > nColorMargin))) { if(m_nNoUsedColorHighBits > 0) { nDifference = nDifference<<nNoShift; } nTestResult = TEST_FAIL; if((nColumn != nLastErrorXpos) || (nRow != nLastErrorYpos)) { nLastErrorXpos = nColumn; nLastErrorYpos = nRow; } if(nDifference > nMaxFailDifference) { nMaxFailDifference = nDifference; // 최대 차이값이 찾아진 좌표를 저장함 ptResultPosition.x = nColumn; ptResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } } // 표준 이미지와 색상값의 차이가 없는 경우, 최대 차이값을 찾아 표시함 else { if(nDifference > nMaxPassDifference) { nMaxPassDifference = nDifference; // 최대 차이값이 찾아진 좌표를 저장함 ptResultPosition.x = nColumn; ptResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } } } } } } else { return TEST_ABORT; } SnapImage.m_bProcessedImageLoaded = TRUE; Progress.SetPos(100); BinaryForMonoImage(NORMAL_BINARY,SnapImage.m_pProcessedImageData,nSnapHeight,nSnapWidth,nSnapBitCount,nColorMargin); if(nTestResult == TEST_PASS) { // Pass인 경우, 정상범위내에서의 최대차이값을 리턴해줌 nMaxDifference = nMaxPassDifference; } else { // Fail인 경우, Fail시의 최대차이값을 리턴해줌 nMaxDifference = nMaxFailDifference; } return nTestResult; } int CImageProc::SignalLineTest(int nType,BOOL bUseMaskImage, CProgressCtrl& Progress) { if((m_LineBitTestData.m_pGrabImage->m_InfoHeader.biBitCount < 24) || (m_LineBitTestData.m_pRefImage->m_InfoHeader.biBitCount < 24)) { AfxMessageBox("Only true color image is supported!"); return TEST_ABORT; } // Dimension of the Reference Image int nRefWidth = m_LineBitTestData.m_pRefImage->m_InfoHeader.biWidth; int nRefHeight = m_LineBitTestData.m_pRefImage->m_InfoHeader.biHeight; int nRefBitCount = m_LineBitTestData.m_pRefImage->m_InfoHeader.biBitCount; // Dimension of the Grab Image int nSnapWidth = m_LineBitTestData.m_pGrabImage->m_InfoHeader.biWidth; int nSnapHeight = m_LineBitTestData.m_pGrabImage->m_InfoHeader.biHeight; int nGrabBitCount = m_LineBitTestData.m_pGrabImage->m_InfoHeader.biBitCount; // Dimension of the Mask Image int nMaskWidth = m_LineBitTestData.m_pMaskImage->m_InfoHeader.biWidth; int nMaskHeight = m_LineBitTestData.m_pMaskImage->m_InfoHeader.biHeight; int nProgress = 0; int nTestResult = TEST_PASS; int nDifference = 0; int nLowBitPairDifference = 0; int nHighBitPairDifference = 0; int nRefRGBvaule = 0; int nGrabRGBvalue = 0; int nNoShift = 0; int nStartXposition = 0; int nStartYposition = 0; int nEndXposition = 0; int nEndYposition = 0; int nBytesInRow = WIDTHBYTES(nRefBitCount*nRefWidth); BYTE* GrabImageBackup = NULL; BYTE* RefImageBackup = NULL; POINT ptPassPlusResultPosition = {0,0}; POINT ptPassMinusResultPosition = {0,0}; POINT ptNgPlusResultPosition = {0,0}; POINT ptNgMinusResultPosition = {0,0}; int nPassPlusMaxDifference = 0; int nNgPlusMaxDifference = 0; int nPassMinusMaxDifference = 0; int nNgMinusMaxDifference = 0; int nImageBufferSize = 0; int nImageSize = 0; CString szErrMsg = _T(""); if(m_LineBitTestData.m_pGrabImage->m_bImageLoaded == FALSE) { AfxMessageBox("Grab Image is not loaded!"); return TEST_ABORT; } if(m_LineBitTestData.m_pRefImage->m_bImageLoaded == FALSE) { AfxMessageBox("Ref Image is not loaded!"); return TEST_ABORT; } if((nRefWidth != nSnapWidth) || (nRefHeight != nSnapHeight)) { AfxMessageBox("The size of two images is different!"); return TEST_ABORT; } if(nRefBitCount != nGrabBitCount) { AfxMessageBox("The color depth of two images is different!"); return TEST_ABORT; } if((m_nRoiWidth >= nSnapWidth) || (m_nRoiHeight >= nSnapHeight)) { szErrMsg.Format("[ROI Error] Roi with & height should be less than witdh & height of image! (W:%d_%d,H:%d_%d)" ,m_nRoiWidth,nSnapWidth,m_nRoiHeight,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if((m_ptRoiPosition.x >= (nSnapWidth-1)) || (m_ptRoiPosition.y >= (nSnapHeight-1))) { szErrMsg.Format("[ROI Error] Roi (x,y) should be less than witdh & height of image! (X:%d,Y:%d,W:%d,H:%d)" ,m_ptRoiPosition.x,m_ptRoiPosition.y,nSnapWidth,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if(m_LineBitTestData.m_pMaskImage->m_bImageLoaded) { if((nRefWidth != nMaskWidth) || (nRefHeight != nMaskHeight)) { AfxMessageBox("The size of a reference image is different from that of a mask image!"); return TEST_ABORT; } } Progress.SetPos(10); nImageSize = m_LineBitTestData.m_pGrabImage->m_InfoHeader.biSizeImage; if(m_LineBitTestData.m_pGrabImage->m_pProcessedImageData != NULL) { nImageBufferSize = _msize(m_LineBitTestData.m_pGrabImage->m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(m_LineBitTestData.m_pGrabImage->m_pProcessedImageData); m_LineBitTestData.m_pGrabImage->m_pProcessedImageData = NULL; m_LineBitTestData.m_pGrabImage->m_pProcessedImageData = (BYTE *)malloc(m_LineBitTestData.m_pGrabImage->m_BmInfo->bmiHeader.biSizeImage); } } else { m_LineBitTestData.m_pGrabImage->m_pProcessedImageData = (BYTE *)malloc(m_LineBitTestData.m_pGrabImage->m_InfoHeader.biSizeImage); } memset(m_LineBitTestData.m_pGrabImage->m_pProcessedImageData,0,m_LineBitTestData.m_pGrabImage->m_InfoHeader.biSizeImage); Progress.SetPos(20); //+change kwmoon 080618 CalcTestRange(*m_LineBitTestData.m_pGrabImage,nStartXposition,nEndXposition,nStartYposition,nEndYposition); m_LineBitTestData.m_pGrabImage->m_bProcessedImageLoaded = FALSE; int nX = 0; int nY = 0; int nColorChannel = 0; int nLastErrorXpos = -1; int nLastErrorYpos = -1; int nGrabImageIndex = 0; int nRefImageIndex = 0; int nMaskValue = 0; BOOL bInvalidMask = TRUE; int nRefBitValue = 0; int nGrabBitValue = 0; float fDifferencePercentage = 0; int nNoTestdPixels = 0; if(m_LineBitTestData.m_pRefImage->m_InfoHeader.biBitCount==24) { for(int nRow=nStartYposition; nRow<=nEndYposition; nRow++) { for(int nColumn=nStartXposition; nColumn<=nEndXposition; nColumn++) { nRefImageIndex = (nRow)*nBytesInRow+3*(nColumn); nGrabImageIndex = (nRow-m_ptPositionShift.y)*nBytesInRow+3*(nColumn+m_ptPositionShift.x); if(m_LineBitTestData.m_pMaskImage->m_bImageLoaded && bUseMaskImage) { nMaskValue = m_LineBitTestData.m_pMaskImage->m_pImageData[nRefImageIndex] | m_LineBitTestData.m_pMaskImage->m_pImageData[nRefImageIndex+1] | m_LineBitTestData.m_pMaskImage->m_pImageData[nRefImageIndex+2]; } m_LineBitTestData.m_nTotalNoUnmaskedPixel++; if(nMaskValue == 0) { bInvalidMask = FALSE; nNoTestdPixels++; m_LineBitTestData.m_nTotalNoMaskedPixel++; for(int j=0; j<3; j++) // R,G,B { nRefRGBvaule = m_LineBitTestData.m_pRefImage->m_pImageData[nRefImageIndex+j]; nGrabRGBvalue = m_LineBitTestData.m_pGrabImage->m_pImageData[nGrabImageIndex+j]; //+add kwmoon 070817 nRefBitValue = 0; nGrabBitValue = 0; for(int k=m_LineBitTestData.m_nNoSkippedSignalLineLowBits; k<MAX_NO_COLOR_BITS; k++) { nRefBitValue = ((((nRefRGBvaule >> k) & 0x01) == 1) ? 1 : 0); if(nRefBitValue) m_LineBitTestData.m_aRefNoHighBit[j][k]++; nGrabBitValue = ((((nGrabRGBvalue >> k) & 0x01) == 1) ? 1 : 0); if(nGrabBitValue) m_LineBitTestData.m_aGrabNoHighBit[j][k]++; } } } } } } else { return TEST_ABORT; } if(bInvalidMask) { CString szMsg; if(nType == GRAB_CHECK_TEST) { szMsg.Format("[Grab_Image_Check] No test was performed because of a mask image values. check mask image!"); } else { szMsg.Format("[Color Test] No test was performed because of a mask image values. check mask image!"); } AfxMessageBox(szMsg); return TEST_ABORT; } Progress.SetPos(100); m_LineBitTestData.m_nBitCount = nRefBitCount; nTestResult = TEST_PASS; for(int j=0; j<3; j++) // R,G,B { for(int k=m_LineBitTestData.m_nNoSkippedSignalLineLowBits; k<(nRefBitCount/3); k++) { if((m_LineBitTestData.m_aGrabNoHighBit[j][k] == 0) || (m_LineBitTestData.m_aGrabNoHighBit[j][k] == nNoTestdPixels)) { m_LineBitTestData.m_nErrorColor = j; m_LineBitTestData.m_nErrorBitPosition = k; nTestResult = TEST_FAIL; break; } } if(nTestResult == TEST_FAIL) break; } return nTestResult; } #define ZOOM_OUT_50 0.5f int CImageProc::NoiseTest(int nType, CBaseImage& SnapImage, CBaseImage& RefImage, CBaseImage& MaskImage, POINT& ptPlusResultPosition,POINT& ptMinusResultPosition, int& nPlusMaxDifference,int& nMinusMaxDifference,int& nTotalNoErrorPixel,BOOL bUseMaskImage,CProgressCtrl& Progress) { // If it's not a true color image, return false if((SnapImage.m_InfoHeader.biBitCount < 24) || (RefImage.m_InfoHeader.biBitCount < 24)) { AfxMessageBox("Only true color image is supported!"); return TEST_ABORT; } int nProgress = 0; int nTestResult = TEST_PASS; // Dimension of the Reference Image int nRefWidth = RefImage.m_InfoHeader.biWidth; int nRefHeight = RefImage.m_InfoHeader.biHeight; int nMaskWidth = 0; int nMaskHeight = 0; if(MaskImage.m_bImageLoaded) { nMaskWidth = MaskImage.m_InfoHeader.biWidth; nMaskHeight = MaskImage.m_InfoHeader.biHeight; } // Dimension of the Snap Image int nSnapWidth = SnapImage.m_InfoHeader.biWidth; int nSnapHeight = SnapImage.m_InfoHeader.biHeight; int nSnapBitCount = SnapImage.m_InfoHeader.biBitCount; int nDifference = 0; int nGrabRcolor = 0; int nGrabGcolor = 0; int nGrabBcolor = 0; int nRefRcolor = 0; int nRefGcolor = 0; int nRefBcolor = 0; int nShiftedDiff = 0; int nColorMargin = 0; int nLowerLimit = 0; int nUpperLimit = 0; int nRefRGBvaule = 0; int nSnapRGBvalue = 0; int nNoShift = 0; int nStartXposition = 0; int nStartYposition = 0; int nEndXposition = 0; int nEndYposition = 0; int nColorDepth = RefImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*RefImage.m_InfoHeader.biWidth); //+change kwmoon 080722 // int nNoLevel = (int)pow(2,(nColorDepth/3)); int nNoLevel = (int)pow(2,(nColorDepth/3))-1; BYTE* SnapImageBackup = NULL; BYTE* RefImageBackup = NULL; POINT ptPassPlusResultPosition = {0,0}; POINT ptPassMinusResultPosition = {0,0}; POINT ptNgPlusResultPosition = {0,0}; POINT ptNgMinusResultPosition = {0,0}; int nPassPlusMaxDifference = 0; int nNgPlusMaxDifference = 0; int nPassMinusMaxDifference = 0; int nNgMinusMaxDifference = 0; int nImageBufferSize = 0; int nImageSize = 0; if((m_nRoiHeight > 0) && (m_nRoiWidth > 0)) { m_nNoRoiPixel = m_nRoiWidth * m_nRoiHeight; } else { m_nNoRoiPixel = nRefWidth * nRefHeight; } //- DWORD dwFuncTickCount = 0; DWORD dwFuncElapsedTime = 0; CString szFuncElapsedTime = _T(""); CString szErrMsg = _T(""); if(SnapImage.m_bImageLoaded == FALSE) { AfxMessageBox("Snap Image is not loaded!"); return TEST_ABORT; } if(RefImage.m_bImageLoaded == FALSE) { AfxMessageBox("Ref Image is not loaded!"); return TEST_ABORT; } if((nRefWidth != nSnapWidth) || (nRefHeight != nSnapHeight)) { szErrMsg.Format("[Image Size Error] Grab(W:%d,H%d), Ref(W:%d,H%d)", nSnapWidth,nSnapHeight,nRefWidth,nRefHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if(RefImage.m_InfoHeader.biBitCount != SnapImage.m_InfoHeader.biBitCount) { AfxMessageBox("The color depth of two images is different!"); return TEST_ABORT; } if((m_nRoiWidth >= nSnapWidth) || (m_nRoiHeight >= nSnapHeight)) { szErrMsg.Format("[ROI Error] Roi with & height should be less than witdh & height of image! (W:%d_%d,H:%d_%d)" ,m_nRoiWidth,nSnapWidth,m_nRoiHeight,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if((m_ptRoiPosition.x >= (nSnapWidth-1)) || (m_ptRoiPosition.y >= (nSnapHeight-1))) { szErrMsg.Format("[ROI Error] Roi (x,y) should be less than witdh & height of image! (X:%d,Y:%d,W:%d,H:%d)" ,m_ptRoiPosition.x,m_ptRoiPosition.y,nSnapWidth,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if(MaskImage.m_bImageLoaded) { if((nRefWidth != nMaskWidth) || (nRefHeight != nMaskHeight)) { szErrMsg.Format("[Image Size Error] Ref(W:%d,H%d), Mask(W:%d,H%d)", nRefWidth,nRefHeight,nMaskWidth,nMaskHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } } // Averaging Process int nAvgMaskWidth = 3; int nAvgMaskHeight = 3; //+change 080129 if(nType == OSD_IMAGE_TEST) { if(Average(nAvgMaskWidth,nAvgMaskHeight,nStartXposition,nEndXposition, nStartYposition,nEndYposition,SnapImage,TRUE) == TEST_FAIL) { AfxMessageBox("Failed to run average-filter"); return TEST_ABORT; } if(Average(nAvgMaskWidth,nAvgMaskHeight,nStartXposition,nEndXposition, nStartYposition,nEndYposition,RefImage,TRUE) == TEST_FAIL) { AfxMessageBox("Failed to run average-filter"); return TEST_ABORT; } } else { if(Average(nAvgMaskWidth,nAvgMaskHeight,nStartXposition,nEndXposition, nStartYposition,nEndYposition,SnapImage,TRUE) == TEST_FAIL) { AfxMessageBox("Failed to run average-filter"); return TEST_ABORT; } } m_nNoErrorInfo = 0; nTotalNoErrorPixel = 0; for(int i=0; i<3; i++) { for(int j=0; j<NO_DIFFERENT_POINT_BLOCK; j++) m_aNoDifferentPoint[i][j] = 0; } m_nSecondDifferentPointFreePercent = -1; //+add kwmoon 080715 for(int i=0; i<5;i++) { m_nNoBandErrorPixel[i] = 0; m_nNoAllowedBandErrorPixel[i] = 0; m_fBandErrorPixelPercentage[i] = 0.0f; } Progress.SetPos(10); SnapImage.m_bImageLoaded = FALSE; RefImage.m_bImageLoaded = FALSE; //+change kwmoon 080130 : 0.4f -> 0.5f ZoomOut(SnapImage,ZOOM_OUT_50); ZoomOut(RefImage, ZOOM_OUT_50); if(MaskImage.m_bImageLoaded) { ZoomOut(MaskImage,ZOOM_OUT_50); } //+add kwmoon 080130 m_ptRoiPosition.x = (int)(m_ptRoiPosition.x * ZOOM_OUT_50); m_ptRoiPosition.y = (int)(m_ptRoiPosition.y * ZOOM_OUT_50); m_nRoiWidth = (int)(m_nRoiWidth * ZOOM_OUT_50); m_nRoiHeight = (int)(m_nRoiHeight * ZOOM_OUT_50); //- // Dimension of the Reference Image nRefWidth = RefImage.m_InfoHeader.biWidth; nRefHeight = RefImage.m_InfoHeader.biHeight; if(MaskImage.m_bImageLoaded) { nMaskWidth = MaskImage.m_InfoHeader.biWidth; nMaskHeight = MaskImage.m_InfoHeader.biHeight; } // Dimension of the Snap Image nSnapWidth = SnapImage.m_InfoHeader.biWidth; nSnapHeight = SnapImage.m_InfoHeader.biHeight; nSnapBitCount = SnapImage.m_InfoHeader.biBitCount; nColorDepth = RefImage.m_InfoHeader.biBitCount; nBytesInRow = WIDTHBYTES(nColorDepth*RefImage.m_InfoHeader.biWidth); nImageSize = SnapImage.m_InfoHeader.biSizeImage; if(SnapImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(SnapImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(SnapImage.m_pProcessedImageData); SnapImage.m_pProcessedImageData = NULL; SnapImage.m_pProcessedImageData = (BYTE *)malloc(SnapImage.m_BmInfo->bmiHeader.biSizeImage); } } else { SnapImage.m_pProcessedImageData = (BYTE *)malloc(SnapImage.m_BmInfo->bmiHeader.biSizeImage); } memset(SnapImage.m_pProcessedImageData,0,SnapImage.m_BmInfo->bmiHeader.biSizeImage); // Allocate memory (store the processed image) BYTE* pProcessedImageData = (BYTE *)malloc(SnapImage.m_InfoHeader.biSizeImage); memset(pProcessedImageData,0,SnapImage.m_InfoHeader.biSizeImage); Progress.SetPos(20); nLowerLimit = Percentage2Level(m_fLowerLimit,nNoLevel); nUpperLimit = Percentage2Level(m_fUpperLimit,nNoLevel); if(m_nNoUsedColorHighBits > 0) { nNoShift = SnapImage.m_InfoHeader.biBitCount/3 - m_nNoUsedColorHighBits; } //+change kwmoon 080618 CalcTestRange(SnapImage,nStartXposition,nEndXposition,nStartYposition,nEndYposition); SnapImage.m_bProcessedImageLoaded = FALSE; int nX = 0; int nY = 0; int nColorChannel = 0; int nLastErrorXpos = -1; int nLastErrorYpos = -1; int nSnapImageIndex = 0; int nRefImageIndex = 0; int nBlockIndex = 0; int nMaskValue = 0; BOOL bInvalidMask = TRUE; //+add kwmoon 080124 int nDifferenceR = 0; int nDifferenceG = 0; int nDifferenceB = 0; int nMaxDifference = 0; int nMinDifference = 0; //+add kwmoon 080716 m_nNoTargetPixel = 0; if(RefImage.m_InfoHeader.biBitCount==24) // If the color depth of image is 24 bits { for(int nRow=nStartYposition; nRow<=nEndYposition; nRow++) { for(int nColumn=nStartXposition; nColumn<=nEndXposition; nColumn++) { nRefImageIndex = (nRow)*nBytesInRow+3*(nColumn); nSnapImageIndex = (nRow-m_ptPositionShift.y)*nBytesInRow+3*(nColumn+m_ptPositionShift.x); if(MaskImage.m_bImageLoaded && bUseMaskImage) { nMaskValue = MaskImage.m_pImageData[nRefImageIndex] | MaskImage.m_pImageData[nRefImageIndex+1] | MaskImage.m_pImageData[nRefImageIndex+2]; } if(nMaskValue == 0) { //+add kwmoon 080716 m_nNoTargetPixel++; bInvalidMask = FALSE; // for(int j=0; j<3; j++) // R,G,B { // nRefRGBvaule = RefImage.m_pImageData[nRefImageIndex+j]; // nSnapRGBvalue = SnapImage.m_pImageData[nSnapImageIndex+j]; // B nRefBcolor = RefImage.m_pImageData[nRefImageIndex]; nGrabBcolor = SnapImage.m_pImageData[nSnapImageIndex]; // G nRefGcolor = RefImage.m_pImageData[nRefImageIndex+1]; nGrabGcolor = SnapImage.m_pImageData[nSnapImageIndex+1]; // R nRefRcolor = RefImage.m_pImageData[nRefImageIndex+2]; nGrabRcolor = SnapImage.m_pImageData[nSnapImageIndex+2]; // if(m_nNoUsedColorHighBits > 0) // { // nDifference = ((nSnapRGBvalue>>nNoShift) - (nRefRGBvaule>>nNoShift)); // } // else // { // nDifference = (nSnapRGBvalue - nRefRGBvaule); // } if(m_nNoUsedColorHighBits > 0) { nDifferenceB = ((nGrabBcolor>>nNoShift) - (nRefBcolor>>nNoShift)); nDifferenceG = ((nGrabGcolor>>nNoShift) - (nRefGcolor>>nNoShift)); nDifferenceR = ((nGrabRcolor>>nNoShift) - (nRefRcolor>>nNoShift)); } else { nDifferenceB = (nGrabBcolor - nRefBcolor); nDifferenceG = (nGrabGcolor - nRefGcolor); nDifferenceR = (nGrabRcolor - nRefRcolor); } // pProcessedImageData[nRefImageIndex+j] = abs(nDifference); pProcessedImageData[nRefImageIndex] = abs(nDifferenceB); pProcessedImageData[nRefImageIndex+1] = abs(nDifferenceG); pProcessedImageData[nRefImageIndex+2] = abs(nDifferenceR); nMaxDifference = GetMaxValue(nDifferenceB,nDifferenceG,nDifferenceR); nMinDifference = GetMinValue(nDifferenceB,nDifferenceG,nDifferenceR); nDifference = abs(nMaxDifference) >= abs(nMinDifference) ? nMaxDifference : nMinDifference; // Error Pixel if(((m_nNoUsedColorHighBits > 0) && (abs(nDifference) > 0)) // || ((m_nNoUsedColorHighBits == 0) && (nDifference > nUpperLimit)) // || ((m_nNoUsedColorHighBits == 0) && (nDifference < nLowerLimit))) || ((m_nNoUsedColorHighBits == 0) && (nMaxDifference > nUpperLimit)) || ((m_nNoUsedColorHighBits == 0) && (nMinDifference < nLowerLimit))) { // Spec-Out : White // pProcessedImageData[nRefImageIndex] = 255; // pProcessedImageData[nRefImageIndex+1] = 255; // pProcessedImageData[nRefImageIndex+2] = 255; if(m_nNoUsedColorHighBits > 0) { nDifference = nDifference<<nNoShift; } if((nColumn != nLastErrorXpos) || (nRow != nLastErrorYpos)) { nTotalNoErrorPixel++; float fDifferenePercentage = 0; if(nDifference >= 0) // nDifference > nUpperLimit { fDifferenePercentage = Level2Percentage(abs(nDifference-nUpperLimit),nNoLevel); if(fDifferenePercentage <= 2) m_nNoBandErrorPixel[0]++; if((fDifferenePercentage > 2) && (fDifferenePercentage <= 4)) m_nNoBandErrorPixel[1]++; if((fDifferenePercentage > 4) && (fDifferenePercentage <= 6)) m_nNoBandErrorPixel[2]++; if((fDifferenePercentage > 6) && (fDifferenePercentage <= 8)) m_nNoBandErrorPixel[3]++; if(fDifferenePercentage > 8) m_nNoBandErrorPixel[4]++; } else // nDifference < nLowerLimit { fDifferenePercentage = Level2Percentage(abs(nDifference-nLowerLimit),nNoLevel); if(fDifferenePercentage <= 2) m_nNoBandErrorPixel[0]++; if((fDifferenePercentage > 2) && (fDifferenePercentage <= 4)) m_nNoBandErrorPixel[1]++; if((fDifferenePercentage > 4) && (fDifferenePercentage <= 6)) m_nNoBandErrorPixel[2]++; if((fDifferenePercentage > 6) && (fDifferenePercentage <= 8)) m_nNoBandErrorPixel[3]++; if(fDifferenePercentage > 8) m_nNoBandErrorPixel[4]++; } nLastErrorXpos = nColumn; nLastErrorYpos = nRow; } if((nDifference <0) && (nDifference < nNgMinusMaxDifference)) { nNgMinusMaxDifference = nDifference; ptNgMinusResultPosition.x = nColumn; ptNgMinusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); if((ptNgMinusResultPosition.x == 340) && (ptNgMinusResultPosition.y == 168)) { int nDebug = 1; } } if((nDifference >=0) && (nDifference >= nNgPlusMaxDifference)) { nNgPlusMaxDifference = nDifference; ptNgPlusResultPosition.x = nColumn; ptNgPlusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } } // Good Pixel else { //+add kwmoon 080124 // Spec-In : Black // pProcessedImageData[nRefImageIndex] = 0; // pProcessedImageData[nRefImageIndex+1] = 0; // pProcessedImageData[nRefImageIndex+2] = 0; //+add kwmoon 080716 m_nNoGoodPixel++; if((nDifference <0) && (nDifference < nPassMinusMaxDifference)) { nPassMinusMaxDifference = nDifference; ptPassMinusResultPosition.x = nColumn; ptPassMinusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } if((nDifference >=0) && (nDifference >= nPassPlusMaxDifference)) { nPassPlusMaxDifference = nDifference; ptPassPlusResultPosition.x = nColumn; ptPassPlusResultPosition.y = (RefImage.m_InfoHeader.biHeight-nRow-1); } } //+change kwmoon 080124 // nBlockIndex = (int)floor((float)abs(nDifference)*100/(float)nNoLevel); // m_aNoDifferentPoint[j][nBlockIndex]++; //+change kwmoon 080716 // if(CurrentSet->bSaveDistributionTable || g_pView->m_bAdjSpecMode) if(CurrentSet->bSaveReviewData || CurrentSet->bSaveDetailResultData || g_pView->m_bAdjSpecMode) { nBlockIndex = (int)((float)abs(nDifferenceB)*100/(float)nNoLevel); m_aNoDifferentPoint[0][nBlockIndex]++; nBlockIndex = (int)((float)abs(nDifferenceG)*100/(float)nNoLevel); m_aNoDifferentPoint[1][nBlockIndex]++; nBlockIndex = (int)((float)abs(nDifferenceR)*100/(float)nNoLevel); m_aNoDifferentPoint[2][nBlockIndex]++; } } } } } } else { //+add kwmoon 080201 CString szMsg; szMsg.Format("Reference image data may be corrupted. Color depth is not 24bits.(%d)bits",RefImage.m_InfoHeader.biBitCount); AfxMessageBox(szMsg); //- return TEST_ABORT; } int nDifferentPointFreePercentNo = 0; //+change kwmoon 080716 // if(CurrentSet->bSaveDistributionTable || g_pView->m_bAdjSpecMode) if(CurrentSet->bSaveReviewData || CurrentSet->bSaveDetailResultData || g_pView->m_bAdjSpecMode) { for(int j=0; j<NO_DIFFERENT_POINT_BLOCK; j++) { if((m_aNoDifferentPoint[0][j] == 0) && (m_aNoDifferentPoint[1][j] == 0) && (m_aNoDifferentPoint[2][j] == 0)) { nDifferentPointFreePercentNo++; if(nDifferentPointFreePercentNo == 2) { m_nSecondDifferentPointFreePercent = j; break; } } } } if(bInvalidMask) { CString szMsg; if(nType == GRAB_CHECK_TEST) { szMsg.Format("[Grab_Image_Check] No test was performed because of a mask image values. check mask image!"); } else { szMsg.Format("[Color Test] No test was performed because of a mask image values. check mask image!"); } AfxMessageBox(szMsg); return TEST_ABORT; } SnapImage.m_bProcessedImageLoaded = TRUE; Progress.SetPos(100); //+change kwmoon 080124 // for(j=0; j<(int)SnapImage.m_InfoHeader.biSizeImage; j++) // { // SnapImage.m_pProcessedImageData[j] = pProcessedImageData[j]; // } memcpy((BYTE*)SnapImage.m_pProcessedImageData,(BYTE*)pProcessedImageData,(int)SnapImage.m_InfoHeader.biSizeImage); if(pProcessedImageData != NULL) { free(pProcessedImageData); pProcessedImageData = NULL; } //+change kwmoon 071112 // BinaryForDiffImage(NORMAL_BINARY,SnapImage,RefImage,nLowerLimit,nUpperLimit); BinaryForDiffImage(NORMAL_BINARY,SnapImage,nLowerLimit,nUpperLimit); //+add kwmoon 080716 for(int i=0; i<10; i++) { if(m_nNoBandErrorPixel[i] == 0) { m_fBandErrorPixelPercentage[i] = 0; } else { m_fBandErrorPixelPercentage[i] = (float)m_nNoBandErrorPixel[i] * 100 / (float)m_nNoTargetPixel; } //+change kwmoon 080804 // m_nNoAllowedBandErrorPixel[i] = (int)((float)m_fAllowedBandErrorPixelPercentage[i] * (float)m_nNoTargetPixel); m_nNoAllowedBandErrorPixel[i] = (int)((float)m_fAllowedBandErrorPixelPercentage[i] * 0.01 * (float)m_nNoTargetPixel); } m_fGoodPixelPercentage =(float)m_nNoGoodPixel * 100 / (float)m_nNoTargetPixel; if(nTotalNoErrorPixel == 0) { nTestResult = TEST_PASS; nPlusMaxDifference = nPassPlusMaxDifference; nMinusMaxDifference = nPassMinusMaxDifference; ptPlusResultPosition = ptPassPlusResultPosition; ptMinusResultPosition = ptPassMinusResultPosition; } else { //+del kwmoon 080716 /* if(nType == OSD_IMAGE_TEST) { if(nTotalNoErrorPixel > m_fAllowedErrorPixelPercentageForOsdTest) { nTestResult = TEST_FAIL; nPlusMaxDifference = nNgPlusMaxDifference; nMinusMaxDifference = nNgMinusMaxDifference; ptPlusResultPosition = ptNgPlusResultPosition; ptMinusResultPosition = ptNgMinusResultPosition; } else { nTestResult = TEST_PASS; nPlusMaxDifference = nPassPlusMaxDifference; nMinusMaxDifference = nPassMinusMaxDifference; ptPlusResultPosition = ptPassPlusResultPosition; ptMinusResultPosition = ptPassMinusResultPosition; } } */ // else { //+change kwmoon 080716 if((m_fBandErrorPixelPercentage[0] < CurrentSet->fAllowedBandErrorPixelPercentage[0]) && (m_fBandErrorPixelPercentage[1] < CurrentSet->fAllowedBandErrorPixelPercentage[1]) && (m_fBandErrorPixelPercentage[2] < CurrentSet->fAllowedBandErrorPixelPercentage[2]) && (m_fBandErrorPixelPercentage[3] < CurrentSet->fAllowedBandErrorPixelPercentage[3]) && (m_fBandErrorPixelPercentage[4] < CurrentSet->fAllowedBandErrorPixelPercentage[4])) { nTestResult = TEST_PASS; nPlusMaxDifference = nPassPlusMaxDifference; nMinusMaxDifference = nPassMinusMaxDifference; ptPlusResultPosition = ptPassPlusResultPosition; ptMinusResultPosition = ptPassMinusResultPosition; } else { nTestResult = TEST_FAIL; nPlusMaxDifference = nNgPlusMaxDifference; nMinusMaxDifference = nNgMinusMaxDifference; ptPlusResultPosition = ptNgPlusResultPosition; ptMinusResultPosition = ptNgMinusResultPosition; } //+del kwmoon 080716 /* if(nTotalNoErrorPixel > m_fAllowedErrorPixelPercentage) { nTestResult = TEST_FAIL; nPlusMaxDifference = nNgPlusMaxDifference; nMinusMaxDifference = nNgMinusMaxDifference; ptPlusResultPosition = ptNgPlusResultPosition; ptMinusResultPosition = ptNgMinusResultPosition; } else { nTestResult = TEST_PASS; nPlusMaxDifference = nPassPlusMaxDifference; nMinusMaxDifference = nPassMinusMaxDifference; ptPlusResultPosition = ptPassPlusResultPosition; ptMinusResultPosition = ptPassMinusResultPosition; } */ } } SnapImage.m_bImageLoaded = TRUE; RefImage.m_bImageLoaded = TRUE; return nTestResult; } void CImageProc::SetAvgMaskSize(int nMaskWidth, int nMaskHeight,int nNoRepeat) { m_nAvgMaskWidth = nMaskWidth; m_nAvgMaskHeight = nMaskHeight; m_nNoRepeat = nNoRepeat; } //+change kwmoon 080820 //int CImageProc::Average(int nMaskWidth, int nMaskHeight, CBaseImage& DstImage,BOOL bOverwrite) int CImageProc::Average(int nMaskWidth, int nMaskHeight, CBaseImage& DstImage) { if(nMaskWidth > MAX_MASK_SIZE) { AfxMessageBox("Max width of average-mask is 9!"); return TEST_FAIL; } if(nMaskHeight > MAX_MASK_SIZE) { AfxMessageBox("Max height of average-mask is 9!"); return TEST_FAIL; } if(((nMaskWidth % 2) != 1) || ((nMaskHeight % 2) != 1)) // Mask size should be an odd number! { AfxMessageBox("Mask size should be an odd number!"); return TEST_FAIL; } int nNewRValue = 0; int nNewGValue = 0; int nNewBValue = 0; int nXmargin = nMaskWidth/2; int nYmargin = nMaskHeight/2; int nMaskBox[MAX_MASK_SIZE][MAX_MASK_SIZE]; int nBytesInRow= WIDTHBYTES(DstImage.m_InfoHeader.biBitCount*DstImage.m_InfoHeader.biWidth); int nImageBufferSize = 0; int nImageSize = 0; for(int nX=0; nX<MAX_MASK_SIZE; nX++) { for(int nY=0; nY<MAX_MASK_SIZE; nY++) { nMaskBox[nX][nY] = 1; } } nImageSize = DstImage.m_InfoHeader.biSizeImage; if(DstImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pProcessedImageData); DstImage.m_pProcessedImageData = NULL; DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } } else { DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } memset(DstImage.m_pProcessedImageData,0,DstImage.m_BmInfo->bmiHeader.biSizeImage); for(int j=0; j<(int)DstImage.m_InfoHeader.biSizeImage; j++) { DstImage.m_pProcessedImageData[j] = DstImage.m_pImageData[j]; } DstImage.m_bProcessedImageLoaded = FALSE; if(DstImage.m_InfoHeader.biBitCount==24) // If the color depth of image is 24 bits { for(int nRow=nYmargin; nRow<DstImage.m_InfoHeader.biHeight-nYmargin; nRow++) { for(int nColumn=nXmargin; nColumn<DstImage.m_InfoHeader.biWidth-nXmargin; nColumn++) { nNewRValue = 0; nNewGValue = 0; nNewBValue = 0; for(int nX=0; nX<nMaskWidth; nX++) { for(int nY=0; nY<nMaskHeight; nY++) { nNewBValue += nMaskBox[nX][nY] * DstImage.m_pImageData[(nRow+nY-nYmargin)*nBytesInRow+3*(nColumn+nX-nXmargin)]; nNewGValue += nMaskBox[nX][nY] * DstImage.m_pImageData[(nRow+nY-nYmargin)*nBytesInRow+3*(nColumn+nX-nXmargin)+1]; nNewRValue += nMaskBox[nX][nY] * DstImage.m_pImageData[(nRow+nY-nYmargin)*nBytesInRow+3*(nColumn+nX-nXmargin)+2]; } } nNewRValue /= nMaskWidth*nMaskHeight; nNewGValue /= nMaskWidth*nMaskHeight; nNewBValue /= nMaskWidth*nMaskHeight; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn] = (BYTE)nNewBValue;//BYTE값으로 변환 DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+1] = (BYTE)nNewGValue;//BYTE값으로 변환 DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2] = (BYTE)nNewRValue;//BYTE값으로 변환 } } } DstImage.m_bProcessedImageLoaded = TRUE; //+del kwmoon 080820 // if(bOverwrite) { for(int j=0; j<(int)DstImage.m_InfoHeader.biSizeImage; j++) { DstImage.m_pImageData[j] = DstImage.m_pProcessedImageData[j]; } } return TEST_PASS; } /*----------------------------------------------------------------------------------------- 함수명 : Average 기 능 : - 파라미터로 넘어온 이미지에 대하여 주어진 Mask 사이즈에 따라 Average Filter를 적용함 입력파라미터 : - int nMaskWidth : Average Filter의 Mask의 Width - int nMaskHeight : Average Filter의 Mask의 Height - int nStartXposition : Average Filter를 적용할 영역의 X1 좌표 - int nEndXposition : Average Filter를 적용할 영역의 Y1 좌표 - int nStartYposition : Average Filter를 적용할 영역의 X2 좌표 - int nEndYposition : Average Filter를 적용할 영역의 Y2 좌표 - CBaseImage& DstImage : Average Filter를 적용한 이미지가 저장되어 있는 Object - BOOL bOverwrite : Average Filter를 적용한 결과를 입력 이미지 Object에 OverWrite할가의 여부 Return 값 : - TEST_PASS 또는 TEST_FAIL -----------------------------------------------------------------------------------------*/ int CImageProc::Average(int nMaskWidth, int nMaskHeight, int nStartXposition, int nEndXposition, int nStartYposition, int nEndYposition, CBaseImage& DstImage,BOOL bOverwrite) { if(nMaskWidth > MAX_MASK_SIZE) { AfxMessageBox("Max width of average-mask is 9!"); return TEST_FAIL; } if(nMaskHeight > MAX_MASK_SIZE) { AfxMessageBox("Max height of average-mask is 9!"); return TEST_FAIL; } if(((nMaskWidth % 2) != 1) || ((nMaskHeight % 2) != 1)) { AfxMessageBox("Mask size should be an odd number!"); return TEST_FAIL; } int nNewRValue = 0; int nNewGValue = 0; int nNewBValue = 0; int nXmargin = nMaskWidth/2; int nYmargin = nMaskHeight/2; int nMaskBox[MAX_MASK_SIZE][MAX_MASK_SIZE]; int nBytesInRow= WIDTHBYTES(DstImage.m_InfoHeader.biBitCount*DstImage.m_InfoHeader.biWidth); int nImageBufferSize = 0; int nImageSize = 0; for(int nX=0; nX<MAX_MASK_SIZE; nX++) { for(int nY=0; nY<MAX_MASK_SIZE; nY++) { nMaskBox[nX][nY] = 1; } } nImageSize = DstImage.m_InfoHeader.biSizeImage; if(DstImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pProcessedImageData); DstImage.m_pProcessedImageData = NULL; DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } } else { DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } memset(DstImage.m_pProcessedImageData,0,DstImage.m_BmInfo->bmiHeader.biSizeImage); for(int j=0; j<(int)DstImage.m_InfoHeader.biSizeImage; j++) { DstImage.m_pProcessedImageData[j] = DstImage.m_pImageData[j]; } DstImage.m_bProcessedImageLoaded = FALSE; //+add kwmoon 080820 if(nStartXposition > 6) { nStartXposition -= 5; } if(nEndXposition < (DstImage.m_InfoHeader.biWidth-6)) { nEndXposition += 5; } if(nStartYposition > 6) { nStartYposition -= 5; } if(nEndYposition < (DstImage.m_InfoHeader.biHeight-6)) { nEndYposition += 5; } //- if(nStartXposition - nXmargin < 0) { nStartXposition = nXmargin; } if(nEndXposition + nXmargin >= DstImage.m_InfoHeader.biWidth) { nEndXposition = nEndXposition - nXmargin; } if(nStartYposition - nYmargin < 0) { nStartYposition = nYmargin; } if(nEndYposition + nYmargin >= DstImage.m_InfoHeader.biHeight) { nEndYposition = nEndYposition - nYmargin; } //+add 090130 unsigned char *p1, *p2, *p3, *p4, *p5, *p6, *p7, *p8, *p9, *pD; if(DstImage.m_InfoHeader.biBitCount==24) { for(int nRow=nStartYposition; nRow<=nEndYposition; nRow++) { //+add 090130 p1 = DstImage.m_pImageData + (nRow-nYmargin) *nBytesInRow+3*(nStartXposition-nXmargin); p2 = DstImage.m_pImageData + (nRow-nYmargin) *nBytesInRow+3*(nStartXposition-nXmargin+1); p3 = DstImage.m_pImageData + (nRow-nYmargin) *nBytesInRow+3*(nStartXposition-nXmargin+2); p4 = DstImage.m_pImageData + (nRow-nYmargin+1)*nBytesInRow+3*(nStartXposition-nXmargin); p5 = DstImage.m_pImageData + (nRow-nYmargin+1)*nBytesInRow+3*(nStartXposition-nXmargin+1); p6 = DstImage.m_pImageData + (nRow-nYmargin+1)*nBytesInRow+3*(nStartXposition-nXmargin+2); p7 = DstImage.m_pImageData + (nRow-nYmargin+2)*nBytesInRow+3*(nStartXposition-nXmargin); p8 = DstImage.m_pImageData + (nRow-nYmargin+2)*nBytesInRow+3*(nStartXposition-nXmargin+1); p9 = DstImage.m_pImageData + (nRow-nYmargin+2)*nBytesInRow+3*(nStartXposition-nXmargin+2); pD = DstImage.m_pProcessedImageData + nRow*nBytesInRow + 3*nStartXposition; //- for(int nColumn=nStartXposition; nColumn<=nEndXposition; nColumn++) { //+add 090130 *pD++ = (*p1++ + *p2++ + *p3++ + *p4++ + *p5++ + *p6++ + *p7++ + *p8++ + *p9++)/9; *pD++ = (*p1++ + *p2++ + *p3++ + *p4++ + *p5++ + *p6++ + *p7++ + *p8++ + *p9++)/9; *pD++ = (*p1++ + *p2++ + *p3++ + *p4++ + *p5++ + *p6++ + *p7++ + *p8++ + *p9++)/9; //+del 090130 /* nNewRValue = 0; nNewGValue = 0; nNewBValue = 0; for(int nX=0; nX<nMaskWidth; nX++) { for(int nY=0; nY<nMaskHeight; nY++) { nNewBValue += nMaskBox[nX][nY] * DstImage.m_pImageData[(nRow+nY-nYmargin)*nBytesInRow+3*(nColumn+nX-nXmargin)]; nNewGValue += nMaskBox[nX][nY] * DstImage.m_pImageData[(nRow+nY-nYmargin)*nBytesInRow+3*(nColumn+nX-nXmargin)+1]; nNewRValue += nMaskBox[nX][nY] * DstImage.m_pImageData[(nRow+nY-nYmargin)*nBytesInRow+3*(nColumn+nX-nXmargin)+2]; } } nNewRValue /= nMaskWidth*nMaskHeight; nNewGValue /= nMaskWidth*nMaskHeight; nNewBValue /= nMaskWidth*nMaskHeight; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn] = (BYTE)nNewBValue; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+1] = (BYTE)nNewGValue; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2] = (BYTE)nNewRValue; */ } } } DstImage.m_bProcessedImageLoaded = TRUE; if(bOverwrite) { for(int j=0; j<(int)DstImage.m_InfoHeader.biSizeImage; j++) { DstImage.m_pImageData[j] = DstImage.m_pProcessedImageData[j]; } } return TEST_PASS; } BOOL CImageProc::BinaryForMaskImage(int nType,CBaseImage& DstImage,int nThreshold,BOOL bOverwrite) { if(DstImage.m_InfoHeader.biBitCount < 24) { AfxMessageBox("Only true color image is supported!"); return TEST_FAIL; } int nProgress = 0; int nColorDepth = DstImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*DstImage.m_InfoHeader.biWidth); int nBinaryValue1 = 0; int nBinaryValue2 = 0; int nImageBufferSize = 0; int nImageSize = 0; if(nType == NORMAL_BINARY) { nBinaryValue1 = 255; nBinaryValue2 = 0; } else { nBinaryValue1 = 0; nBinaryValue2 = 255; } nImageSize = DstImage.m_InfoHeader.biSizeImage; if(DstImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pProcessedImageData); DstImage.m_pProcessedImageData = NULL; DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } } else { DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } memset(DstImage.m_pProcessedImageData,0,DstImage.m_BmInfo->bmiHeader.biSizeImage); DstImage.m_bProcessedImageLoaded = FALSE; for(int nRow=0; nRow<DstImage.m_InfoHeader.biHeight; nRow++) { for(int nColumn=0; nColumn<DstImage.m_InfoHeader.biWidth; nColumn++) { if((DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2] > nThreshold) // R || (DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1] > nThreshold) // G || (DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn] > nThreshold)) // B { DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue1; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue1; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue1; } else { DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue2; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue2; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue2; } } } DstImage.m_bProcessedImageLoaded = TRUE; if(bOverwrite) { for(int j=0; j<(int)DstImage.m_InfoHeader.biSizeImage; j++) { DstImage.m_pImageData[j] = DstImage.m_pProcessedImageData[j]; } } return TEST_PASS; } // Under Threshold : Black, Over Threashold : White int CImageProc::BinaryForMonoImage(int nType, BYTE* pImageData,int nHeight,int nWidth,int nBitCount,int nThreshold) { if(pImageData == NULL) { AfxMessageBox("Input data is null!"); return TEST_FAIL; } int nProgress = 0; int nColorDepth = nBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*nWidth); int nBinaryValue1 = 0; int nBinaryValue2 = 0; if(nType == NORMAL_BINARY) { nBinaryValue1 = 255; nBinaryValue2 = 0; } else { nBinaryValue1 = 0; nBinaryValue2 = 255; } for(int nRow=0; nRow<nHeight; nRow++) { for(int nColumn=0; nColumn<nWidth; nColumn++) { if((pImageData[nRow*nBytesInRow+3*nColumn+2] > nThreshold)) // R { pImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue1; pImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue1; pImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue1; } else { pImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue2; pImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue2; pImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue2; } } } return TEST_PASS; } int CImageProc::BinaryForDiffImage(int nType, CBaseImage& DstImage, CBaseImage& RefImage, int nLowerLimit, int nUpperLimit) { int nImageBufferSize = 0; int nImageSize = DstImage.m_InfoHeader.biSizeImage; if(DstImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pProcessedImageData); DstImage.m_pProcessedImageData = NULL; DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } } else { DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } memset(DstImage.m_pProcessedImageData,0,DstImage.m_BmInfo->bmiHeader.biSizeImage); BYTE* pImageData = DstImage.m_pProcessedImageData; int nProgress = 0; int nColorDepth = RefImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*RefImage.m_InfoHeader.biWidth); int nBinaryValue1 = 0; int nBinaryValue2 = 0; int nDifferenceR = 0; int nDifferenceG = 0; int nDifferenceB = 0; int nHeight = RefImage.m_InfoHeader.biHeight; int nWidth = RefImage.m_InfoHeader.biWidth; if(nType == NORMAL_BINARY) { nBinaryValue1 = 255; nBinaryValue2 = 0; } else { nBinaryValue1 = 0; nBinaryValue2 = 255; } for(int nRow=0; nRow<nHeight; nRow++) { for(int nColumn=0; nColumn<nWidth; nColumn++) { nDifferenceR = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2] - RefImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2]; nDifferenceG = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1] - RefImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1]; nDifferenceB = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn ] - RefImage.m_pImageData[nRow*nBytesInRow+3*nColumn ]; if((nDifferenceR <= nUpperLimit) && (nDifferenceR >= nLowerLimit) // R && (nDifferenceG <= nUpperLimit) && (nDifferenceG >= nLowerLimit) // G && (nDifferenceB <= nUpperLimit) && (nDifferenceB >= nLowerLimit)) // B { // Spec In pImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue2; pImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue2; pImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue2; } else { // Spec Out pImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue1; pImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue1; pImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue1; } } } DstImage.m_bProcessedImageLoaded = TRUE; return TEST_PASS; } //+add kwmoon 071112 // Spec-Out : White, Spec-In : Black int CImageProc::BinaryForDiffImage(int nType, CBaseImage& SnapImage, int nLowerLimit, int nUpperLimit) { int nProgress = 0; int nColorDepth = SnapImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*SnapImage.m_InfoHeader.biWidth); int nBinaryValue1 = 0; int nBinaryValue2 = 0; int nDifferenceR = 0; int nDifferenceG = 0; int nDifferenceB = 0; int nHeight = SnapImage.m_InfoHeader.biHeight; int nWidth = SnapImage.m_InfoHeader.biWidth; int nIndex = 0; if(nType == NORMAL_BINARY) { nBinaryValue1 = 255; nBinaryValue2 = 0; } else { nBinaryValue1 = 0; nBinaryValue2 = 255; } for(int nRow=0; nRow<nHeight; nRow++) { for(int nColumn=0; nColumn<nWidth; nColumn++) { nIndex = nRow*nBytesInRow+3*nColumn; if((nColumn == 334) && (nRow == 384)) { int nDebug = 1; } nDifferenceR = SnapImage.m_pProcessedImageData[nIndex+2]; nDifferenceG = SnapImage.m_pProcessedImageData[nIndex+1]; nDifferenceB = SnapImage.m_pProcessedImageData[nIndex ]; if((nDifferenceR <= nUpperLimit) && (nDifferenceR >= nLowerLimit) // R && (nDifferenceG <= nUpperLimit) && (nDifferenceG >= nLowerLimit) // G && (nDifferenceB <= nUpperLimit) && (nDifferenceB >= nLowerLimit)) // B { // Spec In SnapImage.m_pProcessedImageData[nIndex+2] = nBinaryValue2; SnapImage.m_pProcessedImageData[nIndex+1] = nBinaryValue2; SnapImage.m_pProcessedImageData[nIndex ] = nBinaryValue2; } else { // Spec Out SnapImage.m_pProcessedImageData[nIndex+2] = nBinaryValue1; SnapImage.m_pProcessedImageData[nIndex+1] = nBinaryValue1; SnapImage.m_pProcessedImageData[nIndex ] = nBinaryValue1; } } } SnapImage.m_bProcessedImageLoaded = TRUE; return TEST_PASS; } // Under Threshold : Black, Over Threashold : White int CImageProc::BinaryForColorImage(int nType,CBaseImage& DstImage,int nThreshold,BOOL bOverwrite) { int nProgress = 0; int nColorDepth = DstImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*DstImage.m_InfoHeader.biWidth); int nBinaryValue1 = 0; int nBinaryValue2 = 0; int nImageBufferSize = 0; int nImageSize = 0; if(nType == NORMAL_BINARY) { nBinaryValue1 = 255; nBinaryValue2 = 0; } else { nBinaryValue1 = 0; nBinaryValue2 = 255; } nImageSize = DstImage.m_InfoHeader.biSizeImage; if(DstImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pProcessedImageData); DstImage.m_pProcessedImageData = NULL; DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } } else { DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } memset(DstImage.m_pProcessedImageData,0,DstImage.m_BmInfo->bmiHeader.biSizeImage); if(RGB2Gray(NORMAL_BINARY,DstImage,TRUE) == TEST_FAIL) return TEST_ABORT; for(int nRow=0; nRow<DstImage.m_InfoHeader.biHeight; nRow++) { for(int nColumn=0; nColumn<DstImage.m_InfoHeader.biWidth; nColumn++) { if((DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2] > nThreshold)) // R { // Spec In DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue1; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue1; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue1; } else { // Spec Out DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2] = nBinaryValue2; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+1] = nBinaryValue2; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn] = nBinaryValue2; } } } DstImage.m_bProcessedImageLoaded = TRUE; if(bOverwrite) { for(int j=0; j<(int)DstImage.m_InfoHeader.biSizeImage; j++) { DstImage.m_pImageData[j] = DstImage.m_pProcessedImageData[j]; } } return TEST_PASS; } // In case of using ROI, position margin can be applied. int CImageProc::PatternMatching(int nTestType, CBaseImage &SnapImage, CBaseImage &RefImage, POINT& ptResultPosition,float& fMatchRate, CProgressCtrl &Progress) { if((SnapImage.m_InfoHeader.biBitCount < 24) || (RefImage.m_InfoHeader.biBitCount < 24)) { AfxMessageBox("Only true color image is supported!"); return TEST_ABORT; } int nProgress = 0; int nTestResult = TEST_PASS; int nThreshold = 127; int nColorDepth = RefImage.m_InfoHeader.biBitCount; int nMatchXpos = 0; // X position of matching image int nMatchYpos = 0; // Y position of matching image m_nNoErrorInfo = 0; // Image Width in Byte int nSnapBytesInRow = WIDTHBYTES(nColorDepth*SnapImage.m_InfoHeader.biWidth); int nRefBytesInRow = WIDTHBYTES(nColorDepth*RefImage.m_InfoHeader.biWidth); // Dimension of Ref Image int nRefWidth = RefImage.m_InfoHeader.biWidth; int nRefHeight = RefImage.m_InfoHeader.biHeight; // Dimension of Snap Image int nSnapWidth = SnapImage.m_InfoHeader.biWidth; int nSnapHeight = SnapImage.m_InfoHeader.biHeight; CString szErrMsg = _T(""); if((nRefWidth != nSnapWidth) || (nRefHeight != nSnapHeight)) { AfxMessageBox("The size of reference image should be the same!"); return TEST_ABORT; } if(RefImage.m_InfoHeader.biBitCount != SnapImage.m_InfoHeader.biBitCount) { AfxMessageBox("The color depth of two images is different!"); return TEST_ABORT; } if((m_nRoiWidth >= nSnapWidth) || (m_nRoiHeight >= nSnapHeight)) { szErrMsg.Format("[ROI Error] Roi with & height should be less than witdh & height of image! (W:%d_%d,H:%d_%d)" ,m_nRoiWidth,nSnapWidth,m_nRoiHeight,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if((m_ptRoiPosition.x >= (nSnapWidth-1)) || (m_ptRoiPosition.y >= (nSnapHeight-1))) { szErrMsg.Format("[ROI Error] Roi (x,y) should be less than witdh & height of image! (X:%d,Y:%d,W:%d,H:%d)" ,m_ptRoiPosition.x,m_ptRoiPosition.y,nSnapWidth,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if((m_nRoiWidth < 0) || (m_nRoiHeight < 0)) { szErrMsg.Format("[ROI Error] Roi width & height should be more than 0! (Width:%d,Height:%d)" ,m_nRoiWidth,m_nRoiHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } // Set Margin in pixel POINT nPositionMargin; nPositionMargin.x = DEFAULT_POSITION_MARGIN; nPositionMargin.y = DEFAULT_POSITION_MARGIN; int nSnapStartXposition = 0; int nSnapStartYposition = 0; int nSnapEndXposition = 0; int nSnapEndYposition = 0; int nStartXposition = 0; int nStartYposition = 0; int nEndXposition = 0; int nEndYposition = 0; //+change kwmoon 080618 CalcTestRange(SnapImage,nStartXposition,nEndXposition,nStartYposition,nEndYposition); // Binary Process if(RGB2Gray(NORMAL_BINARY,SnapImage,FALSE) == TEST_FAIL) return TEST_ABORT; if(RGB2Gray(NORMAL_BINARY,RefImage,FALSE) == TEST_FAIL) return TEST_ABORT; // Variables for image processing double dwMatchRate = 0.0f; int NoT; float ST,temp, SumT; float MaxCorr, CurCorr, a1, a2, DeNomi, Nomi; float SumI, SI, ScT, tpi; POINT nOutputPosition; ST = 0.0f; temp = 0.0f; SumT = 0.0f; NoT = 0; Progress.SetPos(10); if((m_nRoiHeight > 0) && (m_nRoiWidth > 0)) // In case of applying ROI { for(int nRow=nStartYposition;nRow<=(nStartYposition+m_nRoiHeight);nRow++) { for(int nColumn=nStartXposition;nColumn<=(nStartXposition+m_nRoiWidth) ;nColumn++) { temp =(float)RefImage.m_pProcessedImageData[nRow*nRefBytesInRow+3*nColumn]; SumT += temp; ST += temp * temp; NoT++; } } } else { for(int nRow=0;nRow<nRefHeight;nRow++) { for(int nColumn=0;nColumn<nRefWidth ;nColumn++) { temp =(float)RefImage.m_pProcessedImageData[nRow*nRefBytesInRow+3*nColumn]; SumT += temp; ST += temp * temp; NoT++; } } } Progress.SetPos(20); MaxCorr = 0.0f; CurCorr = 0.0f; a1 = 0.0f; a2 = 0.0f; DeNomi = 0.0f; Nomi = 0.0f; SumI = 0.0f; SI = 0.0f; ScT = 0.0f; tpi = 0.0f; nOutputPosition.x = 0; nOutputPosition.y = 0; if((m_nRoiHeight > 0) && (m_nRoiWidth > 0)) // In case of applying ROI { // Set nSnapStartXposition if((nStartXposition - nPositionMargin.x) < 0) { nSnapStartXposition = 0; } else { nSnapStartXposition = - nPositionMargin.x; } // Set nSnapStartYposition if((nStartYposition - nPositionMargin.y) < 0) { nSnapStartYposition = 0; } else { nSnapStartYposition = - nPositionMargin.y; } // Set nSnapEndXposition if((nEndXposition + nPositionMargin.x) > nSnapWidth) { nSnapEndXposition = (nSnapWidth-1) - nEndXposition; } else { nSnapEndXposition = nPositionMargin.x; } if((nEndYposition + nPositionMargin.y) > nSnapHeight) { nSnapEndYposition = (nSnapHeight-1) - nEndYposition; } else { nSnapEndYposition = nPositionMargin.y; } } else // In case of full size test { // Snap Image Position nSnapStartXposition = 0; nSnapStartYposition = 0; nSnapEndXposition = 0; nSnapEndYposition = 0; } for(int m=nSnapStartYposition; m<=nSnapEndYposition; m++) { for(int n=nSnapStartXposition; n<=nSnapEndXposition; n++) { SumI = SI = ScT = 0.0f; for(int nRow=nStartYposition;nRow<=nEndYposition;nRow++) { for(int nColumn=nStartXposition;nColumn<=nEndXposition ;nColumn++) { temp = (float)SnapImage.m_pProcessedImageData[(m+(nRow-m_ptPositionShift.y))*nSnapBytesInRow+3*(n+(nColumn+m_ptPositionShift.x))]; tpi = (float)RefImage.m_pProcessedImageData[(nRow)*nRefBytesInRow+3*(nColumn)]; SumI += temp; SI += temp * temp ; ScT += tpi*temp; } } a1 = NoT*SI-SumI*SumI; a2 = NoT*ST-SumT*SumT; DeNomi = (float)( a1*a2 ); Nomi = ( NoT*ScT - SumI*SumT); if (DeNomi < 0.0001 ) CurCorr = 0; else CurCorr = Nomi*Nomi/DeNomi; if (CurCorr>MaxCorr) { MaxCorr = CurCorr; nOutputPosition.y = m; nOutputPosition.x = n; } } if(nSnapEndYposition > 0) { nProgress = 20 + (int)((float)m*80/(float)(nSnapEndYposition)); Progress.SetPos(nProgress); } } nMatchXpos = nStartXposition + nOutputPosition.x; if((m_nRoiHeight > 0) && (m_nRoiWidth > 0)) // In case of applying ROI { nMatchYpos = GetOppositeStartYposition(nStartYposition + nOutputPosition.y,m_nRoiHeight,nSnapHeight); } else { nMatchYpos = nOutputPosition.y; } dwMatchRate = sqrt(MaxCorr); dwMatchRate = (float)dwMatchRate * 100; if(dwMatchRate < m_fTargetMatchRate) { nTestResult = TEST_FAIL; } else { ptResultPosition.x = nMatchXpos; ptResultPosition.y = nMatchYpos; } Progress.SetPos(100); fMatchRate = (float)dwMatchRate; //+change kwmoon 071105 if(fMatchRate > 100.0) { fMatchRate = 100.0; } return nTestResult; } int CImageProc::GetOppositeStartYposition(int nPosition, int nRoiHeight, int nImageHeight) { int nResult = 0; int nMidPosition = nImageHeight/2; if(nImageHeight % 2 == 0) // Even Number { if(nPosition <= nMidPosition) { nResult = (nMidPosition - nPosition) + nMidPosition - 1 - nRoiHeight; } else { nResult = nMidPosition - (nPosition - nMidPosition) - 1 - nRoiHeight; } } else // Odd Number { if(nPosition <= nMidPosition) { nResult = (nMidPosition - nPosition) + nMidPosition - nRoiHeight; } else { nResult = nMidPosition - (nPosition - nMidPosition) - nRoiHeight; } } return nResult; } int CImageProc::MakeAvgImg(CStringArray& aFilePathArray,CBaseImage& DstImage,CProgressCtrl& ItemProgress,CProgressCtrl& TotalProgress) { //+add 090219(Modification No2) CString szLog = "B:MakeAvgImg\n"; // if(g_LogFileOpen) g_LogFile.WriteString(szLog); CString szErrMsg = _T(""); CString szFilePath = _T(""); int nTestResult = TEST_PASS; int nImageColorDepth = 0; int nFirstImageColorDepth = 0; int nImageHeight = 0; int nImageWidth = 0; int nFirstImageHeight = 0; int nFirstImageWidth = 0; int nNoImage = aFilePathArray.GetSize(); int nBytesInRow = 0; int nAvgRvalue = 0; int nAvgGvalue = 0; int nAvgBvalue = 0; int nImageSize = 0; int nImageBufferSize = 0; CBaseImage m_aImageList[MAX_NO_IMAGE_TO_MAKE_AVERAGE_IMAGE]; TotalProgress.SetPos(0); if(nNoImage < 2) { AfxMessageBox("To make an average image, at least 2 images are required!"); return TEST_ABORT; } if(nNoImage > MAX_NO_IMAGE_TO_MAKE_AVERAGE_IMAGE) { AfxMessageBox("The maximum number of input images for making an average image is 10 images!"); return TEST_ABORT; } // Load Images for(int i=0; i<nNoImage; i++) { szFilePath = aFilePathArray.GetAt(i); if(!m_aImageList[i].LoadImage(szFilePath,ItemProgress)) { for(int j=0; j<i; j++) { m_aImageList[i].~CBaseImage(); } return TEST_ABORT; } } // Check image size & Color depth nFirstImageWidth = m_aImageList[0].m_InfoHeader.biWidth; nFirstImageHeight = m_aImageList[0].m_InfoHeader.biHeight; nFirstImageColorDepth = m_aImageList[0].m_InfoHeader.biBitCount; for(int j=1; j<nNoImage; j++) { nImageWidth = m_aImageList[j].m_InfoHeader.biWidth; nImageHeight = m_aImageList[j].m_InfoHeader.biHeight; nImageColorDepth = m_aImageList[j].m_InfoHeader.biBitCount; if((nFirstImageWidth != nImageWidth) || (nFirstImageHeight != nImageHeight)) { szErrMsg.Format("The size of two images is different! Img1:(%d,%d) -> Img%d:(%d,%d)", nFirstImageWidth,nFirstImageHeight,j,nImageWidth,nImageHeight); for(int k=0; k<nNoImage; k++) m_aImageList[k].~CBaseImage(); AfxMessageBox(szErrMsg); return TEST_ABORT; } if(nFirstImageColorDepth != nImageColorDepth) { szErrMsg.Format("The color depth of two images is different! Img1:(%dbits) -> Img%d:(%dbits)", nFirstImageColorDepth,j,nImageColorDepth); for(int k=0; k<nNoImage; k++) m_aImageList[k].~CBaseImage(); AfxMessageBox(szErrMsg); return TEST_ABORT; } } nBytesInRow= WIDTHBYTES(nFirstImageColorDepth*nFirstImageWidth); TotalProgress.SetPos(10); nImageSize = nFirstImageHeight * nBytesInRow; if(DstImage.m_pImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pImageData); DstImage.m_pImageData = NULL; DstImage.m_pImageData = (BYTE *)malloc(nImageSize); } } else { DstImage.m_pImageData = (BYTE *)malloc(nImageSize); } memset(DstImage.m_pImageData,0,nImageSize); DstImage.InitHeaders(COLOR_24BIT,nFirstImageWidth,nFirstImageHeight,nImageSize); if(nFirstImageColorDepth == 24) // If the color depth of image is 24 bits { for(int nRow=0; nRow<nFirstImageHeight; nRow++) { for(int nColumn=0; nColumn<nFirstImageWidth; nColumn++) { nAvgRvalue = 0; nAvgGvalue = 0; nAvgBvalue = 0; for(int j=0; j<nNoImage; j++) { nAvgRvalue += m_aImageList[j].m_pImageData[nRow*nBytesInRow+3*nColumn+2]; nAvgGvalue += m_aImageList[j].m_pImageData[nRow*nBytesInRow+3*nColumn+1]; nAvgBvalue += m_aImageList[j].m_pImageData[nRow*nBytesInRow+3*nColumn]; } DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2] = (nAvgRvalue/nNoImage); DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1] = (nAvgGvalue/nNoImage); DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn] = (nAvgBvalue/nNoImage); } } } DstImage.m_bImageLoaded = TRUE; TotalProgress.SetPos(100); //+add 090219(Modification No2) szLog = "E:MakeAvgImg\n"; // if(g_LogFileOpen) g_LogFile.WriteString(szLog); return nTestResult; } int CImageProc::MakeAvgImg(CStringArray& aFilePathArray,CBaseImage& DstImage,CProgressCtrl& ItemProgress) { CString szErrMsg = _T(""); CString szFilePath = _T(""); int nTestResult = TEST_PASS; int nImageColorDepth = 0; int nFirstImageColorDepth = 0; int nImageHeight = 0; int nImageWidth = 0; int nFirstImageHeight = 0; int nFirstImageWidth = 0; int nNoImage = aFilePathArray.GetSize(); int nBytesInRow = 0; int nAvgRvalue = 0; int nAvgGvalue = 0; int nAvgBvalue = 0; int nImageSize = 0; int nImageBufferSize = 0; CBaseImage m_aImageList[MAX_NO_IMAGE_TO_MAKE_AVERAGE_IMAGE]; if(nNoImage < 2) { AfxMessageBox("To make an average image, at least 2 images are required!"); return TEST_ABORT; } if(nNoImage > MAX_NO_IMAGE_TO_MAKE_AVERAGE_IMAGE) { AfxMessageBox("The maximum number of input images for making an average image is 10 images!"); return TEST_ABORT; } // Load Images for(int i=0; i<nNoImage; i++) { szFilePath = aFilePathArray.GetAt(i); if(!m_aImageList[i].LoadImage(szFilePath,ItemProgress)) { for(int j=0; j<i; j++) { m_aImageList[i].~CBaseImage(); } return TEST_ABORT; } } // Check image size & Color depth nFirstImageWidth = m_aImageList[0].m_InfoHeader.biWidth; nFirstImageHeight = m_aImageList[0].m_InfoHeader.biHeight; nFirstImageColorDepth = m_aImageList[0].m_InfoHeader.biBitCount; for(int j=1; j<nNoImage; j++) { nImageWidth = m_aImageList[j].m_InfoHeader.biWidth; nImageHeight = m_aImageList[j].m_InfoHeader.biHeight; nImageColorDepth = m_aImageList[j].m_InfoHeader.biBitCount; if((nFirstImageWidth != nImageWidth) || (nFirstImageHeight != nImageHeight)) { szErrMsg.Format("The size of two images is different! Img1:(%d,%d) -> Img%d:(%d,%d)", nFirstImageWidth,nFirstImageHeight,j,nImageWidth,nImageHeight); for(int k=0; k<nNoImage; k++) m_aImageList[k].~CBaseImage(); AfxMessageBox(szErrMsg); return TEST_ABORT; } if(nFirstImageColorDepth != nImageColorDepth) { szErrMsg.Format("The color depth of two images is different! Img1:(%dbits) -> Img%d:(%dbits)", nFirstImageColorDepth,j,nImageColorDepth); for(int k=0; k<nNoImage; k++) m_aImageList[k].~CBaseImage(); AfxMessageBox(szErrMsg); return TEST_ABORT; } } nBytesInRow= WIDTHBYTES(nFirstImageColorDepth*nFirstImageWidth); nImageSize = nFirstImageHeight * nBytesInRow; if(DstImage.m_pImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pImageData); DstImage.m_pImageData = NULL; DstImage.m_pImageData = (BYTE *)malloc(nImageSize); } } else { DstImage.m_pImageData = (BYTE *)malloc(nImageSize); } memset(DstImage.m_pImageData,0,nImageSize); DstImage.InitHeaders(COLOR_24BIT,nFirstImageWidth,nFirstImageHeight,nImageSize); if(nFirstImageColorDepth == 24) // If the color depth of image is 24 bits { for(int nRow=0; nRow<nFirstImageHeight; nRow++) { for(int nColumn=0; nColumn<nFirstImageWidth; nColumn++) { nAvgRvalue = 0; nAvgGvalue = 0; nAvgBvalue = 0; for(int j=0; j<nNoImage; j++) { nAvgRvalue += m_aImageList[j].m_pImageData[nRow*nBytesInRow+3*nColumn+2]; nAvgGvalue += m_aImageList[j].m_pImageData[nRow*nBytesInRow+3*nColumn+1]; nAvgBvalue += m_aImageList[j].m_pImageData[nRow*nBytesInRow+3*nColumn]; } DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2] = (nAvgRvalue/nNoImage); DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1] = (nAvgGvalue/nNoImage); DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn] = (nAvgBvalue/nNoImage); } } } DstImage.m_bImageLoaded = TRUE; return nTestResult; } //+change kwmoon 080125 //BOOL CImageProc::MakeMaskImg(int nMaskWidth,CBaseImage& SrcImage,CBaseImage& DstImage,CProgressCtrl& Progress) BOOL CImageProc::MakeMaskImg(int nMaskWidth,CBaseImage& SrcImage,CBaseImage& DstImage,CProgressCtrl& Progress,BOOL bInvalidateOsdRegion) { BYTE *lBmBuf; int *lImg[2][3]; // lImg[0] is for the source image and llmg[1] is for the processed image. int **lImgPtr,**lImgPtr0,**lImgPtr1; int l_i,l_j; int lCnt; // Dimension of the Snap Image int nSrcWidth = SrcImage.m_InfoHeader.biWidth; int nSrcHeight = SrcImage.m_InfoHeader.biHeight; int nSrcBitCount = SrcImage.m_InfoHeader.biBitCount; int nBytesInRow= WIDTHBYTES(SrcImage.m_InfoHeader.biBitCount*SrcImage.m_InfoHeader.biWidth); int nImageSize = SrcImage.m_InfoHeader.biSizeImage; int nImageBufferSize = 0; if(&SrcImage != &DstImage) { if(DstImage.m_pImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pImageData); DstImage.m_pImageData = NULL; DstImage.m_pImageData = (BYTE *)malloc(nImageSize); } } else { DstImage.m_pImageData = (BYTE *)malloc(nImageSize); } memset(DstImage.m_pImageData,0,nImageSize); DstImage.InitHeaders(COLOR_24BIT,nSrcWidth,nSrcHeight,nImageSize); for(int i=0; i<nImageSize; i++) { DstImage.m_pImageData[i] = SrcImage.m_pImageData[i]; } } int nDstWidth = DstImage.m_InfoHeader.biWidth; int nDstHeight = DstImage.m_InfoHeader.biHeight; int nDstBitCount = DstImage.m_InfoHeader.biBitCount; Progress.SetPos(10); lBmBuf = DstImage.m_pImageData; CString szMessage; for (l_j = 0; l_j < 2; l_j++) { for (l_i = 0; l_i < 3; l_i++) { if ((lImg[l_j][l_i] = (int*)malloc(nDstWidth*nDstHeight*4)) == NULL) // *4 -> int { szMessage.Format("Allocte Error : size = %d",nDstWidth*nDstHeight*4); AfxMessageBox(szMessage); return FALSE; } } } ExtPlane(lBmBuf,lImg[0],nDstWidth,nDstHeight,nDstBitCount); // Extract each R/G/B Planes from lBmBuf and then save it to llmg[j] Progress.SetPos(20); // lImg[0] is for the source image and llmg[1] is for the processed image. lImgPtr = lImg[0]; lImgPtr0 = lImg[1]; // Process Image for (l_i = 0; l_i < 3; l_i++) { Filter(*(lImgPtr+l_i),*(lImgPtr0+l_i),nDstWidth,nDstHeight,3,3,Mask3x3_a); // Apply Mask3x3_a to all of three R/G/B planes } lImgPtr1 = lImgPtr; lImgPtr = lImgPtr0; lImgPtr0 = lImgPtr1; Progress.SetPos(30); for (l_i = 0; l_i < 3; l_i++) { Filter(*(lImgPtr+l_i),*(lImgPtr0+l_i),nDstWidth,nDstHeight,7,7,Mask7x7_a); // Apply Mask7x7_a to all of three R/G/B planes } lImgPtr1 = lImgPtr; lImgPtr = lImgPtr0; lImgPtr0 = lImgPtr1; Progress.SetPos(40); for (l_i = 0; l_i < 3; l_i++) { OuterFill(*(lImgPtr+l_i),nDstWidth,nDstHeight,4,4,255); // Paint outlines with wihte color } Progress.SetPos(50); for (l_i = 0; l_i < 3; l_i++) { ConstThr(*(lImgPtr+l_i),*(lImgPtr0+l_i),nDstWidth,nDstHeight,-80,80,0,255); // Binary-processing } Progress.SetPos(60); lImgPtr1 = lImgPtr; lImgPtr = lImgPtr0; lImgPtr0 = lImgPtr1; for (lCnt = 0; lCnt < nMaskWidth; lCnt++) { for (l_i = 0; l_i < 3; l_i++) Dilation(*(lImgPtr+l_i),*(lImgPtr0+l_i),nDstWidth,nDstHeight); lImgPtr1 = lImgPtr; lImgPtr = lImgPtr0; lImgPtr0 = lImgPtr1; } Progress.SetPos(70); // Desposit Image DepPlane(lImgPtr,lBmBuf,nDstWidth,nDstHeight,nDstBitCount); // Copy the processed image stored in llmgPtr to lBmBuf for (l_j = 0; l_j < 2; l_j++) { for (l_i = 0; l_i < 3; l_i++) { free(lImg[l_j][l_i]); } } DstImage.m_bImageLoaded = TRUE; // Make Black&White Mask Image BinaryForMaskImage(NORMAL_BINARY,DstImage,0,TRUE); // Make an Osd Region white if(bInvalidateOsdRegion) { InvalidateOsdRegion(DstImage); } //+add kwmoon 080828 if(m_bInvalidateInvalidRegion) { InvalidateInvalidRegion(DstImage); } Progress.SetPos(100); return TRUE; } int CImageProc::ExtPlane(BYTE* aBm,int** aImg,int aBmWid,int aBmHgt,int aPxlWid) { int l_i,l_j,l_k; int *lDstPtr; BYTE *lSrcPtr,*lSrcPtr0; int lOff,lLineOff; lOff = 3; lLineOff = (aBmWid*3 + 3) & ~3; for (l_i = 0; l_i < 3; l_i++) { lSrcPtr0 = aBm; lDstPtr = *aImg; for (l_j = 0; l_j < aBmHgt; l_j++) { lSrcPtr = lSrcPtr0; for (l_k = 0; l_k < aBmWid; l_k++) { *lDstPtr++ = (int)*lSrcPtr; lSrcPtr += lOff; } lSrcPtr0 += lLineOff; } aBm++; aImg++; } return 0; } int CImageProc::DepPlane(int** aImg,BYTE* aBm,int aBmWid,int aBmHgt,int aPxlWid) { int l_i,l_j,l_k; int *lSrcPtr; BYTE *lDstPtr,*lDstPtr0; int lOff,lLineOff; lOff = 3; lLineOff = (aBmWid*3 + 3) & ~3; for (l_i = 0; l_i < 3; l_i++) { lDstPtr0 = aBm; lSrcPtr = *aImg; for (l_j = 0; l_j < aBmHgt; l_j++) { lDstPtr = lDstPtr0; for (l_k = 0; l_k < aBmWid; l_k++) { *lDstPtr = (BYTE)*lSrcPtr++; lDstPtr += lOff; } lDstPtr0 += lLineOff; } aBm++; aImg++; } return 0; } int CImageProc::Filter(int* aSrcImg,int* aDstImg,int aBmWid,int aBmHgt,int aMaskWid,int aMaskHgt,int* aMask) { int l_i,l_j,l_m,l_n; int* lSrc,*lSrc0,*lSrc1,*lSrc2; int* lDst,*lDst0,lVal; int* lMask; if (aMaskWid < 1 || aMaskHgt < 1) return -1; if (aBmWid < aMaskWid || aBmHgt < aMaskHgt) return -1; lSrc0 = aSrcImg + (aMaskHgt/2)*aBmWid + aMaskWid/2; lDst0 = aDstImg + (aMaskHgt/2)*aBmWid + aMaskWid/2; for (l_i = 0; l_i < aBmHgt-(aMaskHgt-1); l_i++) { lSrc = lSrc0; lDst = lDst0; for (l_j = 0; l_j < aBmWid-(aMaskWid-1); l_j++) { lMask = aMask; lSrc1 = (lSrc - (aMaskHgt/2)*aBmWid - aMaskWid/2); lVal = 0; for (l_m = 0; l_m < aMaskHgt; l_m++) { lSrc2 = lSrc1; for (l_n = 0; l_n < aMaskWid; l_n++) lVal += *lSrc2++ * *lMask++; lSrc1 += aBmWid; } *lDst++ = lVal >> 10; lSrc++; } lSrc0 += aBmWid; lDst0 += aBmWid; } return 0; } int CImageProc::OuterFill(int* aSrcImg,int aBmWid,int aBmHgt,int aHor,int aVer,int aVal) { int l_i,l_j; int* lSrc,*lSrc0; if (aBmWid < aHor*2 || aBmHgt < aVer*2) return 0; lSrc0 = aSrcImg; for (l_i = 0; l_i < aBmHgt; l_i++) { lSrc = lSrc0; for (l_j = 0; l_j < aHor; l_j++) *lSrc++ = aVal; lSrc0 += aBmWid; } lSrc0 = aSrcImg + aBmWid - aHor; for (l_i = 0; l_i < aBmHgt; l_i++) { lSrc = lSrc0; for (l_j = 0; l_j < aHor; l_j++) *lSrc++ = aVal; lSrc0 += aBmWid; } lSrc0 = aSrcImg; for (l_i = 0; l_i < aVer; l_i++) { lSrc = lSrc0; for (l_j = 0; l_j < aBmWid; l_j++) *lSrc++ = aVal; lSrc0 += aBmWid; } lSrc0 = aSrcImg + (aBmHgt-aVer)*aBmWid; for (l_i = 0; l_i < aVer; l_i++) { lSrc = lSrc0; for (l_j = 0; l_j < aBmWid; l_j++) *lSrc++ = aVal; lSrc0 += aBmWid; } return 0; } int CImageProc::ConstThr(int* aSrcImg,int* aDstImg,int aBmWid,int aBmHgt,int aThrl,int aThrh,int aInval,int aOutVal) { int l_i,l_j; int* lSrc,*lSrc0,*lDst,*lDst0,lVal; if (aBmWid < 1 || aBmHgt < 1) return 0; lSrc0 = aSrcImg; lDst0 = aDstImg; for (l_i = 0; l_i < aBmHgt; l_i++) { lSrc = lSrc0; lDst = lDst0; for (l_j = 0; l_j < aBmWid; l_j++) { lVal = *lSrc++; if (lVal >= aThrl && lVal <= aThrh) lVal = aInval; else lVal = aOutVal; *lDst++ = lVal; } lSrc0 += aBmWid; lDst0 += aBmWid; } return 0; } int CImageProc::Dilation(int* aSrcImg,int* aDstImg,int aBmWid,int aBmHgt) { int l_i,l_j; int* lSrc,*lSrc0; int* lDst,*lDst0,lVal; if (aBmWid < 3 || aBmHgt < 3) return -1; lSrc0 = aSrcImg; lDst0 = aDstImg; lSrc = lSrc0; lDst = lDst0; lVal = *lSrc | *(lSrc+1); lVal |= *(lSrc+aBmWid) | *(lSrc+aBmWid+1); *lDst++ = lVal; lSrc++; for (l_j = 0; l_j < aBmWid-2; l_j++) { lVal = *(lSrc-1) | *lSrc | *(lSrc+1); lVal |= *(lSrc+aBmWid-1) | *(lSrc+aBmWid) | *(lSrc+aBmWid+1); *lDst++ = lVal; lSrc++; } lVal = *(lSrc-1) | *lSrc; lVal |= *(lSrc+aBmWid-1) | *(lSrc+aBmWid); *lDst = lVal; lSrc0 += aBmWid; lDst0 += aBmWid; for (l_i = 0; l_i < aBmHgt-2; l_i++) { lSrc = lSrc0; lDst = lDst0; lVal = *(lSrc-aBmWid) | *(lSrc-aBmWid+1); lVal |= *lSrc | *(lSrc+1); lVal |= *(lSrc+aBmWid) | *(lSrc+aBmWid+1); *lDst++ = lVal; lSrc++; for (l_j = 0; l_j < aBmWid-2; l_j++) { lVal = *(lSrc-aBmWid-1) | *(lSrc-aBmWid) | *(lSrc-aBmWid+1); lVal |= *(lSrc-1) | *lSrc | *(lSrc+1); lVal |= *(lSrc+aBmWid-1) | *(lSrc+aBmWid) | *(lSrc+aBmWid+1); *lDst++ = lVal; lSrc++; } lVal = *(lSrc-aBmWid-1) | *(lSrc-aBmWid); lVal |= *(lSrc-1) | *lSrc | *(lSrc+1); lVal |= *(lSrc+aBmWid-1) | *(lSrc+aBmWid); *lDst++ = lVal; lSrc0 += aBmWid; lDst0 += aBmWid; } lSrc = lSrc0; lDst = lDst0; lVal = *(lSrc-aBmWid) | *(lSrc-aBmWid+1); lVal |= *lSrc | *(lSrc+1); *lDst++ = lVal; lSrc++; for (l_j = 0; l_j < aBmWid-2; l_j++) { lVal = *(lSrc-aBmWid-1) | *(lSrc-aBmWid) | *(lSrc-aBmWid+1); lVal |= *(lSrc-1) | *lSrc | *(lSrc+1); *lDst++ = lVal; lSrc++; } lVal = *(lSrc-aBmWid-1) | *(lSrc-aBmWid); lVal |= *(lSrc-1) | *lSrc; *lDst = lVal; return 0; } int CImageProc::Xor(int* aSrcImg,int* aDstImg,int aBmWid,int aBmHgt,int aVal) { int l_i,l_j; int* lSrc,*lSrc0,*lDst,*lDst0,lVal; if (aBmWid < 1 || aBmHgt < 1) return 0; lSrc0 = aSrcImg; lDst0 = aDstImg; for (l_i = 0; l_i < aBmHgt; l_i++) { lSrc = lSrc0; lDst = lDst0; for (l_j = 0; l_j < aBmWid; l_j++) { lVal = *lSrc++; *lDst++ = lVal ^ aVal; } lSrc0 += aBmWid; lDst0 += aBmWid; } return 0; } int CImageProc::StackPush(int* stackX, int* stackY, int arr_size, int vx, int vy, int *top) { // forbid overflow if(*top >= arr_size) return -1; (*top)++; stackX[*top] = vx; stackY[*top] = vy; return 1; } int CImageProc::StackPop(int* stackX, int* stackY, int* vx, int* vy, int *top) { // if no data is left in the stack, return -1; if(*top == 0) return -1; *vx = stackX[*top]; *vy = stackY[*top]; (*top)--; return 1; } int CImageProc::Labeling(CBaseImage& SnapImage, CBaseImage& MaskImage, CBaseImage& ProcImage,CProgressCtrl& Progress) { if((SnapImage.m_InfoHeader.biBitCount < 24) || (MaskImage.m_InfoHeader.biBitCount < 24)) { AfxMessageBox("Only true color image is supported!"); return TEST_ABORT; } // Dimension of the Grab Image int nGrabWidth = SnapImage.m_InfoHeader.biWidth; int nGrabHeight = SnapImage.m_InfoHeader.biHeight; int nGrabBitCount = SnapImage.m_InfoHeader.biBitCount; // Dimension of the Mask Image int nMaskWidth = MaskImage.m_InfoHeader.biWidth; int nMaskHeight = MaskImage.m_InfoHeader.biHeight; int nBytesInRow = WIDTHBYTES(nGrabBitCount*nGrabWidth); if(SnapImage.m_bImageLoaded == FALSE) { AfxMessageBox("Grab Image is not loaded!"); return TEST_ABORT; } if(MaskImage.m_bImageLoaded == FALSE) { AfxMessageBox("Mask Image is not loaded!"); return TEST_ABORT; } if((nGrabWidth != nMaskWidth) || (nGrabHeight != nMaskHeight)) { AfxMessageBox("The size of two images is different!"); return TEST_ABORT; } if(&SnapImage == &MaskImage) { AfxMessageBox("Mask Image can not be labeled!"); return TEST_ABORT; } if(&SnapImage == &ProcImage) { AfxMessageBox("Proc Image can not be labeled!"); return TEST_ABORT; } int nGroupNo = 0; int nPixelIndex = 0; int nArraySize = nMaskWidth * nMaskHeight; int r=0,c=0,top=0; int* StackX = (int *)malloc(nMaskWidth * nMaskHeight * 4); memset(StackX,0,SnapImage.m_InfoHeader.biSizeImage); int* StackY = (int *)malloc(nMaskWidth * nMaskHeight * 4); memset(StackY,0,SnapImage.m_InfoHeader.biSizeImage); BYTE* LabelImage = (BYTE *)malloc(SnapImage.m_InfoHeader.biSizeImage); memset(LabelImage,0,SnapImage.m_InfoHeader.biSizeImage); if(SnapImage.m_InfoHeader.biBitCount==24) // If the color depth of image is 24 bits { for(int nRow=0; nRow<nMaskHeight; nRow++) { for(int nColumn=0; nColumn<nMaskWidth; nColumn++) { nPixelIndex = (nRow)*nBytesInRow+3*(nColumn); // 이미 방문한 픽셀인 경우, Skip함 if((LabelImage[nPixelIndex] != 0) || (MaskImage.m_pImageData[nPixelIndex] != 0)) continue; r = nRow; c = nColumn; top = 0; nGroupNo++; // Valid Group No : 1 ~ while(1) { GRASSFIRE: for(int m=r-1; m<=r+1; m++) { for(int n=c-1; n<=c+1; n++) { // 대상영역을 벗어나면, Skip함 if(m<0 || m>=nMaskHeight || n<0 || n>= nMaskWidth) continue; nPixelIndex = (m)*nBytesInRow+3*(n); // 처음 방문한 픽셀인 경우 if((LabelImage[nPixelIndex] == 0) && (MaskImage.m_pImageData[nPixelIndex] == 0)) { LabelImage[nPixelIndex] = nGroupNo; if(StackPush(StackX,StackY,nArraySize,m,n,&top) == -1) continue; r = m; c = n; goto GRASSFIRE; } } } if(StackPop(StackX,StackY,&r,&c,&top) == -1) { break; } } } } } float fGrayGap = 250.0f/(float)nGroupNo; for(int nRow=0; nRow<nMaskHeight; nRow++) { for(int nColumn=0; nColumn<nMaskWidth; nColumn++) { nPixelIndex = (nRow)*nBytesInRow+3*(nColumn); if(MaskImage.m_pImageData[nPixelIndex] == 255) { ProcImage.m_pImageData[nPixelIndex] = 255; ProcImage.m_pImageData[nPixelIndex+1] = 255; ProcImage.m_pImageData[nPixelIndex+2] = 255; } else { ProcImage.m_pImageData[nPixelIndex] = (BYTE)(LabelImage[nPixelIndex]*fGrayGap); ProcImage.m_pImageData[nPixelIndex+1] = (BYTE)(LabelImage[nPixelIndex]*fGrayGap); ProcImage.m_pImageData[nPixelIndex+2] = (BYTE)(LabelImage[nPixelIndex]*fGrayGap); } } } if(StackX != NULL) delete StackX; StackX = NULL; if(StackY != NULL) delete StackY; StackY = NULL; if(LabelImage != NULL) delete LabelImage; LabelImage = NULL; return TEST_PASS; } int CImageProc::Repaint(CBaseImage& SnapImage, CBaseImage& MaskImage, CBaseImage& ProcImage,CProgressCtrl& Progress) { if((SnapImage.m_InfoHeader.biBitCount < 24) || (MaskImage.m_InfoHeader.biBitCount < 24)) { AfxMessageBox("Only true color image is supported!"); return TEST_ABORT; } // Dimension of the Grab Image int nGrabWidth = SnapImage.m_InfoHeader.biWidth; int nGrabHeight = SnapImage.m_InfoHeader.biHeight; int nGrabBitCount = SnapImage.m_InfoHeader.biBitCount; int nImageSize = SnapImage.m_InfoHeader.biSizeImage; // Dimension of the Mask Image int nMaskWidth = MaskImage.m_InfoHeader.biWidth; int nMaskHeight = MaskImage.m_InfoHeader.biHeight; // Dimension of the Mask Image int nProcWidth = ProcImage.m_InfoHeader.biWidth; int nProcHeight = ProcImage.m_InfoHeader.biHeight; int nBytesInRow = WIDTHBYTES(nGrabBitCount*nGrabWidth); int nImageBufferSize = 0; if(SnapImage.m_bImageLoaded == FALSE) { AfxMessageBox("Grab Image is not loaded!"); return TEST_ABORT; } if(MaskImage.m_bImageLoaded == FALSE) { AfxMessageBox("Mask Image is not loaded!"); return TEST_ABORT; } if((nGrabWidth != nMaskWidth) || (nGrabHeight != nMaskHeight)) { AfxMessageBox("The size of two images is different!"); return TEST_ABORT; } if(&SnapImage == &MaskImage) { AfxMessageBox("Mask Image can not be repainted!"); return TEST_ABORT; } if(&SnapImage == &ProcImage) { AfxMessageBox("Proc Image can not be labeled!"); return TEST_ABORT; } if((nGrabWidth != nProcWidth) || (nGrabHeight != nProcHeight)) { if(ProcImage.m_pImageData != NULL) { nImageBufferSize = _msize(ProcImage.m_pImageData); if(nImageBufferSize != nImageSize) { free(ProcImage.m_pImageData); ProcImage.m_pImageData = NULL; ProcImage.m_pImageData = (BYTE *)malloc(nImageSize); } } else { ProcImage.m_pImageData = (BYTE *)malloc(nImageSize); } memset(ProcImage.m_pImageData,0,nImageSize); ProcImage.InitHeaders(COLOR_24BIT,nGrabWidth,nGrabHeight,nImageSize); } for(int i=0; i<nImageSize; i++) { ProcImage.m_pImageData[i] = SnapImage.m_pImageData[i]; } int nGroupNo = 0; int nPixelIndex = 0; int nArraySize = nMaskWidth * nMaskHeight; int r=0,c=0,top=0; int* StackX = (int *)malloc(nMaskWidth * nMaskHeight * 4); memset(StackX,0,SnapImage.m_InfoHeader.biSizeImage); int* StackY = (int *)malloc(nMaskWidth * nMaskHeight * 4); memset(StackY,0,SnapImage.m_InfoHeader.biSizeImage); BYTE* LabelImage = (BYTE *)malloc(SnapImage.m_InfoHeader.biSizeImage); memset(LabelImage,0,SnapImage.m_InfoHeader.biSizeImage); if(SnapImage.m_InfoHeader.biBitCount==24) // If the color depth of image is 24 bits { for(int nRow=0; nRow<nMaskHeight; nRow++) { for(int nColumn=0; nColumn<nMaskWidth; nColumn++) { nPixelIndex = (nRow)*nBytesInRow+3*(nColumn); // 이미 방문한 픽셀인 경우, Skip함 if((LabelImage[nPixelIndex] != 0) || (MaskImage.m_pImageData[nPixelIndex] != 0)) continue; r = nRow; c = nColumn; top = 0; nGroupNo++; // Valid Group No : 1 ~ while(1) { GRASSFIRE: for(int m=r-1; m<=r+1; m++) { for(int n=c-1; n<=c+1; n++) { // 대상영역을 벗어나면, Skip함 if(m<0 || m>=nMaskHeight || n<0 || n>= nMaskWidth) continue; nPixelIndex = (m)*nBytesInRow+3*(n); // 처음 방문한 픽셀인 경우 if((LabelImage[nPixelIndex] == 0) && (MaskImage.m_pImageData[nPixelIndex] == 0)) { LabelImage[nPixelIndex] = nGroupNo; if(StackPush(StackX,StackY,nArraySize,m,n,&top) == -1) continue; r = m; c = n; goto GRASSFIRE; } } } //+add kwmoon 071210 if(CurrentSet->bRunAbort) { return TEST_ABORT; } if(StackPop(StackX,StackY,&r,&c,&top) == -1) break; } } } } if(StackX != NULL) delete StackX; StackX = NULL; if(StackY != NULL) delete StackY; StackY = NULL; int nAvgRColor = 0; int nAvgGColor = 0; int nAvgBColor = 0; int nNoGroupItem = 0; for(int i=1; i<=nGroupNo;i++) { nAvgRColor = 0; nAvgGColor = 0; nAvgBColor = 0; nNoGroupItem = 0; for(int nRow=0; nRow<nMaskHeight; nRow++) { for(int nColumn=0; nColumn<nMaskWidth; nColumn++) { nPixelIndex = (nRow)*nBytesInRow+3*(nColumn); if(LabelImage[nPixelIndex] == i) { nNoGroupItem++; nAvgRColor += SnapImage.m_pImageData[nPixelIndex+2]; nAvgGColor += SnapImage.m_pImageData[nPixelIndex+1]; nAvgBColor += SnapImage.m_pImageData[nPixelIndex]; } } } nAvgRColor = (int)((float)nAvgRColor/(float)nNoGroupItem); nAvgGColor = (int)((float)nAvgGColor/(float)nNoGroupItem); nAvgBColor = (int)((float)nAvgBColor/(float)nNoGroupItem); for(int nRow=0; nRow<nMaskHeight; nRow++) { for(int nColumn=0; nColumn<nMaskWidth; nColumn++) { nPixelIndex = (nRow)*nBytesInRow+3*(nColumn); if(LabelImage[nPixelIndex] == i) { ProcImage.m_pImageData[nPixelIndex+2] = nAvgRColor; ProcImage.m_pImageData[nPixelIndex+1] = nAvgGColor; ProcImage.m_pImageData[nPixelIndex] = nAvgBColor; } } } } if(LabelImage != NULL) delete LabelImage; LabelImage = NULL; return TEST_PASS; } BOOL CImageProc::RGB2Gray(int nType,CBaseImage& DstImage,BOOL bOverwrite) { if(DstImage.m_InfoHeader.biBitCount < 24) { AfxMessageBox("Only true color image is supported!"); return TEST_FAIL; } int nProgress = 0; int nColorDepth = DstImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*DstImage.m_InfoHeader.biWidth); float fRvalue = 0; float fGvalue = 0; float fBvalue = 0; int nGrayValue = 0; int nImageBufferSize = 0; int nImageSize = 0; nImageSize = DstImage.m_InfoHeader.biSizeImage; if(DstImage.m_pProcessedImageData != NULL) { nImageBufferSize = _msize(DstImage.m_pProcessedImageData); if(nImageBufferSize != nImageSize) { free(DstImage.m_pProcessedImageData); DstImage.m_pProcessedImageData = NULL; DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } } else { DstImage.m_pProcessedImageData = (BYTE *)malloc(DstImage.m_BmInfo->bmiHeader.biSizeImage); } memset(DstImage.m_pProcessedImageData,0,DstImage.m_BmInfo->bmiHeader.biSizeImage); DstImage.m_bProcessedImageLoaded = FALSE; for(int nRow=0; nRow<DstImage.m_InfoHeader.biHeight; nRow++) { for(int nColumn=0; nColumn<DstImage.m_InfoHeader.biWidth; nColumn++) { fBvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn]; fGvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1]; fRvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2]; nGrayValue = (int)(fRvalue * 0.3 + fGvalue * 0.59 + fBvalue * 0.11); DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn] = nGrayValue; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+1] = nGrayValue; DstImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2] = nGrayValue; } } DstImage.m_bProcessedImageLoaded = TRUE; if(bOverwrite) { for(int j=0; j<(int)DstImage.m_InfoHeader.biSizeImage; j++) { DstImage.m_pImageData[j] = DstImage.m_pProcessedImageData[j]; } } return TEST_PASS; } void CImageProc::ZoomOut(CBaseImage& SrcImage,float fZoomFactor) { int nProgress = 0; int nHeight = SrcImage.m_InfoHeader.biHeight; int nWidth = SrcImage.m_InfoHeader.biWidth; int nNewHeight = (int)(nHeight * fZoomFactor); int nNewWidth = (int)(nWidth * fZoomFactor); int nRowWidth = WIDTHBYTES(SrcImage.m_BmInfo->bmiHeader.biBitCount*nWidth); int nNewRowWidth = WIDTHBYTES(SrcImage.m_BmInfo->bmiHeader.biBitCount*nNewWidth); int nNewImageSize = nNewRowWidth * nNewHeight; int nRow = 0; int nCol = 0; float fRow = 0; float fCol = 0; BYTE nNewValue = 0; float fSr = 0.0f; float fSc = 0.0f; float fI1,fI2,fI3,fI4; BYTE* pImageData = (BYTE *)malloc(nNewImageSize); memset(pImageData,0,nNewImageSize); for(int r=0;r<nNewHeight;r++) { for(int c=0;c<nNewWidth;c++) { for(int i=0; i<3; i++) { fRow = r/fZoomFactor; fCol = c/fZoomFactor; nRow = (int)floor(fRow); nCol = (int)floor(fCol); fSr = fRow - nRow; fSc = fCol - nCol; if((nRow<0) || (nRow>(nHeight-1)) || (nCol<0) || (nCol>(nWidth-1))) { SrcImage.m_pProcessedImageData[r*nNewWidth+c] = 0; } else { fI1 = (float)SrcImage.m_pImageData[nRow*nRowWidth+(3*nCol+i)]; fI2 = (float)SrcImage.m_pImageData[nRow*nRowWidth+(3*(nCol+1)+i)]; fI3 = (float)SrcImage.m_pImageData[(nRow+1)*nRowWidth+(3*(nCol+1)+i)]; fI4 = (float)SrcImage.m_pImageData[(nRow+1)*nRowWidth+(3*nCol+i)]; nNewValue = (BYTE)( fI1*(1-fSc)*(1-fSr) + fI2*fSc*(1-fSr) + fI3*fSc*fSr + fI4*(1-fSc)*fSr); pImageData[r*nNewRowWidth+3*c+i] = nNewValue; } } } } memcpy(SrcImage.m_pImageData,pImageData,nNewImageSize); if(pImageData != NULL) delete pImageData; pImageData = NULL; SrcImage.InitHeaders(COLOR_24BIT,nNewWidth,nNewHeight,nNewImageSize); SrcImage.m_bImageLoaded = TRUE; } float CImageProc::Level2Percentage(int nLevel, int nNoLevel) { //+change kwmoon 080716 // return (float)floor((float)nLevel*100/(float)nNoLevel); return (float)((float)nLevel*100/(float)nNoLevel); } int CImageProc::Percentage2Level(float fPercent, int nNoLevel) { //+change kwmoon 080716 // return (int)floor(fPercent*0.01*(float)nNoLevel); return (int)(fPercent*0.01*(float)nNoLevel); } #define START_COLOR_LEVEL 25 #define END_COLOR_LEVEL 230 int CImageProc::NoVideoSignalTest(CBaseImage& DstImage,CProgressCtrl& ItemProgress) { if(DstImage.m_pImageData == NULL) { AfxMessageBox("Invalid Image!"); return TEST_ABORT; } CString szErrMsg = _T(""); CString szFilePath = _T(""); int nTestResult = TEST_PASS; int nImageHeight = 0; int nImageWidth = 0; int nImageColorDepth = 0; int nBytesInRow = 0; int nRvalue = 0; int nGvalue = 0; int nBvalue = 0; int nImageDataSize = 0; int nImageBufferSize = 0; // Check image size & Color depth nImageWidth = DstImage.m_InfoHeader.biWidth; nImageHeight = DstImage.m_InfoHeader.biHeight; nImageColorDepth = DstImage.m_InfoHeader.biBitCount; nBytesInRow = WIDTHBYTES(nImageColorDepth*nImageWidth); nImageDataSize = nImageHeight * nBytesInRow; int nHistogram[3][256]; int nImageSize = 0; for(int i=0; i<3; i++) { m_nNoPixelInMiddleRange[i] = 0; m_nNoNonBlackPixel[i] = 0; for(int j=0; j<256; j++) { nHistogram[i][j] = 0; } } if((m_nRoiWidth == 0) && (m_nRoiHeight == 0)) { nImageSize = nImageHeight * nImageWidth - (m_nOsdWidth * m_nOsdHeight); } else { nImageSize = m_nRoiHeight * m_nRoiWidth; } int nStartXposition=0, nEndXposition=0, nStartYposition=0, nEndYposition=0; CalcTestRange(DstImage,nStartXposition, nEndXposition, nStartYposition, nEndYposition); for(int nRow=nStartYposition; nRow<=nEndYposition; nRow++) { for(int nColumn=nStartXposition; nColumn<=nEndXposition; nColumn++) { nRvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2]; nGvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1]; nBvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn]; if((m_nRoiWidth == 0) && (m_nRoiHeight == 0)) { if((m_nOsdWidth != 0) && (nColumn >= m_ptOsdPosition.x) && (nColumn <= (m_ptOsdPosition.x + m_nOsdWidth)) && (m_nOsdHeight != 0) && (nRow >= m_ptOsdPosition.y) && (nRow <= (m_ptOsdPosition.y + m_nOsdHeight))) { continue; } } nHistogram[R_DATA][nRvalue]++; nHistogram[G_DATA][nGvalue]++; nHistogram[B_DATA][nBvalue]++; if(nRvalue > 10) m_nNoNonBlackPixel[R_DATA]++; if(nGvalue > 10) m_nNoNonBlackPixel[G_DATA]++; if(nBvalue > 10) m_nNoNonBlackPixel[B_DATA]++; } } int nPercentageNonBlackPixel = CurrentSet->nNonBlackPixel; int nPercentagePixelInMiddleRange = CurrentSet->nPixelInMiddleRange; for(int i=START_COLOR_LEVEL; i<END_COLOR_LEVEL; i++) { m_nNoPixelInMiddleRange[R_DATA] += nHistogram[R_DATA][i]; m_nNoPixelInMiddleRange[G_DATA] += nHistogram[G_DATA][i]; m_nNoPixelInMiddleRange[B_DATA] += nHistogram[B_DATA][i]; } if((m_nNoNonBlackPixel[R_DATA] > (int)((float)nImageSize * nPercentageNonBlackPixel * 0.01)) || (m_nNoNonBlackPixel[G_DATA] > (int)((float)nImageSize * nPercentageNonBlackPixel * 0.01)) || (m_nNoNonBlackPixel[B_DATA] > (int)((float)nImageSize * nPercentageNonBlackPixel * 0.01))) { if((m_nNoPixelInMiddleRange[R_DATA] > (int)((float)nImageSize * nPercentagePixelInMiddleRange * 0.01)) || (m_nNoPixelInMiddleRange[G_DATA] > (int)((float)nImageSize * nPercentagePixelInMiddleRange * 0.01)) || (m_nNoPixelInMiddleRange[B_DATA] > (int)((float)nImageSize * nPercentagePixelInMiddleRange * 0.01))) { return TEST_PASS; } else { return TEST_FAIL; } } else { return TEST_FAIL; } } void CImageProc::SetAllowedErrorPixel(float fAllowedErrorPixelPercentage[]) { for(int i=0; i<5; i++) { m_fAllowedBandErrorPixelPercentage[i] = fAllowedErrorPixelPercentage[i]; } } int CImageProc::CaptionTest(CBaseImage& SnapImage, CBaseImage& RefImage, CBaseImage& MaskImage, int nLowerLimit, int nUpperLimit, CProgressCtrl& ItemProgress) { if((SnapImage.m_pImageData == NULL) || (RefImage.m_pImageData == NULL)) { AfxMessageBox("Invalid Image!"); return TEST_ABORT; } CString szErrMsg = _T(""); CString szFilePath = _T(""); int nTestResult = TEST_PASS; int nImageHeight = 0; int nImageWidth = 0; int nImageColorDepth = 0; int nBytesInRow = 0; // int nRvalue = 0; // int nGvalue = 0; // int nBvalue = 0; int nValue = 0; // int nNoNonBlackRvalue = 0; // int nNoNonBlackGvalue = 0; // int nNoNonBlackBvalue = 0; int nNoNonBlackValue = 0; int nImageSize = 0; int nImageBufferSize = 0; int nMaskValue = 0; // Check image size & Color depth nImageWidth = SnapImage.m_InfoHeader.biWidth; nImageHeight = SnapImage.m_InfoHeader.biHeight; nImageColorDepth = SnapImage.m_InfoHeader.biBitCount; nBytesInRow = WIDTHBYTES(nImageColorDepth*nImageWidth); nImageSize = nImageHeight * nBytesInRow; //+change kwmoon 071112 BinaryForDiffImage(NORMAL_BINARY,SnapImage,RefImage,nLowerLimit,nUpperLimit); for(int nRow=0; nRow<nImageHeight; nRow++) { for(int nColumn=0; nColumn<nImageWidth; nColumn++) { if(MaskImage.m_bImageLoaded) { nMaskValue = MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn] | MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1] | MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2]; } //+add kwmoon 080213 if((m_nOsdWidth != 0) && (nColumn >= m_ptOsdPosition.x) && (nColumn <= (m_ptOsdPosition.x + m_nOsdWidth)) && (m_nOsdHeight != 0) && (nRow >= m_ptOsdPosition.y) && (nRow <= (m_ptOsdPosition.y + m_nOsdHeight))) { continue; } //- if(nMaskValue == 0) { // nRvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2]; // nGvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1]; // nBvalue = DstImage.m_pImageData[nRow*nBytesInRow+3*nColumn]; nValue = SnapImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2]; // if(nRvalue != 0) nNoNonBlackRvalue++; // if(nGvalue != 0) nNoNonBlackGvalue++; // if(nBvalue != 0) nNoNonBlackBvalue++; if(nValue != 0) nNoNonBlackValue++; } } } // if((nNoNonBlackRvalue > (int)((float)(nImageHeight * nImageWidth) * 0.1)) // || (nNoNonBlackGvalue > (int)((float)(nImageHeight * nImageWidth) * 0.1)) // || (nNoNonBlackBvalue > (int)((float)(nImageHeight * nImageWidth) * 0.1))) if(nNoNonBlackValue > (int)((float)(m_nCaptionWidth * m_nCaptionHeight) * 0.4)) { return TEST_PASS; } else { return TEST_FAIL; } } //+add kwmoon 080121 // Set Osd Region void CImageProc::SetOsdRegion(POINT ptOsd1Position,POINT ptOsd2Position) { m_ptOsdPosition.x = ptOsd1Position.x; m_ptOsdPosition.y = ptOsd1Position.y; m_nOsdWidth = ptOsd2Position.x - ptOsd1Position.x; m_nOsdHeight = ptOsd2Position.y - ptOsd1Position.y; } //+add kwmoon 080828 void CImageProc::SetInvalidRegion(POINT pt1Position,POINT pt2Position) { m_ptInvalidPosition.x = pt1Position.x; m_ptInvalidPosition.y = pt1Position.y; m_nInvalidWidth = pt2Position.x - pt1Position.x; m_nInvalidHeight = pt2Position.y - pt1Position.y; } //+add kwmoon 080121 int CImageProc::InvalidateOsdRegion(CBaseImage& MaskImage) { if((MaskImage.m_pImageData == NULL)) { AfxMessageBox("Invalid Image!"); return TEST_ABORT; } int nTestResult = TEST_PASS; int nImageHeight = 0; int nImageWidth = 0; int nImageColorDepth = 0; int nBytesInRow = 0; int nImageSize = 0; CString szErrorMsg = _T(""); // Check image size & Color depth nImageWidth = MaskImage.m_InfoHeader.biWidth; nImageHeight = MaskImage.m_InfoHeader.biHeight; nImageColorDepth = MaskImage.m_InfoHeader.biBitCount; nBytesInRow = WIDTHBYTES(nImageColorDepth*nImageWidth); nImageSize = nImageHeight * nBytesInRow; if((m_nOsdWidth == 0) || (m_nOsdHeight == 0)) { return TEST_PASS; //+add kwmoon 080409 //SetDefaultOsdRegion(nImageWidth,nImageHeight); } if((m_ptOsdPosition.x < 0) || ((m_ptOsdPosition.x + m_nOsdWidth ) >= nImageWidth ) || (m_ptOsdPosition.y < 0) || ((m_ptOsdPosition.y + m_nOsdHeight) >= nImageHeight)) { szErrorMsg.Format("Wrong OSD coordinates (%d,%d,%d,%d)", m_ptOsdPosition.x,m_ptOsdPosition.y,m_ptOsdPosition.x+m_nOsdWidth,m_ptOsdPosition.y+m_nOsdHeight); AfxMessageBox(szErrorMsg); return TEST_ABORT; } int nStartYposition = GetOppositeStartYposition(m_ptOsdPosition.y,m_nOsdHeight,nImageHeight); int nEndYposition = nStartYposition + m_nOsdHeight; for(int nRow=0; nRow<nImageHeight; nRow++) { for(int nColumn=0; nColumn<nImageWidth; nColumn++) { if((nColumn >= m_ptOsdPosition.x) && (nColumn <= m_ptOsdPosition.x + m_nOsdWidth) && (nRow >= nStartYposition) && (nRow <= nEndYposition)) { MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn] = 255; MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1] = 255; MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2] = 255; } } } return TEST_PASS; } //+add kwmoon 080828 int CImageProc::InvalidateInvalidRegion(CBaseImage& MaskImage) { if((MaskImage.m_pImageData == NULL)) { AfxMessageBox("Invalid Image!"); return TEST_ABORT; } int nTestResult = TEST_PASS; int nImageHeight = 0; int nImageWidth = 0; int nImageColorDepth = 0; int nBytesInRow = 0; int nImageSize = 0; CString szErrorMsg = _T(""); // Check image size & Color depth nImageWidth = MaskImage.m_InfoHeader.biWidth; nImageHeight = MaskImage.m_InfoHeader.biHeight; nImageColorDepth = MaskImage.m_InfoHeader.biBitCount; nBytesInRow = WIDTHBYTES(nImageColorDepth*nImageWidth); nImageSize = nImageHeight * nBytesInRow; if((m_nInvalidWidth == 0) || (m_nInvalidHeight == 0)) { return TEST_PASS; //+add kwmoon 080409 // SetDefaultOsdRegion(nImageWidth,nImageHeight); } if((m_ptInvalidPosition.x < 0) || ((m_ptInvalidPosition.x + m_nInvalidWidth ) >= nImageWidth ) || (m_ptInvalidPosition.y < 0) || ((m_ptInvalidPosition.y + m_nInvalidHeight) >= nImageHeight)) { szErrorMsg.Format("Wrong Invalid coordinates (%d,%d,%d,%d)", m_ptInvalidPosition.x, m_ptInvalidPosition.y, m_ptInvalidPosition.x+m_nInvalidWidth, m_ptInvalidPosition.y+m_nInvalidHeight); AfxMessageBox(szErrorMsg); return TEST_ABORT; } int nStartYposition = GetOppositeStartYposition(m_ptInvalidPosition.y,m_nInvalidHeight,nImageHeight); int nEndYposition = nStartYposition + m_nInvalidHeight; for(int nRow=0; nRow<nImageHeight; nRow++) { for(int nColumn=0; nColumn<nImageWidth; nColumn++) { if((nColumn >= m_ptInvalidPosition.x) && (nColumn <= m_ptInvalidPosition.x + m_nInvalidWidth) && (nRow >= nStartYposition) && (nRow <= nEndYposition)) { MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn] = 255; MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1] = 255; MaskImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2] = 255; } } } return TEST_PASS; } //+add kwmoon 080121 int CImageProc::SetDefaultOsdRegion(int nImageWidth,int nImageHeight) { if((nImageWidth == 852) && (nImageHeight == 480)) { m_ptOsdPosition.x = 0; m_ptOsdPosition.y = 0; m_nOsdWidth = 0; m_nOsdHeight = 0; } else if((nImageWidth == 1024) && (nImageHeight == 768)) { m_ptOsdPosition.x = 0; m_ptOsdPosition.y = 0; m_nOsdWidth = 0; m_nOsdHeight = 0; } else if((nImageWidth == 1280) && (nImageHeight == 768)) { m_ptOsdPosition.x = 0; m_ptOsdPosition.y = 0; m_nOsdWidth = 0; m_nOsdHeight = 0; } else if((nImageWidth == 1280) && (nImageHeight == 1024)) { m_ptOsdPosition.x = 0; m_ptOsdPosition.y = 0; m_nOsdWidth = 0; m_nOsdHeight = 0; } else if((nImageWidth == 1366) && (nImageHeight == 768)) { m_ptOsdPosition.x = 900; m_ptOsdPosition.y = 20; m_nOsdWidth = 450; m_nOsdHeight = 300; } else if((nImageWidth == 1440) && (nImageHeight == 900)) { m_ptOsdPosition.x = 0; m_ptOsdPosition.y = 0; m_nOsdWidth = 0; m_nOsdHeight = 0; } else if((nImageWidth == 1680) && (nImageHeight == 1050)) { m_ptOsdPosition.x = 1300; m_ptOsdPosition.y = 20; m_nOsdWidth = 370; m_nOsdHeight = 250; } else if((nImageWidth == 1920) && (nImageHeight == 1080)) { m_ptOsdPosition.x = 1200; m_ptOsdPosition.y = 20; m_nOsdWidth = 700; m_nOsdHeight = 450; } else { m_ptOsdPosition.x = 0; m_ptOsdPosition.y = 0; m_nOsdWidth = 0; m_nOsdHeight = 0; } return TRUE; } //+add kwmoon 080716 int CImageProc::CheckImageAttribute(CBaseImage& SnapImage, CBaseImage& RefImage,CBaseImage& MaskImage) { int nRefWidth = RefImage.m_InfoHeader.biWidth; int nRefHeight = RefImage.m_InfoHeader.biHeight; int nSnapWidth = SnapImage.m_InfoHeader.biWidth; int nSnapHeight = SnapImage.m_InfoHeader.biHeight; int nMaskWidth = 0; int nMaskHeight = 0; CString szErrMsg = _T(""); CString sRefFileName = _T(""); CString szFileName = _T(""); if((m_nRoiHeight > 0) && (m_nRoiWidth > 0)) { m_nNoRoiPixel = m_nRoiWidth * m_nRoiHeight; } else { m_nNoRoiPixel = nRefWidth * nRefHeight; } if((SnapImage.m_InfoHeader.biBitCount != 24) || (RefImage.m_InfoHeader.biBitCount != 24)) { AfxMessageBox("Only 24Bit color image is supported!"); return TEST_ABORT; } if(SnapImage.m_bImageLoaded == FALSE) { AfxMessageBox("Snap Image is not loaded!"); return TEST_ABORT; } if(RefImage.m_bImageLoaded == FALSE) { AfxMessageBox("Ref Image is not loaded!"); return TEST_ABORT; } if((nRefWidth != nSnapWidth) || (nRefHeight != nSnapHeight)) { szErrMsg.Format("[Image Size Error] Grab(W:%d,H%d), Ref(W:%d,H%d)", nSnapWidth,nSnapHeight,nRefWidth,nRefHeight); // Load a Reference Image if(RefImage.m_szFilePath != _T("")) { szFileName = RefImage.m_szFilePath.Right(RefImage.m_szFilePath.GetLength()-RefImage.m_szFilePath.ReverseFind('\\')-1); //+change kwmoon 080807 // if(!RefImage_DirectLoad(RefImage.m_szFilePath,0)) if(!RefImage_DirectLoad(szFileName,0)) { AfxMessageBox(szErrMsg); return TEST_ABORT; } } } if(MaskImage.m_bImageLoaded) { nMaskWidth = MaskImage.m_InfoHeader.biWidth; nMaskHeight = MaskImage.m_InfoHeader.biHeight; } if((nRefWidth != nSnapWidth) || (nRefHeight != nSnapHeight)) { szErrMsg.Format("[Image Size Error] Grab(W:%d,H%d), Ref(W:%d,H%d)", nSnapWidth,nSnapHeight,nRefWidth,nRefHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if(RefImage.m_InfoHeader.biBitCount != SnapImage.m_InfoHeader.biBitCount) { AfxMessageBox("The color depth of two images is different!"); return TEST_ABORT; } if((m_nRoiWidth >= nSnapWidth) || (m_nRoiHeight >= nSnapHeight)) { szErrMsg.Format("[ROI Error] Roi with & height should be less than witdh & height of image! (W:%d_%d,H:%d_%d)" ,m_nRoiWidth,nSnapWidth,m_nRoiHeight,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if((m_ptRoiPosition.x >= (nSnapWidth-1)) || (m_ptRoiPosition.y >= (nSnapHeight-1))) { szErrMsg.Format("[ROI Error] Roi (x,y) should be less than witdh & height of image! (X:%d,Y:%d,W:%d,H:%d)" ,m_ptRoiPosition.x,m_ptRoiPosition.y,nSnapWidth,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if((m_ptRoiPosition.x >= (nSnapWidth-1)) || (m_ptRoiPosition.y >= (nSnapHeight-1))) { szErrMsg.Format("[ROI Error] Roi (x,y) should be less than witdh & height of image! (X:%d,Y:%d,W:%d,H:%d)" ,m_ptRoiPosition.x,m_ptRoiPosition.y,nSnapWidth,nSnapHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } if(MaskImage.m_bImageLoaded) { if((nRefWidth != nMaskWidth) || (nRefHeight != nMaskHeight)) { szErrMsg.Format("[Image Size Error] Ref(W:%d,H%d), Mask(W:%d,H%d)", nRefWidth,nRefHeight,nMaskWidth,nMaskHeight); AfxMessageBox(szErrMsg); return TEST_ABORT; } } return TEST_PASS; } //+add kwmoon 080722 int CImageProc::ColorBiasTest(CBaseImage& SnapImage, int &nDifference,CString& szResultInfo, CProgressCtrl& ItemProgress) { if((SnapImage.m_pImageData == NULL)) { AfxMessageBox("Invalid Image!"); return TEST_ABORT; } CString szErrMsg = _T(""); CString szFilePath = _T(""); int nTestResult = TEST_PASS; int nSnapWidth = SnapImage.m_InfoHeader.biWidth; int nSnapHeight = SnapImage.m_InfoHeader.biHeight; int nColorDepth = SnapImage.m_InfoHeader.biBitCount; int nBytesInRow = WIDTHBYTES(nColorDepth*nSnapWidth); int nMinColorValue = 0; int nMaxColorValue = 0; int nLowerLimit = 0; int nUpperLimit = 0; //+change kwmoon 080722 // int nNoLevel = (int)pow(2,(nColorDepth/3)); // int nNoLevel = (int)pow(2,(nColorDepth/3))-1; int nNoPixel = 0; int nRvalue=0, nGvalue=0, nBvalue=0; int nAvgRvalue=0, nAvgGvalue=0, nAvgBvalue=0; int nYposition = 0; //+del nLowerLimit = (int)m_fLowerLimit;//Percentage2Level(m_fLowerLimit,nNoLevel); nUpperLimit = (int)m_fUpperLimit;//Percentage2Level(m_fUpperLimit,nNoLevel); //+add kwmoon 080618 int nStartXposition=0, nEndXposition=0, nStartYposition=0, nEndYposition=0; CalcTestRange(SnapImage,nStartXposition, nEndXposition, nStartYposition, nEndYposition); for(int nRow=nStartYposition; nRow<=nEndYposition; nRow++) { for(int nColumn=nStartXposition; nColumn<=nEndXposition; nColumn++) { nRvalue = SnapImage.m_pImageData[nRow*nBytesInRow+3*nColumn+2]; nGvalue = SnapImage.m_pImageData[nRow*nBytesInRow+3*nColumn+1]; nBvalue = SnapImage.m_pImageData[nRow*nBytesInRow+3*nColumn]; //+add kwmoon 080618 if((m_nRoiWidth == 0) && (m_nRoiHeight == 0)) { //+add kwmoon 080129 if((m_nOsdWidth != 0) && (nColumn >= m_ptOsdPosition.x) && (nColumn <= (m_ptOsdPosition.x + m_nOsdWidth)) && (m_nOsdHeight != 0) && (nRow >= m_ptOsdPosition.y) && (nRow <= (m_ptOsdPosition.y + m_nOsdHeight))) { continue; } //- } nNoPixel++; nAvgRvalue += nRvalue; nAvgGvalue += nGvalue; nAvgBvalue += nBvalue; // if(nRvalue || nGvalue || nBvalue) // { // nYposition = GetOppositeStartYposition(nRow,0,nSnapHeight); // } } } nAvgRvalue = nAvgRvalue/nNoPixel; nAvgGvalue = nAvgGvalue/nNoPixel; nAvgBvalue = nAvgBvalue/nNoPixel; nMaxColorValue = GetMaxValue(nAvgRvalue,nAvgGvalue,nAvgBvalue); nMinColorValue = GetMinValue(nAvgRvalue,nAvgGvalue,nAvgBvalue); nDifference = abs(nMaxColorValue - nMinColorValue); szResultInfo.Format("R:%d,G:%d,B:%d",nAvgRvalue,nAvgGvalue,nAvgBvalue); if(nDifference > nUpperLimit) { return TEST_FAIL; } return TEST_PASS; } //+change 090218(Modification No1) BYTE g_byHisto[256*256*256]; //+add 090130 int CImageProc::NoVideoSignalTest2(CBaseImage& DstImage,int ColNumThre, int* pColNum, int nStep) { if(DstImage.m_pImageData == NULL) { AfxMessageBox("Invalid Image!"); return TEST_ABORT; } CString szErrMsg = _T(""); CString szFilePath = _T(""); int nTestResult = TEST_PASS; int nImageHeight = 0; int nImageWidth = 0; int nImageColorDepth = 0; int nBytesInRow = 0; int nRvalue = 0; int nGvalue = 0; int nBvalue = 0; int nImageDataSize = 0; int nImageBufferSize = 0; // Check image size & Color depth nImageWidth = DstImage.m_InfoHeader.biWidth; nImageHeight = DstImage.m_InfoHeader.biHeight; nImageColorDepth = DstImage.m_InfoHeader.biBitCount; nBytesInRow = WIDTHBYTES(nImageColorDepth*nImageWidth); nImageDataSize = nImageHeight * nBytesInRow; int nImageSize = 0; int i; int maxcolor = 256*256*256; int ridx, cidx, RGBVal; int nCount = 0; memset(g_byHisto,0,256*256*256); for(int nRow=0; nRow<nImageHeight; nRow+=nStep) { ridx = nRow*nBytesInRow; for(int nColumn=0; nColumn<nImageWidth; nColumn+=nStep) { cidx = ridx + 3*nColumn; nRvalue = DstImage.m_pImageData[cidx+2]; nGvalue = DstImage.m_pImageData[cidx+1]; nBvalue = DstImage.m_pImageData[cidx]; RGBVal = (nRvalue<<16)|(nGvalue<<8)|nBvalue; g_byHisto[RGBVal] = 1; /* if(Histo[RGBVal]) { nCount -= Histo[RGBVal]-1; } else { Histo[RGBVal]++; nCount++; } */ } } for(int i=0; i<(256*256*256); i++) { if(g_byHisto[i] == 1) nCount++; } *pColNum = nCount; if(nCount > ColNumThre) { return TEST_PASS; } else { return TEST_FAIL; } } //+add 101123 int CImageProc::CopyImage(CBaseImage& SrcImage, CBaseImage& DestImage) { // Dimension of the Grab Image int nGrabWidth = SrcImage.m_InfoHeader.biWidth; int nGrabHeight = SrcImage.m_InfoHeader.biHeight; int nGrabBitCount = SrcImage.m_InfoHeader.biBitCount; int nImageSize = SrcImage.m_InfoHeader.biSizeImage; /* if(DestImage.m_pImageData != NULL) { free(DestImage.m_pImageData); DestImage.m_pImageData = NULL; } DestImage.m_pImageData = (BYTE *)malloc(nImageSize); */ memset(DestImage.m_pImageData,0,nImageSize); DestImage.InitHeaders(COLOR_24BIT,nGrabWidth,nGrabHeight,nImageSize); for(int i=0; i<nImageSize; i++) { DestImage.m_pImageData[i] = SrcImage.m_pImageData[i]; } return TEST_PASS; } int CImageProc::CheckImageDiff(CBaseImage& SnapImage, CBaseImage& RefImage, int nLowerLimit, int nUpperLimit) { if((SnapImage.m_pImageData == NULL) || (RefImage.m_pImageData == NULL)) { AfxMessageBox("Invalid Image!"); return TEST_ABORT; } CString szErrMsg = _T(""); CString szFilePath = _T(""); int nTestResult = TEST_PASS; int nImageHeight = 0; int nImageWidth = 0; int nImageColorDepth = 0; int nBytesInRow = 0; int nValue = 0; int nNoNonBlackValue = 0; int nImageSize = 0; int nImageBufferSize = 0; int nMaskValue = 0; // Check image size & Color depth nImageWidth = SnapImage.m_InfoHeader.biWidth; nImageHeight = SnapImage.m_InfoHeader.biHeight; nImageColorDepth = SnapImage.m_InfoHeader.biBitCount; nBytesInRow = WIDTHBYTES(nImageColorDepth*nImageWidth); nImageSize = nImageHeight * nBytesInRow; //+change kwmoon 071112 BinaryForDiffImage(NORMAL_BINARY,SnapImage,RefImage,nLowerLimit,nUpperLimit); for(int nRow=0; nRow<nImageHeight; nRow++) { for(int nColumn=0; nColumn<nImageWidth; nColumn++) { if((m_nOsdWidth != 0) && (nColumn >= m_ptOsdPosition.x) && (nColumn <= (m_ptOsdPosition.x + m_nOsdWidth)) && (m_nOsdHeight != 0) && (nRow >= m_ptOsdPosition.y) && (nRow <= (m_ptOsdPosition.y + m_nOsdHeight))) { continue; } nValue = SnapImage.m_pProcessedImageData[nRow*nBytesInRow+3*nColumn+2]; if(nValue != 0) nNoNonBlackValue++; } } if(nNoNonBlackValue > (int)((float)(nImageWidth * nImageHeight) * m_fMovingPicTest_Limit)) { return TEST_PASS; } else { return TEST_FAIL; } } void CImageProc::SetMovingPicTestMargin(int nDiff_LoLimit, int nDiff_HiLimit, int nTest_Limit) { m_nDiff_LowerLimit = nDiff_LoLimit; m_nDiff_UpperLimit = nDiff_HiLimit; m_fMovingPicTest_Limit = (double)(nTest_Limit*0.01); } void CImageProc::InitMovingPicTestMargin() { m_nDiff_LowerLimit = -20; m_nDiff_UpperLimit = 20; m_fMovingPicTest_Limit = 0.2; }
[ "godtech@smdigital.co.kr" ]
godtech@smdigital.co.kr
b6ff77ca23563b4dc3bfa34f3a91828c4e0089a1
e247807ef839b744a63892ae4e1b0667f3bb24ec
/source/04_prj/mainwindow.h
caaa17c9c102520b3ed19868333a12841f6d0365
[]
no_license
2226171237/MLView
263201a235102b1f478e4c10cac3dcd2c636ddb5
43dd749e78cdd5ffd3cbd8a281dcc91bb6f6b845
refs/heads/master
2021-07-02T00:34:53.592102
2020-11-10T06:29:52
2020-11-10T06:29:52
186,421,736
2
1
null
null
null
null
UTF-8
C++
false
false
761
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPushButton> #include <QLabel> #include "classifier.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void setNumLabel(int num,int x,int y); QString method; QMap<QString,QString> method_map; QPushButton *run_button; QPushButton *clear_button; QLabel *num_label; QList<QPoint> test_data;//label全局左边网格 QColor color_class_bk[5]={QColor(255,106,106),QColor(127,255,0), QColor(72,118,255),QColor(238,221,130),QColor(100,0,100)}; void run_classifer(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
[ "2226171237@qq.com" ]
2226171237@qq.com
1b8fba4e176534f5457eb4b58a852d402ad9d323
6b4e2a7f51647524db22208eb98e925d1537fb6b
/all/1520. Maximum Number of Non-Overlapping Substrings.cpp
55c08c6e76e1bc3b6344186828dc2d4b5811de87
[]
no_license
denis-gubar/Leetcode
a099e0fd07600ae63456059753332f90ddd96542
ad54bee10fdf59644cc762218277a2f9de9b3509
refs/heads/master
2023-07-21T04:25:57.949932
2023-07-09T12:46:24
2023-07-09T12:46:24
218,048,440
5
0
null
null
null
null
UTF-8
C++
false
false
1,462
cpp
class Solution { public: vector<string> maxNumOfSubstrings(string s) { vector<string> result; int N = s.size(); vector<vector<int>> sum(N + 1, vector<int>(26)); vector<int> first(26, -1), last(26, -1); for (int i = 0; i < N; ++i) { for (int j = 0; j < 26; ++j) sum[i + 1][j] += sum[i][j]; int x = s[i] - 'a'; ++sum[i + 1][x]; if (first[x] < 0) first[x] = i; last[x] = i; } vector<pair<int, int>> P; for (int start = 0; start < 26; ++start) if (first[start] >= 0) for (int finish = 0; finish < 26; ++finish) if (first[finish] >= 0) { int a = first[start], b = last[finish]; if (a > b) continue; bool noIntersection = true; for (int j = 0; noIntersection && j < 26; ++j) noIntersection = sum[b + 1][j] == sum[N][j] && sum[a][j] == 0 || sum[b + 1][j] == sum[a][j]; if (noIntersection) P.emplace_back(b - a + 1, a); } sort(P.begin(), P.end()); vector<pair<int, int>> selected; for (int i = 0; i < P.size(); ++i) { bool noIntersection = true; int I = P[i].second, J = P[i].first + P[i].second - 1; for (auto sel : selected) { int K = sel.second, L = sel.first + sel.second - 1; if (!(J < K || I > L)) { noIntersection = false; break; } } if (noIntersection) selected.emplace_back(P[i]); } for (auto sel : selected) result.push_back(s.substr(sel.second, sel.first)); return result; } };
[ "Denis.Gubar@gmail.com" ]
Denis.Gubar@gmail.com
322821875ddd25e36d02b185f62e10e554886ccf
402a14c2ac6c4f9a202cd0a836539604f2c97c97
/src/models/kimaiDataSortFilterProxyModel.h
11841fd620f043a60c0c656ee733af456ae619bb
[ "MIT" ]
permissive
AlexandrePTJ/kemai
dd32150e17c4cb9ef0ac3ce23c12d4f6f6ca45a9
8f659db4f4b469f91567d72a943170bc1eab23e0
refs/heads/develop
2023-07-24T21:42:07.546470
2023-07-18T19:53:48
2023-07-18T19:53:48
243,105,520
81
23
MIT
2023-07-19T12:07:15
2020-02-25T21:23:42
C++
UTF-8
C++
false
false
631
h
#pragma once #include <vector> #include <QSortFilterProxyModel> namespace kemai { class KimaiDataSortFilterProxyModel : public QSortFilterProxyModel { public: KimaiDataSortFilterProxyModel(); ~KimaiDataSortFilterProxyModel() override; template<class K> void setKimaiFilter(const std::vector<K>& kds) { mIds.clear(); for (const auto& k : kds) { mIds.push_back(k.id); } invalidateFilter(); } protected: bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; private: std::vector<int> mIds; }; } // namespace kemai
[ "alpetitjean@gmail.com" ]
alpetitjean@gmail.com
14f8405831c84b728ebc8f29992cf8745af307e9
393140731cf4b041a64d783bd562dae97a2d47bb
/ses/src/v20201002/SesClient.cpp
d96414ec73d887013a3e20d0a4fe15f215c0a95f
[ "Apache-2.0" ]
permissive
mrjianghb/tencentcloud-sdk-cpp
06754185a462ee57bd762c12606922a89983ecdf
896da198abe6f75c0dc90901131d709143186b77
refs/heads/master
2023-08-15T08:45:23.408810
2021-10-19T02:26:52
2021-10-19T02:26:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,793
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/ses/v20201002/SesClient.h> #include <tencentcloud/core/Executor.h> #include <tencentcloud/core/Runnable.h> using namespace TencentCloud; using namespace TencentCloud::Ses::V20201002; using namespace TencentCloud::Ses::V20201002::Model; using namespace std; namespace { const string VERSION = "2020-10-02"; const string ENDPOINT = "ses.tencentcloudapi.com"; } SesClient::SesClient(const Credential &credential, const string &region) : SesClient(credential, region, ClientProfile()) { } SesClient::SesClient(const Credential &credential, const string &region, const ClientProfile &profile) : AbstractClient(ENDPOINT, VERSION, credential, region, profile) { } SesClient::CreateEmailAddressOutcome SesClient::CreateEmailAddress(const CreateEmailAddressRequest &request) { auto outcome = MakeRequest(request, "CreateEmailAddress"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateEmailAddressResponse rsp = CreateEmailAddressResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateEmailAddressOutcome(rsp); else return CreateEmailAddressOutcome(o.GetError()); } else { return CreateEmailAddressOutcome(outcome.GetError()); } } void SesClient::CreateEmailAddressAsync(const CreateEmailAddressRequest& request, const CreateEmailAddressAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateEmailAddress(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::CreateEmailAddressOutcomeCallable SesClient::CreateEmailAddressCallable(const CreateEmailAddressRequest &request) { auto task = std::make_shared<std::packaged_task<CreateEmailAddressOutcome()>>( [this, request]() { return this->CreateEmailAddress(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::CreateEmailIdentityOutcome SesClient::CreateEmailIdentity(const CreateEmailIdentityRequest &request) { auto outcome = MakeRequest(request, "CreateEmailIdentity"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateEmailIdentityResponse rsp = CreateEmailIdentityResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateEmailIdentityOutcome(rsp); else return CreateEmailIdentityOutcome(o.GetError()); } else { return CreateEmailIdentityOutcome(outcome.GetError()); } } void SesClient::CreateEmailIdentityAsync(const CreateEmailIdentityRequest& request, const CreateEmailIdentityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateEmailIdentity(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::CreateEmailIdentityOutcomeCallable SesClient::CreateEmailIdentityCallable(const CreateEmailIdentityRequest &request) { auto task = std::make_shared<std::packaged_task<CreateEmailIdentityOutcome()>>( [this, request]() { return this->CreateEmailIdentity(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::CreateEmailTemplateOutcome SesClient::CreateEmailTemplate(const CreateEmailTemplateRequest &request) { auto outcome = MakeRequest(request, "CreateEmailTemplate"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateEmailTemplateResponse rsp = CreateEmailTemplateResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateEmailTemplateOutcome(rsp); else return CreateEmailTemplateOutcome(o.GetError()); } else { return CreateEmailTemplateOutcome(outcome.GetError()); } } void SesClient::CreateEmailTemplateAsync(const CreateEmailTemplateRequest& request, const CreateEmailTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateEmailTemplate(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::CreateEmailTemplateOutcomeCallable SesClient::CreateEmailTemplateCallable(const CreateEmailTemplateRequest &request) { auto task = std::make_shared<std::packaged_task<CreateEmailTemplateOutcome()>>( [this, request]() { return this->CreateEmailTemplate(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::DeleteBlackListOutcome SesClient::DeleteBlackList(const DeleteBlackListRequest &request) { auto outcome = MakeRequest(request, "DeleteBlackList"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteBlackListResponse rsp = DeleteBlackListResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteBlackListOutcome(rsp); else return DeleteBlackListOutcome(o.GetError()); } else { return DeleteBlackListOutcome(outcome.GetError()); } } void SesClient::DeleteBlackListAsync(const DeleteBlackListRequest& request, const DeleteBlackListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteBlackList(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::DeleteBlackListOutcomeCallable SesClient::DeleteBlackListCallable(const DeleteBlackListRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteBlackListOutcome()>>( [this, request]() { return this->DeleteBlackList(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::DeleteEmailAddressOutcome SesClient::DeleteEmailAddress(const DeleteEmailAddressRequest &request) { auto outcome = MakeRequest(request, "DeleteEmailAddress"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteEmailAddressResponse rsp = DeleteEmailAddressResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteEmailAddressOutcome(rsp); else return DeleteEmailAddressOutcome(o.GetError()); } else { return DeleteEmailAddressOutcome(outcome.GetError()); } } void SesClient::DeleteEmailAddressAsync(const DeleteEmailAddressRequest& request, const DeleteEmailAddressAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteEmailAddress(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::DeleteEmailAddressOutcomeCallable SesClient::DeleteEmailAddressCallable(const DeleteEmailAddressRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteEmailAddressOutcome()>>( [this, request]() { return this->DeleteEmailAddress(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::DeleteEmailIdentityOutcome SesClient::DeleteEmailIdentity(const DeleteEmailIdentityRequest &request) { auto outcome = MakeRequest(request, "DeleteEmailIdentity"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteEmailIdentityResponse rsp = DeleteEmailIdentityResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteEmailIdentityOutcome(rsp); else return DeleteEmailIdentityOutcome(o.GetError()); } else { return DeleteEmailIdentityOutcome(outcome.GetError()); } } void SesClient::DeleteEmailIdentityAsync(const DeleteEmailIdentityRequest& request, const DeleteEmailIdentityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteEmailIdentity(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::DeleteEmailIdentityOutcomeCallable SesClient::DeleteEmailIdentityCallable(const DeleteEmailIdentityRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteEmailIdentityOutcome()>>( [this, request]() { return this->DeleteEmailIdentity(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::DeleteEmailTemplateOutcome SesClient::DeleteEmailTemplate(const DeleteEmailTemplateRequest &request) { auto outcome = MakeRequest(request, "DeleteEmailTemplate"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteEmailTemplateResponse rsp = DeleteEmailTemplateResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteEmailTemplateOutcome(rsp); else return DeleteEmailTemplateOutcome(o.GetError()); } else { return DeleteEmailTemplateOutcome(outcome.GetError()); } } void SesClient::DeleteEmailTemplateAsync(const DeleteEmailTemplateRequest& request, const DeleteEmailTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteEmailTemplate(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::DeleteEmailTemplateOutcomeCallable SesClient::DeleteEmailTemplateCallable(const DeleteEmailTemplateRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteEmailTemplateOutcome()>>( [this, request]() { return this->DeleteEmailTemplate(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::GetEmailIdentityOutcome SesClient::GetEmailIdentity(const GetEmailIdentityRequest &request) { auto outcome = MakeRequest(request, "GetEmailIdentity"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); GetEmailIdentityResponse rsp = GetEmailIdentityResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return GetEmailIdentityOutcome(rsp); else return GetEmailIdentityOutcome(o.GetError()); } else { return GetEmailIdentityOutcome(outcome.GetError()); } } void SesClient::GetEmailIdentityAsync(const GetEmailIdentityRequest& request, const GetEmailIdentityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->GetEmailIdentity(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::GetEmailIdentityOutcomeCallable SesClient::GetEmailIdentityCallable(const GetEmailIdentityRequest &request) { auto task = std::make_shared<std::packaged_task<GetEmailIdentityOutcome()>>( [this, request]() { return this->GetEmailIdentity(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::GetEmailTemplateOutcome SesClient::GetEmailTemplate(const GetEmailTemplateRequest &request) { auto outcome = MakeRequest(request, "GetEmailTemplate"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); GetEmailTemplateResponse rsp = GetEmailTemplateResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return GetEmailTemplateOutcome(rsp); else return GetEmailTemplateOutcome(o.GetError()); } else { return GetEmailTemplateOutcome(outcome.GetError()); } } void SesClient::GetEmailTemplateAsync(const GetEmailTemplateRequest& request, const GetEmailTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->GetEmailTemplate(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::GetEmailTemplateOutcomeCallable SesClient::GetEmailTemplateCallable(const GetEmailTemplateRequest &request) { auto task = std::make_shared<std::packaged_task<GetEmailTemplateOutcome()>>( [this, request]() { return this->GetEmailTemplate(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::GetSendEmailStatusOutcome SesClient::GetSendEmailStatus(const GetSendEmailStatusRequest &request) { auto outcome = MakeRequest(request, "GetSendEmailStatus"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); GetSendEmailStatusResponse rsp = GetSendEmailStatusResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return GetSendEmailStatusOutcome(rsp); else return GetSendEmailStatusOutcome(o.GetError()); } else { return GetSendEmailStatusOutcome(outcome.GetError()); } } void SesClient::GetSendEmailStatusAsync(const GetSendEmailStatusRequest& request, const GetSendEmailStatusAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->GetSendEmailStatus(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::GetSendEmailStatusOutcomeCallable SesClient::GetSendEmailStatusCallable(const GetSendEmailStatusRequest &request) { auto task = std::make_shared<std::packaged_task<GetSendEmailStatusOutcome()>>( [this, request]() { return this->GetSendEmailStatus(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::GetStatisticsReportOutcome SesClient::GetStatisticsReport(const GetStatisticsReportRequest &request) { auto outcome = MakeRequest(request, "GetStatisticsReport"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); GetStatisticsReportResponse rsp = GetStatisticsReportResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return GetStatisticsReportOutcome(rsp); else return GetStatisticsReportOutcome(o.GetError()); } else { return GetStatisticsReportOutcome(outcome.GetError()); } } void SesClient::GetStatisticsReportAsync(const GetStatisticsReportRequest& request, const GetStatisticsReportAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->GetStatisticsReport(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::GetStatisticsReportOutcomeCallable SesClient::GetStatisticsReportCallable(const GetStatisticsReportRequest &request) { auto task = std::make_shared<std::packaged_task<GetStatisticsReportOutcome()>>( [this, request]() { return this->GetStatisticsReport(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::ListBlackEmailAddressOutcome SesClient::ListBlackEmailAddress(const ListBlackEmailAddressRequest &request) { auto outcome = MakeRequest(request, "ListBlackEmailAddress"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ListBlackEmailAddressResponse rsp = ListBlackEmailAddressResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ListBlackEmailAddressOutcome(rsp); else return ListBlackEmailAddressOutcome(o.GetError()); } else { return ListBlackEmailAddressOutcome(outcome.GetError()); } } void SesClient::ListBlackEmailAddressAsync(const ListBlackEmailAddressRequest& request, const ListBlackEmailAddressAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ListBlackEmailAddress(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::ListBlackEmailAddressOutcomeCallable SesClient::ListBlackEmailAddressCallable(const ListBlackEmailAddressRequest &request) { auto task = std::make_shared<std::packaged_task<ListBlackEmailAddressOutcome()>>( [this, request]() { return this->ListBlackEmailAddress(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::ListEmailAddressOutcome SesClient::ListEmailAddress(const ListEmailAddressRequest &request) { auto outcome = MakeRequest(request, "ListEmailAddress"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ListEmailAddressResponse rsp = ListEmailAddressResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ListEmailAddressOutcome(rsp); else return ListEmailAddressOutcome(o.GetError()); } else { return ListEmailAddressOutcome(outcome.GetError()); } } void SesClient::ListEmailAddressAsync(const ListEmailAddressRequest& request, const ListEmailAddressAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ListEmailAddress(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::ListEmailAddressOutcomeCallable SesClient::ListEmailAddressCallable(const ListEmailAddressRequest &request) { auto task = std::make_shared<std::packaged_task<ListEmailAddressOutcome()>>( [this, request]() { return this->ListEmailAddress(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::ListEmailIdentitiesOutcome SesClient::ListEmailIdentities(const ListEmailIdentitiesRequest &request) { auto outcome = MakeRequest(request, "ListEmailIdentities"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ListEmailIdentitiesResponse rsp = ListEmailIdentitiesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ListEmailIdentitiesOutcome(rsp); else return ListEmailIdentitiesOutcome(o.GetError()); } else { return ListEmailIdentitiesOutcome(outcome.GetError()); } } void SesClient::ListEmailIdentitiesAsync(const ListEmailIdentitiesRequest& request, const ListEmailIdentitiesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ListEmailIdentities(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::ListEmailIdentitiesOutcomeCallable SesClient::ListEmailIdentitiesCallable(const ListEmailIdentitiesRequest &request) { auto task = std::make_shared<std::packaged_task<ListEmailIdentitiesOutcome()>>( [this, request]() { return this->ListEmailIdentities(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::ListEmailTemplatesOutcome SesClient::ListEmailTemplates(const ListEmailTemplatesRequest &request) { auto outcome = MakeRequest(request, "ListEmailTemplates"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); ListEmailTemplatesResponse rsp = ListEmailTemplatesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return ListEmailTemplatesOutcome(rsp); else return ListEmailTemplatesOutcome(o.GetError()); } else { return ListEmailTemplatesOutcome(outcome.GetError()); } } void SesClient::ListEmailTemplatesAsync(const ListEmailTemplatesRequest& request, const ListEmailTemplatesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->ListEmailTemplates(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::ListEmailTemplatesOutcomeCallable SesClient::ListEmailTemplatesCallable(const ListEmailTemplatesRequest &request) { auto task = std::make_shared<std::packaged_task<ListEmailTemplatesOutcome()>>( [this, request]() { return this->ListEmailTemplates(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::SendEmailOutcome SesClient::SendEmail(const SendEmailRequest &request) { auto outcome = MakeRequest(request, "SendEmail"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); SendEmailResponse rsp = SendEmailResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return SendEmailOutcome(rsp); else return SendEmailOutcome(o.GetError()); } else { return SendEmailOutcome(outcome.GetError()); } } void SesClient::SendEmailAsync(const SendEmailRequest& request, const SendEmailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->SendEmail(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::SendEmailOutcomeCallable SesClient::SendEmailCallable(const SendEmailRequest &request) { auto task = std::make_shared<std::packaged_task<SendEmailOutcome()>>( [this, request]() { return this->SendEmail(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::UpdateEmailIdentityOutcome SesClient::UpdateEmailIdentity(const UpdateEmailIdentityRequest &request) { auto outcome = MakeRequest(request, "UpdateEmailIdentity"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateEmailIdentityResponse rsp = UpdateEmailIdentityResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateEmailIdentityOutcome(rsp); else return UpdateEmailIdentityOutcome(o.GetError()); } else { return UpdateEmailIdentityOutcome(outcome.GetError()); } } void SesClient::UpdateEmailIdentityAsync(const UpdateEmailIdentityRequest& request, const UpdateEmailIdentityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateEmailIdentity(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::UpdateEmailIdentityOutcomeCallable SesClient::UpdateEmailIdentityCallable(const UpdateEmailIdentityRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateEmailIdentityOutcome()>>( [this, request]() { return this->UpdateEmailIdentity(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } SesClient::UpdateEmailTemplateOutcome SesClient::UpdateEmailTemplate(const UpdateEmailTemplateRequest &request) { auto outcome = MakeRequest(request, "UpdateEmailTemplate"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateEmailTemplateResponse rsp = UpdateEmailTemplateResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateEmailTemplateOutcome(rsp); else return UpdateEmailTemplateOutcome(o.GetError()); } else { return UpdateEmailTemplateOutcome(outcome.GetError()); } } void SesClient::UpdateEmailTemplateAsync(const UpdateEmailTemplateRequest& request, const UpdateEmailTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateEmailTemplate(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } SesClient::UpdateEmailTemplateOutcomeCallable SesClient::UpdateEmailTemplateCallable(const UpdateEmailTemplateRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateEmailTemplateOutcome()>>( [this, request]() { return this->UpdateEmailTemplate(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); }
[ "tencentcloudapi@tenent.com" ]
tencentcloudapi@tenent.com
0cb59a3f97d2515e379fd8907478fef39912c6e3
b1e1428e311a505eef3cbe2c632c242ca7856d2c
/nico/uva/195.cpp
eef061754289c4e7a83e7a5800a5bec0c3eb4ad7
[]
no_license
RodrigoDePool/algorithms
5c3576bd1080f13a7e604d49cbdc12871da0d11f
337cc47915e104db47717f860c72822c6820efdb
refs/heads/master
2020-04-09T07:39:00.976685
2019-11-12T00:10:01
2019-11-12T00:10:01
160,164,525
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
/* AC */ #include <iostream> #include <algorithm> #include <string> using namespace std; string word; int t; bool comparator(char a, char b){ if(tolower(a) == tolower(b)) return a < b; return tolower(a) < tolower(b); } int main(){ cin >> t; while(t--){ cin >> word; sort(word.begin(), word.end(), comparator); do{ cout << word << endl; }while(next_permutation(word.begin(), word.end(), comparator)); } return 0; }
[ "nicolas.wolyniec@estudiante.uam.es" ]
nicolas.wolyniec@estudiante.uam.es
5a3bea16028a259ff83d6b60ee22508bd291cf7e
168b9963c510b84f1978e6a7602202aebd5adb5e
/streaming-pointcloud/merger/merger/pointcloudmerger.h
fdebaf82cd2cc7ba9edf08bde25dcd4264de2938
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
PieMyth/Azure-Kinect-Samples
e226b94912a9c932b6bdaa5d0be77b5e38e41d00
c7949aee5dea0231f4cb8ea212a6f2fe40373d6b
refs/heads/master
2022-12-13T01:01:04.652633
2020-09-08T18:07:54
2020-09-08T18:07:54
288,911,663
0
0
MIT
2020-08-20T05:08:02
2020-08-20T05:08:02
null
UTF-8
C++
false
false
1,044
h
#pragma once #include <unordered_map> #include "concurrent_queue.h" #include "messageBuffer.h" class pointCloudMerger { public: //Functions pointCloudMerger(); pointCloudMerger(uint32_t buffSize); ~pointCloudMerger(); bool setBufferSize(uint32_t buffSize); bool createNewIndex(std::string indexName); bool addMessage(std::string indexName, messageBuffer* &msg); bool readMessage(std::string indexName, messageBuffer*& msg); bool eraseList(); bool eraseIndex(std::string& indexName); bool merge(); bool setRestart(bool toSet); bool isRestart(); bool setDone(bool toSet); bool isDone(); bool giveIndexNames(std::string &indexNames); private: //Functions bool errorCantFindEntry(std::string indexName); bool merge(std::vector<messageBuffer*>& frames); private: //Variables std::unordered_map<std::string, concurrency::concurrent_queue<messageBuffer*>*> buffer; uint32_t framePointCount; uint64_t frameBufferSize; uint64_t frameTimestamp; bool frameColor; uint32_t bufferSize; bool done; bool restart; bool syncMode; };
[ "thomas@thomaswester.com" ]
thomas@thomaswester.com
4f13f79fd5302db0da49a731e2afd34f521c3509
b88011c60f897076cbe1256ed92a06d571e575eb
/src/desktop/include/InitTasks.h
f3c3a9eff1dbe42198ef0dd7155aa1cde8df1af4
[ "MIT" ]
permissive
umer936/QDriverStation
6431055c5d5089b2ec79ede32153b88945278f86
bc660294b1a699a126b4602104b0c7ea88a27748
refs/heads/master
2020-12-25T00:03:44.292143
2015-09-13T23:14:43
2015-09-13T23:14:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,138
h
/* * Copyright (c) 2015 WinT 3794 <http://wint3794.org> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef _QDS_INIT_TASKS_H #define _QDS_INIT_TASKS_H /** * @class InitTasks * @brief Isolates complex first run tasks from the MainWindow * * The purpose of this class is to isolate the tasks that the application must * perform during initalization and - specifically - during the first run, * such as asking the user for his/her team number of downloading additional * drivers required by the Open DriverStation. */ class InitTasks { public: /** * Returns the team number to be used to control the robot. * If this is the first launch, it will ask the user to input his/her team * number using a \c QInputDialog */ static int getTeamNumber(); /** * Initializes the CPU querying process and prompts the user to download * additional software required for the correct functionality of the * Open DriverStation */ static void executeFirstRunTasks(); }; #endif /* _QDS_INIT_TASKS_H */
[ "alex.racotta@gmail.com" ]
alex.racotta@gmail.com
c29d648161eac4d59cf0b87b5ca77f5aa4d5e24f
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-opensearch/include/aws/opensearch/model/DescribeDomainConfigRequest.h
5c72e46b5bc9ea7accd75c35286da5f070be5690
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
3,003
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/opensearch/OpenSearchService_EXPORTS.h> #include <aws/opensearch/OpenSearchServiceRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace OpenSearchService { namespace Model { /** * <p>Container for the parameters to the <code>DescribeDomainConfig</code> * operation. Specifies the domain name for which you want configuration * information. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/opensearch-2021-01-01/DescribeDomainConfigRequest">AWS * API Reference</a></p> */ class AWS_OPENSEARCHSERVICE_API DescribeDomainConfigRequest : public OpenSearchServiceRequest { public: DescribeDomainConfigRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DescribeDomainConfig"; } Aws::String SerializePayload() const override; /** * <p>The domain you want to get information about.</p> */ inline const Aws::String& GetDomainName() const{ return m_domainName; } /** * <p>The domain you want to get information about.</p> */ inline bool DomainNameHasBeenSet() const { return m_domainNameHasBeenSet; } /** * <p>The domain you want to get information about.</p> */ inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; } /** * <p>The domain you want to get information about.</p> */ inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = std::move(value); } /** * <p>The domain you want to get information about.</p> */ inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); } /** * <p>The domain you want to get information about.</p> */ inline DescribeDomainConfigRequest& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;} /** * <p>The domain you want to get information about.</p> */ inline DescribeDomainConfigRequest& WithDomainName(Aws::String&& value) { SetDomainName(std::move(value)); return *this;} /** * <p>The domain you want to get information about.</p> */ inline DescribeDomainConfigRequest& WithDomainName(const char* value) { SetDomainName(value); return *this;} private: Aws::String m_domainName; bool m_domainNameHasBeenSet; }; } // namespace Model } // namespace OpenSearchService } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
80e58299a04703aee4130377dfc5c00e30e230eb
87129c5c2613cade4b027d67cd7d68c9f2b26bc7
/Design pattern/accumulate.cpp
3a01d2754f7a3bb61967e7586824d47ae002117f
[]
no_license
841194253/Design-pattern
0b8b89345a6faaf4cc57570aaec59c24dc6cb736
b8154805eac0b2f66ae4a79710406d27cb94483e
refs/heads/main
2023-07-02T21:58:24.343737
2021-08-11T11:46:13
2021-08-11T11:46:13
394,938,382
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
// // Created by apple on 7/31/21. // #include <iostream> #include <numeric> #include <vector> #include <algorithm> struct MyPrint{ void operator() (int a) { std::cout << a << " "; } }; int main() { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); int a = std::accumulate(v.begin(),v.end(),0);//求和 std::cout << a << std::endl; std::vector<int> v2; v2.resize(10); std::fill(v2.begin(),v2.end(),10);//填充 std::for_each(v2.begin(),v2.end(),MyPrint()); }
[ "48153306+841194253@users.noreply.github.com" ]
48153306+841194253@users.noreply.github.com
0fede594ebf8d5487ca0bf633ccd460338cd9315
82a0ee95b3fe0cd58a3a25efff82d7f0e3527b09
/server.cpp
e2d872c21ffdcf4cda9b1311ff9c929240ea8559
[]
no_license
alexvasiliev/http_server
bfb75bd51b4c555afe9f271be61e6f85c4da2e2c
95d45b75262b61a8b182f551ec2e61f2bc2f7758
refs/heads/master
2020-09-22T15:01:55.438752
2014-10-03T10:07:49
2014-10-03T10:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,136
cpp
#include "server.h" #include <qdebug.h> #include <QString> bool char_isspace(char c) { return std::isspace(static_cast<unsigned char>(c)); } ERequestType getRequestMethod(string sRequest) { size_t endMethod = sRequest.find(" "); std::string sMethod = sRequest.substr(0, endMethod); ERequestType requestType; if(sMethod == "GET") requestType = eGET; else if (sMethod == "POST") requestType = ePOST; else if (sMethod == "HEAD") requestType = eHEAD; return requestType; } string getDecodedPath(string sRequest) { //qDebug()<<QString::fromStdString(sRequest) << "sRequest"; size_t startURI = sRequest.find(" ") + 1; size_t endURI = sRequest.find("HTTP") - 5; std::string sPath = sRequest.substr(startURI, endURI); size_t paramString = sPath.find("?"); sPath = sPath.substr(0, paramString); string res = urlDecode(sPath); //qDebug()<<QString::fromStdString(res) << "res"; return res; } EContentType getContentType(string sPath) { unsigned found = sPath.find_last_of("/\\"); string sFile = sPath.substr(found+1); unsigned extensionPos = sFile.find_last_of(".") + 1; string sExtension = sFile.substr(extensionPos); EContentType eContentType = eUnknown; if(sExtension == "html") eContentType = eHTML; else if(sExtension == "png") eContentType = ePNG; else if(sExtension == "jpg") eContentType = eJPG; else if(sExtension == "jpeg") eContentType = eJPEG; else if(sExtension == "css") eContentType = eCSS; else if(sExtension == "js") eContentType = eJS; else if(sExtension == "gif") eContentType = eGIF; else if(sExtension == "swf") eContentType = eSWF; return eContentType; } bool isPathDirectory(string sPath) { return true; } void writeHeader(HttpHeader *pHttpHeader, evbuffer *pOutput) { string sResponse; if(pHttpHeader->eResponseType == eOK) { sResponse.append("HTTP/1.1 200 OK\r\n"); //Parse time char timeStr[22]; time_t now = time(NULL); strftime(timeStr, 22, "%Y-%m-%d %H:%M:%S", localtime(&now)); string sDate = "Date: " + string(timeStr) + "\r\n"; sResponse.append(sDate); sResponse.append("Server: badServer\r\n"); //Parse content type string sContent; if(pHttpHeader->eContentType == eJPG){ sContent = "image/jpeg"; } else if(pHttpHeader->eContentType == ePNG){ sContent = "image/png"; } else if(pHttpHeader->eContentType == eJPEG){ sContent = "image/jpeg"; } else if(pHttpHeader->eContentType == eCSS){ sContent = "text/css"; } else if(pHttpHeader->eContentType == eJS){ sContent = "application/x-javascript"; } else if(pHttpHeader->eContentType == eGIF){ sContent = "image/gif"; } else if(pHttpHeader->eContentType == eSWF){ sContent = "application/x-shockwave-flash"; } else{//(pHttpHeader->eContentType == eHTML){ sContent = "text/html"; } sResponse.append("Content-Type: " + sContent + "\r\n"); sResponse.append("Content-Length: " + convertInt(pHttpHeader->nContentLength) + "\r\n"); sResponse.append("Connection: close\r\n\r\n"); } else if(pHttpHeader->eResponseType == eNotFound) { sResponse.append("HTTP/1.1 404 Not Found\r\n\r\n"); sResponse.append("404 Not Found"); } else if(pHttpHeader->eResponseType == eBadRequest) { sResponse.append("HTTP/1.1 405 Bad Request\r\n\r\n"); sResponse.append("405 Bad Request"); } else if(pHttpHeader->eResponseType == eForbiden) { sResponse.append("HTTP/1.1 403 Forbidden\r\n\r\n"); sResponse.append("403 Forbidden"); } evbuffer_add_printf(pOutput, sResponse.c_str()); } void sendDocument(struct bufferevent *pBufferEvent) { struct evbuffer* pInput = bufferevent_get_input(pBufferEvent); struct evbuffer* pOutput = bufferevent_get_output(pBufferEvent); string sRequest = string((char*)evbuffer_pullup(pInput, -1)); /*printf("Received %zu bytes\n", evbuffer_get_length(pInput)); printf("----- data ----\n"); printf("%.*s\n", (int)evbuffer_get_length(pInput), sRequest.c_str());*/ ERequestType eRequestType = getRequestMethod(sRequest); string sPath = getDecodedPath(sRequest); bool bIsPathOk = isPathCorrect(sPath); HttpHeader* pHttpHeader = new HttpHeader(); //Load home page char c = *sPath.rbegin(); if(c == '/'){ sPath = sPath.append("index.html"); } //Open file on disk int fd = -1; struct stat st; string sWholePath = SERVER_PATH + sPath; if (eRequestType == eHEAD) { sWholePath.erase(remove_if(sWholePath.begin(), sWholePath.end(), char_isspace),sWholePath.end()); fd = open(sWholePath.c_str(), O_RDONLY); //qDebug()<<QString::fromStdString(sWholePath.c_str()) << "HEAD"; if (fstat(fd, &st)<0) { perror("fstat"); } else { pHttpHeader->eResponseType = eOK; pHttpHeader->nContentLength = st.st_size; pHttpHeader->eContentType = getContentType(sPath); } } //else //qDebug()<<QString::fromStdString(sWholePath.c_str()); else if(eRequestType != eGET)//(eRequestType != eGET && eRequestType != eHEAD) { pHttpHeader->eResponseType = eBadRequest; } else if(!bIsPathOk) { pHttpHeader->eResponseType = eForbiden; } else if((fd = open(sWholePath.c_str(), O_RDONLY)) < 0) { if(c != '/') pHttpHeader->eResponseType = eNotFound; else pHttpHeader->eResponseType = eForbiden; } else { if (fstat(fd, &st)<0) { /* Make sure the length still matches, now that we * opened the file :/ */ perror("fstat"); } pHttpHeader->eResponseType = eOK; pHttpHeader->nContentLength = st.st_size; pHttpHeader->eContentType = getContentType(sPath); } //Write http header writeHeader(pHttpHeader, pOutput); //Write static file to output //if(fd != -1) if(eRequestType == eGET) evbuffer_add_file(pOutput, fd, 0, st.st_size); //else if(eRequestType == eHEAD) //evbuffer_add_printf(pOutput, "\r\n\r\n");//evbuffer_add(pOutput, CRLF, 2); delete pHttpHeader; } string convertInt(int number) { if (number == 0) return "0"; string temp=""; string returnvalue=""; while (number>0) { temp+=number%10+48; number/=10; } for (int i=0;i<temp.length();i++) returnvalue+=temp[temp.length()-i-1]; return returnvalue; } string urlDecode(string &SRC) { string ret; char ch; int i, ii; for (i=0; i<SRC.length(); i++) { if (int(SRC[i])==37) { sscanf(SRC.substr(i+1,2).c_str(), "%x", &ii); ch=static_cast<char>(ii); ret+=ch; i=i+2; } else { ret+=SRC[i]; } } return (ret); } bool isPathCorrect(string sPath) { std::vector<std::string> dirVector = split(sPath, '/'); int upCount = 0; int downCount = 0; for(std::vector<std::string>::iterator it = dirVector.begin(); it != dirVector.end(); ++it) { string sDir = it.operator *(); if(sDir == "..") ++downCount; else if (!sDir.empty()) ++upCount; } return upCount >= downCount ? true : false; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); }
[ "alexvasiliev92@gmailcom" ]
alexvasiliev92@gmailcom
d7f3e5f70398530ece78f81aa02ff2de7442fdb8
e927f667f2784f5bcd3b42398a76f9aea77c1595
/new_keylogger/main.cpp
780f3a69b73ecd1ddb2cfa3d4e94b61049a2409b
[]
no_license
avlad171/Info
6fda6690c8d0f6eda10ea49198d4d6e942f61891
af4aef016aef2349556d07c3aa6330e0ea307255
refs/heads/master
2022-02-24T12:28:18.523896
2022-02-04T23:22:40
2022-02-04T23:22:40
159,320,658
2
2
null
null
null
null
UTF-8
C++
false
false
5,273
cpp
#include <iostream> #include <fstream> #include <windows.h> #include <string.h> using namespace std; //asta e in mare parte cod generic de keylogger de pe net, putin modificat ca sa va puteti juca cu inputurile KBDLLHOOKSTRUCT kb; HHOOK hKeyHook; HANDLE hOut; int shift = 0, caps = 0; char buf[16]; char * translate(int vk, int up) { if (up) { if ((vk == 0x10) || (vk == 0xa0) || (vk == 0xa1)) shift = 0; return 0; } else if ((vk == 0x10) || (vk == 0xa0) || (vk == 0xa1)) { shift = 1; return 0; //nu e necesar sa mentionam apasarea shiftului } memset(buf, 0, 16); if (vk < 0x29) { switch (vk) { case 0x08: strcpy(buf, "[BS]"); break; case 0x09: strcpy(buf, "[TAB]"); break; case 0x0d: strcpy(buf, "[CR]"); break; case 0x14: caps ^= 1; break; case 0x20: buf[0] = ' '; break; case 0x25: strcpy(buf, "[LT]"); break; case 0x26: strcpy(buf, "[UP]"); break; case 0x27: strcpy(buf, "[RT]"); break; case 0x28: strcpy(buf, "[DN]"); break; } return buf; } if (vk > 0x69 && vk < 0x70) buf[0] = (char)(vk - 0x40); else if (vk > 0x6f && vk < 0x88) sprintf(buf, "[F%d]", vk - 0x6f); //tastele functionale: F1, F2,... else if (isalpha(vk)) { if (!caps) { if (shift) buf[0] = (char)(toupper(vk)); else buf[0] = (char)(tolower(vk)); } else { if (!shift) buf[0] = (char)(toupper(vk)); else buf[0] = (char)(tolower(vk)); } } else { switch (vk) { case '1': if (!shift) buf[0]=(char)vk; else buf[0]='!'; break; case '2': if (!shift) buf[0]=(char)vk; else buf[0]='@'; break; case '3': if (!shift) buf[0]=(char)vk; else buf[0]='#'; break; case '4': if (!shift) buf[0]=(char)vk; else buf[0]='$'; break; case '5': if (!shift) buf[0]=(char)vk; else buf[0]='%'; break; case '6': if (!shift) buf[0]=(char)vk; else buf[0]='^'; break; case '7': if (!shift) buf[0]=(char)vk; else buf[0]='&'; break; case '8': if (!shift) buf[0]=(char)vk; else buf[0]='*'; break; case '9': if (!shift) buf[0]=(char)vk; else buf[0]='('; break; case '0': if (!shift) buf[0]=(char)vk; else buf[0]=')'; break; case 0xba: if (!shift) buf[0]=';'; else buf[0]=':'; break; case 0xbb: if (!shift) buf[0]='='; else buf[0]='+'; break; case 0xbc: if (!shift) buf[0]=','; else buf[0]='<'; break; case 0xbd: if (!shift) buf[0]='-'; else buf[0]='_'; break; case 0xbe: if (!shift) buf[0]='.'; else buf[0]='>'; break; case 0xbf: if (!shift) buf[0]='/'; else buf[0]='?'; break; case 0xc0: if (!shift) buf[0]='`'; else buf[0]='~'; break; case 0xdb: if (!shift) buf[0]='['; else buf[0]='{'; break; case 0xdc: if (!shift) buf[0]='\\'; else buf[0]='|'; break; case 0xdd: if (!shift) buf[0]=']'; else buf[0]='}'; break; case 0xde: if (!shift) buf[0]='\''; else buf[0]='\"'; break; } } return buf; } LRESULT WINAPI KeyEvent(int nCode, WPARAM wParam, LPARAM lParam) { kb = *((KBDLLHOOKSTRUCT*)lParam); char * str = NULL; if(nCode == HC_ACTION) { if (wParam == WM_KEYUP) //daca nu va plac culorile, deschideti un cmd, scrieti "color -h" si alegeti de acolo { SetConsoleTextAttribute(hOut, 0x0f); cout<<'['; SetConsoleTextAttribute(hOut, 0x04); cout<<"KEY RELEASE"; SetConsoleTextAttribute(hOut, 0x0f); cout<<']'; SetConsoleTextAttribute(hOut, 0x0c); cout<<" User released key with scan code: "<<kb.scanCode<<" and key code: "<<kb.vkCode<<"\n"; str = translate(kb.vkCode, 1); } else if (wParam == WM_KEYDOWN) { SetConsoleTextAttribute(hOut, 0x0f); cout<<'['; SetConsoleTextAttribute(hOut, 0x02); cout<<"KEY RELEASE"; SetConsoleTextAttribute(hOut, 0x0f); cout<<']'; SetConsoleTextAttribute(hOut, 0x0a); cout<<"User pressed key with scan code: "<<kb.scanCode<<" and key code: "<<kb.vkCode<<"\n"; str = translate(kb.vkCode, 0); } } if(str) { ofstream out ("log.txt", ios::app); out<<str; out.close(); } return CallNextHookEx(hKeyHook, nCode, wParam, lParam); } int main() { hOut = GetStdHandle(STD_OUTPUT_HANDLE); hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)KeyEvent, GetModuleHandle(NULL), 0); MSG message; while(GetMessage(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } UnhookWindowsHookEx(hKeyHook); return 0; }
[ "blacklordakium@gmail.com" ]
blacklordakium@gmail.com
6d1c9c8abba011f9afd37908fe63ceef3bc424fb
2f51a587b0c97050dc995c59cb8653aae7aeb3df
/PolynomialsLib/PolynomialsLib.cpp
1f8fcf45ad2957cc0ff895f0da2b5f330cb170d8
[]
no_license
chrisfowlkes/Polynomials
40cdb2636c1f3d6d2b620b5258c22ee997a62dff
1162f4ea44354869846b3471fa862213ea762167
refs/heads/master
2021-07-13T01:45:17.278439
2020-06-29T00:21:57
2020-06-29T00:21:57
174,723,893
0
0
null
null
null
null
UTF-8
C++
false
false
5,365
cpp
// PolynomialsLib.cpp : Defines the functions for the static library. // #include "pch.h" #include "framework.h" #include "PolynomialsLib.h" #include <ostream> using namespace std; // TODO: This is an example of a library function void fnPolynomialsLib() { } /* Constructor. Takes the coefficients of the polynomial. The coefficients should be at the index of their variables exponent. For example, 4x^3 + 2x^2 - 7 would be passed in as Polynomial(int[4]{7, 0, 2, 4}). */ Polynomial::Polynomial(vector<double> coefficients) { this->coefficients = coefficients; while (this->coefficients.size() > 0 && this->coefficients[this->coefficients.size()-1] == 0) { this->coefficients.pop_back(); } } /* Gets the degree of the polynomial, or the highest eponent of the polynomial. */ int Polynomial::GetDegree() const { int degree = coefficients.size() - 1; if (degree < 0) { degree = 0; } return degree; } /* Gets the coefficient of the monomial for the given degree. */ double Polynomial::GetCoefficient(int degree) const { return coefficients[degree]; } /* Overloads the + operator to allow two polynomials to be added. */ Polynomial Polynomial::operator+(Polynomial const& p) { int sumDegree; if (p.GetDegree() > GetDegree()) { sumDegree = p.GetDegree(); } else { sumDegree = GetDegree(); } vector<double> sumCoefficients(sumDegree + 1, 0); for (int i = 0;i <= sumDegree;i++) { if (GetDegree() >= i) { sumCoefficients[i] += coefficients[i]; } if (p.GetDegree() >= i) { sumCoefficients[i] += p.coefficients[i]; } } return Polynomial(sumCoefficients); } /* Overloads the - operator to allow two polynomials to be subtracted. */ Polynomial Polynomial::operator-(Polynomial const& p) { int differenceDegree; if (p.GetDegree() > GetDegree()) { differenceDegree = p.GetDegree(); } else { differenceDegree = GetDegree(); } vector<double> differenceCoefficients(differenceDegree + 1, 0); for (int i = 0;i <= differenceDegree;i++) { if (GetDegree() >= i) { differenceCoefficients[i] += coefficients[i]; } if (p.GetDegree() >= i) { differenceCoefficients[i] -= p.coefficients[i]; } } return Polynomial(differenceCoefficients); } /* Overloads the * operator to allow two polynomials to be multiplied. */ Polynomial Polynomial::operator*(Polynomial const& p) { int productDegree = GetDegree() + p.GetDegree(); vector<double> productCoefficients(productDegree + 1, 0); for (int i = GetDegree();i >= 0;i--) { for (int j = p.GetDegree();j >= 0;j--) { productCoefficients[i + j] += GetCoefficient(i) * p.GetCoefficient(j); } } return Polynomial(productCoefficients); } /* Overloads the / operator to allow two polynomials to be divided. */ Polynomial Polynomial::operator/(Polynomial const& p) { int quotientDegree = GetDegree() - p.GetDegree(); vector<double> quotientCoefficients(quotientDegree + 1, 0); Polynomial remainder = *this; while (remainder.GetDegree() >= p.GetDegree()) { int i = remainder.GetDegree() - p.GetDegree(); vector<double> quotientPartCoefficient = vector<double>(i + 1, 0); quotientPartCoefficient[i] += remainder.GetCoefficient(remainder.GetDegree()) / p.GetCoefficient(p.GetDegree()); quotientCoefficients[i] += quotientPartCoefficient[i]; Polynomial product = Polynomial(quotientPartCoefficient) * p; remainder = remainder - product; } return Polynomial(quotientCoefficients); } /* Overloads the << operator to write the polynomial to an output stream. */ ostream& operator<<(ostream& out, const Polynomial& p) { bool secondary = false; for (int i = p.GetDegree();i >= 0;i--) { int coefficient = p.GetCoefficient(i); if (coefficient != 0) { if (secondary) { out << " + "; } else { secondary = true; } out << coefficient; if (i > 0) { out << "x"; if (i > 1) { out << "^" << i; } } } } return out; } /* Constructor. */ ComplexNumber::ComplexNumber(double a, double b) { this->a = a; this->b = b; } /* Gets the a portion of the number in the format ai + b. */ double ComplexNumber::GetA() const { return a; } /* Gets the b portion of the number in the format ai + b. */ double ComplexNumber::GetB() const { return b; } /* Gets the conjugate of the complex number. */ ComplexNumber ComplexNumber::GetConjugate() const { return ComplexNumber(a * -1, b); } /* Overloads the * operator to allow two complex numbers to be multiplied. */ ComplexNumber ComplexNumber::operator*(ComplexNumber const& n) { Polynomial polynomialA(vector<double> { b, a }); Polynomial polynomialB(vector<double> { n.GetB(), n.GetA() }); Polynomial product = polynomialA * polynomialB; return ComplexNumber(product.GetCoefficient(1), (product.GetCoefficient(2) * -1) + product.GetCoefficient(0)); } /* Overloads the / operator to allow two complex numbers to be divided. */ ComplexNumber ComplexNumber::operator/(ComplexNumber const& n) { ComplexNumber conjugate = n.GetConjugate(); ComplexNumber numerator = *this * conjugate; double denominator = (conjugate * n).GetB(); return ComplexNumber(numerator.GetA() / denominator, numerator.GetB() / denominator); } /* Overloads the << operator to write the complex number to an output stream. */ ostream& operator<<(ostream& out, const ComplexNumber& n) { out << n.GetA() << "i + " << n.GetB(); return out; }
[ "chrisfowlkes@gmail.com" ]
chrisfowlkes@gmail.com
d43db152895574c147cf44274e196228c444cf87
24b8109f0b04240c675d864490b94c3f96d9b63f
/Source/RPGGame/Public/UI/UIInventory.h
a3749fa6091950f968c0516ca3673f14a0367252
[]
no_license
leerang92/RPGGame
ffee35cc19362bd1719eea203c091366174d2c0c
1e9fc49085d368c0eefa5a9b11e43c287238861e
refs/heads/master
2021-08-28T14:54:04.269190
2017-12-12T13:37:14
2017-12-12T13:37:14
112,612,761
1
0
null
null
null
null
UHC
C++
false
false
758
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "UIInventorySlot.h" #include "UI/UIBaseWindow.h" #include "UIInventory.generated.h" /** * */ UCLASS() class RPGGAME_API UUIInventory : public UUIBaseWindow { GENERATED_BODY() public: virtual void NativeConstruct() override; // 아이템 리스트 생성 void CreateItemList(); // 아이템 추가 void AddItem(FItemInfo NewItem); // 전체 아이템 리스트 크기 UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Slot) int ListSize; // 이미 있는 아이템 여부 검사 bool IsPresentItem(FItemInfo& NewItem); private: // 슬롯을 저장할 배열 TArray<class UUIInventorySlot*> SlotArr; };
[ "asw77id@gmail.com" ]
asw77id@gmail.com
128b845cfbfcf8d034843bb29801cb2d5c6687e0
98b63e3dc79c75048163512c3d1b71d4b6987493
/tensorflow/core/lib/monitoring/mobile_percentile_sampler.h
2c792f0e0cb9c55af883e70d7323c1515f163917
[ "Apache-2.0" ]
permissive
galeone/tensorflow
11a4e4a3f42f4f61a65b432c429ace00401c9cc4
1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206
refs/heads/master
2022-11-13T11:56:56.143276
2020-11-10T14:35:01
2020-11-10T14:35:01
310,642,488
21
12
Apache-2.0
2020-11-06T16:01:03
2020-11-06T16:01:02
null
UTF-8
C++
false
false
2,269
h
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_LIB_MONITORING_MOBILE_PERCENTILE_SAMPLER_H_ #define TENSORFLOW_CORE_LIB_MONITORING_MOBILE_PERCENTILE_SAMPLER_H_ #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/monitoring/collection_registry.h" #include "tensorflow/core/lib/monitoring/metric_def.h" #include "tensorflow/core/lib/monitoring/types.h" #include "tensorflow/core/platform/macros.h" namespace tensorflow { namespace monitoring { class PercentileSamplerCell { public: void Add(double sample) {} Percentiles value() const { return Percentiles(); } }; template <int NumLabels> class PercentileSampler { public: static PercentileSampler* New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& metric_def, std::vector<double> percentiles, size_t max_samples, UnitOfMeasure unit_of_measure); template <typename... Labels> PercentileSamplerCell* GetCell(const Labels&... labels) { return &default_cell_; } Status GetStatus() { return Status::OK(); } private: PercentileSamplerCell default_cell_; TF_DISALLOW_COPY_AND_ASSIGN(PercentileSampler); }; template <int NumLabels> PercentileSampler<NumLabels>* PercentileSampler<NumLabels>::New( const MetricDef<MetricKind::kCumulative, Percentiles, NumLabels>& /* metric_def */, std::vector<double> /* percentiles */, size_t /* max_samples */, UnitOfMeasure /* unit_of_measure */) { return new PercentileSampler<NumLabels>(); } } // namespace monitoring } // namespace tensorflow #endif // TENSORFLOW_CORE_LIB_MONITORING_MOBILE_PERCENTILE_SAMPLER_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
8acf9a7d4a6af8a7827b0b56595331f80821dea8
7819775fcda1a3f2ac79e0373a4247a1a4b3b4cf
/src/cicada/util/logging/logger.cpp
b4167769070a80613c18622d895daa1b1c950807
[]
no_license
AhramanOld/cicada_engine
aa3a743faea8f95692d1d4303a1a443c7c03560b
a5b6740ae8aa16564efc9093e8811f2325b740b4
refs/heads/master
2020-08-12T22:32:35.432261
2019-10-19T21:27:42
2019-10-19T21:27:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
950
cpp
#include "cicada/util/logging/logger.h" #include <iostream> ccd::logger::logger() noexcept : m_name("Logger"), m_severity(log_severity::info) {} ccd::logger::logger(const std::string& p_name, log_severity p_initialSeverity) noexcept : m_name(p_name), m_severity(p_initialSeverity) {} ccd::logger& ccd::logger::operator<<(log_severity p_severity) noexcept { this->m_severity = p_severity; return (*this); } const ccd::logger& ccd::logger::operator<<(const std::string& p_message) const noexcept { std::cout << "[" + to_string(this->m_severity) + "]" << p_message; return (*this); } std::string ccd::to_string(log_severity p_severity) noexcept { switch (p_severity) { case log_severity::verbose: return "verbose"; case log_severity::debug: return "debug"; case log_severity::warning: return "warning"; case log_severity::error: return "error"; case log_severity::fatal: return "fatal"; default: return "unknown"; } }
[ "cm12000.creations@gmail.com" ]
cm12000.creations@gmail.com
20eff3375eab27980a6e0ce8c3dd660540d6bca2
aa53e6ba0f23550ec80abf487581143ba1fca490
/Final_term_project/Final_term_project/Particle.h
d3aa90ee5e339d40ce881ccbc35481bf113901bc
[]
no_license
sos0911/Physics_simulation_project
0ee5f72caf4b21dfd909f8c99cdeaa3e0dbe6f0f
13c65ac0b5b224f4a708c8ae3060bef2c95da1f1
refs/heads/main
2023-03-13T03:32:43.132648
2021-03-02T08:19:37
2021-03-02T08:19:37
343,113,756
1
0
null
null
null
null
UHC
C++
false
false
890
h
#ifndef PARTICLE_CPP #define PARTICLE_CPP #include "glm/glm.hpp" #include <random> #include <iostream> #include <windows.h> #include <iostream> using namespace glm; using namespace std; class particle { public: int MIN_INIT_VELOCITY; int MAX_INIT_VELOCITY; // 바운더리 박스 한 변 길이 float LENGTH = 30; // 입자 반지름 float RADIUS = 0.5f; float Particles_radius; // 파티클 시스템 반경 // 입자 최대 생존 가능시간 float maxlifetime; // 입자 생존시간(경과한 시간) float lifetime; int mass = 1; vec3 velocity, position; vec3 ps_center_pos; // 파티클 시스템 중심점 void init(vec3 center_pos, int _MIN_INIT_VELOCITY, int _MAX_INIT_VELOCITY, int _LENGTH, float _RADIUS, int _mass); float rand_float(); float rand_zero_center_float(); // euler void Movement(float dt, vec3 force); void Collision_Boundary(); }; #endif
[ "sos0911@korea.ac.kr" ]
sos0911@korea.ac.kr
0a7db896f4a52079259304eb3d250c2fb6d382ca
83d47b2a4aab88aa95c3a8742bb069088846e9c0
/repository/2629.cpp
dcd8b62f7f04ed748b02469ebbb3510393ccef20
[]
no_license
motxx/AOJ
9285ef7c51c866bab479759a68d3dcac1d3e2abe
3ac7c25d2cb51bf852706b603a5c936a57400b64
refs/heads/master
2021-01-09T20:40:11.522538
2016-07-13T21:00:27
2016-07-13T21:00:27
61,233,346
0
0
null
null
null
null
UTF-8
C++
false
false
1,064
cpp
#include <assert.h> #include <algorithm> #include <array> #include <bitset> #include <cmath> #include <complex> #include <cstdio> #include <cstring> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <random> #include <set> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; struct before_main { before_main() { cin.tie(0); ios::sync_with_stdio(false); } } before_main; #define REP(i, a, b) for (int i = a; i < (int)b; i++) #define rep(i, n) REP(i, 0, n) #define all(c) (c).begin(), (c).end() #define zero(a) memset(a, 0, sizeof a) #define minus(a) memset(a, -1, sizeof a) template <class T1, class T2> inline bool minimize(T1 &a, T2 b) { return b < a && (a = b, 1); } template <class T1, class T2> inline bool maximize(T1 &a, T2 b) { return a < b && (a = b, 1); } typedef long long ll; int const inf = 1 << 29; int main() { double d; cin >> d; printf("%.10f\n", max(1.0 + floor(d), d * sqrt(2))); return 0; }
[ "motohiko.ave@gmail.com" ]
motohiko.ave@gmail.com
a2551dbb451decb5fccb76fa75a3eb60ac406f91
c60a810d25bb8e5d614daeb37212568f614a4401
/Notebook/topo-kosaraju.cpp
e9f01b94d59436b8ea1ae89206ff42c98d069637
[]
no_license
jonasla/icpc
f5d0af087a54b7bb57bc92e4191ddc09e2669d5b
4f464de0b374f4c5b756b1a87322f87b08d9551a
refs/heads/master
2021-01-24T03:42:37.957660
2018-03-17T15:30:05
2018-03-17T15:30:05
122,900,491
1
0
null
null
null
null
UTF-8
C++
false
false
1,468
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long tint; typedef vector<tint> vi; #define forn(i,n) for (tint i = 0; i < (tint)(n); i++) #define forsn(i,s,n) for (tint i = (s); i < (tint)(n); i++) void dfsTopo(vector<vi> &g, tint s, vi &vis, vi &ord, vi &comp) { vis[s] = true; for(auto ad : g[s]) if (!vis[ad]) dfsTopo(g, ad, vis, ord, comp); ord.push_back(s); comp.push_back(s); } vi topoSort(vector<vi> &g) {// Devuelve el orden topologico int N = g.size(); vi vis, ord, aux; vis.assign(N, 0); forn(i,N) if (!vis[i]) dfsTopo(g, i, vis, ord, aux); reverse(ord.begin(), ord.end()); return ord; } // Devuelve las componentes en orden topologico vector<vi> kosaraju(vector<vi> &graf) { vi ord = topoSort(graf); // Invertimos el grafo tint N = graf.size(); vector<vi> grafInv(N, vi()); forn(i,N) for(auto j : graf[i]) grafInv[j].push_back(i); vi vis(N, false), aux; vector<vi> comps; for (auto o : ord) if (!vis[o]) { vi comp; dfsTopo(grafInv, o, vis, aux, comp); comps.push_back(comp); } return comps; } int main() { int N = 6; vector<vi> graf(N, vi()); graf[0].push_back(1); graf[1].push_back(2); graf[2].push_back(0); graf[2].push_back(3); graf[3].push_back(4); graf[4].push_back(3); graf[4].push_back(5); vector<vi> comps = kosaraju(graf); for(auto &c : comps) { for(auto &e : c) cout << e << " "; cout << endl; } return 0; }
[ "jonaslevy5@gmail.com" ]
jonaslevy5@gmail.com
d3295ee520ff785adf84f01b0192306ba4d00551
ec484fab327dded72c423644d18cbbfda78938a8
/KL-FatC/Type-D/TPolyDSaved.cpp
bc3d86699aa26c184dfda6b7a78f816188000b43
[]
no_license
kstolcenberg/KL-Polys
b1bba0649123605fae627f849b1b0ff3eb8c1406
07150f79a4a4a8afe745c46acd34ccd771909d9a
refs/heads/master
2021-01-20T10:59:35.546110
2017-04-24T03:21:08
2017-04-24T03:21:08
81,620,049
0
0
null
null
null
null
UTF-8
C++
false
false
8,205
cpp
#include <string> #include <sstream> #include <iostream> #include <algorithm> #include <cassert> #include "TPolyD.h" //See TPoly.h for more information about underlying data structures. //The graph that is used sparsely for information such as the number of weights in the graph. //Most information is contained already in TPoly, its weyl string, or the structure of the weights. const Graph *TPoly::mGraph; //The output stream for printing debugging information. std::ofstream *TPoly::mStream; //The polynomial dictionary that is used to help minimize redundant information by storing the most //common polynomials in terms of t^2 generated throughout the calculation. PolyStore TPoly::mStore(100); //Constructs a TPoly. TPoly::TPoly(const std::vector<unsigned char> &tWeylString) { //Allocates underlying datastructures and sets TPoly equal to 1*T0. int tLength = tWeylString.size(); int tNumberOfWeights = mGraph->getUpperBoundEx(tLength).mIndex; mPolySize = 2*mGraph->getLongestLength(); Poly tZero; Poly tOne(true); mZero = mStore.store(tZero); const Poly* pOne = mStore.store(tOne); //Note that each TPoly takes up a lot of space. For n=9, ~3.4 million pointers. mPolys = new std::vector<const Poly*>(tNumberOfWeights, mZero); mBack = new std::vector<const Poly*>(tNumberOfWeights, mZero); mPolys->at(0) = pOne; mIndex.push_back(&(mGraph->getZero())); //Tells us that the poly at index 0 is nonzero. mGlobalOffset = 0; //Begins to construct TPoly for specified weyl string. int tEnd = tLength; for(int i = 0; i < tEnd; i++) multiplyBy(tWeylString[i]); //Gets rid of the backing array used during the construction of the TPoly. //Note that with the dictionary, polynomials can't be simply deleted as they may be referenced elsewhere. for(int i = 0; i < mBack->size(); i++) if(!(mStore.contains(*(mBack->at(i))))) delete mBack->at(i); delete mBack; } //A destructor TPoly::~TPoly() { unsigned int tStartSize = mIndex.size(); for(unsigned int i = 0; i < tStartSize; i++) mStore.dispose(mPolys->at(mIndex[i]->mIndex)); delete mPolys; } void TPoly::multiplyBy(int aS) { //Deletes previous polynomials and zeros them out. for(int i = 0; i < mBack->size(); i++) mStore.dispose(mBack->at(i)); for(int i = 0; i < mBack->size(); i++) mBack->at(i) = mZero; //Given how large the TPoly's are we need to iterate only through non-zero elements. //Thus, we look at the vector of non-zero indices: mIndex. unsigned int tStartSize = mIndex.size(); for(unsigned int i = 0; i < tStartSize; i++) { const Poly& tCurrent = *(mPolys->at(mIndex[i]->mIndex)); const Weight &tNu = *mIndex[i]; const Weight &tNuS = *(tNu.mEdges[aS]); //Performs multiplication rules writing to mBack and then at the end swapping mPoly and mBack. if(tNuS.mLength > tNu.mLength) { Poly tNuPoly(*(mBack->at(tNu.mIndex)),mPolySize); //Get any polynomial computed earlier in for loop. Poly tNuSPoly(*(mBack->at(tNuS.mIndex)),mPolySize); //Get any polynomial computed earlier in for loop. tNuPoly.add(1, 0, tCurrent); //Add the current polynomial to it. mStore.dispose(mBack->at(tNu.mIndex)); //Get rid of old polynomial. mBack->at(tNu.mIndex) = mStore.store(tNuPoly); //Store polynomial in dictionary and write it back to mBack. //We may need to add the tNuS into mIndex if we have never generated a polynomial with that index before. if(mBack->at(tNuS.mIndex)->isZero() && mPolys->at(tNuS.mIndex)->isZero()) mIndex.push_back(&tNuS); //Similar to before. tNuSPoly.add(1, 0, tCurrent); mStore.dispose(mBack->at(tNuS.mIndex)); mBack->at(tNuS.mIndex) = mStore.store(tNuSPoly); } else if(tNuS.mLength < tNu.mLength) { //See previous if statement. Poly tNuPoly(*(mBack->at(tNu.mIndex)),mPolySize); Poly tNuSPoly(*(mBack->at(tNuS.mIndex)),mPolySize); tNuPoly.add(1, 2, tCurrent); mStore.dispose(mBack->at(tNu.mIndex)); mBack->at(tNu.mIndex) = mStore.store(tNuPoly); if(mBack->at(tNuS.mIndex)->isZero() && mPolys->at(tNuS.mIndex)->isZero()) mIndex.push_back(&tNuS); tNuSPoly.add(1, 2, tCurrent); mStore.dispose(mBack->at(tNuS.mIndex)); mBack->at(tNuS.mIndex) = mStore.store(tNuSPoly); } else { //See previous if statement. Poly tNuPoly(*(mBack->at(tNu.mIndex)),mPolySize); tNuPoly.add(1, 0, tCurrent); tNuPoly.add(1, 2, tCurrent); mStore.dispose(mBack->at(tNu.mIndex)); mBack->at(tNu.mIndex) = mStore.store(tNuPoly); } } //Swap the new results with old TPoly. std::vector<const Poly*> *tSwap = mPolys; mPolys = mBack; mBack = tSwap; //Need to increase offset so that we can have polynomials in terms of positive powers of t and thus easier to store. mGlobalOffset++; } //Prints out the weight. Probably could be moved to graph.cpp. std::string printWeight(const unsigned char* tWeight) { std::stringstream tStream; tStream << "( " << (int) tWeight[0]; for(int i = 1; i < RANK - 1; i++) tStream << " , " << (int) tWeight[i]; tStream << " )"; return tStream.str(); } //Prints out the TPoly in a somewhat easy to understand way (given that it is a polynomial of polynomials). std::string TPoly::toString() { int tLength = mGraph->getLongestLength(); std::stringstream tStream; unsigned char tFinal[] = MAX_WEIGHT; std::string sFinal = printWeight(tFinal); for(unsigned int i = 0; i < mIndex.size(); i++) tStream << printWeight(mIndex[i]->mValue) << '\t' << sFinal << '\t' << (int) (mIndex[i]->mLength) << '\t' << mPolys->at(mIndex[i]->mIndex)->toString() << std::endl; return tStream.str(); } void TPoly::fix() { //Gets indices in sorted order. sort(mIndex.begin(), mIndex.end()); //Starting at nearly the end (lowest degree term) of the TPoly. for(int i = (int) mIndex.size() - 2; i >= 0; i--) { //Lets you know status of computation. if(i % 100 == 0) std::cout << i << std::endl; //Get current polynomial. const Poly& tPoly = *(mPolys->at(mIndex[i]->mIndex)); int tLength = mIndex[i]->mLength; //Figure out what the real zero degree is. int tOurZeroDegree = mGlobalOffset - tLength; //Get g(t). Poly tAdd = tPoly.greaterThan(tOurZeroDegree); //Get C. int tZeroth = tPoly.getCoefficient(tOurZeroDegree); //Polynomial may be zero, so eliminate any leading zero terms. tAdd.trim(); if(tAdd.isZero() && tZeroth == 0) continue; //(*mStream) << "WEIGHT:" << printWeight(mGraph->getWeight(mIndex[i]).mValue) << std::endl; //(*mStream) << toString() << std::endl; TPoly tNu(mGraph->getWeylString(*(mIndex[i]))); //Do TPoly addition. addSymmetric(tOurZeroDegree, tAdd, tZeroth, tNu); //*mStream << toString() <<std::endl; } //(*mStream) << "Final:\n" << toString() << std::endl; } //Adds two TPolys. void TPoly::addSymmetric(int aOurZeroDegree, const Poly& aPoly, int aZeroCoefficient, const TPoly& aNuTPoly) { int tEnd = aNuTPoly.mIndex.size(); //Could be that aOurZeroDegree is odd. In this case, we have to modify it so that we aren't adding together odd degrees in our t^2 polynomials. int tParityOffset = aOurZeroDegree % 2; for(int i = 0; i < tEnd; i++) { const Weight &tWeight = *(aNuTPoly.mIndex[i]); //Get the two polys associated with the same weight from NuTPoly and this TPoly. const Poly& tNuPoly = *(aNuTPoly.mPolys->at(tWeight.mIndex)); assert(mPolys->at(tWeight.mIndex) != NULL); Poly tGammaPoly(*(mPolys->at(tWeight.mIndex)), mPolySize); //OK? //Does g*(t) = g(t) + f(t)h(t) where g(t) is tGammaPoly, f(t) is (aPoly + aZeroCoefficient + aPoly with inverted degrees), h(t) is aNuPoly. int tPolyLength = aPoly.getLength(); for(int j = 0; j < tPolyLength; j++) { tGammaPoly.add(-aPoly.getCoefficient(2*j), aOurZeroDegree + 2*(j + 1) - tParityOffset, tNuPoly); tGammaPoly.add(-aPoly.getCoefficient(2*j), aOurZeroDegree - 2*(j + 1) + tParityOffset, tNuPoly); } //Add zero coefficient. if(tParityOffset == 0) tGammaPoly.add(-aZeroCoefficient, aOurZeroDegree, tNuPoly); //Delete old polynomial and store new result. mStore.dispose(mPolys->at(tWeight.mIndex)); mPolys->at(tWeight.mIndex) = mStore.store(tGammaPoly); } } void TPoly::setGraph(const Graph& aGraph) { mGraph = &aGraph; mStream = new std::ofstream(DEBUG_FILE); }
[ "kyle.stolcenberg@gmail.com" ]
kyle.stolcenberg@gmail.com
464b356454dfa1638ac633ecc7379a39b4ad8f92
5010fdc8d15aae16fe754da41945755f632ee268
/try.cpp
c42d1336172a1090fb75d0a96c90b764f3d872bb
[]
no_license
deepakks1995/Practise
294c661fde02d0468b876930603a81ac5a6da526
2a96a2a51907641f240bf4e6465d60883bff67d0
refs/heads/master
2021-01-23T08:44:46.723322
2018-03-29T08:03:21
2018-03-29T08:03:21
102,544,532
0
0
null
null
null
null
UTF-8
C++
false
false
1,121
cpp
/*input 6 3 1 8 2 6 4 */ #include <bits/stdc++.h> using namespace std; int min(int a, int b, int c) { return a < b ? (a < c ? a : c) : (b < c ? b : c); } int max(int a, int b, int c) { return a > b ? (a > c ? a : c) : (b > c ? b : c); } int applyDynamic(std::vector<int> v, int start, int end){ int dp[v.size()][2]; dp[start][0] = 0; dp[start][1] = v[start]; for (int i = start+1; i < end+1; ++i){ dp[i][0] = dp[i-1][1]; // either i-1 gets the desert or i-2 gets the desert if i gets the desert dp[i][1] = v[i] + min(dp[i-1][1], dp[i-1][0]); } return min(dp[end][0], dp[end][1]); } int main(){ ios_base::sync_with_stdio(false); int N; cin>>N; std::vector<int> array(N); for (int i = 0; i < N; ++i) cin>>array[i]; //King arthur gets his desert int ans1 = applyDynamic(array, 1, array.size()-1) + array[0]; //King arthur does not gets his desert, last knight gets desert int ans2 = applyDynamic(array, 0, array.size()-2) + array[array.size()-1]; cout<<min(ans2, ans1)<<endl; }
[ "deepakks1995@gmail.com" ]
deepakks1995@gmail.com
19d9a82581de2bf1639baccab418c79534adcae6
67515036be6eea3f83c88547b79e26018137d526
/MainMenuUI.cpp
1c736c17274594680dbc8eb7371088ecf393d68c
[]
no_license
parhelia512/jyqxzXreMake
ec3d50bca72211f187131305ddd0af1818227c9f
4382e248b534486e4c127eaf8993951e5dd0cd10
refs/heads/master
2020-05-14T14:20:19.005501
2019-03-13T05:35:22
2019-03-13T05:35:22
null
0
0
null
null
null
null
GB18030
C++
false
false
4,317
cpp
#include "MainMenuUI.h" USING_NS_CC; USING_NS_MGE; USING_NS_TL; USING_NS_UI; bool MainMenuUI::init() { if(!Layer::init()) return false; is_on_touched = false; return true; } MainMenuUI * MainMenuUI::createWithPoint(const cocos2d::Point & point, std::vector<cocos2d::Sprite*>& spriteVec, std::vector<std::function<void(cocos2d::Node*,cocos2d::EventMouse*)>>& callBackVec) { auto mui = create(); auto rotateSprite = trimImage(CV::templateImage, "UI/mainMenuSprite.png"); rotateSprite->setPosition(point); mui->addChild(rotateSprite, 10, "rotateSprite"); //auto size = 100, 100 if (spriteVec.size() != callBackVec.size()) { CCLOG("size of spriteVec not equal size of callBackVec "); } int size = std::min(spriteVec.size(),callBackVec.size()); //半径 float r =100*1.5f; Vec2 vec = {r,0 }; float angle = 2.0f*3.14159f / size; mui->SpriteVec.swap(std::move(spriteVec)); mui->CallBackVec.swap(std::move(callBackVec)); for (int i = 0; i != size; i++) { mui->SpriteVec[i]->setPosition(vec); vec.rotate(Vec2::ZERO, angle); rotateSprite->addChild(mui->SpriteVec[i], 10, "rotateSprite_n"); } // mui->schedule(CC_CALLBACK_1(MainMenuUI::checkTouch, mui), "checkTouch"); return mui; } void MainMenuUI::checkTouch(float f) { if (is_on_touched) { auto rotation = RotateBy::create(0.1f, 10); this->getChildByName("rotateSprite")->runAction(rotation); } } void MainMenuUI::InertialSliding(cocos2d::Node* node,float init_angle,float f ) { //角加速度 if (is_stop) return; float a = 1; //角初速度 auto init_v = abs(init_angle)/f; auto angle2 = init_v * (lastTime + f) - 0.5f*a*(lastTime + f)*(lastTime + f); if (angle2 < lastAngle) { is_stop = true; return; } auto angle = angle2 - lastAngle; lastAngle = angle2; lastTime += f; node->runAction( RotateBy::create(0, CC_RADIANS_TO_DEGREES( init_angle>0? angle: (-angle) ) ) ); } void MainMenuUI::onEnter() { Layer::onEnter(); if (listenerMouse == nullptr) { listenerMouse = EventListenerMouse::create(); listenerMouse->onMouseDown = [this](EventMouse* event) { is_on_touched = true; this->touchedPoint= event->getLocationInView(); this->unschedule("InertialSliding"); // CCLOG("%d,%d", touchedPoint.x, touchedPoint.y); }; listenerMouse->onMouseMove=[this](EventMouse* event) { if (is_on_touched) { auto sprite = this->getChildByName("rotateSprite"); //auto vec1 = touchedPoint - sprite->getPosition(); //检测是否惯性滑动 auto vec = event->getLocationInView() - touchedPoint; if (vec.getDistance(Vec2::ZERO)>20) { lastAngle = 0; lastTime = 0; is_stop = false; auto init_angle = event->getLocationInView().getAngle() - touchedPoint.getAngle(); this->schedule(std::bind(&MainMenuUI::InertialSliding, this, this->getChildByName("rotateSprite") , init_angle, std::placeholders::_1), "InertialSliding"); is_on_touched = false; return; } //普通滑动 auto vec2 = event->getLocationInView() - sprite->getPosition(); auto vec1 = touchedPoint - sprite->getPosition(); auto angle =- CC_RADIANS_TO_DEGREES((vec2.getAngle()- vec1.getAngle())); touchedPoint = event->getLocationInView(); //CCLOG("%f,%f", vec2.x, vec2.y); //sprite->setRotation(angle); sprite->runAction( RotateBy::create(0,angle) ); } }; listenerMouse->onMouseUp= [this](EventMouse* event) { if (is_on_touched == true) { for (int i = 0; i != SpriteVec.size(); i++) { if (SpriteVec[i]->getBoundingBox().containsPoint( this->getChildByName("rotateSprite")->convertToNodeSpace( event->getLocationInView() ) )) { return CallBackVec[i](this, event); } auto s = SpriteVec[i]->getBoundingBox(); CCLOG("%f,%f,%f,%f", s.getMaxX(), s.getMaxY(), s.getMinX(), s.getMinY()); } } is_on_touched = false; }; } if (listenerMouse) { _eventDispatcher->pauseEventListenersForTarget(this->getParent(), true); _eventDispatcher->addEventListenerWithSceneGraphPriority(listenerMouse, this); } } void MainMenuUI::onExit() { Layer::onExit(); if (listenerMouse) { _eventDispatcher->removeEventListener(listenerMouse); _eventDispatcher->resumeEventListenersForTarget(this->getParent(), true); } }
[ "812125110@qq.com" ]
812125110@qq.com
1b6e3c4f06af01c70fd497193592c2b5e9f71ab4
743dcee2eb0a2f97b60bfc0dc7939d63681f1fa8
/tag/demo_nov-13/Server/mongodb/mongo/util/version.h
c7f850d48cced686c9535c551adfa74775d8bf7f
[]
no_license
l0gicpath/scribble-websocket-server
e3e5f035055a8534e48853dc550e516b977b37c6
c86955abc71e4f9c856924a93ddb510a463eed95
refs/heads/master
2021-01-21T00:25:20.570140
2013-04-29T18:18:43
2013-04-29T18:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,216
h
/** * Copyright (C) 2012 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef UTIL_VERSION_HEADER #define UTIL_VERSION_HEADER #include <string> #include "mongo/base/string_data.h" namespace mongo { struct BSONArray; // mongo version extern const char versionString[]; extern const BSONArray versionArray; std::string mongodVersion(); int versionCmp(StringData rhs, StringData lhs); // like strcmp const char * gitVersion(); void printGitVersion(); std::string sysInfo(); void printSysInfo(); void show_warnings(); } // namespace mongo #endif // UTIL_VERSION_HEADER
[ "frankyn@ubuntu.(none)" ]
frankyn@ubuntu.(none)
ea3bd6cf451085aae3e6573dd7f7b041db05f2e6
09a20466c1650ab4beb6554ceabc8649a7540c06
/core/src/jni/jni/TezosLikeAddress.hpp
98aa75f92d21ff1124c7ee3da8ca3f746c4160e9
[ "MIT" ]
permissive
LedgerHQ/lib-ledger-core
2f1153655ed7c116b866d2b21920a8a3017f5d96
ad1e271b5f61e92f663ff08c337acc8b107fc85f
refs/heads/main
2023-07-09T18:24:41.408616
2023-07-06T13:09:06
2023-07-06T13:09:06
68,716,694
99
99
MIT
2023-06-30T08:36:20
2016-09-20T13:51:06
C++
UTF-8
C++
false
false
1,351
hpp
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from addresses.djinni #ifndef DJINNI_GENERATED_TEZOSLIKEADDRESS_HPP_JNI_ #define DJINNI_GENERATED_TEZOSLIKEADDRESS_HPP_JNI_ #include "../../api/TezosLikeAddress.hpp" #include "djinni_support.hpp" namespace djinni_generated { class TezosLikeAddress final : ::djinni::JniInterface<::ledger::core::api::TezosLikeAddress, TezosLikeAddress> { public: using CppType = std::shared_ptr<::ledger::core::api::TezosLikeAddress>; using CppOptType = std::shared_ptr<::ledger::core::api::TezosLikeAddress>; using JniType = jobject; using Boxed = TezosLikeAddress; ~TezosLikeAddress(); static CppType toCpp(JNIEnv* jniEnv, JniType j) { return ::djinni::JniClass<TezosLikeAddress>::get()._fromJava(jniEnv, j); } static ::djinni::LocalRef<JniType> fromCppOpt(JNIEnv* jniEnv, const CppOptType& c) { return {jniEnv, ::djinni::JniClass<TezosLikeAddress>::get()._toJava(jniEnv, c)}; } static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c) { return fromCppOpt(jniEnv, c); } private: TezosLikeAddress(); friend ::djinni::JniClass<TezosLikeAddress>; friend ::djinni::JniInterface<::ledger::core::api::TezosLikeAddress, TezosLikeAddress>; }; } // namespace djinni_generated #endif //DJINNI_GENERATED_TEZOSLIKEADDRESS_HPP_JNI_
[ "khalil.bellakrid@ledger.fr" ]
khalil.bellakrid@ledger.fr
1aa46eb0e78dce9d15b9d3c1742e7b34e8feb9d5
114282bd391c1c9b7df22cef5bffcbbc4e16dbf1
/roswrap/src/include/sick_scan/SickImu.h
e49008953fd52957223f984be40336fb7181947e
[ "Apache-2.0" ]
permissive
lpc921/sick_scan_base
1d648f2910bd976e047106785e8db98b9daf86cf
ae07b658071d43ed24d2b6105996847d8194b4ff
refs/heads/master
2020-12-15T19:15:28.409008
2020-01-21T00:39:44
2020-01-21T00:39:44
235,225,253
0
0
Apache-2.0
2020-01-21T00:30:45
2020-01-21T00:30:45
null
UTF-8
C++
false
false
10,268
h
// Generated by gencpp from file sick_scan/SickImu.msg // DO NOT EDIT! #ifndef SICK_SCAN_MESSAGE_SICKIMU_H #define SICK_SCAN_MESSAGE_SICKIMU_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> #include <std_msgs/Header.h> #include <sensor_msgs/Imu.h> namespace sick_scan { template <class ContainerAllocator> struct SickImu_ { typedef SickImu_<ContainerAllocator> Type; SickImu_() : header() , Imu() , ticks(0) , quaternion_accuracy(0.0) , angular_velocity_reliability(0) , linear_acceleration_reliability(0) { } SickImu_(const ContainerAllocator& _alloc) : header(_alloc) , Imu(_alloc) , ticks(0) , quaternion_accuracy(0.0) , angular_velocity_reliability(0) , linear_acceleration_reliability(0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::sensor_msgs::Imu_<ContainerAllocator> _Imu_type; _Imu_type Imu; typedef uint32_t _ticks_type; _ticks_type ticks; typedef float _quaternion_accuracy_type; _quaternion_accuracy_type quaternion_accuracy; typedef uint8_t _angular_velocity_reliability_type; _angular_velocity_reliability_type angular_velocity_reliability; typedef uint8_t _linear_acceleration_reliability_type; _linear_acceleration_reliability_type linear_acceleration_reliability; typedef boost::shared_ptr< ::sick_scan::SickImu_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::sick_scan::SickImu_<ContainerAllocator> const> ConstPtr; }; // struct SickImu_ typedef ::sick_scan::SickImu_<std::allocator<void> > SickImu; typedef boost::shared_ptr< ::sick_scan::SickImu > SickImuPtr; typedef boost::shared_ptr< ::sick_scan::SickImu const> SickImuConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::sick_scan::SickImu_<ContainerAllocator> & v) { ros::message_operations::Printer< ::sick_scan::SickImu_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace sick_scan namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'sensor_msgs': ['/opt/ros/melodic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/melodic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg'], 'sick_scan': ['/home/rosuser/catkin_ws/src/sick_scan/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< ::sick_scan::SickImu_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::sick_scan::SickImu_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::sick_scan::SickImu_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::sick_scan::SickImu_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sick_scan::SickImu_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sick_scan::SickImu_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::sick_scan::SickImu_<ContainerAllocator> > { static const char* value() { return "136303711a1d592affd8713883708711"; } static const char* value(const ::sick_scan::SickImu_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x136303711a1d592aULL; static const uint64_t static_value2 = 0xffd8713883708711ULL; }; template<class ContainerAllocator> struct DataType< ::sick_scan::SickImu_<ContainerAllocator> > { static const char* value() { return "sick_scan/SickImu"; } static const char* value(const ::sick_scan::SickImu_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::sick_scan::SickImu_<ContainerAllocator> > { static const char* value() { return "# This message contains the IMU data of a Sick laser scanner as an IMU message.\n" "# The ticks correspond to the internal time stamps of the laser scanner and increase linearly with time, the tickcounter overflows.\n" "# The quaternion_accuracy has the unit rad.\n" "# The accuracy measures for Lienar acceleration and angular velocity are abitre values, where higher values are better.\n" "# \n" "#\n" "Header header\n" "\n" "sensor_msgs/Imu Imu\n" "#IMU Message\n" "\n" "uint32 ticks\n" "# timestamp Ticks from laser scanner\n" "\n" "float32 quaternion_accuracy\n" "#quaternion accuracy in rad\n" "\n" "uint8 angular_velocity_reliability\n" "#angular velocity reliability 0 low 255 high, value should be over 3\n" "\n" "uint8 linear_acceleration_reliability\n" "#linear acceleration reliability 0 low 255 high, value should be over 3\n" "\n" "================================================================================\n" "MSG: std_msgs/Header\n" "# Standard metadata for higher-level stamped data types.\n" "# This is generally used to communicate timestamped data \n" "# in a particular coordinate frame.\n" "# \n" "# sequence ID: consecutively increasing ID \n" "uint32 seq\n" "#Two-integer timestamp that is expressed as:\n" "# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n" "# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n" "# time-handling sugar is provided by the client library\n" "time stamp\n" "#Frame this data is associated with\n" "string frame_id\n" "\n" "================================================================================\n" "MSG: sensor_msgs/Imu\n" "# This is a message to hold data from an IMU (Inertial Measurement Unit)\n" "#\n" "# Accelerations should be in m/s^2 (not in g's), and rotational velocity should be in rad/sec\n" "#\n" "# If the covariance of the measurement is known, it should be filled in (if all you know is the \n" "# variance of each measurement, e.g. from the datasheet, just put those along the diagonal)\n" "# A covariance matrix of all zeros will be interpreted as \"covariance unknown\", and to use the\n" "# data a covariance will have to be assumed or gotten from some other source\n" "#\n" "# If you have no estimate for one of the data elements (e.g. your IMU doesn't produce an orientation \n" "# estimate), please set element 0 of the associated covariance matrix to -1\n" "# If you are interpreting this message, please check for a value of -1 in the first element of each \n" "# covariance matrix, and disregard the associated estimate.\n" "\n" "Header header\n" "\n" "geometry_msgs/Quaternion orientation\n" "float64[9] orientation_covariance # Row major about x, y, z axes\n" "\n" "geometry_msgs/Vector3 angular_velocity\n" "float64[9] angular_velocity_covariance # Row major about x, y, z axes\n" "\n" "geometry_msgs/Vector3 linear_acceleration\n" "float64[9] linear_acceleration_covariance # Row major x, y z \n" "\n" "================================================================================\n" "MSG: geometry_msgs/Quaternion\n" "# This represents an orientation in free space in quaternion form.\n" "\n" "float64 x\n" "float64 y\n" "float64 z\n" "float64 w\n" "\n" "================================================================================\n" "MSG: geometry_msgs/Vector3\n" "# This represents a vector in free space. \n" "# It is only meant to represent a direction. Therefore, it does not\n" "# make sense to apply a translation to it (e.g., when applying a \n" "# generic rigid transformation to a Vector3, tf2 will only apply the\n" "# rotation). If you want your data to be translatable too, use the\n" "# geometry_msgs/Point message instead.\n" "\n" "float64 x\n" "float64 y\n" "float64 z\n" ; } static const char* value(const ::sick_scan::SickImu_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::sick_scan::SickImu_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.Imu); stream.next(m.ticks); stream.next(m.quaternion_accuracy); stream.next(m.angular_velocity_reliability); stream.next(m.linear_acceleration_reliability); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct SickImu_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::sick_scan::SickImu_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::sick_scan::SickImu_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "Imu: "; s << std::endl; Printer< ::sensor_msgs::Imu_<ContainerAllocator> >::stream(s, indent + " ", v.Imu); s << indent << "ticks: "; Printer<uint32_t>::stream(s, indent + " ", v.ticks); s << indent << "quaternion_accuracy: "; Printer<float>::stream(s, indent + " ", v.quaternion_accuracy); s << indent << "angular_velocity_reliability: "; Printer<uint8_t>::stream(s, indent + " ", v.angular_velocity_reliability); s << indent << "linear_acceleration_reliability: "; Printer<uint8_t>::stream(s, indent + " ", v.linear_acceleration_reliability); } }; } // namespace message_operations } // namespace ros #endif // SICK_SCAN_MESSAGE_SICKIMU_H
[ "michael.lehning@lehning.de" ]
michael.lehning@lehning.de
76a92d2e7130c7d23706693887f5230c04ef5c79
bb21001749efae23170926b6ee498f0f5fea2c0b
/Moving Face/src/ofApp.cpp
e85e6c6a7987eaf17f9c28c8dc71228c9571c8c8
[]
no_license
trizmegistus/CreativeCoding
9132e7470ba857b466bf1f847d42f59fb3796d8a
2d4d123f31909538bc96bcfd8b587ba7d679b236
refs/heads/master
2020-12-24T21:21:30.315569
2016-04-11T22:11:43
2016-04-11T22:11:43
55,999,373
0
0
null
null
null
null
UTF-8
C++
false
false
2,383
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofBackground(0, 0, 0); faceX = 100; faceY = 100; moveX = ofRandom(5); moveY = ofRandom(5); mousey = false; } //-------------------------------------------------------------- void ofApp::update() { //MOTION if (ofGetMousePressed()) { faceX = mouseX; faceY = mouseY; } else { faceX = faceX + moveX; faceY = faceY + moveY; if (faceX > 1000 || faceX < 0) { moveX = moveX* -1; } if (faceY > 1000 || faceY < 0) { moveY = moveY* -1; } } } //-------------------------------------------------------------- void ofApp::draw(){ //DRAW FACE // Background ofFill(); ofSetCircleResolution(100); ofHideCursor(); ofSetColor(254, 250, 0); //Makes background YELLOW ofDrawCircle(faceX, faceY, 50); //Draws background circle //Facial features ofSetColor(0, 0, 0); //Makes features BLACK ofDrawCircle(faceX - 15, faceY - 15, 10); //Left eye ofDrawCircle(faceX + 15, faceY - 15, 10); //Right eye ofDrawLine(faceX - 15, faceY + 15, faceX + 15, faceY + 15); //Mouth } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ ofGetKeyPressed(); } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ mousey = false; } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "mr.trizmegistus@gmail.com" ]
mr.trizmegistus@gmail.com
54fbf0e1222569dd439475cc40d9be187412b372
e3313835b27992ef262398514cd28ad60a47201e
/WineApi/Utils.h
ee5e2ab9021e2f94dfaa9eca4d5aa2adda7a8277
[]
no_license
fcccode/WineApi_CXX
22e08e77e064f896be6cd80a708dddbc346148bd
42e2c69a1d09669eca81548526c2667277bbe73d
refs/heads/master
2021-12-02T13:39:53.407445
2012-01-26T10:29:29
2012-01-26T10:29:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,140
h
#ifndef _Utils_h_ #define _Utils_h_ extern HRESULT UtilsInterfaceSupportsErrorInfo (REFIID p_riid1, REFIID p_riid2); extern void UtilsAppendNameValueToQueryString ( _bstr_t& p_sbstrUrl, const _bstr_t& p_sbstrName, const _bstr_t& p_sbstrValue); extern void UtilsAppendNameValueToQueryString ( _bstr_t& p_sbstrUrl, const _bstr_t& p_sbstrName, long p_lValue); extern HRESULT UtilsPropertyGetHelper ( BSTR* p_pbstrProperty, const _bstr_t& p_sbstrProperty); extern HRESULT UtilsPropertyPutHelper ( BSTR p_bstrProperty, _bstr_t& p_sbstrProperty); extern HRESULT UtilsPropertyGetHelper ( long* p_plProperty, long p_lProperty); extern HRESULT UtilsPropertyGetHelper ( double* p_pdblProperty, double p_dblProperty); extern HRESULT UtilsPropertyGetHelper ( VARIANT_BOOL* p_pvbProperty, bool p_bProperty); //***************************************************************************** //* Function Name: UtilsGetInterfacePointerHelper //* Description: Helper function to return an interface pointer. //* //* An example of U and V might be: //* U = IStatus //* V = IStatusPtr //***************************************************************************** template<typename U, typename V> extern HRESULT UtilsGetInterfacePointerHelper ( U** p_ppRawInterfacePointer, const V& p_spSmartInterfacePointer) { HRESULT l_hr = S_OK; // Have we been given a valid return location ? if (p_ppRawInterfacePointer == NULL) { // No - Oops. return E_POINTER; } // Yes - so initialise it to NULL. *p_ppRawInterfacePointer = NULL; try { // Do we have an interface pointer to return ? if (p_spSmartInterfacePointer) { // Yes - so set the return value. *p_ppRawInterfacePointer = p_spSmartInterfacePointer; // Double check that we have returned a valid interface pointer... if ((*p_ppRawInterfacePointer) != NULL) { // ...and if we have, then we need to bump the reference count. (*p_ppRawInterfacePointer)->AddRef (); } } } catch (const _com_error& l_ce) { l_hr = l_ce.Error (); // An error occurred so ensure that we have initialised the logical return value to NULL. *p_ppRawInterfacePointer = NULL; } return l_hr; } //***************************************************************************** //* Function Name: UtilsSelfQueryInterfaceHelper //* Description: Helper function to wrap a call to QueryInterface(). Checks //* p_ppSelf for NULL. //* //* An example of U and V might be: //* U = CComObject<CCatalogService> //* V = ICatalogService //***************************************************************************** template<typename U, typename V> extern HRESULT UtilsSelfQueryInterfaceHelper ( U* p_pThis, V** p_ppSelf) { HRESULT l_hr = S_OK; // Have we been given a valid return location ? if (p_ppSelf == NULL) { // No - Oops. return E_POINTER; } // Yes - so initialise it to NULL. *p_ppSelf = NULL; return p_pThis->QueryInterface ( __uuidof (*p_ppSelf), reinterpret_cast<void**>(p_ppSelf)); } #endif
[ "jonathan.taylor@dsl.pipex.com" ]
jonathan.taylor@dsl.pipex.com
68d215d7fbbe26c2a5c67d7b7c7fd37eeca28bb1
dd7160aeb66ea05568f147f7375fe6f98cf07982
/qmllanguage.h
15e6ceaf922ce0eb35483cdac6b807a8edff5891
[]
no_license
tonightgarden/LanguageSwitch
8cf2cd37c78c31d762e6ebba8207986c73f78a38
aa143037dace2c4bbc90107b70ce4c66b7a344b6
refs/heads/master
2020-03-24T22:41:56.930209
2018-08-01T03:34:34
2018-08-01T03:34:34
143,098,340
2
0
null
null
null
null
UTF-8
C++
false
false
469
h
#ifndef QMLLANGUAGE_H #define QMLLANGUAGE_H #include <QObject> #include <QTranslator> #include <QGuiApplication> #include <QQmlApplicationEngine> class QmlLanguage : public QObject { Q_OBJECT public: QmlLanguage(QGuiApplication& app, QQmlApplicationEngine &engine); Q_INVOKABLE void setLanguage(int nLanguage); signals: void languageChanged(); private: QGuiApplication *m_app; QQmlApplicationEngine *m_engine; }; #endif // QMLLANGUAGE_H
[ "tom@join-link.com.cn" ]
tom@join-link.com.cn
49cefe88230e0e76bc6ffdc874a4fea955d3da8e
302945a362836fb2e3c453f1aa981500a792f6e1
/Validator/GenICam/library/CPP/include/xsde/cxx/errno.ixx
5cc6e6141b7ea1f8705f4c7a583c127fce772f31
[ "Apache-2.0" ]
permissive
genicam/GenICamXmlValidator
a39b0802a0b9fda51021a435fcc0f2f79b8ade5a
f3d0873dc2f39e09e98933aee927274a087a2a90
refs/heads/master
2023-01-13T01:14:26.518680
2020-11-09T02:07:32
2020-11-09T02:07:32
268,628,419
2
1
Apache-2.0
2020-11-09T01:55:48
2020-06-01T20:44:51
C++
UTF-8
C++
false
false
766
ixx
// file : xsde/cxx/errno.ixx // author : Boris Kolpackov <boris@codesynthesis.com> // copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC // license : GNU GPL v2 + exceptions; see accompanying LICENSE file #include <xsde/cxx/config.hxx> #ifdef XSDE_PLATFORM_WINCE # include <winbase.h> // Get/SetLastError #else # include <errno.h> #endif namespace xsde { namespace cxx { #ifdef XSDE_PLATFORM_WINCE inline int get_errno () { return static_cast<int> (GetLastError ()); } inline void set_errno (int e) { SetLastError (static_cast<DWORD> (e)); } #else inline int get_errno () { return errno; } inline void set_errno (int e) { errno = e; } #endif } }
[ "kola@imperx.com" ]
kola@imperx.com
5a923b426e673f9197155b18a31a3e1defd091f2
709ea9949d193c18de69b923c045bd71977f7d50
/src/library/include/imu_preintegration/preintegration.h
6a18a44da59217fb329792947235bdb37eec49b0
[ "MIT" ]
permissive
shibowing/ugpm
e669d42dffc120fd64669242d685a1d713accd68
3f1a432a0752d2b2aa106df8d7d3e6ab7b79592d
refs/heads/main
2023-06-15T04:46:04.570404
2021-07-12T08:57:44
2021-07-12T08:57:44
386,692,471
1
0
NOASSERTION
2021-07-16T16:00:18
2021-07-16T16:00:17
null
UTF-8
C++
false
false
18,784
h
/** * Author: Cedric LE GENTIL * * Copyright 2021 Cedric LE GENTIL * * For any further question, recommendation or contribution * le.gentil.cedric@gmail.com **/ #ifndef PREINTEGRATION_H #define PREINTEGRATION_H #include "common/types.h" #include "common/internal_utils.h" #include <iostream> #include "libgp/include/gp.h" #include <ceres/ceres.h> #include <memory> namespace celib { const double kNumDtJacobianDelta = 0.001; const double kNumAccBiasJacobianDelta = 0.01; const double kNumGyrBiasJacobianDelta = 0.01; enum PreintType {LPM, GPM, UGPM}; struct PreintOption { double min_freq = 1000; PreintType type = GPM; bool train_gpm = false; double quantum = -1; }; struct PreintPrior { std::vector<double> acc_bias = {0,0,0}; std::vector<double> gyr_bias = {0,0,0}; }; // Class to perform nice integration over SO3 class RotIntegrator{ public: RotIntegrator( celib::ImuData& imu_data, const double start_time, const PreintPrior bias_prior ); // Method for inference void get(const double t, Mat3& rot, Mat3& var, Vec3& d_rot_d_t, Mat3& d_rot_d_q); Mat3 get(const double t); private: Eigen::MatrixXd ang_vel_; double l2_; double lik_; std::vector<double> sf2_; std::vector<double> mean_; Eigen::VectorXd data_time_; double start_t_; int nb_data_; Eigen::MatrixXd state_; std::vector<Eigen::MatrixXd> d_state_bw_; //std::vector<Eigen::MatrixXd> L_; std::vector<Eigen::VectorXd> alpha_; std::vector<Eigen::MatrixXd> KK_inv_; std::vector<Eigen::MatrixXd> K_int_K_inv_; std::vector<Eigen::MatrixXd> K_inv_; }; // Class for GP inference of signal's integrals class GPMGP { public: GPMGP( const std::vector<ImuSample>& samples, const int axis, const double var, const bool train); GPMGP( const std::vector<ImuSample>& samples, const int axis, const double var, const bool train, std::shared_ptr<MatX> data_d_bf, std::shared_ptr<MatX> data_d_bw, std::shared_ptr<VecX> data_d_dt); void integralAndVar(const double a, const Eigen::VectorXd& b, Eigen::VectorXd& integral_out, Eigen::VectorXd& var_integral_out, Eigen::MatrixXd& d_bf, Eigen::MatrixXd& d_bw, Eigen::VectorXd& d_dt); void integral2AndVar(const double a, const Eigen::VectorXd& b, Eigen::VectorXd& integral_out, Eigen::VectorXd& var_integral_out, Eigen::MatrixXd& d_bf, Eigen::MatrixXd& d_bw, Eigen::VectorXd& d_dt); private: double mean_; Eigen::VectorXd alpha_vec_; Eigen::MatrixXd L_; std::vector<double> hyp_sq_; std::vector<double> data_time_; std::shared_ptr<Eigen::MatrixXd> data_d_bf_; std::shared_ptr<Eigen::MatrixXd> data_d_bw_; std::shared_ptr<Eigen::VectorXd> data_d_dt_; }; // Class to compute preintegrated measurements and potentially store the pre-computed meausrements class ImuPreintegration { public: // Constructor given IMU data and inference timestamps ImuPreintegration(celib::ImuData& imu_data, const double start_t, std::vector<std::vector<double> >& infer_t, const PreintOption opt, const PreintPrior prior, const bool rot_only = false); ~ImuPreintegration(){ if(rot_integrator_) delete rot_integrator_; } // Compute the preintegrated measurement for a given timestamp PreintMeas get(const double t); // Get the preintegrated measurement as per indexed in the given inference times of the constructor PreintMeas get(const int index_1, const int index_2); // Accessor for prior PreintPrior getPrior() { return prior_;} private: // Store a copy of the imu_data used celib::ImuData imu_data_; double start_t_; int start_index_; PreintOption opt_; PreintPrior prior_; RotIntegrator* rot_integrator_ = nullptr; std::vector<GPMGP> vel_ugpm_; // Store the pre-computed preintegrated measurements if contructor with time-stamps std::vector<std::vector<PreintMeas> > preint_; // Reproject the accelerometer data in imu_data_ based on the given rotational preintegrated measurements void reprojectAccData( const std::vector<PreintMeas>& preint, const std::vector<double>& prior, const Mat3& delta_R_dt_start, std::vector<std::shared_ptr<MatX> >& d_acc_d_bf, std::vector<std::shared_ptr<MatX> >& d_acc_d_bw, std::vector<std::shared_ptr<VecX> >& d_acc_d_dt); // Compute the preintegration for the rotational part std::vector<PreintMeas> rotPreintIterative( const SortIndexTracker2<double>& t, const std::vector<bool>& interest_t, const PreintType type, const PreintPrior prior); void rotPreintLoop( const std::vector<std::vector<std::pair<double, double> > >& inter_data, const SortIndexTracker2<double>& t, const PreintPrior prior, std::vector<PreintMeas>& output); void rotPreintLoop( const std::vector<std::vector<std::pair<double, double> > >& inter_data, const SortIndexTracker2<double>& t, const PreintPrior prior, std::vector<Mat3>& output); // Compute the preintegration for the velocity and position part void velPosPreintLPM( std::vector<std::vector<double> >& t, const std::vector<std::shared_ptr<MatX> >& d_acc_d_bf, const std::vector<std::shared_ptr<MatX> >& d_acc_d_bw, const std::vector<std::shared_ptr<VecX> >& d_acc_d_dt, std::vector<std::vector<PreintMeas> >& preint); void velPosPreintLPMPartial( const SortIndexTracker2<double>& time, std::vector<ImuSample>& acc_data, std::vector<std::vector<PreintMeas> >& preint); void velPosPreintGPM( const std::vector<std::vector<double> >& t, std::vector<std::shared_ptr<MatX> >& d_acc_d_bf, std::vector<std::shared_ptr<MatX> >& d_acc_d_bw, std::vector<std::shared_ptr<VecX> >& d_acc_d_dt, std::vector<std::vector<PreintMeas> >& preint); // Interpolation methods std::vector<std::pair<double, double> > linearInterpolation( const std::vector<ImuSample>& samples, const int axis, const double var, const SortIndexTracker2<double>& infer_t); std::vector<std::pair<double, double> > gpInterpolation( const std::vector<ImuSample>& samples, const int axis, const double var, const SortIndexTracker2<double>& infer_t); void prepareUGPM( celib::ImuData& imu_data, const double start_time, const PreintPrior bias_prior); PreintMeas getUGPM( const double t); }; // Class to perform GP interpolation for the preintegration class GpInterpolator { public: GpInterpolator(const std::vector<ImuSample>& samples, const int axis, const double var, const bool train); std::vector<std::pair<double, double> > get(const SortIndexTracker2<double>& t); std::vector<std::pair<double, double> > getShifted(const SortIndexTracker2<double>& t, const double dt); private: libgp::GaussianProcess gp_; double mean_; }; class IntegrationCostFunction: public ceres::CostFunction { public: IntegrationCostFunction( Eigen::MatrixXd* ang_vel, std::vector<MatX>* KK_inv, std::vector<MatX>* K_int_K_inv, std::vector<double>* t, double start_t, std::vector<double>* mean): ang_vel_(ang_vel), KK_inv_(KK_inv), K_int_K_inv_(K_int_K_inv), t_(t), start_t_(start_t), mean_(mean) { nb_data_ = KK_inv_->at(0).cols(); set_num_residuals(6*nb_data_); std::vector<int>* block_sizes = mutable_parameter_block_sizes(); block_sizes->push_back(3*nb_data_); }; // Inherited from ceres::CostFunction, compute the residuals and jacobians virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const; bool CheckGradient(bool show_report = true); private: Eigen::MatrixXd* ang_vel_; std::vector<MatX>* KK_inv_; std::vector<MatX>* K_int_K_inv_; std::vector<double>* t_; double start_t_; std::vector<double>* mean_; int nb_data_; }; inline celib::Mat3_6 JacobianRes(celib::Vec3 rot_vec, celib::Vec3 d_r) { celib::Mat3_6 output; double r0_sq = rot_vec(0)*rot_vec(0); double r1_sq = rot_vec(1)*rot_vec(1); double r2_sq = rot_vec(2)*rot_vec(2); double temp_r = (r0_sq + r1_sq + r2_sq); double norm_r = std::sqrt(temp_r); celib::Vec3 r = rot_vec; //if(norm_r >= 2.0*M_PI) //{ // celib::Vec3 unit_vec; // unit_vec = rot_vec / norm_r; // norm_r = std::fmod(norm_r,2.0*M_PI); // r = unit_vec*norm_r; // r0_sq = r(0)*r(0); // r1_sq = r(1)*r(1); // r2_sq = r(2)*r(2); // temp_r = (r0_sq + r1_sq + r2_sq); //} if(norm_r > kExpNormTolerance) { double r0_cu = r(0)*r(0)*r(0); double r1_cu = r(1)*r(1)*r(1); double r2_cu = r(2)*r(2)*r(2); double norm_r_2 = std::pow(temp_r, 2); double norm_r_3 = std::pow(temp_r, 1.5); double norm_r_5 = std::pow(temp_r, 2.5); double s_r = std::sin(norm_r); double c_r = std::cos(norm_r); output(0,0) = d_r(1)*((r(0)*r(2)*s_r)/norm_r_3 - (r(1)*(s_r - norm_r))/norm_r_3 + (2.0*r(0)*r(2)*(c_r - 1.0))/norm_r_2 + (3.0*r0_sq*r(1)*(s_r - norm_r))/norm_r_5 + (r(0)*r(1)*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3) - d_r(2)*((r(2)*(s_r - norm_r))/norm_r_3 + (r(0)*r(1)*s_r)/norm_r_3 + (2.0*r(0)*r(1)*(c_r - 1.0))/norm_r_2 - (3.0*r0_sq*r(2)*(s_r - norm_r))/norm_r_5 - (r(0)*r(2)*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3) - d_r(0)*((r1_sq*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 + (r2_sq*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 + (3.0*r(0)*r1_sq*(s_r - norm_r))/norm_r_5 + (3.0*r(0)*r2_sq*(s_r - norm_r))/norm_r_5); output(0,1) = d_r(2)*((c_r - 1.0)/temp_r - (r1_sq*s_r)/norm_r_3 - (2.0*r1_sq*(c_r - 1.0))/norm_r_2 + (r(0)*r(2)*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 + (3.0*r(0)*r(1)*r(2)*(s_r - norm_r))/norm_r_5) - d_r(0)*((3.0*r1_cu*(s_r - norm_r))/norm_r_5 + (r1_sq*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 + (r2_sq*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 - (2.0*r(1)*(s_r - norm_r))/norm_r_3 + (3.0*r(1)*r2_sq*(s_r - norm_r))/norm_r_5) + d_r(1)*((r(1)*r(2)*s_r)/norm_r_3 - (r(0)*(s_r - norm_r))/norm_r_3 + (2.0*r(1)*r(2)*(c_r - 1.0))/norm_r_2 + (3.0*r(0)*r1_sq*(s_r - norm_r))/norm_r_5 + (r(0)*r(1)*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3); output(0,2) = d_r(1)*((r2_sq*s_r)/norm_r_3 - (c_r - 1.0)/temp_r + (2.0*r2_sq*(c_r - 1.0))/norm_r_2 + (r(0)*r(1)*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 + (3.0*r(0)*r(1)*r(2)*(s_r - norm_r))/norm_r_5) - d_r(0)*((3.0*r2_cu*(s_r - norm_r))/norm_r_5 + (r1_sq*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 + (r2_sq*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 - (2.0*r(2)*(s_r - norm_r))/norm_r_3 + (3.0*r1_sq*r(2)*(s_r - norm_r))/norm_r_5) - d_r(2)*((r(0)*(s_r - norm_r))/norm_r_3 + (r(1)*r(2)*s_r)/norm_r_3 + (2.0*r(1)*r(2)*(c_r - 1.0))/norm_r_2 - (3.0*r(0)*r2_sq*(s_r - norm_r))/norm_r_5 - (r(0)*r(2)*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3); output(0,3) = (r1_sq*(s_r - norm_r))/norm_r_3 + (r2_sq*(s_r - norm_r))/norm_r_3 + 1.0; output(0,4) = - (r(2)*(c_r - 1.0))/temp_r - (r(0)*r(1)*(s_r - norm_r))/norm_r_3; output(0,5) = (r(1)*(c_r - 1.0))/temp_r - (r(0)*r(2)*(s_r - norm_r))/norm_r_3; output(1,0) = d_r(2)*((r0_sq*s_r)/norm_r_3 - (c_r - 1.0)/temp_r + (2.0*r0_sq*(c_r - 1.0))/norm_r_2 + (r(1)*r(2)*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 + (3.0*r(0)*r(1)*r(2)*(s_r - norm_r))/norm_r_5) - d_r(1)*((3.0*r0_cu*(s_r - norm_r))/norm_r_5 + (r0_sq*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 + (r2_sq*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 - (2.0*r(0)*(s_r - norm_r))/norm_r_3 + (3.0*r(0)*r2_sq*(s_r - norm_r))/norm_r_5) - d_r(0)*((r(1)*(s_r - norm_r))/norm_r_3 + (r(0)*r(2)*s_r)/norm_r_3 + (2.0*r(0)*r(2)*(c_r - 1.0))/norm_r_2 - (3.0*r0_sq*r(1)*(s_r - norm_r))/norm_r_5 - (r(0)*r(1)*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3); output(1,1) = d_r(2)*((r(0)*r(1)*s_r)/norm_r_3 - (r(2)*(s_r - norm_r))/norm_r_3 + (2.0*r(0)*r(1)*(c_r - 1.0))/norm_r_2 + (3.0*r1_sq*r(2)*(s_r - norm_r))/norm_r_5 + (r(1)*r(2)*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3) - d_r(0)*((r(0)*(s_r - norm_r))/norm_r_3 + (r(1)*r(2)*s_r)/norm_r_3 + (2.0*r(1)*r(2)*(c_r - 1.0))/norm_r_2 - (3.0*r(0)*r1_sq*(s_r - norm_r))/norm_r_5 - (r(0)*r(1)*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3) - d_r(1)*((r0_sq*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 + (r2_sq*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 + (3.0*r0_sq*r(1)*(s_r - norm_r))/norm_r_5 + (3.0*r(1)*r2_sq*(s_r - norm_r))/norm_r_5); output(1,2) = d_r(0)*((c_r - 1.0)/temp_r - (r2_sq*s_r)/norm_r_3 - (2.0*r2_sq*(c_r - 1.0))/norm_r_2 + (r(0)*r(1)*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 + (3.0*r(0)*r(1)*r(2)*(s_r - norm_r))/norm_r_5) - d_r(1)*((3.0*r2_cu*(s_r - norm_r))/norm_r_5 + (r0_sq*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 + (r2_sq*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 - (2.0*r(2)*(s_r - norm_r))/norm_r_3 + (3.0*r0_sq*r(2)*(s_r - norm_r))/norm_r_5) + d_r(2)*((r(0)*r(2)*s_r)/norm_r_3 - (r(1)*(s_r - norm_r))/norm_r_3 + (2.0*r(0)*r(2)*(c_r - 1.0))/norm_r_2 + (3.0*r(1)*r2_sq*(s_r - norm_r))/norm_r_5 + (r(1)*r(2)*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3); output(1,3) = (r(2)*(c_r - 1.0))/temp_r - (r(0)*r(1)*(s_r - norm_r))/norm_r_3; output(1,4) = (r0_sq*(s_r - norm_r))/norm_r_3 + (r2_sq*(s_r - norm_r))/norm_r_3 + 1.0; output(1,5) = - (r(0)*(c_r - 1.0))/temp_r - (r(1)*r(2)*(s_r - norm_r))/norm_r_3; output(2,0) = d_r(1)*((c_r - 1.0)/temp_r - (r0_sq*s_r)/norm_r_3 - (2.0*r0_sq*(c_r - 1.0))/norm_r_2 + (r(1)*r(2)*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 + (3.0*r(0)*r(1)*r(2)*(s_r - norm_r))/norm_r_5) - d_r(2)*((3.0*r0_cu*(s_r - norm_r))/norm_r_5 + (r0_sq*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 + (r1_sq*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3 - (2.0*r(0)*(s_r - norm_r))/norm_r_3 + (3.0*r(0)*r1_sq*(s_r - norm_r))/norm_r_5) + d_r(0)*((r(0)*r(1)*s_r)/norm_r_3 - (r(2)*(s_r - norm_r))/norm_r_3 + (2.0*r(0)*r(1)*(c_r - 1.0))/norm_r_2 + (3.0*r0_sq*r(2)*(s_r - norm_r))/norm_r_5 + (r(0)*r(2)*(r(0)/norm_r - (r(0)*c_r)/norm_r))/norm_r_3); output(2,1) = d_r(0)*((r1_sq*s_r)/norm_r_3 - (c_r - 1.0)/temp_r + (2.0*r1_sq*(c_r - 1.0))/norm_r_2 + (r(0)*r(2)*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 + (3.0*r(0)*r(1)*r(2)*(s_r - norm_r))/norm_r_5) - d_r(2)*((3.0*r1_cu*(s_r - norm_r))/norm_r_5 + (r0_sq*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 + (r1_sq*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3 - (2.0*r(1)*(s_r - norm_r))/norm_r_3 + (3.0*r0_sq*r(1)*(s_r - norm_r))/norm_r_5) - d_r(1)*((r(2)*(s_r - norm_r))/norm_r_3 + (r(0)*r(1)*s_r)/norm_r_3 + (2.0*r(0)*r(1)*(c_r - 1.0))/norm_r_2 - (3.0*r1_sq*r(2)*(s_r - norm_r))/norm_r_5 - (r(1)*r(2)*(r(1)/norm_r - (r(1)*c_r)/norm_r))/norm_r_3); output(2,2) = d_r(0)*((r(1)*r(2)*s_r)/norm_r_3 - (r(0)*(s_r - norm_r))/norm_r_3 + (2.0*r(1)*r(2)*(c_r - 1.0))/norm_r_2 + (3.0*r(0)*r2_sq*(s_r - norm_r))/norm_r_5 + (r(0)*r(2)*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3) - d_r(1)*((r(1)*(s_r - norm_r))/norm_r_3 + (r(0)*r(2)*s_r)/norm_r_3 + (2.0*r(0)*r(2)*(c_r - 1.0))/norm_r_2 - (3.0*r(1)*r2_sq*(s_r - norm_r))/norm_r_5 - (r(1)*r(2)*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3) - d_r(2)*((r0_sq*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 + (r1_sq*(r(2)/norm_r - (r(2)*c_r)/norm_r))/norm_r_3 + (3.0*r0_sq*r(2)*(s_r - norm_r))/norm_r_5 + (3.0*r1_sq*r(2)*(s_r - norm_r))/norm_r_5); output(2,3) = - (r(1)*(c_r - 1.0))/temp_r - (r(0)*r(2)*(s_r - norm_r))/norm_r_3; output(2,4) = (r(0)*(c_r - 1.0))/temp_r - (r(1)*r(2)*(s_r - norm_r))/norm_r_3; output(2,5) = (r0_sq*(s_r - norm_r))/norm_r_3 + (r1_sq*(s_r - norm_r))/norm_r_3 + 1.0; } else { output.block<3,3>(0,0) = 0.5*ToSkewSymMat(d_r); output.block<3,3>(0,3) = Mat3::Identity(); } return output; } } #endif
[ "le.gentil.cedric@gmail.com" ]
le.gentil.cedric@gmail.com
0020506d029d36344cb4cb35059c5ae5dadac24d
7fb149b31b9321fc14396dad040fabf7e6e6eb52
/build/tmp/expandedArchives/wpiutil-cpp-2019.2.1-headers.zip_961601eb64e5456d71ed70c0f9da8e94/wpi/uv/Udp.h
7ceb0bbb9248ea5cc28122e9eb9e786265ea7e77
[ "BSD-3-Clause" ]
permissive
FRCTeam5458DigitalMinds/Axon
4feb4e7cc1a50d93d77c204dbf6cca863850ba3f
af571142de3f9d6589252c89537210015a1a26a0
refs/heads/master
2020-04-18T20:14:50.004225
2019-10-30T03:05:29
2019-10-30T03:05:29
167,732,922
3
0
BSD-3-Clause
2019-03-11T01:25:14
2019-01-26T20:00:28
C++
UTF-8
C++
false
false
9,462
h
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #ifndef WPIUTIL_WPI_UV_UDP_H_ #define WPIUTIL_WPI_UV_UDP_H_ #include <uv.h> #include <functional> #include <memory> #include "wpi/ArrayRef.h" #include "wpi/Signal.h" #include "wpi/Twine.h" #include "wpi/uv/Handle.h" #include "wpi/uv/Request.h" namespace wpi { namespace uv { class Loop; class Udp; /** * UDP send request. */ class UdpSendReq : public RequestImpl<UdpSendReq, uv_udp_send_t> { public: UdpSendReq(); Udp& GetUdp() const { return *static_cast<Udp*>(GetRaw()->handle->data); } /** * Send completed signal. This is called even if an error occurred. * @param err error value */ sig::Signal<Error> complete; }; /** * UDP handle. * UDP handles encapsulate UDP communication for both clients and servers. */ class Udp final : public HandleImpl<Udp, uv_udp_t> { struct private_init {}; public: explicit Udp(const private_init&) {} ~Udp() noexcept override = default; /** * Create a UDP handle. * * @param loop Loop object where this handle runs. * @param flags Flags */ static std::shared_ptr<Udp> Create(Loop& loop, unsigned int flags = AF_UNSPEC); /** * Create a UDP handle. * * @param loop Loop object where this handle runs. * @param flags Flags */ static std::shared_ptr<Udp> Create(const std::shared_ptr<Loop>& loop, unsigned int flags = AF_UNSPEC) { return Create(*loop, flags); } /** * Open an existing file descriptor or SOCKET as a UDP handle. * * @param sock A valid socket handle (either a file descriptor or a SOCKET). */ void Open(uv_os_sock_t sock) { Invoke(&uv_udp_open, GetRaw(), sock); } /** * Bind the handle to an IPv4 or IPv6 address and port. * * @param addr Initialized `sockaddr_in` or `sockaddr_in6` data structure. * @param flags Optional additional flags. */ void Bind(const sockaddr& addr, unsigned int flags = 0) { Invoke(&uv_udp_bind, GetRaw(), &addr, flags); } void Bind(const sockaddr_in& addr, unsigned int flags = 0) { Bind(reinterpret_cast<const sockaddr&>(addr), flags); } void Bind(const sockaddr_in6& addr, unsigned int flags = 0) { Bind(reinterpret_cast<const sockaddr&>(addr), flags); } /** * Bind the handle to an IPv4 address and port. * * @param ip The address to which to bind. * @param port The port to which to bind. * @param flags Optional additional flags. */ void Bind(const Twine& ip, unsigned int port, unsigned int flags = 0); /** * Bind the handle to an IPv6 address and port. * * @param ip The address to which to bind. * @param port The port to which to bind. * @param flags Optional additional flags. */ void Bind6(const Twine& ip, unsigned int port, unsigned int flags = 0); /** * Get the current address to which the handle is bound. * @return The address (will be zeroed if an error occurred). */ sockaddr_storage GetSock(); /** * Set membership for a multicast address. * * @param multicastAddr Multicast address to set membership for * @param interfaceAddr Interface address * @param membership Should be UV_JOIN_GROUP or UV_LEAVE_GROUP */ void SetMembership(const Twine& multicastAddr, const Twine& interfaceAddr, uv_membership membership); /** * Set IP multicast loop flag. Makes multicast packets loop back to local * sockets. * * @param enabled True for enabled, false for disabled */ void SetMulticastLoop(bool enabled) { Invoke(&uv_udp_set_multicast_loop, GetRaw(), enabled ? 1 : 0); } /** * Set the multicast TTL. * * @param ttl Time to live (1-255) */ void SetMulticastTtl(int ttl) { Invoke(&uv_udp_set_multicast_ttl, GetRaw(), ttl); } /** * Set the multicast interface to send or receive data on. * * @param interfaceAddr Interface address */ void SetMulticastInterface(const Twine& interfaceAddr); /** * Set broadcast on or off. * * @param enabled True for enabled, false for disabled */ void SetBroadcast(bool enabled) { Invoke(&uv_udp_set_broadcast, GetRaw(), enabled ? 1 : 0); } /** * Set the time to live (TTL). * * @param ttl Time to live (1-255) */ void SetTtl(int ttl) { Invoke(&uv_udp_set_ttl, GetRaw(), ttl); } /** * Send data over the UDP socket. If the socket has not previously been bound * with Bind() it will be bound to 0.0.0.0 (the "all interfaces" IPv4 address) * and a random port number. * * Data are written in order. The lifetime of the data pointers passed in * the `bufs` parameter must exceed the lifetime of the send request. * The callback can be used to free data after the request completes. * * HandleSendComplete() will be called on the request object when the data * has been written. HandleSendComplete() is called even if an error occurs. * HandleError() will be called on the request object in case of errors. * * @param addr sockaddr_in or sockaddr_in6 with the address and port of the * remote peer. * @param bufs The buffers to be written to the stream. * @param req write request */ void Send(const sockaddr& addr, ArrayRef<Buffer> bufs, const std::shared_ptr<UdpSendReq>& req); void Send(const sockaddr_in& addr, ArrayRef<Buffer> bufs, const std::shared_ptr<UdpSendReq>& req) { Send(reinterpret_cast<const sockaddr&>(addr), bufs, req); } void Send(const sockaddr_in6& addr, ArrayRef<Buffer> bufs, const std::shared_ptr<UdpSendReq>& req) { Send(reinterpret_cast<const sockaddr&>(addr), bufs, req); } /** * Send data over the UDP socket. If the socket has not previously been bound * with Bind() it will be bound to 0.0.0.0 (the "all interfaces" IPv4 address) * and a random port number. * * Data are written in order. The lifetime of the data pointers passed in * the `bufs` parameter must exceed the lifetime of the send request. * The callback can be used to free data after the request completes. * * The callback will be called when the data has been sent. Errors will * be reported via the error signal. * * @param addr sockaddr_in or sockaddr_in6 with the address and port of the * remote peer. * @param bufs The buffers to be sent. * @param callback Callback function to call when the data has been sent. */ void Send(const sockaddr& addr, ArrayRef<Buffer> bufs, std::function<void(MutableArrayRef<Buffer>, Error)> callback); void Send(const sockaddr_in& addr, ArrayRef<Buffer> bufs, std::function<void(MutableArrayRef<Buffer>, Error)> callback) { Send(reinterpret_cast<const sockaddr&>(addr), bufs, callback); } void Send(const sockaddr_in6& addr, ArrayRef<Buffer> bufs, std::function<void(MutableArrayRef<Buffer>, Error)> callback) { Send(reinterpret_cast<const sockaddr&>(addr), bufs, callback); } /** * Same as Send(), but won't queue a send request if it can't be completed * immediately. * * @param addr sockaddr_in or sockaddr_in6 with the address and port of the * remote peer. * @param bufs The buffers to be send. * @return Number of bytes sent. */ int TrySend(const sockaddr& addr, ArrayRef<Buffer> bufs) { int val = uv_udp_try_send(GetRaw(), bufs.data(), bufs.size(), &addr); if (val < 0) { this->ReportError(val); return 0; } return val; } int TrySend(const sockaddr_in& addr, ArrayRef<Buffer> bufs) { return TrySend(reinterpret_cast<const sockaddr&>(addr), bufs); } int TrySend(const sockaddr_in6& addr, ArrayRef<Buffer> bufs) { return TrySend(reinterpret_cast<const sockaddr&>(addr), bufs); } /** * Prepare for receiving data. If the socket has not previously been bound * with Bind() it is bound to 0.0.0.0 (the "all interfaces" IPv4 address) and * a random port number. * * A received signal will be emitted for each received data packet until * `StopRecv()` is called. */ void StartRecv(); /** * Stop listening for incoming datagrams. */ void StopRecv() { Invoke(&uv_udp_recv_stop, GetRaw()); } /** * Gets the amount of queued bytes waiting to be sent. * @return Amount of queued bytes waiting to be sent. */ size_t GetSendQueueSize() const noexcept { return GetRaw()->send_queue_size; } /** * Gets the amount of queued packets waiting to be sent. * @return Amount of queued packets waiting to be sent. */ size_t GetSendQueueCount() const noexcept { return GetRaw()->send_queue_count; } /** * Signal generated for each incoming datagram. Parameters are the buffer, * the number of bytes received, the address of the sender, and flags. */ sig::Signal<Buffer&, size_t, const sockaddr&, unsigned> received; }; } // namespace uv } // namespace wpi #endif // WPIUTIL_WPI_UV_UDP_H_
[ "maximo43873@gmail.com" ]
maximo43873@gmail.com
cab12da46120150451469c8e909c3093cb98b67d
62a8f4772b86178ff4c1601f08de27480464bb5f
/fileHandler.cpp
22862af11d61f6f002a0176a4bdc4a8315bae6c2
[ "MIT" ]
permissive
theProgrammerDavid/Board-Project
ebc85e6650f84b8af32271ad34b2fd400dceca06
93ce38b17687c3cd3d24ef22b0d0b4cffacd1bd0
refs/heads/master
2021-07-15T02:01:47.374890
2020-05-26T08:32:44
2020-05-26T08:32:44
155,164,463
1
0
null
null
null
null
UTF-8
C++
false
false
2,431
cpp
#include "fileHandler.h" fileHandler::fileHandler() { /**constructor to open the streams to the files */ ftemp.open("elements_temp.data", ios::out); fout.open("elements.data", ios::out|ios::app); fin.open("elements.data", ios::in); } int fileHandler::fileExists() { /**checks if the file exists or not */ ifstream fs; fs.open("elements.data", ios::in); return fs.good(); } void fileHandler::split(const string& str, const string& delim, vector<string>& parts) { /**accepts a string which is a line from the file and splits it using the delimiter and stores the individual fields in a vector of type string */ size_t start, end = 0; while (end < str.size()) { start = end; while (start < str.size() && (delim.find(str[start]) != string::npos)) { start++; // skip initial whitespace } end = start; while (end < str.size() && (delim.find(str[end]) == string::npos)) { end++; // skip to end of word } if (end-start != 0) // just ignore zero-length strings. { parts.push_back(string(str, start, end-start)); } } } void fileHandler::writeElementToFile(element *ele) { /**accepts element as a parameter and writes the corresponding fields to file */ fout<<ele->getName()<<"+"<<ele->getAtNo()<<"+"<<ele->getAtWt()<<"+"<<ele->getSymbol()<<"\n"; } void fileHandler::readElementFromFile(element *ele) { /**reads a line from the file and extracts the data elements and stores it in the parameter passed */ char line[1024]; vector<string> parts; fin.getline(line, 80); string str(line); split(str, "+", parts); ele->setName(parts[0].c_str()); ele->setAtNo(stoi(parts[1])); ele->setAtWt(stoi(parts[2])); ele->setSymbol(parts[3].c_str()); } void fileHandler::writeToTempFile(element *ele) { /**writes the fields of the parameter to the temp file */ ftemp<<ele->getName()<<"+"<<ele->getAtNo()<<"+"<<ele->getAtWt()<<"+"<<ele->getSymbol()<<"\n"; } int fileHandler::noOfElements() { /**counts number of elements based on whether the input file stream is able to get a new line from the file */ int n=0; ifstream flines; char line[80]; flines.open("elements.data", ios::in); while(flines.getline(line, 80)) { n++; } flines.close(); return n; }
[ "davidvelho2awesome@gmail.com" ]
davidvelho2awesome@gmail.com
ad006c6265837824fcff55a9da18222ada23a803
b827699a066d8b6e4e34f8ecd22acf28572dab88
/iree/tools/run_module_main.cc
48be6079c2b336301434dff7384c8e9f5a8841cc
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lamarrr/iree
ff12136dda3ce4cfed668a0b6a43b07fb39e7678
d38ef06d886fec83cc870669ba055c54082cd69a
refs/heads/master
2020-07-30T12:17:44.733253
2019-09-22T18:33:35
2019-09-22T18:33:35
210,231,069
0
0
null
2019-09-23T00:06:25
2019-09-23T00:06:25
null
UTF-8
C++
false
false
7,685
cc
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include "absl/flags/flag.h" #include "absl/strings/numbers.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "iree/base/file_io.h" #include "iree/base/init.h" #include "iree/base/source_location.h" #include "iree/base/status.h" #include "iree/hal/buffer_view_string_util.h" #include "iree/hal/driver_registry.h" #include "iree/schemas/module_def_generated.h" #include "iree/vm/bytecode_printer.h" #include "iree/vm/bytecode_tables_sequencer.h" #include "iree/vm/debug/debug_server_flags.h" #include "iree/vm/fiber_state.h" #include "iree/vm/function.h" #include "iree/vm/instance.h" #include "iree/vm/module.h" #include "iree/vm/module_printer.h" #include "iree/vm/sequencer_context.h" ABSL_FLAG(std::string, main_module, "", "Main module with entry point."); ABSL_FLAG(std::string, main_function, "", "Function within the main module to execute."); ABSL_FLAG(bool, print_source_info, false, "Prints source map information in bytecode output."); ABSL_FLAG(std::string, input_values, "", "Input shapes and optional values."); ABSL_FLAG(std::string, input_file, "", "Input shapes and optional values serialized in a file."); ABSL_FLAG(std::string, output_types, "", "Output data types (comma delimited list of b/i/u/f for " "binary/signed int/unsigned int/float)."); namespace iree { namespace vm { namespace { using ::iree::hal::BufferView; // Parses a list of input shapes and values from a string of newline-separated // inputs. Expects the contents to have one value per line with each value // listed as // [shape]xtype=[value] // Example: // 4x4xi8=0,1,2,3 StatusOr<std::vector<BufferView>> ParseInputsFromFlags( hal::Allocator* allocator) { std::string file_contents; if (!absl::GetFlag(FLAGS_input_values).empty()) { file_contents = absl::StrReplaceAll(absl::GetFlag(FLAGS_input_values), {{"\\n", "\n"}}); } else if (!absl::GetFlag(FLAGS_input_file).empty()) { ASSIGN_OR_RETURN(file_contents, file_io::GetFileContents(absl::GetFlag(FLAGS_input_file))); } std::vector<BufferView> inputs; for (const auto& line : absl::StrSplit(file_contents, '\n', absl::SkipWhitespace())) { ASSIGN_OR_RETURN(auto input, hal::ParseBufferViewFromString(line, allocator)); inputs.push_back(input); } return inputs; } } // namespace Status Run() { ASSIGN_OR_RETURN(auto debug_server, debug::CreateDebugServerFromFlags()); auto instance = std::make_shared<Instance>(std::move(debug_server)); ASSIGN_OR_RETURN(auto driver, hal::DriverRegistry::shared_registry()->Create( "interpreter")); ASSIGN_OR_RETURN(auto device, driver->CreateDefaultDevice()); RETURN_IF_ERROR(instance->device_manager()->RegisterDevice(device)); SequencerContext context(instance); // Load main module. ASSIGN_OR_RETURN( auto main_module_file, ModuleFile::LoadFile(ModuleDefIdentifier(), absl::GetFlag(FLAGS_main_module)), _ << "while loading module file " << absl::GetFlag(FLAGS_main_module)); ASSIGN_OR_RETURN(auto main_module, Module::FromFile(std::move(main_module_file))); // Add native functions for use by the module. RETURN_IF_ERROR(context.RegisterNativeFunction( "fabsf", [](Stack* stack, absl::Span<const BufferView> args, absl::Span<BufferView> results) -> Status { // TODO(benvanik): example native functions. LOG(INFO) << "fabsf"; return OkStatus(); })); // Register the main module with the context. // We could add additional modules (specializations, shared libraries, etc). // ModuleFioles are stateless so we could have the same module_file used by // multiple contexts simultaneously. auto* main_module_ptr = main_module.get(); RETURN_IF_ERROR(context.RegisterModule(std::move(main_module))); // Dump the registered modules. PrintModuleFlagBitfield print_flags = PrintModuleFlag::kNone; if (absl::GetFlag(FLAGS_print_source_info)) { print_flags |= PrintModuleFlag::kIncludeSourceMapping; } for (const auto& module : context.modules()) { RETURN_IF_ERROR(PrintModuleToStream(sequencer_opcode_table(), *module, print_flags, &std::cout)); } // Setup a new fiber. FiberState fiber_state(instance); // Setup arguments and storage for results. Function main_function; if (!absl::GetFlag(FLAGS_main_function).empty()) { // User-specified main function. ASSIGN_OR_RETURN(main_function, context.LookupExport(absl::GetFlag(FLAGS_main_function))); } else { // No main function specified; to prevent non-deterministic behavior we // require one unless there's exactly one exported function in the module. auto* exports = main_module_ptr->function_table().def().exports(); if (exports && exports->size() == 1) { ASSIGN_OR_RETURN( main_function, main_module_ptr->function_table().LookupFunction(exports->Get(0))); } else { return InvalidArgumentErrorBuilder(IREE_LOC) << "--main_function= must be specified to disambiguate the " "function to run"; } } ASSIGN_OR_RETURN(std::vector<BufferView> args, ParseInputsFromFlags(device->allocator())); std::vector<BufferView> results; results.resize(main_function.result_count()); // Call into the main function. RETURN_IF_ERROR(context.Invoke(&fiber_state, main_function, absl::MakeSpan(args), absl::MakeSpan(results))); // Dump all results to stdout. std::vector<std::string> output_types = absl::StrSplit(absl::GetFlag(FLAGS_output_types), absl::delimiter::AnyOf(", "), absl::SkipWhitespace()); if (!output_types.empty() && output_types.size() != results.size()) { return InvalidArgumentErrorBuilder(IREE_LOC) << "--output_types= specified but has " << output_types.size() << " types when the function returns " << results.size(); } for (int i = 0; i < results.size(); ++i) { const auto& result = results[i]; auto print_mode = hal::BufferViewPrintMode::kFloatingPoint; if (!output_types.empty()) { ASSIGN_OR_RETURN(print_mode, hal::ParseBufferViewPrintMode(output_types[i])); } ASSIGN_OR_RETURN(auto result_str, PrintBufferViewToString(result, print_mode, 1024)); const auto& buffer = result.buffer; if (!buffer) { return InternalErrorBuilder(IREE_LOC) << "result[" << i << "] unexpectedly has no buffer"; } LOG(INFO) << "result[" << i << "]: " << buffer->DebugString(); std::cout << result_str << "\n"; } return OkStatus(); } extern "C" int main(int argc, char** argv) { InitializeEnvironment(&argc, &argv); CHECK_OK(Run()); return 0; } } // namespace vm } // namespace iree
[ "ben.vanik@gmail.com" ]
ben.vanik@gmail.com
f062d1ceec27c95b55bc378c032fdaba882ba7bb
119b14cc2352ac9d87dff1377690a7a3aaeb1eb3
/extern/glm/glm/detail/type_mat2x2.hpp
fbcc5d88cf7e00ce3679efdbea40b1811801558b
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "LicenseRef-scancode-happy-bunny" ]
permissive
prideout/clumpy
cc64d0907ab882ad260189ac14972f9b5e68326e
91de9ec4711dcd3acf51a2d1d79ab0aedfa0c354
refs/heads/master
2023-01-10T17:57:02.274338
2022-02-23T22:59:23
2022-02-23T22:59:23
140,956,826
44
3
MIT
2022-12-27T16:35:22
2018-07-14T15:27:51
C++
UTF-8
C++
false
false
6,313
hpp
/// @ref core /// @file glm/detail/type_mat2x2.hpp #pragma once #include "../fwd.hpp" #include "type_vec2.hpp" #include "type_mat.hpp" #include <limits> #include <cstddef> namespace glm { template<typename T, qualifier Q> struct mat<2, 2, T, Q> { typedef vec<2, T, Q> col_type; typedef vec<2, T, Q> row_type; typedef mat<2, 2, T, Q> type; typedef mat<2, 2, T, Q> transpose_type; typedef T value_type; private: col_type value[2]; public: // -- Accesses -- typedef length_t length_type; GLM_FUNC_DECL static GLM_CONSTEXPR_CXX11 length_type length() { return 2; } GLM_FUNC_DECL col_type & operator[](length_type i); GLM_FUNC_DECL GLM_CONSTEXPR_CXX14 col_type const& operator[](length_type i) const; // -- Constructors -- GLM_FUNC_DECL GLM_CONSTEXPR_CXX14 mat() GLM_DEFAULT_CTOR; template<qualifier P> GLM_FUNC_DECL GLM_CONSTEXPR_CXX14 mat(mat<2, 2, T, P> const& m); GLM_FUNC_DECL explicit GLM_CONSTEXPR_CXX14 mat(T scalar); GLM_FUNC_DECL GLM_CONSTEXPR_CXX14 mat( T const& x1, T const& y1, T const& x2, T const& y2); GLM_FUNC_DECL GLM_CONSTEXPR_CXX14 mat( col_type const& v1, col_type const& v2); // -- Conversions -- template<typename U, typename V, typename M, typename N> GLM_FUNC_DECL GLM_CONSTEXPR_CXX14 mat( U const& x1, V const& y1, M const& x2, N const& y2); template<typename U, typename V> GLM_FUNC_DECL GLM_CONSTEXPR_CXX14 mat( vec<2, U, Q> const& v1, vec<2, V, Q> const& v2); // -- Matrix conversions -- template<typename U, qualifier P> GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<2, 2, U, P> const& m); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<3, 3, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<4, 4, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<2, 3, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<3, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<2, 4, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<4, 2, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<3, 4, T, Q> const& x); GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR_CXX14 mat(mat<4, 3, T, Q> const& x); // -- Unary arithmetic operators -- template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator=(mat<2, 2, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator+=(U s); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator+=(mat<2, 2, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator-=(U s); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator-=(mat<2, 2, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator*=(U s); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator*=(mat<2, 2, U, Q> const& m); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator/=(U s); template<typename U> GLM_FUNC_DECL mat<2, 2, T, Q> & operator/=(mat<2, 2, U, Q> const& m); // -- Increment and decrement operators -- GLM_FUNC_DECL mat<2, 2, T, Q> & operator++ (); GLM_FUNC_DECL mat<2, 2, T, Q> & operator-- (); GLM_FUNC_DECL mat<2, 2, T, Q> operator++(int); GLM_FUNC_DECL mat<2, 2, T, Q> operator--(int); }; // -- Unary operators -- template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator+(mat<2, 2, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator-(mat<2, 2, T, Q> const& m); // -- Binary operators -- template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator+(mat<2, 2, T, Q> const& m, T scalar); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator+(T scalar, mat<2, 2, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator+(mat<2, 2, T, Q> const& m1, mat<2, 2, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator-(mat<2, 2, T, Q> const& m, T scalar); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator-(T scalar, mat<2, 2, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator-(mat<2, 2, T, Q> const& m1, mat<2, 2, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator*(mat<2, 2, T, Q> const& m, T scalar); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator*(T scalar, mat<2, 2, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<2, 2, T, Q>::col_type operator*(mat<2, 2, T, Q> const& m, typename mat<2, 2, T, Q>::row_type const& v); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<2, 2, T, Q>::row_type operator*(typename mat<2, 2, T, Q>::col_type const& v, mat<2, 2, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator*(mat<2, 2, T, Q> const& m1, mat<2, 2, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<3, 2, T, Q> operator*(mat<2, 2, T, Q> const& m1, mat<3, 2, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<4, 2, T, Q> operator*(mat<2, 2, T, Q> const& m1, mat<4, 2, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator/(mat<2, 2, T, Q> const& m, T scalar); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator/(T scalar, mat<2, 2, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<2, 2, T, Q>::col_type operator/(mat<2, 2, T, Q> const& m, typename mat<2, 2, T, Q>::row_type const& v); template<typename T, qualifier Q> GLM_FUNC_DECL typename mat<2, 2, T, Q>::row_type operator/(typename mat<2, 2, T, Q>::col_type const& v, mat<2, 2, T, Q> const& m); template<typename T, qualifier Q> GLM_FUNC_DECL mat<2, 2, T, Q> operator/(mat<2, 2, T, Q> const& m1, mat<2, 2, T, Q> const& m2); // -- Boolean operators -- template<typename T, qualifier Q> GLM_FUNC_DECL bool operator==(mat<2, 2, T, Q> const& m1, mat<2, 2, T, Q> const& m2); template<typename T, qualifier Q> GLM_FUNC_DECL bool operator!=(mat<2, 2, T, Q> const& m1, mat<2, 2, T, Q> const& m2); } //namespace glm #ifndef GLM_EXTERNAL_TEMPLATE #include "type_mat2x2.inl" #endif
[ "philiprideout@gmail.com" ]
philiprideout@gmail.com
1ba8c113890058e5be755a69efc435bb37d74c47
453ac5def5b625c11ffc5cb0bf2671fbf109da6b
/week9/noiseParticles/src/noiseField.cpp
6c5a548cfb07c2d50e23f8308fd78bd9db2f0f93
[ "MIT" ]
permissive
n1ckfg/algo2012
42aa3cecff3178df8defb679dc10f60089dd01d7
ee3a3d80cbb36be35a7b57cb54c95d1b4c5ccb20
refs/heads/master
2021-07-09T16:21:44.167936
2019-09-11T14:28:01
2019-09-11T14:28:01
98,332,878
0
0
null
2017-07-25T17:31:23
2017-07-25T17:31:23
null
UTF-8
C++
false
false
782
cpp
/* * noiseField.cpp * class12 * * Created by zachary lieberman on 11/16/10. * Copyright 2010 __MyCompanyName__. All rights reserved. * */ #include "noiseField.h" void noiseField::setup(){ scaleOfField = 0.001f; } ofVec2f noiseField::getNoiseForPosition(float x, float y, float scale){ float angle = ofNoise(x*scaleOfField,y*scaleOfField,noiseTime) * TWO_PI * 1.6; ofVec2f result; result.x = cos(angle); result.y = sin(angle); result *= scale; return result; } void noiseField::draw(){ ofSetColor(127,127,255); for (int i = 0; i < ofGetWidth(); i+=10){ for (int j = 0; j < ofGetHeight(); j+=10){ ofVec2f noise = getNoiseForPosition(i,j,30); ofLine(i,j,i+noise.x, j+noise.y); } } } void noiseField::setTime(float t){ noiseTime = t; }
[ "zach@openframeworks.cc" ]
zach@openframeworks.cc
177ae0ff866197e4fa16ce5b826a2453b71acd81
24d934a3d6344575fcc570cbcec9a3de601c78e2
/CSC8503/CSC8503Common/PositionConstraint.cpp
b9d087afe41be229163e3706829d848fe1e4a804
[]
no_license
tiaylinen/CSC8503
128ce82dae58b6ddb008ec2afd42d1516b11c151
d6a30eda3e540f94ebfa07316679663b7bc6710b
refs/heads/main
2023-03-14T06:50:38.962773
2021-03-01T17:44:16
2021-03-01T17:44:16
343,511,795
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
cpp
#include "PhysicsSystem.h" #include "PhysicsObject.h" #include "PositionConstraint.h" using namespace NCL; using namespace CSC8503; void PositionConstraint::UpdateConstraint(float dt) { Vector3 relativePos = objectA->GetTransform().GetPosition() - objectB->GetTransform().GetPosition(); float currentDistance = relativePos.Length(); float offset = distance - currentDistance; if (abs(offset) > 0.0f) { Vector3 offsetDir = relativePos.Normalised(); PhysicsObject* physA = objectA->GetPhysicsObject(); PhysicsObject* physB = objectB->GetPhysicsObject(); Vector3 relativeVelocity = physA->GetLinearVelocity() - physB->GetLinearVelocity(); float constraintMass = physA->GetInverseMass() + physB->GetInverseMass(); if (constraintMass > 0.0f) { // how much of their relative force is affecting the constraint float velocityDot = Vector3::Dot(relativeVelocity, offsetDir); float biasFactor = 0.01f; float bias = -(biasFactor / dt) * offset; float lambda = -(velocityDot + bias) / constraintMass; Vector3 aImpulse = offsetDir * lambda; Vector3 bImpulse = -offsetDir * lambda; physA->ApplyLinearImpulse(aImpulse); // multiplied by mass here physB->ApplyLinearImpulse(bImpulse); // multiplied by mass here } } }
[ "78483459+tiaylinen@users.noreply.github.com" ]
78483459+tiaylinen@users.noreply.github.com
fef79e1b77cc1a29c79e2c1b299ab72219819724
35114fccf3e579daba158c0c8cbcb7601e2f8e0d
/Car.h
962ef735f36fee4bf53f49a996653519a9f8081f
[]
no_license
sakamotojin/CPlusPlus_Car_Racing
a2f33d0e5693639123198e64a5cfe1d4f946b0c9
8728b4df3a53274bc8b1b74c51deb63620834363
refs/heads/master
2022-12-15T12:07:56.838638
2020-09-10T17:42:02
2020-09-10T17:42:02
294,439,090
0
0
null
null
null
null
UTF-8
C++
false
false
760
h
// // Created by sakamoto on 10/09/20. // #ifndef MYFIRSTSFMLGAME_CAR_H #define MYFIRSTSFMLGAME_CAR_H #include <SFML/Graphics.hpp> class Car { float PosX , PosY ; float VelX , VelY ; float Angle ; float AcX , AcY ; sf::Color CarColor; public : Car(int X ,int Y , sf::Color CaCol){ PosX = X , PosY = Y ; CarColor = CaCol ; Angle = 0 ; VelX = 0 , VelY = 0 ; AcX = 0 , AcY = 0 ; } sf::Color GetColour(){ return CarColor; } float GetX(){ return PosX; } float GetY(){ return PosY; } float GetAngle(){ return Angle;} void ForwardPress(); void RotateLeft(); void RotateRight(); void BackwardPress(); void Move(); }; #endif //MYFIRSTSFMLGAME_CAR_H
[ "sumitjoshi_16146@aitpune.edu.in" ]
sumitjoshi_16146@aitpune.edu.in
6f4a7d60d4289e09fd38a1bb579176f371b515fc
d92c158f1ead9b908ddd5417d1e9945518f50170
/benchmarks/Sudoku/sudoku_cpp.cpp
4020f0ca8a938790dea42a293d4b02dfdf79637f
[ "BSD-2-Clause-Views" ]
permissive
kanghua1981/Cello
9f9961ffc0524b622bac0651fd96c346b9c70ae7
54ce26793693fd6ca890dea63a7578baacd11d40
refs/heads/master
2021-07-03T13:05:44.835408
2021-01-22T02:50:01
2021-01-22T02:50:01
217,445,138
0
0
NOASSERTION
2019-10-25T03:40:09
2019-10-25T03:40:08
null
UTF-8
C++
false
false
8,382
cpp
/* The MIT License Copyright (c) 2011 by Attractive Chaos <attractor@live.co.uk> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This file implements an improved algorithm of Guenter Stertenbrink's suexco.c // (http://magictour.free.fr/suexco.txt). #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdio.h> /* For Sudoku, there are 9x9x9=729 possible choices (9 numbers to choose for each cell in a 9x9 grid), and 4x9x9=324 constraints with each constraint representing a set of choices that are mutually conflictive with each other. The 324 constraints are classified into 4 categories: 1. row-column where each cell contains only one number 2. box-number where each number appears only once in one 3x3 box 3. row-number where each number appears only once in one row 4. col-number where each number appears only once in one column Each category consists of 81 constraints. We number these constraints from 0 to 323. In this program, for example, constraint 0 requires that the (0,0) cell contains only one number; constraint 81 requires that number 1 appears only once in the upper-left 3x3 box; constraint 162 requires that number 1 appears only once in row 1; constraint 243 requires that number 1 appears only once in column 1. Noting that a constraint is a subset of choices, we may represent a constraint with a binary vector of 729 elements. Thus we have a 729x324 binary matrix M with M(r,c)=1 indicating the constraint c involves choice r. Solving a Sudoku is reduced to finding a subset of choices such that no choices are present in the same constaint. This is equivalent to finding the minimal subset of choices intersecting all constraints, a minimum hitting set problem or a eqivalence of the exact cover problem. The 729x324 binary matrix is a sparse matrix, with each row containing 4 non-zero elements and each column 9 non-zero elements. In practical implementation, we store the coordinate of non-zero elements instead of the binary matrix itself. We use a binary row vector to indicate the constraints that have not been used and use a column vector to keep the number of times a choice has been forbidden. When we set a choice, we will use up 4 constraints and forbid other choices in the 4 constraints. When we make wrong choices, we will find an unused constraint with all choices forbidden, in which case, we have to backtrack to make new choices. Once we understand what the 729x324 matrix represents, the backtracking algorithm itself is easy. A major difference between the algorithm implemented here and Guenter Stertenbrink's suexco.c lies in how to count the number of the available choices for each constraint. Suexco.c computes the count with a loop, while the algorithm here keeps the count in an array. The latter is a little more complex to implement as we have to keep the counts synchronized all the time, but it is 50-100% faster, depending on the input. */ // the sparse representation of the binary matrix class sdaux_t { uint16_t r[324][9]; // M(r[c][i], c) is a non-zero element uint16_t c[729][4]; // M(r, c[r][j]) is a non-zero element public: sdaux_t(); int update(int8_t sr[729], uint8_t sc[324], int r, int v); int solve(const char *_s); }; // generate the sparse representation of the binary matrix sdaux_t::sdaux_t() { int i, j, k, r, c, c2, r2; int8_t nr[324]; for (i = r = 0; i < 9; ++i) // generate c[729][4] for (j = 0; j < 9; ++j) for (k = 0; k < 9; ++k) // this "9" means each cell has 9 possible numbers this->c[r][0] = 9 * i + j, // row-column constraint this->c[r][1] = (i/3*3 + j/3) * 9 + k + 81, // box-number constraint this->c[r][2] = 9 * i + k + 162, // row-number constraint this->c[r][3] = 9 * j + k + 243, // col-number constraint ++r; for (c = 0; c < 324; ++c) nr[c] = 0; for (r = 0; r < 729; ++r) // generate r[][] from c[][] for (c2 = 0; c2 < 4; ++c2) k = this->c[r][c2], this->r[k][nr[k]++] = r; } // update the state vectors when we pick up choice r; v=1 for setting choice; v=-1 for reverting int sdaux_t::update(int8_t sr[729], uint8_t sc[324], int r, int v) { int c2, min = 10, min_c = 0; for (c2 = 0; c2 < 4; ++c2) sc[this->c[r][c2]] += v<<7; for (c2 = 0; c2 < 4; ++c2) { // update # available choices int r2, rr, cc2, c = this->c[r][c2]; if (v > 0) { // move forward for (r2 = 0; r2 < 9; ++r2) { if (sr[rr = this->r[c][r2]]++ != 0) continue; // update the row status for (cc2 = 0; cc2 < 4; ++cc2) { int cc = this->c[rr][cc2]; if (--sc[cc] < min) // update # allowed choices min = sc[cc], min_c = cc; // register the minimum number } } } else { // revert const uint16_t *p; for (r2 = 0; r2 < 9; ++r2) { if (--sr[rr = this->r[c][r2]] != 0) continue; // update the row status p = this->c[rr]; ++sc[p[0]]; ++sc[p[1]]; ++sc[p[2]]; ++sc[p[3]]; // update the count array } } } return min<<16 | min_c; // return the col that has been modified and with the minimal available choices } // solve a Sudoku; _s is the standard dot/number representation int sdaux_t::solve(const char *_s) { int i, j, r, c, r2, dir, cand, n = 0, min, hints = 0; // dir=1: forward; dir=-1: backtrack int8_t sr[729], cr[81]; // sr[r]: # times the row is forbidden by others; cr[i]: row chosen at step i uint8_t sc[324]; // bit 1-7: # allowed choices; bit 8: the constraint has been used or not int16_t cc[81]; // cc[i]: col chosen at step i char out[82]; for (r = 0; r < 729; ++r) sr[r] = 0; // no row is forbidden for (c = 0; c < 324; ++c) sc[c] = 0<<7|9; // 9 allowed choices; no constraint has been used for (i = 0; i < 81; ++i) { int a = _s[i] >= '1' && _s[i] <= '9'? _s[i] - '1' : -1; // number from -1 to 8 if (a >= 0) this->update(sr, sc, i * 9 + a, 1); // set the choice if (a >= 0) ++hints; // count the number of hints cr[i] = cc[i] = -1, out[i] = _s[i]; } for (i = 0, dir = 1, cand = 10<<16|0, out[81] = 0;;) { while (i >= 0 && i < 81 - hints) { // maximum 81-hints steps if (dir == 1) { min = cand>>16, cc[i] = cand&0xffff; if (min > 1) { for (c = 0; c < 324; ++c) { if (sc[c] < min) { min = sc[c], cc[i] = c; // choose the top constraint if (min <= 1) break; // this is for acceleration; slower without this line } } } if (min == 0 || min == 10) cr[i--] = dir = -1; // backtrack } c = cc[i]; if (dir == -1 && cr[i] >= 0) this->update(sr, sc, this->r[c][cr[i]], -1); // revert the choice for (r2 = cr[i] + 1; r2 < 9; ++r2) // search for the choice to make if (sr[this->r[c][r2]] == 0) break; // found if the state equals 0 if (r2 < 9) { cand = this->update(sr, sc, this->r[c][r2], 1); // set the choice cr[i++] = r2; dir = 1; // moving forward } else cr[i--] = dir = -1; // backtrack } if (i < 0) break; for (j = 0; j < i; ++j) r = this->r[cc[j]][cr[j]], out[r/9] = r%9 + '1'; // print //puts(out); ++n; --i; dir = -1; // backtrack } return n; // return the number of solutions } int main() { sdaux_t *a = new sdaux_t(); char buf[1024]; while (fgets(buf, 1024, stdin) != 0) { if (strlen(buf) < 81) continue; a->solve(buf); //putchar('\n'); } delete a; return 0; }
[ "contact@theorangeduck.com" ]
contact@theorangeduck.com
bd104efb0e3a57de27e53eb00f2ff24a9e05d96b
7f17edf564ae234dda92e2ea00166ea9a6b6900d
/cPlusPlus/OOP1/main.cpp
c48315a9ef75ca52a60a4896e891e47ea154f0a6
[]
no_license
tusharuiit/EvergreenCPlusPlus
8e67214c866f0f7aa1851c47b60254c796a93209
4de15b417f994748aec2a6c2e45de2994b1d170e
refs/heads/master
2021-01-10T03:01:45.794394
2016-01-04T23:24:36
2016-01-04T23:24:36
48,965,558
1
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
#include<iostream> #include"./class1.hpp" #include"class2.hpp" int main() { class1 class1object1(5) ; std::cout << class1object1.getter1() << std::endl ; class1object1.setter1(6) ; std::cout << class1object1.getter1() << std::endl ; std::cout << get_beauty(class1object1) << std::endl ; class1 class1object2(13); class1 class1object3 = class1object1 + class1object2 ; std::cout << class1object3.getter1() << std::endl ; std::cout << (class1object1 + class1object2).getter1() << std::endl ; }
[ "tusharuiit@gmail.com" ]
tusharuiit@gmail.com
1ca76bef8edfb4739820981384fccc79ec748b0e
c65219ca468f95a5d60fd4655910f9869bfde582
/src/version.cpp
83783d3cac411fbb9403f1bb83c3a988e8f09193
[]
no_license
internetcoin/internetcoin
dd3e968046b9c3e600b712db60e32737a6a6c916
cd853b70c2c278e11d41a381151edce77edf6054
refs/heads/master
2021-01-13T02:18:10.570943
2014-01-06T08:28:37
2014-01-06T08:28:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,623
cpp
// Copyright (c) 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. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "chinait" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
[ "zhang@softmax.cn" ]
zhang@softmax.cn
cb83f3ef63af0a620d697ebe3168b084fec8f55a
9242761db4783ef80dea9d33fab9b071c0e237e6
/exb_7/3_39.cpp
081519b44b70453cd76d46c06b4fa60007a22c21
[]
no_license
venustom85/gragon
41cf138c07bfdf7dc4c10c872415b0071ea3b923
ef2bd122cefa7b12bfd3178b6efe5829121c2718
refs/heads/master
2016-09-10T12:16:14.749371
2014-04-30T09:38:24
2014-04-30T09:38:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,230
cpp
/* p226 7-3-39 一棵二叉链树,利用结点的右子指针将叶子结点按从左往右的顺序串成一个单链表。 */ #include "common/bi_tree.h" using namespace std; namespace exb_7_3_39 { typedef BiNode<char> node_t; void leaf_list(node_t * root, node_t * & tail) { if (root == NULL) { return; } if (root->lc == NULL && root->rc == NULL) { tail->rc = root; tail = root; return; } leaf_list(root->lc, tail); leaf_list(root->rc, tail); } node_t * to_leaf_list(node_t * root) { if (root == NULL) { return NULL; } node_t head_node; node_t * p_head = &head_node; leaf_list(root, p_head); return head_node.rc; } int g_main(int argc, char ** argv) { node_t * root = NULL; int counter = 0; while ((root = bitree_read<char>(cin)) != NULL) { ++counter; cout << "CASE [" << counter << "] " << bitree_io(root) << endl; node_t * head = to_leaf_list(root); while (head != NULL) { cout << head->data << ' '; head = head->rc; } cout << endl; cout << "=================================" << endl; } } } // namespace exb_7_3_39
[ "tangqiming@tigerknows.com" ]
tangqiming@tigerknows.com
f57033f4a850f4fc44b24527c08608c344bc677c
7d3422fea5cf801320aa5a12d8cc85f0936186a1
/ZZMatrixElement/MELA/interface/MELANCSplineFactory_3D.h
a8143d55bc8e8a69609dbe748a22e5a8bb262c26
[]
no_license
rehamMaly/MonoHiggs-ZZ-4lanalysis-2017_NEW
f37ac9571078dedd581e5ffd2000ec7befc3d40b
b43f0f66dc98a514d5a09b1637f2f10987a064db
refs/heads/master
2020-04-02T10:46:02.563372
2018-10-23T15:50:13
2018-10-23T15:50:13
154,353,964
0
0
null
null
null
null
UTF-8
C++
false
false
2,610
h
#ifndef MELANCSPLINEFACTORY_3D #define MELANCSPLINEFACTORY_3D #include <vector> #include <utility> #include <algorithm> #include "TTree.h" #include "TNumericUtil.hh" #include "MELANCSpline_3D_fast.h" #include "MELAFuncPdf.h" typedef TNumericUtil::quadruplet<MELANCSplineCore::T> splineQuadruplet_t; class MELANCSplineFactory_3D{ protected: TString appendName; RooAbsReal* XVar; RooAbsReal* YVar; RooAbsReal* ZVar; MELANCSpline_3D_fast* fcn; MELAFuncPdf* PDF; const std::vector<splineQuadruplet_t> getPoints(const std::vector<MELANCSplineCore::T>& XList, const std::vector<MELANCSplineCore::T>& YList, const std::vector<MELANCSplineCore::T>& ZList, const std::vector<MELANCSplineCore::T>& FcnList); void destroyPDF(); void initPDF(const std::vector<splineQuadruplet_t>& pList); void addUnique(std::vector<MELANCSplineCore::T>& list, MELANCSplineCore::T val); public: MELANCSplineFactory_3D(RooAbsReal& XVar_, RooAbsReal& YVar_, RooAbsReal& ZVar_, TString appendName_=""); ~MELANCSplineFactory_3D(); MELANCSpline_3D_fast* getFunc(){ return fcn; } MELAFuncPdf* getPDF(){ return PDF; } void setPoints(TTree* tree); void setPoints(const std::vector<splineQuadruplet_t>& pList){ initPDF(pList); } template<typename inType> void setPoints(const std::vector<inType>& XList, const std::vector<inType>& YList, const std::vector<inType>& ZList, const std::vector<inType>& FcnList){ std::vector<MELANCSplineCore::T> transXList; std::vector<MELANCSplineCore::T> transYList; std::vector<MELANCSplineCore::T> transZList; std::vector<MELANCSplineCore::T> transFcnList; for (unsigned int ip=0; ip<XList.size(); ip++) transXList.push_back((MELANCSplineCore::T)XList.at(ip)); for (unsigned int ip=0; ip<YList.size(); ip++) transYList.push_back((MELANCSplineCore::T)YList.at(ip)); for (unsigned int ip=0; ip<ZList.size(); ip++) transZList.push_back((MELANCSplineCore::T)ZList.at(ip)); for (unsigned int ip=0; ip<FcnList.size(); ip++) transFcnList.push_back((MELANCSplineCore::T)FcnList.at(ip)); const std::vector<splineQuadruplet_t> pList = getPoints(transXList, transYList, transZList, transFcnList); setPoints(pList); } }; template void MELANCSplineFactory_3D::setPoints<Float_t>(const std::vector<Float_t>& XList, const std::vector<Float_t>& YList, const std::vector<Float_t>& ZList, const std::vector<Float_t>& FcnList); template void MELANCSplineFactory_3D::setPoints<Double_t>(const std::vector<Double_t>& XList, const std::vector<Double_t>& YList, const std::vector<Double_t>& ZList, const std::vector<Double_t>& FcnList); #endif
[ "reham.aly@cern.ch" ]
reham.aly@cern.ch
478c407f855cb064cd2f88802d48872ddf6cbbee
fc90c90a3e21460a2a3632b37c5f17bb16ea8609
/models/StandardModel/StandardModel_two_scale_susy_beta_Ye.cpp
6fe2759d7d5ac8e3b93321274d2e6d485f84bfef
[]
no_license
pathron/SM-code
81cee78d174b44ecf52c125f692e8e8130e2cf01
d836b58adeb0bf2867dcc95690c3d068b33c8cab
refs/heads/master
2021-01-17T17:07:37.778189
2014-11-30T10:59:05
2014-11-30T10:59:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,045
cpp
// ==================================================================== // This file is part of FlexibleSUSY. // // FlexibleSUSY is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // FlexibleSUSY is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FlexibleSUSY. If not, see // <http://www.gnu.org/licenses/>. // ==================================================================== // File generated at Sat 29 Nov 2014 17:55:08 #include "StandardModel_two_scale_susy_parameters.hpp" #include "wrappers.hpp" namespace flexiblesusy { #define INPUT(parameter) input.parameter #define TRACE_STRUCT susy_traces /** * Calculates the one-loop beta function of Ye. * * @return one-loop beta function */ Eigen::Matrix<double,3,3> StandardModel_susy_parameters::calc_beta_Ye_one_loop(const Susy_traces& susy_traces) const { const double traceYdAdjYd = TRACE_STRUCT.traceYdAdjYd; const double traceYeAdjYe = TRACE_STRUCT.traceYeAdjYe; const double traceYuAdjYu = TRACE_STRUCT.traceYuAdjYu; Eigen::Matrix<double,3,3> beta_Ye; beta_Ye = oneOver16PiSqr*(Ye*(3*traceYdAdjYd + traceYeAdjYe + 3* traceYuAdjYu - 2.25*Sqr(g1) - 2.25*Sqr(g2)) + 1.5*(Ye*Ye.adjoint()*Ye)); return beta_Ye; } /** * Calculates the two-loop beta function of Ye. * * @return two-loop beta function */ Eigen::Matrix<double,3,3> StandardModel_susy_parameters::calc_beta_Ye_two_loop(const Susy_traces& susy_traces) const { const double traceYdAdjYd = TRACE_STRUCT.traceYdAdjYd; const double traceYeAdjYe = TRACE_STRUCT.traceYeAdjYe; const double traceYuAdjYu = TRACE_STRUCT.traceYuAdjYu; const double traceYdAdjYdYdAdjYd = TRACE_STRUCT.traceYdAdjYdYdAdjYd; const double traceYdAdjYuYuAdjYd = TRACE_STRUCT.traceYdAdjYuYuAdjYd; const double traceYeAdjYeYeAdjYe = TRACE_STRUCT.traceYeAdjYeYeAdjYe; const double traceYuAdjYuYuAdjYu = TRACE_STRUCT.traceYuAdjYuYuAdjYu; Eigen::Matrix<double,3,3> beta_Ye; beta_Ye = 0.0025*twoLoop*(Ye*(2742*Power(g1,4) - 2300*Power(g2,4) - 2700*traceYdAdjYdYdAdjYd + 600*traceYdAdjYuYuAdjYd - 900* traceYeAdjYeYeAdjYe - 2700*traceYuAdjYuYuAdjYu + 850*traceYuAdjYu*Sqr(g1) + 2250*traceYuAdjYu*Sqr(g2) + 540*Sqr(g1)*Sqr(g2) + 750*traceYeAdjYe*( Sqr(g1) + Sqr(g2)) + 8000*traceYuAdjYu*Sqr(g3) + 250*traceYdAdjYd*(Sqr(g1 ) + 9*Sqr(g2) + 32*Sqr(g3)) + 600*Sqr(Lambdax)) + 15*((-180*traceYdAdjYd - 60*traceYeAdjYe - 180*traceYuAdjYu - 160*Lambdax + 129*Sqr(g1) + 225* Sqr(g2))*(Ye*Ye.adjoint()*Ye) + 40*(Ye*Ye.adjoint()*Ye*Ye.adjoint()*Ye))) ; return beta_Ye; } } // namespace flexiblesusy
[ "peter.athron@coepp14.physics.adelaide.edu.au" ]
peter.athron@coepp14.physics.adelaide.edu.au
fa4c864ad9430e8341c32bdb2e3d7abac4548e20
c456402dcc0a87a7a65c1efe4084638d9e0b3d96
/game/utils/string_frm.h
cfd66b7a13165f7e78fefcfbacaba8c52c8f1aa0
[ "MIT" ]
permissive
Try/OpenGothic
059be5c346235f94942309e7ac07b80e8392e3cc
e70d3865887f316b458d33065fa428edf72c496e
refs/heads/master
2023-08-29T19:04:30.564135
2023-08-21T22:19:42
2023-08-21T22:19:42
165,291,205
910
102
MIT
2023-09-08T14:16:46
2019-01-11T18:32:20
C++
UTF-8
C++
false
false
4,115
h
#pragma once #include <cstdio> #include <cstring> #include <string_view> template<size_t storageSz = 64 /* one cache-line :D */ > class alignas(64) string_frm { public: template<class ... Args> inline string_frm(const Args&... arg) { size_t at = 0; implFormat(stk, sizeof(stk)-1, at, arg...); if(at+1<sizeof(stk)) { stk[at] = '\0'; return; } heap = new char[at+1]; heap[at] = '\0'; stk[sizeof(stk)-1] = '*'; at = 0; implFormat(heap, size_t(-1), at, arg...); } inline ~string_frm() { if(stk[sizeof(stk)-1]!=0) delete[] heap; } string_frm(string_frm&& other) { std::swap(stk,other.stk); } string_frm& operator = (string_frm&& other) { std::swap(stk,other.stk); return *this; } inline operator std::string_view() const { if(stk[storageSz-1]) return heap; return stk; } inline bool empty() const { if(stk[storageSz-1]) return heap[0]=='\0'; return stk[0]=='\0'; } inline char* c_str() { if(stk[storageSz-1]) return heap; return stk; } inline char* begin() { if(stk[storageSz-1]) return heap; return stk; } inline char* end() { if(stk[storageSz-1]) return heap+std::strlen(heap); return stk+std::strlen(stk); } inline const char* begin() const { if(stk[storageSz-1]) return heap; return stk; } inline const char* end() const { if(stk[storageSz-1]) return heap+std::strlen(heap); return stk+std::strlen(stk); } template<size_t sz> friend bool operator == (const string_frm<sz>& l, std::string_view v); template<size_t sz> friend bool operator == (std::string_view v, const string_frm<sz>& l); private: union { char stk[storageSz] = {}; char* heap; }; void implFormat(char* out, size_t maxSz, size_t& at) { at = 0; } template<class ... Args> void implFormat(char* out, size_t maxSz, size_t& at, const Args&... arg) { (implWrite(out,maxSz,at,arg),... ); } // NOTE: const-ref is better for inline-pass in optimizer void implWrite(char* out, size_t maxSz, size_t& at, const std::string_view& arg) { for(size_t i=0; i<arg.size(); ++i) { if(at+i>=maxSz) break; out[at+i] = arg[i]; } at += arg.size(); } void implWrite(char* out, size_t maxSz, size_t& at, const char* arg) { for(size_t i=0; arg[i]; ++i) { if(at>=maxSz) break; out[at] = arg[i]; at++; } } void implWrite(char* out, size_t maxSz, size_t& at, char arg) { if(at<maxSz) out[at] = arg; ++at; } void implWrite(char* out, size_t maxSz, size_t& at, int arg) { char buf[20] = {}; std::snprintf(buf,sizeof(buf),"%d",arg); implWrite(out, maxSz, at, buf); } void implWrite(char* out, size_t maxSz, size_t& at, unsigned arg) { char buf[20] = {}; std::snprintf(buf,sizeof(buf),"%u",arg); implWrite(out, maxSz, at, buf); } void implWrite(char* out, size_t maxSz, size_t& at, size_t arg) { char buf[20] = {}; std::snprintf(buf,sizeof(buf),"%u",uint32_t(arg)); implWrite(out, maxSz, at, buf); } void implWrite(char* out, size_t maxSz, size_t& at, float arg) { char buf[20] = {}; std::snprintf(buf,sizeof(buf),"%f",arg); implWrite(out, maxSz, at, buf); } void implWrite(char* out, size_t maxSz, size_t& at, const void* arg) { char buf[20] = {}; std::snprintf(buf,sizeof(buf),"%p",arg); implWrite(out, maxSz, at, buf); } }; template<size_t sz> bool operator == (const string_frm<sz>& l, std::string_view v) { auto ptr = l.begin(); return v==ptr; } template<size_t sz> bool operator == (std::string_view v, const string_frm<sz>& l) { auto ptr = l.begin(); return v==ptr; }
[ "try9998@gmail.com" ]
try9998@gmail.com
34d00de582c87b028714cabaf85c65de1150a4a4
1afca5d9b6fb6d16921a27c1bdd3ed67ac089c39
/demo-isubd-bs/isubd-bs.cpp
08bd944b35b70014234102d85f37ad467091313c
[ "LicenseRef-scancode-public-domain" ]
permissive
jdupuy/opengl-framework
5191cd334552eec6fe58c1122c83932d0f750323
547aed6affae10f3d86fc3080815bc28de79391f
refs/heads/master
2023-02-21T03:48:41.661679
2023-02-14T14:10:35
2023-02-14T14:10:35
126,613,346
160
25
null
2018-10-08T09:03:36
2018-03-24T15:33:22
C
UTF-8
C++
false
false
40,125
cpp
//////////////////////////////////////////////////////////////////////////////// // Implicit Subdivition for Basis Spline Rendering // #include "glad/glad.h" #include "GLFW/glfw3.h" #include "imgui.h" #include "imgui_impl.h" #include <cstdio> #include <cstdlib> #include <exception> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" #define DJ_OPENGL_IMPLEMENTATION 1 #include "dj_opengl.h" #define DJ_ALGEBRA_IMPLEMENTATION 1 #include "dj_algebra.h" #define DJ_BRDF_IMPLEMENTATION 1 #include "dj_brdf.h" #define LOG(fmt, ...) fprintf(stdout, fmt, ##__VA_ARGS__); fflush(stdout); //////////////////////////////////////////////////////////////////////////////// // Tweakable Constants // //////////////////////////////////////////////////////////////////////////////// #define VIEWER_DEFAULT_WIDTH 1680 #define VIEWER_DEFAULT_HEIGHT 1050 // default path to the directory holding the source files #ifndef PATH_TO_SRC_DIRECTORY # define PATH_TO_SRC_DIRECTORY "./" #endif //////////////////////////////////////////////////////////////////////////////// // Global Variables // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // Framebuffer Manager enum { AA_NONE, AA_MSAA2, AA_MSAA4, AA_MSAA8, AA_MSAA16 }; struct FramebufferManager { int w, h, aa; struct {int fixed;} msaa; struct {float r, g, b;} clearColor; } g_framebuffer = { VIEWER_DEFAULT_WIDTH, VIEWER_DEFAULT_HEIGHT, AA_MSAA2, {false}, {220./255., 220./255., 220./255} }; // ----------------------------------------------------------------------------- // Quadtree Manager struct PatchManager { dja::vec4 vertices[4]; struct {bool uniform, freeze, reset, net;} flags; int gpuSubd, uniformSubd; int pingPong; float primitivePixelLengthTarget; } g_patch = { { {-0.50f, -0.5f, 0, 1}, {-0.25f, 0.5f, 0, 1}, {+0.25f, +0.5f, 0, 1}, {+0.50f, -0.5f, 0, 1} }, {true, false, true, true}, 0, 2, 0, 10.f }; // ----------------------------------------------------------------------------- // Application Manager struct AppManager { struct { const char *shader; const char *output; } dir; struct { int w, h; bool hud; } viewer; struct { int on, frame, capture; } recorder; int frame, frameLimit; } g_app = { /*dir*/ { PATH_TO_SRC_DIRECTORY "./shaders/", PATH_TO_SRC_DIRECTORY "./" }, /*viewer*/ { VIEWER_DEFAULT_WIDTH, VIEWER_DEFAULT_HEIGHT, true }, /*record*/ {false, 0, 0}, /*frame*/ 0, -1 }; // ----------------------------------------------------------------------------- // OpenGL Manager enum { CLOCK_SPF, CLOCK_COUNT }; enum { FRAMEBUFFER_BACK, FRAMEBUFFER_SCENE, FRAMEBUFFER_COUNT }; enum { STREAM_SUBD_COUNTER, STREAM_COUNT }; enum { VERTEXARRAY_EMPTY, VERTEXARRAY_COUNT }; enum { TEXTURE_BACK, TEXTURE_SCENE, TEXTURE_Z, TEXTURE_DMAP, TEXTURE_COUNT }; enum { BUFFER_GEOMETRY_VERTICES = STREAM_COUNT, BUFFER_GEOMETRY_INDEXES, BUFFER_SUBD1, BUFFER_SUBD2, BUFFER_PATCH, BUFFER_COUNT }; enum { PROGRAM_VIEWER, PROGRAM_BS, PROGRAM_BSNET_EDGES, PROGRAM_BSNET_VERTICES, PROGRAM_COUNT }; enum { UNIFORM_VIEWER_FRAMEBUFFER_SAMPLER, UNIFORM_BS_LOD_FACTOR, UNIFORM_COUNT }; struct OpenGLManager { GLuint programs[PROGRAM_COUNT]; GLuint framebuffers[FRAMEBUFFER_COUNT]; GLuint textures[TEXTURE_COUNT]; GLuint vertexArrays[VERTEXARRAY_COUNT]; GLuint buffers[BUFFER_COUNT]; GLint uniforms[UNIFORM_COUNT]; djg_buffer *streams[STREAM_COUNT]; djg_clock *clocks[CLOCK_COUNT]; } g_gl = {{0}}; //////////////////////////////////////////////////////////////////////////////// // Utility functions // //////////////////////////////////////////////////////////////////////////////// #ifndef M_PI #define M_PI 3.141592654 #endif #define BUFFER_SIZE(x) ((int)(sizeof(x)/sizeof(x[0]))) #define BUFFER_OFFSET(i) ((char *)NULL + (i)) float radians(float degrees) { return degrees * M_PI / 180.f; } char *strcat2(char *dst, const char *src1, const char *src2) { strcpy(dst, src1); return strcat(dst, src2); } static void APIENTRY debug_output_logger( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const GLvoid* userParam ) { char srcstr[32], typestr[32]; switch(source) { case GL_DEBUG_SOURCE_API: strcpy(srcstr, "OpenGL"); break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: strcpy(srcstr, "Windows"); break; case GL_DEBUG_SOURCE_SHADER_COMPILER: strcpy(srcstr, "Shader Compiler"); break; case GL_DEBUG_SOURCE_THIRD_PARTY: strcpy(srcstr, "Third Party"); break; case GL_DEBUG_SOURCE_APPLICATION: strcpy(srcstr, "Application"); break; case GL_DEBUG_SOURCE_OTHER: strcpy(srcstr, "Other"); break; default: strcpy(srcstr, "???"); break; }; switch(type) { case GL_DEBUG_TYPE_ERROR: strcpy(typestr, "Error"); break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: strcpy(typestr, "Deprecated Behavior"); break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: strcpy(typestr, "Undefined Behavior"); break; case GL_DEBUG_TYPE_PORTABILITY: strcpy(typestr, "Portability"); break; case GL_DEBUG_TYPE_PERFORMANCE: strcpy(typestr, "Performance"); break; case GL_DEBUG_TYPE_OTHER: strcpy(typestr, "Message"); break; default: strcpy(typestr, "???"); break; } if(severity == GL_DEBUG_SEVERITY_HIGH || severity == GL_DEBUG_SEVERITY_MEDIUM) { LOG("djg_error: %s %s\n" \ "-- Begin -- GL_debug_output\n" \ "%s\n" \ "-- End -- GL_debug_output\n", srcstr, typestr, message); } else if(severity == GL_DEBUG_SEVERITY_MEDIUM) { LOG("djg_warn: %s %s\n" \ "-- Begin -- GL_debug_output\n" \ "%s\n" \ "-- End -- GL_debug_output\n", srcstr, typestr, message); } } void log_debug_output(void) { glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(&debug_output_logger, NULL); } //////////////////////////////////////////////////////////////////////////////// // Program Configuration // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // set viewer program uniforms void configureViewerProgram() { glProgramUniform1i(g_gl.programs[PROGRAM_VIEWER], g_gl.uniforms[UNIFORM_VIEWER_FRAMEBUFFER_SAMPLER], TEXTURE_SCENE); } // ----------------------------------------------------------------------------- // set terrain program uniforms void configureBasisSplineProgram() { // TODO } //////////////////////////////////////////////////////////////////////////////// // Program Loading // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- /** * Load the Viewer Program * * This program is responsible for blitting the scene framebuffer to * the back framebuffer, while applying gamma correction and tone mapping to * the rendering. */ bool loadViewerProgram() { djg_program *djp = djgp_create(); GLuint *program = &g_gl.programs[PROGRAM_VIEWER]; char buf[1024]; LOG("Loading {Viewer-Program}\n"); if (g_framebuffer.aa >= AA_MSAA2 && g_framebuffer.aa <= AA_MSAA16) djgp_push_string(djp, "#define MSAA_FACTOR %i\n", 1 << g_framebuffer.aa); djgp_push_file(djp, strcat2(buf, g_app.dir.shader, "viewer.glsl")); LOG("loading: %s\n", strcat2(buf, g_app.dir.shader, "viewer.glsl")); if (!djgp_to_gl(djp, 450, false, true, program)) { LOG("=> Failure <=\n"); djgp_release(djp); return false; } djgp_release(djp); g_gl.uniforms[UNIFORM_VIEWER_FRAMEBUFFER_SAMPLER] = glGetUniformLocation(g_gl.programs[PROGRAM_VIEWER], "u_FramebufferSampler"); configureViewerProgram(); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load the Catmull Clark Program * * This program renders an adaptive terrain using the implicit subdivision * technique discribed in XXX. */ bool loadBasisSplineProgram() { djg_program *djp = djgp_create(); GLuint *program = &g_gl.programs[PROGRAM_BS]; char buf[1024]; LOG("Loading {BS-Program}\n"); if (g_patch.flags.freeze) djgp_push_string(djp, "#define FLAG_FREEZE 1\n"); if (g_patch.flags.uniform) { djgp_push_string(djp, "#define FLAG_UNIFORM 1\n"); djgp_push_string(djp, "#define UNIFORM_SUBD_FACTOR %i\n", g_patch.uniformSubd); } djgp_push_string(djp, "#define BUFFER_BINDING_PATCH %i\n", BUFFER_PATCH); djgp_push_string(djp, "#define PATCH_TESS_LEVEL %i\n", 1 << g_patch.gpuSubd); djgp_push_string(djp, "#define BUFFER_BINDING_SUBD_COUNTER %i\n", STREAM_SUBD_COUNTER); djgp_push_string(djp, "#define BUFFER_BINDING_SUBD1 %i\n", BUFFER_SUBD1); djgp_push_string(djp, "#define BUFFER_BINDING_SUBD2 %i\n", BUFFER_SUBD2); djgp_push_file(djp, strcat2(buf, g_app.dir.shader, "isubd_bs.glsl")); djgp_push_file(djp, strcat2(buf, g_app.dir.shader, "bs.glsl")); if (!djgp_to_gl(djp, 450, false, true, program)) { LOG("=> Failure <=\n"); djgp_release(djp); return false; } djgp_release(djp); g_gl.uniforms[UNIFORM_BS_LOD_FACTOR] = glGetUniformLocation(g_gl.programs[PROGRAM_BS], "u_LodFactor"); configureBasisSplineProgram(); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load the Catmull Clark Net Program * * This program renders the net of the BS patch using a geometry shader. */ bool loadBasisSplineNetVerticesProgram() { djg_program *djp = djgp_create(); GLuint *program = &g_gl.programs[PROGRAM_BSNET_VERTICES]; char buf[1024]; LOG("Loading {BSNet-Program}\n"); djgp_push_string(djp, "#define SCREEN_XRES %i\n", VIEWER_DEFAULT_WIDTH); djgp_push_string(djp, "#define SCREEN_YRES %i\n", VIEWER_DEFAULT_HEIGHT); djgp_push_string(djp, "#define BUFFER_BINDING_PATCH %i\n", BUFFER_PATCH); djgp_push_file(djp, strcat2(buf, g_app.dir.shader, "bsnet_vertices.glsl")); if (!djgp_to_gl(djp, 450, false, true, program)) { LOG("=> Failure <=\n"); djgp_release(djp); return false; } djgp_release(djp); return (glGetError() == GL_NO_ERROR); } bool loadBasisSplineNetEdgesProgram() { djg_program *djp = djgp_create(); GLuint *program = &g_gl.programs[PROGRAM_BSNET_EDGES]; char buf[1024]; LOG("Loading {BSNet-Program}\n"); djgp_push_string(djp, "#define SCREEN_XRES %i\n", VIEWER_DEFAULT_WIDTH); djgp_push_string(djp, "#define SCREEN_YRES %i\n", VIEWER_DEFAULT_HEIGHT); djgp_push_string(djp, "#define BUFFER_BINDING_PATCH %i\n", BUFFER_PATCH); djgp_push_file(djp, strcat2(buf, g_app.dir.shader, "bsnet_edges.glsl")); if (!djgp_to_gl(djp, 450, false, true, program)) { LOG("=> Failure <=\n"); djgp_release(djp); return false; } djgp_release(djp); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load All Programs * */ bool loadPrograms() { bool v = true; if (v) v&= loadViewerProgram(); if (v) v&= loadBasisSplineProgram(); if (v) v&= loadBasisSplineNetEdgesProgram(); if (v) v&= loadBasisSplineNetVerticesProgram(); return v; } //////////////////////////////////////////////////////////////////////////////// // Texture Loading // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- /** * Load the Scene Framebuffer Textures * * Depending on the scene framebuffer AA mode, this function load 2 or * 3 textures. In FSAA mode, two RGBA16F and one DEPTH24_STENCIL8 textures * are created. In other modes, one RGBA16F and one DEPTH24_STENCIL8 textures * are created. */ bool loadSceneFramebufferTexture() { if (glIsTexture(g_gl.textures[TEXTURE_SCENE])) glDeleteTextures(1, &g_gl.textures[TEXTURE_SCENE]); if (glIsTexture(g_gl.textures[TEXTURE_Z])) glDeleteTextures(1, &g_gl.textures[TEXTURE_Z]); glGenTextures(1, &g_gl.textures[TEXTURE_Z]); glGenTextures(1, &g_gl.textures[TEXTURE_SCENE]); switch (g_framebuffer.aa) { case AA_NONE: LOG("Loading {Scene-Z-Framebuffer-Texture}\n"); glActiveTexture(GL_TEXTURE0 + TEXTURE_Z); glBindTexture(GL_TEXTURE_2D, g_gl.textures[TEXTURE_Z]); glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH24_STENCIL8, g_framebuffer.w, g_framebuffer.h); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); LOG("Loading {Scene-RGBA-Framebuffer-Texture}\n"); glActiveTexture(GL_TEXTURE0 + TEXTURE_SCENE); glBindTexture(GL_TEXTURE_2D, g_gl.textures[TEXTURE_SCENE]); glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA32F, g_framebuffer.w, g_framebuffer.h); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); break; case AA_MSAA2: case AA_MSAA4: case AA_MSAA8: case AA_MSAA16: { int samples = 1 << g_framebuffer.aa; int maxSamples; glGetIntegerv(GL_MAX_INTEGER_SAMPLES, &maxSamples); if (samples > maxSamples) { LOG("note: MSAA is %ix\n", maxSamples); samples = maxSamples; } LOG("Loading {Scene-MSAA-Z-Framebuffer-Texture}\n"); glActiveTexture(GL_TEXTURE0 + TEXTURE_Z); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, g_gl.textures[TEXTURE_Z]); glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_DEPTH24_STENCIL8, g_framebuffer.w, g_framebuffer.h, g_framebuffer.msaa.fixed); LOG("Loading {Scene-MSAA-RGBA-Framebuffer-Texture}\n"); glActiveTexture(GL_TEXTURE0 + TEXTURE_SCENE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, g_gl.textures[TEXTURE_SCENE]); glTexStorage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA32F, g_framebuffer.w, g_framebuffer.h, g_framebuffer.msaa.fixed); } break; } glActiveTexture(GL_TEXTURE0); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load the Back Framebuffer Texture * * This loads an RGBA8 texture used as a color buffer for the back * framebuffer. */ bool loadBackFramebufferTexture() { LOG("Loading {Back-Framebuffer-Texture}\n"); if (glIsTexture(g_gl.textures[TEXTURE_BACK])) glDeleteTextures(1, &g_gl.textures[TEXTURE_BACK]); glGenTextures(1, &g_gl.textures[TEXTURE_BACK]); glActiveTexture(GL_TEXTURE0 + TEXTURE_BACK); glBindTexture(GL_TEXTURE_2D, g_gl.textures[TEXTURE_BACK]); glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, g_app.viewer.w, g_app.viewer.h); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glActiveTexture(GL_TEXTURE0); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load All Textures */ bool loadTextures() { bool v = true; if (v) v&= loadSceneFramebufferTexture(); if (v) v&= loadBackFramebufferTexture(); return v; } //////////////////////////////////////////////////////////////////////////////// // Buffer Loading // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- /** * Load the Geometry Buffer * * This procedure loads the scene geometry into an index and * vertex buffer. Here, we only load 2 triangles to define the * terrain. */ bool loadPatchBuffer() { LOG("Loading {Patch-Vertex-Buffer}\n"); if (glIsBuffer(g_gl.buffers[BUFFER_PATCH])) glDeleteBuffers(1, &g_gl.buffers[BUFFER_PATCH]); glGenBuffers(1, &g_gl.buffers[BUFFER_PATCH]); glBindBuffer(GL_ARRAY_BUFFER, g_gl.buffers[BUFFER_PATCH]); glBufferData(GL_ARRAY_BUFFER, sizeof(g_patch.vertices), (const void*)g_patch.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BUFFER_PATCH, g_gl.buffers[BUFFER_PATCH]); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load the Subdivision Buffers * * This procedure allocates and initialises the subdivision buffers. * We allocate 256 MBytes of memory to store the data. */ void loadSubdBuffer(int id, size_t bufferCapacity) { const uint32_t data[] = {0, 1}; if (glIsBuffer(g_gl.buffers[id])) glDeleteBuffers(1, &g_gl.buffers[id]); glGenBuffers(1, &g_gl.buffers[id]); glBindBuffer(GL_SHADER_STORAGE_BUFFER, g_gl.buffers[id]); glBufferData(GL_SHADER_STORAGE_BUFFER, bufferCapacity, NULL, GL_STATIC_DRAW); glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(data), (const GLvoid *)data); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, id, g_gl.buffers[id]); } bool loadSubdivisionBuffers() { LOG("Loading {Subd-Buffer}\n"); const size_t bufferCapacity = 1 << 28; loadSubdBuffer(BUFFER_SUBD1, bufferCapacity); loadSubdBuffer(BUFFER_SUBD2, bufferCapacity); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load Subd Counter Buffer * * This procedure creates a buffer that stores indirect drawing commands. */ bool loadSubdCounterBuffer(int *bufferOffset = NULL) { static bool first = true; struct DrawArraysIndirect { uint32_t count, primCount, first, baseInstance; } drawCmd = {0, 1, 0, 0}; if (first) { g_gl.streams[STREAM_SUBD_COUNTER] = djgb_create(sizeof(drawCmd)); first = false; } // upload to GPU djgb_to_gl(g_gl.streams[STREAM_SUBD_COUNTER], (const void *)&drawCmd, bufferOffset); djgb_glbindrange(g_gl.streams[STREAM_SUBD_COUNTER], GL_ATOMIC_COUNTER_BUFFER, STREAM_SUBD_COUNTER); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load All Buffers * */ bool loadBuffers() { bool v = true; if (v) v&= loadPatchBuffer(); if (v) v&= loadSubdivisionBuffers(); if (v) v&= loadSubdCounterBuffer(); return v; } //////////////////////////////////////////////////////////////////////////////// // Vertex Array Loading // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- /** * Load an Empty Vertex Array * * This will be used to draw procedural geometry, e.g., a fullscreen quad. */ bool loadEmptyVertexArray() { LOG("Loading {Empty-VertexArray}\n"); if (glIsVertexArray(g_gl.vertexArrays[VERTEXARRAY_EMPTY])) glDeleteVertexArrays(1, &g_gl.vertexArrays[VERTEXARRAY_EMPTY]); glGenVertexArrays(1, &g_gl.vertexArrays[VERTEXARRAY_EMPTY]); glBindVertexArray(g_gl.vertexArrays[VERTEXARRAY_EMPTY]); glBindVertexArray(0); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load All Vertex Arrays * */ bool loadVertexArrays() { bool v = true; if (v) v&= loadEmptyVertexArray(); return v; } //////////////////////////////////////////////////////////////////////////////// // Framebuffer Loading // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- /** * Load the Back Framebuffer * * This framebuffer contains the final image. It will be blitted to the * OpenGL window's backbuffer. */ bool loadBackFramebuffer() { LOG("Loading {Back-Framebuffer}\n"); if (glIsFramebuffer(g_gl.framebuffers[FRAMEBUFFER_BACK])) glDeleteFramebuffers(1, &g_gl.framebuffers[FRAMEBUFFER_BACK]); glGenFramebuffers(1, &g_gl.framebuffers[FRAMEBUFFER_BACK]); glBindFramebuffer(GL_FRAMEBUFFER, g_gl.framebuffers[FRAMEBUFFER_BACK]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_gl.textures[TEXTURE_BACK], 0); glDrawBuffer(GL_COLOR_ATTACHMENT0); if (GL_FRAMEBUFFER_COMPLETE != glCheckFramebufferStatus(GL_FRAMEBUFFER)) { LOG("=> Failure <=\n"); return false; } glBindFramebuffer(GL_FRAMEBUFFER, 0); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load the Scene Framebuffer * * This framebuffer is used to draw the 3D scene. * A single framebuffer is created, holding a color and Z buffer. * The scene writes directly to it. */ bool loadSceneFramebuffer() { LOG("Loading {Scene-Framebuffer}\n"); if (glIsFramebuffer(g_gl.framebuffers[FRAMEBUFFER_SCENE])) glDeleteFramebuffers(1, &g_gl.framebuffers[FRAMEBUFFER_SCENE]); glGenFramebuffers(1, &g_gl.framebuffers[FRAMEBUFFER_SCENE]); glBindFramebuffer(GL_FRAMEBUFFER, g_gl.framebuffers[FRAMEBUFFER_SCENE]); if (g_framebuffer.aa >= AA_MSAA2 && g_framebuffer.aa <= AA_MSAA16) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, g_gl.textures[TEXTURE_SCENE], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, g_gl.textures[TEXTURE_Z], 0); } else { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_gl.textures[TEXTURE_SCENE], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, g_gl.textures[TEXTURE_Z], 0); } glDrawBuffer(GL_COLOR_ATTACHMENT0); if (GL_FRAMEBUFFER_COMPLETE != glCheckFramebufferStatus(GL_FRAMEBUFFER)) { LOG("=> Failure <=\n"); return false; } glBindFramebuffer(GL_FRAMEBUFFER, 0); return (glGetError() == GL_NO_ERROR); } // ----------------------------------------------------------------------------- /** * Load All Framebuffers * */ bool loadFramebuffers() { bool v = true; if (v) v&= loadBackFramebuffer(); if (v) v&= loadSceneFramebuffer(); return v; } //////////////////////////////////////////////////////////////////////////////// // OpenGL Resource Loading // //////////////////////////////////////////////////////////////////////////////// void init() { bool v = true; int i; for (i = 0; i < CLOCK_COUNT; ++i) { if (g_gl.clocks[i]) djgc_release(g_gl.clocks[i]); g_gl.clocks[i] = djgc_create(); } if (v) v&= loadTextures(); if (v) v&= loadBuffers(); if (v) v&= loadFramebuffers(); if (v) v&= loadVertexArrays(); if (v) v&= loadPrograms(); if (!v) throw std::exception(); } void release() { int i; for (i = 0; i < CLOCK_COUNT; ++i) if (g_gl.clocks[i]) djgc_release(g_gl.clocks[i]); for (i = 0; i < STREAM_COUNT; ++i) if (g_gl.streams[i]) djgb_release(g_gl.streams[i]); for (i = 0; i < PROGRAM_COUNT; ++i) if (glIsProgram(g_gl.programs[i])) glDeleteProgram(g_gl.programs[i]); for (i = 0; i < TEXTURE_COUNT; ++i) if (glIsTexture(g_gl.textures[i])) glDeleteTextures(1, &g_gl.textures[i]); for (i = 0; i < BUFFER_COUNT; ++i) if (glIsBuffer(g_gl.buffers[i])) glDeleteBuffers(1, &g_gl.buffers[i]); for (i = 0; i < FRAMEBUFFER_COUNT; ++i) if (glIsFramebuffer(g_gl.framebuffers[i])) glDeleteFramebuffers(1, &g_gl.framebuffers[i]); for (i = 0; i < VERTEXARRAY_COUNT; ++i) if (glIsVertexArray(g_gl.vertexArrays[i])) glDeleteVertexArrays(1, &g_gl.vertexArrays[i]); } //////////////////////////////////////////////////////////////////////////////// // OpenGL Rendering // //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- void renderSceneTs(int offset) { // render terrain if (g_patch.flags.reset) { loadSubdivisionBuffers(); g_patch.pingPong = 0; glDrawArrays(GL_PATCHES, 0, 1); g_patch.flags.reset = false; } else { glMemoryBarrier(GL_ATOMIC_COUNTER_BARRIER_BIT); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BUFFER_SUBD1, g_gl.buffers[BUFFER_SUBD1 + 1 - g_patch.pingPong]); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, BUFFER_SUBD2, g_gl.buffers[BUFFER_SUBD1 + g_patch.pingPong]); glDrawArraysIndirect(GL_PATCHES, BUFFER_OFFSET(offset)); g_patch.pingPong = 1 - g_patch.pingPong; } } // ----------------------------------------------------------------------------- void renderScene() { static int offset = 0; int nextOffset = 0; // configure GL state glLineWidth(5.f); glBindFramebuffer(GL_FRAMEBUFFER, g_gl.framebuffers[FRAMEBUFFER_SCENE]); glViewport(0, 0, g_framebuffer.w, g_framebuffer.h); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glPatchParameteri(GL_PATCH_VERTICES, 1); // clear framebuffer glClearColor(g_framebuffer.clearColor.r, g_framebuffer.clearColor.g, g_framebuffer.clearColor.b, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // bind buffers djgb_glbind(g_gl.streams[STREAM_SUBD_COUNTER], GL_DRAW_INDIRECT_BUFFER); loadSubdCounterBuffer(&nextOffset); glUseProgram(g_gl.programs[PROGRAM_BS]); glBindVertexArray(g_gl.vertexArrays[VERTEXARRAY_EMPTY]); // render spline renderSceneTs(offset); offset = nextOffset; // render the BS net if (g_patch.flags.net) { glUseProgram(g_gl.programs[PROGRAM_BSNET_EDGES]); glDrawArrays(GL_POINTS, 0, BUFFER_SIZE(g_patch.vertices)); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(g_gl.programs[PROGRAM_BSNET_VERTICES]); glDrawArrays(GL_POINTS, 0, BUFFER_SIZE(g_patch.vertices)); glDisable(GL_BLEND); } // reset GL state glLineWidth(1.f); glDisable(GL_DEPTH_TEST); } // ----------------------------------------------------------------------------- /** * Blit the Scene Framebuffer and draw GUI * * This drawing pass blits the scene framebuffer with possible magnification * and renders the HUD and TweakBar. */ void imguiSetAa() { if (!loadSceneFramebufferTexture() || !loadSceneFramebuffer() || !loadViewerProgram()) { LOG("=> Framebuffer config failed <=\n"); throw std::exception(); } } void renderGui(double cpuDt, double gpuDt) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, g_gl.framebuffers[FRAMEBUFFER_BACK]); glBindFramebuffer(GL_READ_FRAMEBUFFER, g_gl.framebuffers[FRAMEBUFFER_SCENE]); glViewport(0, 0, g_app.viewer.w, g_app.viewer.h); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); // post process the scene framebuffer glUseProgram(g_gl.programs[PROGRAM_VIEWER]); glBindVertexArray(g_gl.vertexArrays[VERTEXARRAY_EMPTY]); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // draw HUD if (g_app.viewer.hud) { // ImGui ImGui_ImplGlfwGL3_NewFrame(); // Viewer Widgets ImGui::SetNextWindowPos(ImVec2(400, 10)/*, ImGuiSetCond_FirstUseEver*/); ImGui::SetNextWindowSize(ImVec2(250, 120)/*, ImGuiSetCond_FirstUseEver*/); ImGui::Begin("Framebuffer"); { const char* aaItems[] = { "None", "MSAA x2", "MSAA x4", "MSAA x8", "MSAA x16" }; if (ImGui::Combo("AA", &g_framebuffer.aa, aaItems, BUFFER_SIZE(aaItems))) imguiSetAa(); if (ImGui::Combo("MSAA", &g_framebuffer.msaa.fixed, "Fixed\0Random\0\0")) imguiSetAa(); if (ImGui::Button("Screenshot")) { static int cnt = 0; char buf[1024]; snprintf(buf, 1024, "screenshot%03i", cnt); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); djgt_save_glcolorbuffer_png(GL_FRONT, GL_RGBA, buf); ++cnt; } ImGui::SameLine(); if (ImGui::Button("Record")) g_app.recorder.on = !g_app.recorder.on; if (g_app.recorder.on) { ImGui::SameLine(); ImGui::Text("Recording..."); } } ImGui::End(); #if 0 // Framebuffer Widgets ImGui::SetNextWindowPos(ImVec2(530, 10)/*, ImGuiSetCond_FirstUseEver*/); ImGui::SetNextWindowSize(ImVec2(250, 120)/*, ImGuiSetCond_FirstUseEver*/); ImGui::Begin("Viewer"); { if (ImGui::SliderFloat("Exposure", &g_app.viewer.exposure, -3.0f, 3.0f)) configureViewerProgram(); if (ImGui::SliderFloat("Gamma", &g_app.viewer.gamma, 1.0f, 4.0f)) configureViewerProgram(); } ImGui::End(); #endif // Subd Patch Widgets ImGui::SetNextWindowPos(ImVec2(10, 10)/*, ImGuiSetCond_FirstUseEver*/); ImGui::SetNextWindowSize(ImVec2(380, 120)/*, ImGuiSetCond_FirstUseEver*/); ImGui::Begin("Patch"); { ImGui::Text("CPU_dt: %.3f %s", cpuDt < 1. ? cpuDt * 1e3 : cpuDt, cpuDt < 1. ? "ms" : " s"); ImGui::SameLine(); ImGui::Text("GPU_dt: %.3f %s", gpuDt < 1. ? gpuDt * 1e3 : gpuDt, gpuDt < 1. ? "ms" : " s"); ImGui::Text("flags: "); ImGui::SameLine(); if (ImGui::Checkbox("uniform", &g_patch.flags.uniform)) loadBasisSplineProgram(); ImGui::SameLine(); if (ImGui::Checkbox("freeze", &g_patch.flags.freeze)) loadBasisSplineProgram(); ImGui::SameLine(); ImGui::Checkbox("net", &g_patch.flags.net); if (ImGui::SliderInt("PatchSubdLevel", &g_patch.gpuSubd, 0, 6)) { loadBasisSplineProgram(); g_patch.flags.reset = true; } if (g_patch.flags.uniform) { if (ImGui::SliderInt("SubdLevel", &g_patch.uniformSubd, 0, 15)) { loadBasisSplineProgram(); } } else { if (ImGui::SliderFloat("ScreenRes", &g_patch.primitivePixelLengthTarget, 1, 64)) { configureBasisSplineProgram(); } } #if 0 ImGui::Text("control patch vertices:"); for (int i = 0; i < BUFFER_SIZE(g_patch.vertices); ++i) { char name[64]; sprintf(name, "v%02i", i); if (ImGui::SliderFloat2(name, &(g_patch.vertices[i].x), -4.0f, 4.0f)) { loadPatchBuffer(); } } #endif } ImGui::End(); ImGui::Render(); ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData()); } // screen recording if (g_app.recorder.on) { char name[64], path[1024]; glBindFramebuffer(GL_READ_FRAMEBUFFER, g_gl.framebuffers[FRAMEBUFFER_BACK]); sprintf(name, "capture_%02i_%09i", g_app.recorder.capture, g_app.recorder.frame); strcat2(path, g_app.dir.output, name); djgt_save_glcolorbuffer_bmp(GL_COLOR_ATTACHMENT0, GL_RGB, path); ++g_app.recorder.frame; } // restore state glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); } // ----------------------------------------------------------------------------- /** * Blit the Composited Framebuffer to the Window Backbuffer * * Final drawing step: the composited framebuffer is blitted to the * OpenGL window backbuffer */ void renderBack() { glBindFramebuffer(GL_READ_FRAMEBUFFER, g_gl.framebuffers[FRAMEBUFFER_BACK]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); // blit scene framebuffer glBlitFramebuffer(0, 0, g_app.viewer.w, g_app.viewer.h, 0, 0, g_app.viewer.w, g_app.viewer.h, GL_COLOR_BUFFER_BIT, GL_NEAREST); } // ----------------------------------------------------------------------------- /** * Render Everything * */ void render() { double cpuDt, gpuDt; djgc_start(g_gl.clocks[CLOCK_SPF]); renderScene(); djgc_stop(g_gl.clocks[CLOCK_SPF]); djgc_ticks(g_gl.clocks[CLOCK_SPF], &cpuDt, &gpuDt); renderGui(cpuDt, gpuDt); renderBack(); ++g_app.frame; } //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- int vertexTest(float x, float y) { dja::vec2 res = dja::vec2(VIEWER_DEFAULT_WIDTH, VIEWER_DEFAULT_HEIGHT); dja::vec2 ndc = 2.0f * dja::vec2(x, VIEWER_DEFAULT_HEIGHT - y) / res - dja::vec2(1.0f); int idx = -1; for (int i = 0; i < BUFFER_SIZE(g_patch.vertices) && idx == -1; ++i) { dja::vec4 p4 = g_patch.vertices[i]; dja::vec2 p2 = dja::vec2(p4.x, p4.y); float nrm = dja::norm(p2 - ndc); if (nrm < 32.f / res.x) idx = i; } return idx; } // ----------------------------------------------------------------------------- void keyboardCallback( GLFWwindow* window, int key, int, int action, int ) { ImGuiIO& io = ImGui::GetIO(); if (io.WantCaptureKeyboard) return; if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: //glfwSetWindowShouldClose(window, GL_TRUE); g_app.viewer.hud = !g_app.viewer.hud; break; case GLFW_KEY_R: loadPrograms(); g_patch.flags.reset = true; break; default: break; } } } void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { ImGuiIO& io = ImGui::GetIO(); if (io.WantCaptureMouse) return; } void mouseMotionCallback(GLFWwindow* window, double x, double y) { static double x0 = 0, y0 = 0; double dx = x - x0, dy = y - y0; ImGuiIO& io = ImGui::GetIO(); if (io.WantCaptureMouse) return; if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { int i = vertexTest(x, y); if (i != -1) { dja::vec2 res = dja::vec2(VIEWER_DEFAULT_WIDTH, VIEWER_DEFAULT_HEIGHT); dja::vec2 ndc = 2.0f * dja::vec2(x, VIEWER_DEFAULT_HEIGHT - y) / res - dja::vec2(1.0f); g_patch.vertices[i].x = ndc.x; g_patch.vertices[i].y = ndc.y; loadPatchBuffer(); } } else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) { } x0 = x; y0 = y; } void mouseScrollCallback(GLFWwindow* window, double xoffset, double yoffset) { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplGlfw_ScrollCallback(window, xoffset, yoffset); if (io.WantCaptureMouse) return; } void usage(const char *app) { printf("%s -- OpenGL Terrain Renderer\n", app); printf("usage: %s --shader-dir path_to_shader_dir\n", app); } // ----------------------------------------------------------------------------- int main(int argc, char **argv) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); // Create the Window LOG("Loading {Window-Main}\n"); GLFWwindow* window = glfwCreateWindow( VIEWER_DEFAULT_WIDTH, VIEWER_DEFAULT_HEIGHT, "Implicit GPU Subdivision Demo", NULL, NULL ); if (window == NULL) { LOG("=> Failure <=\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, &keyboardCallback); glfwSetCursorPosCallback(window, &mouseMotionCallback); glfwSetMouseButtonCallback(window, &mouseButtonCallback); glfwSetScrollCallback(window, &mouseScrollCallback); // Load OpenGL functions LOG("Loading {OpenGL}\n"); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { LOG("gladLoadGLLoader failed\n"); return -1; } LOG("-- Begin -- Demo\n"); try { log_debug_output(); ImGui::CreateContext(); ImGui_ImplGlfwGL3_Init(window, false); ImGui::StyleColorsDark(); init(); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); render(); glfwSwapBuffers(window); } release(); ImGui_ImplGlfwGL3_Shutdown(); ImGui::DestroyContext(); glfwTerminate(); } catch (std::exception& e) { LOG("%s", e.what()); ImGui_ImplGlfwGL3_Shutdown(); ImGui::DestroyContext(); glfwTerminate(); LOG("(!) Demo Killed (!)\n"); return EXIT_FAILURE; } catch (...) { ImGui_ImplGlfwGL3_Shutdown(); ImGui::DestroyContext(); glfwTerminate(); LOG("(!) Demo Killed (!)\n"); return EXIT_FAILURE; } LOG("-- End -- Demo\n"); return 0; }
[ "etu.jdupuy@gmail.com" ]
etu.jdupuy@gmail.com
fa2ab16e1f498eb3639ed017da4d28d63522bd2c
1044ec02e6bf2a53f2ad687c8fe5a73cae66612a
/cpp/safeArray/main.cpp
93754d562a0b1c7689e5f780067ee39e75713226
[]
no_license
rnjsxn/C_Language
aa5cc2ddfcbfd80757f55011da4918068cd64af5
c2bad00fdbce760afd15d188367c47a29c727291
refs/heads/master
2023-04-12T09:07:43.601205
2021-05-12T11:38:23
2021-05-12T11:38:23
365,967,347
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
#include <iostream> #include "safeArray.h" int main() { SafeArray arr1; SafeArray arr2(10); int nums[]={1,2,3,4,5}; SafeArray arr3(nums,5); SafeArray arr4(arr3); arr1=arr3; if(arr1==arr3) std::cout<<"arr1 and arr3 are equal"<<std::endl; else std::cout<<"arr1 and arr3 are not equal"<<std::endl; Array arr5(nums,5); for(int i=0;i<=arr5.size();i++) std::cout<<arr5[i]<<std::endl; //arr5=Array type //for(int i=0;i<=arr1.size();i++) // std::cout<<arr1[i]<<std::endl; //arr1=SafeArray type Array *pArr= new SafeArray(nums,5); (*pArr)[5]=5; //(*pArr).operator[](5) or pArr->operator[](5) delete pArr; return 0; }
[ "kp1180@naver.com" ]
kp1180@naver.com
73b6c6fb4155f6db91e5b7692120a657e21e53a9
b3961d7b0b87ca5975070e889f93bc5b7510c777
/client/sources/main.cpp
2e0f33834fdb863cdc6a797e0e202cf7ee2ddf7b
[]
no_license
DanielThurau/Simple-RuleBase-Inference-Engine
b97f3736b1522b02b35c464d37418cf2d6608fd3
54de7bf17a7ca1ac6626e418219c631d214cb7f2
refs/heads/master
2021-01-20T00:11:40.510312
2018-07-12T00:04:42
2018-07-12T00:04:42
81,189,763
0
0
null
null
null
null
UTF-8
C++
false
false
492
cpp
#include "../headers/common.h" #include "../headers/Interface.h" int main(int argc, char *argv[]){ Interface * ourSRI; if(argc == 1){ ourSRI = new Interface(); }else if(argc == 2){ // create a command for load of the file passed and execute ourSRI = new Interface(); std::string arg(argv[1]); std::string command = "LOAD " + arg; ourSRI->commandLine(command); }else{ std::cout << "Usages: ./SRI [path_to_file]\n"; return 1; } ourSRI -> commandLine(); return 0; }
[ "Daniel.N.Thurau@gmail.com" ]
Daniel.N.Thurau@gmail.com
5fd62342764fe64b24a1ea7771548335850edd5f
d84967ba1e6adc72e120f84524c51ad57912df5a
/devel/electron8/files/patch-chrome_browser_policy_policy__prefs__browsertest.cc
8d21dd83905d3bb955bb1accdd048f37f1abf5f3
[]
no_license
tagattie/FreeBSD-Electron
f191d03c067d03ad3007e7748de905da06ba67f9
af26f766e772bb04db5eb95148ee071101301e4e
refs/heads/master
2023-09-04T10:56:17.446818
2023-09-04T09:03:11
2023-09-04T09:03:11
176,520,396
73
9
null
2023-08-31T03:29:16
2019-03-19T13:41:20
C++
UTF-8
C++
false
false
387
cc
--- chrome/browser/policy/policy_prefs_browsertest.cc.orig 2020-03-03 07:02:30 UTC +++ chrome/browser/policy/policy_prefs_browsertest.cc @@ -250,6 +250,8 @@ class PolicyTestCase { const std::string os("chromeos"); #elif defined(OS_LINUX) const std::string os("linux"); +#elif defined(OS_FREEBSD) + const std::string os("freebsd"); #else #error "Unknown platform" #endif
[ "tagattie@gmail.com" ]
tagattie@gmail.com
8e95f9b7f21c5551e05f2b015efc70513877da5a
3f7a046813c59ca4367ff4c9337ec861ad5b0563
/JointProject1 - Aoife Powders/JointProject1 - Aoife Powders/Player.cpp
61582caf31c76c1e65a156d1a14fe7a67328ddf6
[]
no_license
Aoife-Powders/JointProject-1stYear
57731e936fda85322fe8d1a6ee30c600babb9a49
98246b56476a084aa3885335051aaa71e7287e43
refs/heads/master
2020-03-29T07:20:37.588940
2018-09-20T19:43:08
2018-09-20T19:43:08
149,661,460
0
0
null
null
null
null
UTF-8
C++
false
false
1,651
cpp
#include "Player.h" //gives values to variables Player::Player() : playerWidth{100} ,playerHeight{20} ,playerPosition{ 450,550 } ,playerX{ playerPosition.x } ,playerY{ playerPosition.y } ,playerSpeed(5.0f) { //creates player m_playerBody.setFillColor(sf::Color::White); m_playerBody.setPosition(playerPosition); m_playerBody.setSize(size); } //moves player up void Player::playerMovementUp() { playerY = playerY - playerSpeed; m_playerBody.setPosition(playerX, playerY); } //moves player down void Player::playerMovementDown() { playerY = playerY + playerSpeed; m_playerBody.setPosition(playerX, playerY); } //moves player right void Player::playerMovementRight() { playerX = playerX + playerSpeed; m_playerBody.setPosition(playerX, playerY); } //moes player left void Player::playerMovementLeft() { playerX = playerX - playerSpeed; m_playerBody.setPosition(playerX, playerY); } //if player moves outside the screen it wraps around to the other side void Player::playerBoundaryRight() { if (playerX >= 1000) { playerX = 10; m_playerBody.setPosition(playerX, playerY); } } void Player::playerBoundaryLeft() { if (playerX <= 0) { playerX = 1000; m_playerBody.setPosition(playerX, playerY); } } void Player::playerBoundaryUp() { if (playerY <= 0) { playerY = 600; m_playerBody.setPosition(playerX, playerY); } } void Player::playerBoundaryDown() { if (playerY >= 600) { playerY = 10; m_playerBody.setPosition(playerX, playerY); } } //resets player when a collision takes place void Player::playerEnemyCollision() { playerX = 450; playerY = 550; m_playerBody.setPosition(playerX, playerY); }
[ "c00218374@itcarlow.ie" ]
c00218374@itcarlow.ie
ee152724d0571de35e7d5567ed45029c5b920180
ce1e8b29ffd9d97ffc5c693fe3bd4ee358b5e1d5
/src/VoxieClient/ObjectExport/ClientManager.cpp
5315b95a30b17d19d28793edc3310c57b9c96b6a
[ "MIT" ]
permissive
voxie-viewer/voxie
d76fe7d3990b14dea34e654378d82ddeb48f6445
2b4f23116ab1c2fd44b134c4265a59987049dcdb
refs/heads/master
2023-04-14T13:30:18.668070
2023-04-04T10:58:24
2023-04-04T10:58:24
60,341,017
6
1
MIT
2022-11-29T06:52:16
2016-06-03T10:50:54
C++
UTF-8
C++
false
false
4,141
cpp
/* * Copyright (c) 2014-2022 The Voxie Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "ClientManager.hpp" #include <VoxieClient/ObjectExport/BusManager.hpp> #include <VoxieClient/ObjectExport/Client.hpp> using namespace vx; class ClientManagerAdaptorImpl : public ClientManagerAdaptor { Q_OBJECT ClientManager* object; public: ClientManagerAdaptorImpl(ClientManager* object) : ClientManagerAdaptor(object), object(object) {} ~ClientManagerAdaptorImpl() {} QDBusObjectPath CreateClient( const QMap<QString, QDBusVariant>& options) override; QDBusObjectPath CreateIndependentClient( const QMap<QString, QDBusVariant>& options) override; void DestroyClient(const QDBusObjectPath& client, const QMap<QString, QDBusVariant>& options) override; }; QDBusObjectPath ClientManagerAdaptorImpl::CreateClient( const QMap<QString, QDBusVariant>& options) { try { ExportedObject::checkOptions(options); if (!object->calledFromDBus()) { throw vx::Exception("de.uni_stuttgart.Voxie.InternalError", "ClientManagerAdaptorImpl::CreateClient() called " "from non-DBus context"); } auto connection = getBusManager()->findConnection(object->connection()); QString name = object->message().service(); if (connection->isBus()) { if (name == "") throw vx::Exception("de.uni_stuttgart.Voxie.InternalError", "Got empty service name on bus connection"); } else { if (name != "") qWarning() << "Got non-empty service name for connection" << connection->connectionName() << ":" << name; } Client* client = new Client(this, name, connection); return ExportedObject::getPath(client); } catch (Exception& e) { e.handle(object); return ExportedObject::getPath(nullptr); } } QDBusObjectPath ClientManagerAdaptorImpl::CreateIndependentClient( const QMap<QString, QDBusVariant>& options) { try { ExportedObject::checkOptions(options); auto connection = getBusManager()->findConnection(object->connection()); Client* client = new Client(this, "", connection); return ExportedObject::getPath(client); } catch (Exception& e) { e.handle(object); return ExportedObject::getPath(nullptr); } } void ClientManagerAdaptorImpl::DestroyClient( const QDBusObjectPath& client, const QMap<QString, QDBusVariant>& options) { try { ExportedObject::checkOptions(options); Client* clientPtr = qobject_cast<Client*>(ExportedObject::lookupWeakObject(client)); if (!clientPtr) { throw Exception("de.uni_stuttgart.Voxie.ClientNotFound", "The client cannot be found, might be already destroyed"); } delete clientPtr; return; } catch (Exception& e) { e.handle(object); return; } } ClientManager::ClientManager() : ExportedObject("ClientManager", nullptr, true) { new ClientManagerAdaptorImpl(this); } ClientManager::~ClientManager() {} #include "ClientManager.moc"
[ "steffen.kiess@cis.iti.uni-stuttgart.de" ]
steffen.kiess@cis.iti.uni-stuttgart.de
fff5b0aee24c45b15643760d75b9141d50b8355b
932575acb68a8308f62e651d8eb04378f3085b5d
/C++_Test0907/C++_Test0907/seqlish.h
3166224b08d362d3c806fb90a7f9cb19a1f61b8b
[]
no_license
adong001/C-DS-CPP
308b54ab4e3061461074dc0b592591e743558942
2df3b1a61adb4bfc28cc421b2fd475af1ffd40d3
refs/heads/master
2023-01-21T05:09:07.463759
2020-11-15T01:38:47
2020-11-15T01:38:47
191,345,672
2
1
null
null
null
null
UTF-8
C++
false
false
119
h
#pragma once #include<iostream> using namespace std; template<class T> class SeqList { T *m_data; size_t m_size; }
[ "1792095378@qq.com" ]
1792095378@qq.com
ab37499fa30fab627486a5798c9e2bb0e7bd86db
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/ISA2+pooncerelease+fencembonceonce+poacquireacquire.c.cbmc.cpp
704a973a2eeb7102d939304d41fd3976d15502a1
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
43,716
cpp
// Global variabls: // 0:vars:3 // 3:atom_1_X0_1:1 // 4:atom_2_X0_1:1 // 5:atom_2_X2_0:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 #define ADDRSIZE 6 #define LOCALADDRSIZE 3 #define NTHREAD 4 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); co(4,0) = 0; delta(4,0) = -1; mem(4,1) = meminit(4,1); co(4,1) = coinit(4,1); delta(4,1) = deltainit(4,1); mem(4,2) = meminit(4,2); co(4,2) = coinit(4,2); delta(4,2) = deltainit(4,2); mem(4,3) = meminit(4,3); co(4,3) = coinit(4,3); delta(4,3) = deltainit(4,3); mem(4,4) = meminit(4,4); co(4,4) = coinit(4,4); delta(4,4) = deltainit(4,4); co(5,0) = 0; delta(5,0) = -1; mem(5,1) = meminit(5,1); co(5,1) = coinit(5,1); delta(5,1) = deltainit(5,1); mem(5,2) = meminit(5,2); co(5,2) = coinit(5,2); delta(5,2) = deltainit(5,2); mem(5,3) = meminit(5,3); co(5,3) = coinit(5,3); delta(5,3) = deltainit(5,3); mem(5,4) = meminit(5,4); co(5,4) = coinit(5,4); delta(5,4) = deltainit(5,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !38, metadata !DIExpression()), !dbg !47 // br label %label_1, !dbg !48 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !46), !dbg !49 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !39, metadata !DIExpression()), !dbg !50 // call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !50 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !51 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l21_c3 old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l21_c3 // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !43, metadata !DIExpression()), !dbg !52 // call void @llvm.dbg.value(metadata i64 1, metadata !45, metadata !DIExpression()), !dbg !52 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !53 // ST: Guess // : Release iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l22_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l22_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); ASSUME(cw(1,0) >= cr(1,0+0)); ASSUME(cw(1,0) >= cr(1,0+1)); ASSUME(cw(1,0) >= cr(1,0+2)); ASSUME(cw(1,0) >= cr(1,3+0)); ASSUME(cw(1,0) >= cr(1,4+0)); ASSUME(cw(1,0) >= cr(1,5+0)); ASSUME(cw(1,0) >= cw(1,0+0)); ASSUME(cw(1,0) >= cw(1,0+1)); ASSUME(cw(1,0) >= cw(1,0+2)); ASSUME(cw(1,0) >= cw(1,3+0)); ASSUME(cw(1,0) >= cw(1,4+0)); ASSUME(cw(1,0) >= cw(1,5+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; is(1,0) = iw(1,0); cs(1,0) = cw(1,0); ASSUME(creturn[1] >= cw(1,0)); // ret i8* null, !dbg !54 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !57, metadata !DIExpression()), !dbg !67 // br label %label_2, !dbg !50 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !66), !dbg !69 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !59, metadata !DIExpression()), !dbg !70 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !53 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l28_c15 // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r0 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r0 = buff(2,0); ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r0 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %0, metadata !61, metadata !DIExpression()), !dbg !70 // %conv = trunc i64 %0 to i32, !dbg !54 // call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !67 // call void (...) @dmbsy(), !dbg !55 // dumbsy: Guess old_cdy = cdy[2]; cdy[2] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[2] >= old_cdy); ASSUME(cdy[2] >= cisb[2]); ASSUME(cdy[2] >= cdl[2]); ASSUME(cdy[2] >= cds[2]); ASSUME(cdy[2] >= cctrl[2]); ASSUME(cdy[2] >= cw(2,0+0)); ASSUME(cdy[2] >= cw(2,0+1)); ASSUME(cdy[2] >= cw(2,0+2)); ASSUME(cdy[2] >= cw(2,3+0)); ASSUME(cdy[2] >= cw(2,4+0)); ASSUME(cdy[2] >= cw(2,5+0)); ASSUME(cdy[2] >= cr(2,0+0)); ASSUME(cdy[2] >= cr(2,0+1)); ASSUME(cdy[2] >= cr(2,0+2)); ASSUME(cdy[2] >= cr(2,3+0)); ASSUME(cdy[2] >= cr(2,4+0)); ASSUME(cdy[2] >= cr(2,5+0)); ASSUME(creturn[2] >= cdy[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !62, metadata !DIExpression()), !dbg !74 // call void @llvm.dbg.value(metadata i64 1, metadata !64, metadata !DIExpression()), !dbg !74 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !57 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l30_c3 old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l30_c3 // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = 1; mem(0+2*1,cw(2,0+2*1)) = 1; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // %cmp = icmp eq i32 %conv, 1, !dbg !58 creg__r0__1_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !58 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !65, metadata !DIExpression()), !dbg !67 // store i32 %conv1, i32* @atom_1_X0_1, align 4, !dbg !59, !tbaa !60 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l32_c15 old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l32_c15 // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= creg__r0__1_); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==1); mem(3,cw(2,3)) = (r0==1); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // ret i8* null, !dbg !64 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !85, metadata !DIExpression()), !dbg !97 // br label %label_3, !dbg !52 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !96), !dbg !99 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !87, metadata !DIExpression()), !dbg !100 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) acquire, align 8, !dbg !55 // LD: Guess // : Acquire old_cr = cr(3,0+2*1); cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l38_c15 // Check ASSUME(active[cr(3,0+2*1)] == 3); ASSUME(cr(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cr(3,0+2*1) >= 0); ASSUME(cr(3,0+2*1) >= cdy[3]); ASSUME(cr(3,0+2*1) >= cisb[3]); ASSUME(cr(3,0+2*1) >= cdl[3]); ASSUME(cr(3,0+2*1) >= cl[3]); ASSUME(cr(3,0+2*1) >= cx(3,0+2*1)); ASSUME(cr(3,0+2*1) >= cs(3,0+0)); ASSUME(cr(3,0+2*1) >= cs(3,0+1)); ASSUME(cr(3,0+2*1) >= cs(3,0+2)); ASSUME(cr(3,0+2*1) >= cs(3,3+0)); ASSUME(cr(3,0+2*1) >= cs(3,4+0)); ASSUME(cr(3,0+2*1) >= cs(3,5+0)); // Update creg_r1 = cr(3,0+2*1); crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+2*1) < cw(3,0+2*1)) { r1 = buff(3,0+2*1); ASSUME((!(( (cw(3,0+2*1) < 1) && (1 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,1)> 0)); ASSUME((!(( (cw(3,0+2*1) < 2) && (2 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,2)> 0)); ASSUME((!(( (cw(3,0+2*1) < 3) && (3 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,3)> 0)); ASSUME((!(( (cw(3,0+2*1) < 4) && (4 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,4)> 0)); } else { if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) { ASSUME(cr(3,0+2*1) >= old_cr); } pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1)); r1 = mem(0+2*1,cr(3,0+2*1)); } cl[3] = max(cl[3],cr(3,0+2*1)); ASSUME(creturn[3] >= cr(3,0+2*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !89, metadata !DIExpression()), !dbg !100 // %conv = trunc i64 %0 to i32, !dbg !56 // call void @llvm.dbg.value(metadata i32 %conv, metadata !86, metadata !DIExpression()), !dbg !97 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !91, metadata !DIExpression()), !dbg !103 // %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) acquire, align 8, !dbg !58 // LD: Guess // : Acquire old_cr = cr(3,0+1*1); cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l39_c15 // Check ASSUME(active[cr(3,0+1*1)] == 3); ASSUME(cr(3,0+1*1) >= iw(3,0+1*1)); ASSUME(cr(3,0+1*1) >= 0); ASSUME(cr(3,0+1*1) >= cdy[3]); ASSUME(cr(3,0+1*1) >= cisb[3]); ASSUME(cr(3,0+1*1) >= cdl[3]); ASSUME(cr(3,0+1*1) >= cl[3]); ASSUME(cr(3,0+1*1) >= cx(3,0+1*1)); ASSUME(cr(3,0+1*1) >= cs(3,0+0)); ASSUME(cr(3,0+1*1) >= cs(3,0+1)); ASSUME(cr(3,0+1*1) >= cs(3,0+2)); ASSUME(cr(3,0+1*1) >= cs(3,3+0)); ASSUME(cr(3,0+1*1) >= cs(3,4+0)); ASSUME(cr(3,0+1*1) >= cs(3,5+0)); // Update creg_r2 = cr(3,0+1*1); crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+1*1) < cw(3,0+1*1)) { r2 = buff(3,0+1*1); ASSUME((!(( (cw(3,0+1*1) < 1) && (1 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(3,0+1*1) < 2) && (2 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(3,0+1*1) < 3) && (3 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(3,0+1*1) < 4) && (4 < crmax(3,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) { ASSUME(cr(3,0+1*1) >= old_cr); } pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1)); r2 = mem(0+1*1,cr(3,0+1*1)); } cl[3] = max(cl[3],cr(3,0+1*1)); ASSUME(creturn[3] >= cr(3,0+1*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !93, metadata !DIExpression()), !dbg !103 // %conv4 = trunc i64 %1 to i32, !dbg !59 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !90, metadata !DIExpression()), !dbg !97 // %cmp = icmp eq i32 %conv, 1, !dbg !60 creg__r1__1_ = max(0,creg_r1); // %conv5 = zext i1 %cmp to i32, !dbg !60 // call void @llvm.dbg.value(metadata i32 %conv5, metadata !94, metadata !DIExpression()), !dbg !97 // store i32 %conv5, i32* @atom_2_X0_1, align 4, !dbg !61, !tbaa !62 // ST: Guess iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l41_c15 old_cw = cw(3,4); cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l41_c15 // Check ASSUME(active[iw(3,4)] == 3); ASSUME(active[cw(3,4)] == 3); ASSUME(sforbid(4,cw(3,4))== 0); ASSUME(iw(3,4) >= creg__r1__1_); ASSUME(iw(3,4) >= 0); ASSUME(cw(3,4) >= iw(3,4)); ASSUME(cw(3,4) >= old_cw); ASSUME(cw(3,4) >= cr(3,4)); ASSUME(cw(3,4) >= cl[3]); ASSUME(cw(3,4) >= cisb[3]); ASSUME(cw(3,4) >= cdy[3]); ASSUME(cw(3,4) >= cdl[3]); ASSUME(cw(3,4) >= cds[3]); ASSUME(cw(3,4) >= cctrl[3]); ASSUME(cw(3,4) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,4) = (r1==1); mem(4,cw(3,4)) = (r1==1); co(4,cw(3,4))+=1; delta(4,cw(3,4)) = -1; ASSUME(creturn[3] >= cw(3,4)); // %cmp6 = icmp eq i32 %conv4, 0, !dbg !66 creg__r2__0_ = max(0,creg_r2); // %conv7 = zext i1 %cmp6 to i32, !dbg !66 // call void @llvm.dbg.value(metadata i32 %conv7, metadata !95, metadata !DIExpression()), !dbg !97 // store i32 %conv7, i32* @atom_2_X2_0, align 4, !dbg !67, !tbaa !62 // ST: Guess iw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l43_c15 old_cw = cw(3,5); cw(3,5) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l43_c15 // Check ASSUME(active[iw(3,5)] == 3); ASSUME(active[cw(3,5)] == 3); ASSUME(sforbid(5,cw(3,5))== 0); ASSUME(iw(3,5) >= creg__r2__0_); ASSUME(iw(3,5) >= 0); ASSUME(cw(3,5) >= iw(3,5)); ASSUME(cw(3,5) >= old_cw); ASSUME(cw(3,5) >= cr(3,5)); ASSUME(cw(3,5) >= cl[3]); ASSUME(cw(3,5) >= cisb[3]); ASSUME(cw(3,5) >= cdy[3]); ASSUME(cw(3,5) >= cdl[3]); ASSUME(cw(3,5) >= cds[3]); ASSUME(cw(3,5) >= cctrl[3]); ASSUME(cw(3,5) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,5) = (r2==0); mem(5,cw(3,5)) = (r2==0); co(5,cw(3,5))+=1; delta(5,cw(3,5)) = -1; ASSUME(creturn[3] >= cw(3,5)); // ret i8* null, !dbg !68 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !118, metadata !DIExpression()), !dbg !140 // call void @llvm.dbg.value(metadata i8** %argv, metadata !119, metadata !DIExpression()), !dbg !140 // %0 = bitcast i64* %thr0 to i8*, !dbg !65 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !65 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !120, metadata !DIExpression()), !dbg !142 // %1 = bitcast i64* %thr1 to i8*, !dbg !67 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !67 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !124, metadata !DIExpression()), !dbg !144 // %2 = bitcast i64* %thr2 to i8*, !dbg !69 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !69 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !125, metadata !DIExpression()), !dbg !146 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !126, metadata !DIExpression()), !dbg !147 // call void @llvm.dbg.value(metadata i64 0, metadata !128, metadata !DIExpression()), !dbg !147 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !72 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l52_c3 old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l52_c3 // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !129, metadata !DIExpression()), !dbg !149 // call void @llvm.dbg.value(metadata i64 0, metadata !131, metadata !DIExpression()), !dbg !149 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !74 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l53_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l53_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !132, metadata !DIExpression()), !dbg !151 // call void @llvm.dbg.value(metadata i64 0, metadata !134, metadata !DIExpression()), !dbg !151 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !76 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l54_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l54_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_1_X0_1, align 4, !dbg !77, !tbaa !78 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l55_c15 old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l55_c15 // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // store i32 0, i32* @atom_2_X0_1, align 4, !dbg !82, !tbaa !78 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l56_c15 old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l56_c15 // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // store i32 0, i32* @atom_2_X2_0, align 4, !dbg !83, !tbaa !78 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l57_c15 old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l57_c15 // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !84 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !85 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call6 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !86 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !87, !tbaa !88 r4 = local_mem[0]; // %call7 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !90 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !91, !tbaa !88 r5 = local_mem[1]; // %call8 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !92 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !93, !tbaa !88 r6 = local_mem[2]; // %call9 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !94 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // %6 = load i32, i32* @atom_1_X0_1, align 4, !dbg !95, !tbaa !78 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l67_c13 // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r7 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r7 = buff(0,3); ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0)); ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0)); ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0)); ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0)); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r7 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i32 %6, metadata !135, metadata !DIExpression()), !dbg !140 // %7 = load i32, i32* @atom_2_X0_1, align 4, !dbg !96, !tbaa !78 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l68_c13 // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r8 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r8 = buff(0,4); ASSUME((!(( (cw(0,4) < 1) && (1 < crmax(0,4)) )))||(sforbid(4,1)> 0)); ASSUME((!(( (cw(0,4) < 2) && (2 < crmax(0,4)) )))||(sforbid(4,2)> 0)); ASSUME((!(( (cw(0,4) < 3) && (3 < crmax(0,4)) )))||(sforbid(4,3)> 0)); ASSUME((!(( (cw(0,4) < 4) && (4 < crmax(0,4)) )))||(sforbid(4,4)> 0)); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r8 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i32 %7, metadata !136, metadata !DIExpression()), !dbg !140 // %8 = load i32, i32* @atom_2_X2_0, align 4, !dbg !97, !tbaa !78 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l69_c13 // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r9 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r9 = buff(0,5); ASSUME((!(( (cw(0,5) < 1) && (1 < crmax(0,5)) )))||(sforbid(5,1)> 0)); ASSUME((!(( (cw(0,5) < 2) && (2 < crmax(0,5)) )))||(sforbid(5,2)> 0)); ASSUME((!(( (cw(0,5) < 3) && (3 < crmax(0,5)) )))||(sforbid(5,3)> 0)); ASSUME((!(( (cw(0,5) < 4) && (4 < crmax(0,5)) )))||(sforbid(5,4)> 0)); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r9 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i32 %8, metadata !137, metadata !DIExpression()), !dbg !140 // %and = and i32 %7, %8, !dbg !98 creg_r10 = max(creg_r8,creg_r9); r10 = r8 & r9; // call void @llvm.dbg.value(metadata i32 %and, metadata !138, metadata !DIExpression()), !dbg !140 // %and10 = and i32 %6, %and, !dbg !99 creg_r11 = max(creg_r10,creg_r7); r11 = r7 & r10; // call void @llvm.dbg.value(metadata i32 %and10, metadata !139, metadata !DIExpression()), !dbg !140 // %cmp = icmp eq i32 %and10, 1, !dbg !100 creg__r11__1_ = max(0,creg_r11); // br i1 %cmp, label %if.then, label %if.end, !dbg !102 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r11__1_); if((r11==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([136 x i8], [136 x i8]* @.str.1, i64 0, i64 0), i32 noundef 72, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !103 // unreachable, !dbg !103 r12 = 1; goto T0BLOCK_END; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !106 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !106 // %10 = bitcast i64* %thr1 to i8*, !dbg !106 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !106 // %11 = bitcast i64* %thr0 to i8*, !dbg !106 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !106 // ret i32 0, !dbg !107 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSUME(meminit(4,1) == mem(4,0)); ASSUME(coinit(4,1) == co(4,0)); ASSUME(deltainit(4,1) == delta(4,0)); ASSUME(meminit(4,2) == mem(4,1)); ASSUME(coinit(4,2) == co(4,1)); ASSUME(deltainit(4,2) == delta(4,1)); ASSUME(meminit(4,3) == mem(4,2)); ASSUME(coinit(4,3) == co(4,2)); ASSUME(deltainit(4,3) == delta(4,2)); ASSUME(meminit(4,4) == mem(4,3)); ASSUME(coinit(4,4) == co(4,3)); ASSUME(deltainit(4,4) == delta(4,3)); ASSUME(meminit(5,1) == mem(5,0)); ASSUME(coinit(5,1) == co(5,0)); ASSUME(deltainit(5,1) == delta(5,0)); ASSUME(meminit(5,2) == mem(5,1)); ASSUME(coinit(5,2) == co(5,1)); ASSUME(deltainit(5,2) == delta(5,1)); ASSUME(meminit(5,3) == mem(5,2)); ASSUME(coinit(5,3) == co(5,2)); ASSUME(deltainit(5,3) == delta(5,2)); ASSUME(meminit(5,4) == mem(5,3)); ASSUME(coinit(5,4) == co(5,3)); ASSUME(deltainit(5,4) == delta(5,3)); ASSERT(r12== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
fa6f8e5c1fc6eafcf9cf3f9b1c7ad3ac0a54d317
74ef98dbfc8936ebe68bdfe08b19d72cbc4cbca8
/SoundexTest.cpp
fd8b83f430f3b84de172a986400f006829b574ad
[]
no_license
farluccio/SdxKata
cb679ee0f6eb7d72fb60ddac2d99b041621a5554
02d443ef6fc19293b1873254a25d846e7e399256
refs/heads/master
2020-04-11T09:20:53.043966
2018-12-13T17:44:51
2018-12-13T17:44:51
161,674,454
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
#include "gmock/gmock.h" class Soundex { }; TEST(SoundexEncoding, RetainsSoleLetterOfOneLetterWord) { /// Arrange Soundex soundex; /// Act auto encode = soundex encode("A"); /// Assert ASSERT_THAT(encode, testing::EQ("A")); }
[ "ericfarley@ad.weber.edu" ]
ericfarley@ad.weber.edu
ca7e65b96e05a7c9347419d2c13b690ff57527d6
d508027427b9a11a6bab0722479ee8d7b7eda72b
/3rd/include/maya2012sdk/tbb/spin_mutex.h
8959766a251909066da4548e92c6fed7d4981908
[]
no_license
gaoyakun/atom3d
421bc029ee005f501e0adb6daed778662eb73bac
129adf3ceca175faa8acf715c05e3c8f099399fe
refs/heads/master
2021-01-10T18:28:50.562540
2019-12-06T13:17:00
2019-12-06T13:17:00
56,327,530
5
0
null
null
null
null
UTF-8
C++
false
false
5,841
h
/* Copyright 2005-2010 Intel Corporation. All Rights Reserved. The source code contained or described herein and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or its suppliers and licensors. The Material is protected by worldwide copyright laws and treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without Intel's prior express written permission. No license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and approved by Intel in writing. */ #ifndef __TBB_spin_mutex_H #define __TBB_spin_mutex_H #include <cstddef> #include <new> #include "aligned_space.h" #include "tbb_stddef.h" #include "tbb_machine.h" #include "tbb_profiling.h" namespace tbb { //! A lock that occupies a single byte. /** A spin_mutex is a spin mutex that fits in a single byte. It should be used only for locking short critical sections (typically less than 20 instructions) when fairness is not an issue. If zero-initialized, the mutex is considered unheld. @ingroup synchronization */ class spin_mutex { //! 0 if lock is released, 1 if lock is acquired. unsigned char flag; public: //! Construct unacquired lock. /** Equivalent to zero-initialization of *this. */ spin_mutex() : flag(0) { #if TBB_USE_THREADING_TOOLS internal_construct(); #endif } //! Represents acquisition of a mutex. class scoped_lock : internal::no_copy { private: //! Points to currently held mutex, or NULL if no lock is held. spin_mutex* my_mutex; //! Value to store into spin_mutex::flag to unlock the mutex. uintptr_t my_unlock_value; //! Like acquire, but with ITT instrumentation. void __TBB_EXPORTED_METHOD internal_acquire( spin_mutex& m ); //! Like try_acquire, but with ITT instrumentation. bool __TBB_EXPORTED_METHOD internal_try_acquire( spin_mutex& m ); //! Like release, but with ITT instrumentation. void __TBB_EXPORTED_METHOD internal_release(); friend class spin_mutex; public: //! Construct without acquiring a mutex. scoped_lock() : my_mutex(NULL), my_unlock_value(0) {} //! Construct and acquire lock on a mutex. scoped_lock( spin_mutex& m ) { #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT my_mutex=NULL; internal_acquire(m); #else my_unlock_value = __TBB_LockByte(m.flag); my_mutex=&m; #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT*/ } //! Acquire lock. void acquire( spin_mutex& m ) { #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT internal_acquire(m); #else my_unlock_value = __TBB_LockByte(m.flag); my_mutex = &m; #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT*/ } //! Try acquiring lock (non-blocking) /** Return true if lock acquired; false otherwise. */ bool try_acquire( spin_mutex& m ) { #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT return internal_try_acquire(m); #else bool result = __TBB_TryLockByte(m.flag); if( result ) { my_unlock_value = 0; my_mutex = &m; } return result; #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT*/ } //! Release lock void release() { #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT internal_release(); #else __TBB_store_with_release(my_mutex->flag, static_cast<unsigned char>(my_unlock_value)); my_mutex = NULL; #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */ } //! Destroy lock. If holding a lock, releases the lock first. ~scoped_lock() { if( my_mutex ) { #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT internal_release(); #else __TBB_store_with_release(my_mutex->flag, static_cast<unsigned char>(my_unlock_value)); #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */ } } }; void __TBB_EXPORTED_METHOD internal_construct(); // Mutex traits static const bool is_rw_mutex = false; static const bool is_recursive_mutex = false; static const bool is_fair_mutex = false; // ISO C++0x compatibility methods //! Acquire lock void lock() { #if TBB_USE_THREADING_TOOLS aligned_space<scoped_lock,1> tmp; new(tmp.begin()) scoped_lock(*this); #else __TBB_LockByte(flag); #endif /* TBB_USE_THREADING_TOOLS*/ } //! Try acquiring lock (non-blocking) /** Return true if lock acquired; false otherwise. */ bool try_lock() { #if TBB_USE_THREADING_TOOLS aligned_space<scoped_lock,1> tmp; return (new(tmp.begin()) scoped_lock)->internal_try_acquire(*this); #else return __TBB_TryLockByte(flag); #endif /* TBB_USE_THREADING_TOOLS*/ } //! Release lock void unlock() { #if TBB_USE_THREADING_TOOLS aligned_space<scoped_lock,1> tmp; scoped_lock& s = *tmp.begin(); s.my_mutex = this; s.my_unlock_value = 0; s.internal_release(); #else __TBB_store_with_release(flag, 0); #endif /* TBB_USE_THREADING_TOOLS */ } friend class scoped_lock; }; __TBB_DEFINE_PROFILING_SET_NAME(spin_mutex) } // namespace tbb #endif /* __TBB_spin_mutex_H */
[ "80844871@qq.com" ]
80844871@qq.com
52ab19ef888051efe554b276467545aebece46d9
71dc7126621726818bc116a697e392eb69b0624d
/cmrtlib/agnostic/share/cm_device_def.h
2f2aa5b08809052f73e114c08f1ba2b8e5b100a8
[ "MIT", "BSD-3-Clause" ]
permissive
intel-cgss/media-driver
3a1977f59affedefd5ee3287b0138e96001cc08f
310104a4693c476a215de13e7e9fabdf2afbad0a
refs/heads/master
2021-08-24T00:08:11.235718
2017-12-06T05:58:24
2017-12-06T05:58:24
113,535,378
0
1
null
2017-12-08T05:26:15
2017-12-08T05:26:15
null
UTF-8
C++
false
false
9,370
h
/* * Copyright (c) 2017, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ //! //! Declaration of types and data stuctures used by implementations of CmDevice on various operating systems. //! #ifndef CMRTLIB_AGNOSTIC_SHARE_CM_DEVICE_DEF_H_ #define CMRTLIB_AGNOSTIC_SHARE_CM_DEVICE_DEF_H_ #include <cstdint> #include "cm_surface_properties.h" #include "cm_l3_cache_config.h" #include "cm_queue_base.h" #include "cm_def.h" typedef enum _CM_DEVICE_CAP_NAME { CAP_KERNEL_COUNT_PER_TASK, CAP_KERNEL_BINARY_SIZE, CAP_SAMPLER_COUNT , CAP_SAMPLER_COUNT_PER_KERNEL, CAP_BUFFER_COUNT , CAP_SURFACE2D_COUNT, CAP_SURFACE3D_COUNT, CAP_SURFACE_COUNT_PER_KERNEL, CAP_ARG_COUNT_PER_KERNEL, CAP_ARG_SIZE_PER_KERNEL , CAP_USER_DEFINED_THREAD_COUNT_PER_TASK, CAP_HW_THREAD_COUNT, CAP_SURFACE2D_FORMAT_COUNT, CAP_SURFACE2D_FORMATS, CAP_SURFACE3D_FORMAT_COUNT, CAP_SURFACE3D_FORMATS, CAP_VME_STATE_COUNT, CAP_GPU_PLATFORM, CAP_GT_PLATFORM, CAP_MIN_FREQUENCY, CAP_MAX_FREQUENCY, CAP_L3_CONFIG, CAP_GPU_CURRENT_FREQUENCY, CAP_USER_DEFINED_THREAD_COUNT_PER_TASK_NO_THREAD_ARG, CAP_USER_DEFINED_THREAD_COUNT_PER_MEDIA_WALKER, CAP_USER_DEFINED_THREAD_COUNT_PER_THREAD_GROUP, CAP_SURFACE2DUP_COUNT, CAP_PLATFORM_INFO, CAP_MAX_BUFFER_SIZE } CM_DEVICE_CAP_NAME; // CM RT DLL File Version typedef struct _CM_DLL_FILE_VERSION { uint16_t wMANVERSION; uint16_t wMANREVISION; uint16_t wSUBREVISION; uint16_t wBUILD_NUMBER; //Version constructed as : "wMANVERSION.wMANREVISION.wSUBREVISION.wBUILD_NUMBER" } CM_DLL_FILE_VERSION, *PCM_DLL_FILE_VERSION; // parameters used to set the surface state of the CmSurface struct CM_VME_SURFACE_STATE_PARAM { uint32_t width; uint32_t height; }; #define CM_DEFAULT_PRINT_BUFFER_SIZE (1*1024*1024) // 1M print buffer size #define CM_SAMPLER_ARRAY_SIZE 100 #define MAX_BUFFER_SIZE 256 #define CM_VME_VIDEO_TYPE_AVC 1 //default value for AVC #define CM_VME_VIDEO_TYPE_HEVC 2 typedef enum _CM_SUB_MAJOR_STEPPING { A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, O = 14, P = 15, Q = 16, R = 17, S = 18, T = 19, U = 20, V = 21, W = 22, X = 23, Y = 24, Z = 25 } CM_SUB_MAJOR_STEPPING; typedef enum _CM_SUB_PLATFORM_USE_SKU { GT1 = 1, GT2 = 2, GT3 = 3, GT4 = 4, GTA = 5, GTC = 6, GTX = 7, GT1_5 = 8 } CM_SUB_PLATFORM_USE_SKU; typedef int32_t (__cdecl *ReleaseSurfaceCallback)(void *cmDevice, void *surface); struct CmDeviceCreationParam { uint32_t createOption; // [in] Dev create option ReleaseSurfaceCallback ReleaseSurfaceFunc; // [in] Function Pointer to free surface void *deviceHandleInUmd; // [out] pointer to handle in driver uint32_t version; // [out] the Cm version uint32_t driverStoreEnabled; // [out] DriverStoreEnable flag int32_t returnValue; // [out] the return value from CMRT@UMD }; #define CM_MAX_SPILL_SIZE_IN_BYTE_PER_HW_THREAD 9216 // 9K #define CM_MAX_SURFACE3D_FORMAT_COUNT 3 #define CM_RT_PLATFORM "CM_RT_PLATFORM" #define CM_RT_SKU "CM_RT_SKU" #define CM_RT_MAX_THREADS "CM_RT_MAX_THREADS" #define CM_RT_AUB_PARAM "CM_RT_AUB_PARAM" #define CM_RT_MULTIPLE_FRAMES "CM_RT_MULTIPLE_FRAMES" #define CM_RT_STEPPING "CM_RT_STEPPING" #define CM_DEVICE_CREATE_OPTION_DEFAULT 0 #define IGFX_UNKNOWN_CORE 0 struct CM_PLATFORM_INFO { uint32_t numSlices; uint32_t numSubSlices; uint32_t numEUsPerSubSlice; uint32_t numHWThreadsPerEU; uint32_t numMaxEUsPerPool; }; enum CM_QUERY_TYPE { CM_QUERY_VERSION, CM_QUERY_REG_HANDLE, CM_QUERY_MAX_VALUES, CM_QUERY_GPU, CM_QUERY_GT, CM_QUERY_MIN_RENDER_FREQ, CM_QUERY_MAX_RENDER_FREQ, CM_QUERY_STEP, CM_QUERY_GPU_FREQ, CM_QUERY_MAX_VALUES_EX, CM_QUERY_SURFACE2D_FORMAT_COUNT, CM_QUERY_SURFACE2D_FORMATS, CM_QUERY_PLATFORM_INFO }; struct CM_QUERY_CAPS { CM_QUERY_TYPE Type; union { int32_t iVersion; HANDLE hRegistration; CM_HAL_MAX_VALUES MaxValues; CM_HAL_MAX_VALUES_EX MaxValuesEx; uint32_t MaxVmeTableSize; uint32_t genCore; uint32_t genGT; uint32_t MinRenderFreq; uint32_t MaxRenderFreq; uint32_t genStepId; uint32_t GPUCurrentFreq; uint32_t Surf2DCount; uint32_t *pSurf2DFormats; CM_PLATFORM_INFO PlatformInfo; }; }; // Dummy param for execute struct CM_PARAMS { uint32_t placeHolder; }; enum CM_FUNCTION_ID { CM_FN_RT_ULT = 0x900, // (This function code is only used to run ults for CM_RT@UMD) CM_FN_CREATECMDEVICE = 0x1000, CM_FN_DESTROYCMDEVICE = 0x1001, CM_FN_CMDEVICE_CREATEBUFFER = 0x1100, CM_FN_CMDEVICE_DESTROYBUFFER = 0x1101, CM_FN_CMDEVICE_CREATEBUFFERUP = 0x1102, CM_FN_CMDEVICE_DESTROYBUFFERUP = 0x1103, CM_FN_CMDEVICE_CREATESURFACE2D = 0x1104, CM_FN_CMDEVICE_DESTROYSURFACE2D = 0x1105, CM_FN_CMDEVICE_CREATESURFACE2DUP = 0x1106, CM_FN_CMDEVICE_DESTROYSURFACE2DUP = 0x1107, CM_FN_CMDEVICE_GETSURFACE2DINFO = 0x1108, CM_FN_CMDEVICE_CREATESURFACE3D = 0x1109, CM_FN_CMDEVICE_DESTROYSURFACE3D = 0x110A, CM_FN_CMDEVICE_CREATEQUEUE = 0x110B, CM_FN_CMDEVICE_LOADPROGRAM = 0x110C, CM_FN_CMDEVICE_DESTROYPROGRAM = 0x110D, CM_FN_CMDEVICE_CREATEKERNEL = 0x110E, CM_FN_CMDEVICE_DESTROYKERNEL = 0x110F, CM_FN_CMDEVICE_CREATETASK = 0x1110, CM_FN_CMDEVICE_DESTROYTASK = 0x1111, CM_FN_CMDEVICE_GETCAPS = 0x1112, CM_FN_CMDEVICE_SETCAPS = 0x1113, CM_FN_CMDEVICE_CREATETHREADSPACE = 0x1114, CM_FN_CMDEVICE_DESTROYTHREADSPACE = 0x1115, CM_FN_CMDEVICE_CREATETHREADGROUPSPACE = 0x1116, CM_FN_CMDEVICE_DESTROYTHREADGROUPSPACE = 0x1117, CM_FN_CMDEVICE_SETL3CONFIG = 0x1118, CM_FN_CMDEVICE_SETSUGGESTEDL3CONFIG = 0x1119, CM_FN_CMDEVICE_CREATESAMPLER = 0x111A, CM_FN_CMDEVICE_DESTROYSAMPLER = 0x111B, CM_FN_CMDEVICE_CREATESAMPLER8X8 = 0x111C, CM_FN_CMDEVICE_DESTROYSAMPLER8X8 = 0x111D, CM_FN_CMDEVICE_CREATESAMPLER8X8SURFACE = 0x111E, CM_FN_CMDEVICE_DESTROYSAMPLER8X8SURFACE= 0x111F, CM_FN_CMDEVICE_DESTROYVMESURFACE = 0x1123, CM_FN_CMDEVICE_CREATEVMESURFACEG7_5 = 0x1124, CM_FN_CMDEVICE_DESTROYVMESURFACEG7_5 = 0x1125, CM_FN_CMDEVICE_CREATESAMPLERSURFACE2D = 0x1126, CM_FN_CMDEVICE_CREATESAMPLERSURFACE3D = 0x1127, CM_FN_CMDEVICE_DESTROYSAMPLERSURFACE = 0x1128, CM_FN_CMDEVICE_ENABLE_GTPIN = 0x112A, CM_FN_CMDEVICE_INIT_PRINT_BUFFER = 0x112C, CM_FN_CMDEVICE_CREATEVEBOX = 0x112D, CM_FN_CMDEVICE_DESTROYVEBOX = 0x112E, CM_FN_CMDEVICE_CREATEBUFFERSVM = 0x1131, CM_FN_CMDEVICE_DESTROYBUFFERSVM = 0x1132, CM_FN_CMDEVICE_CREATESAMPLERSURFACE2DUP= 0x1133, CM_FN_CMDEVICE_CHECK_EXISTING_2DWRAPPER= 0x1135, CM_FN_CMDEVICE_REGISTER_GTPIN_MARKERS = 0x1136, CM_FN_CMDEVICE_CLONEKERNEL = 0x1137, CM_FN_CMDEVICE_CREATESURFACE2D_ALIAS = 0x1138, CM_FN_CMDEVICE_CREATESAMPLER_EX = 0x1139, CM_FN_CMDEVICE_CREATESAMPLER8X8SURFACE_EX = 0x113A, CM_FN_CMDEVICE_CREATESAMPLERSURFACE2D_EX = 0x113B, CM_FN_CMDEVICE_CREATESURFACE2D_EX = 0x113C, CM_FN_CMDEVICE_CREATEBUFFER_ALIAS = 0x113D, CM_FN_CMDEVICE_CONFIGVMESURFACEDIMENSION = 0x113E, CM_FN_CMDEVICE_CREATEHEVCVMESURFACEG10 = 0x113F, CM_FN_CMDEVICE_GETVISAVERSION = 0x1140, CM_FN_CMQUEUE_ENQUEUE = 0x1500, CM_FN_CMQUEUE_DESTROYEVENT = 0x1501, CM_FN_CMQUEUE_ENQUEUECOPY = 0x1502, CM_FN_CMQUEUE_ENQUEUEWITHGROUP = 0x1504, CM_FN_CMQUEUE_ENQUEUESURF2DINIT = 0x1505, CM_FN_CMQUEUE_ENQUEUECOPY_V2V = 0x1506, CM_FN_CMQUEUE_ENQUEUECOPY_L2L = 0x1507, CM_FN_CMQUEUE_ENQUEUEVEBOX = 0x1508, CM_FN_CMQUEUE_ENQUEUEWITHHINTS = 0x1509, }; #endif // #ifndef CMRTLIB_AGNOSTIC_SHARE_CM_DEVICE_DEF_H_
[ "oliver.sang@intel.com" ]
oliver.sang@intel.com
1427080071fac6531ac87ff2ae58704cd1440d1a
998d4ce1054987f24562219bd6f79c37cbaa19c2
/套题/2014ACMICPC亚洲区北京站/EE.cpp
a8b8161f96e9928f4e34c5361a485f2776d654e2
[]
no_license
tankche1/ACM-NOI
0cedccd7f5fa53070c03cbc1845d5de06385f52b
1cb3d1fc08493e62c5cb4396e0352abef65b93f8
refs/heads/master
2022-12-13T03:22:18.971576
2022-12-05T15:56:34
2022-12-05T15:56:34
98,779,042
2
0
null
null
null
null
UTF-8
C++
false
false
3,343
cpp
# include<stdio.h> # include<string.h> # include<algorithm> using namespace std; typedef long long LL; bool a[210][210]; int n; LL p[210][210],sum[210][210]; LL px[210][210],py[210][210]; int R[210][210],U[210][210]; int t[210][210];//a=i b<=j LL tank[210][210];//a>=i b<=j int gcd(int a,int b){ return b==0?a:gcd(b,a%b); } void prepare(){ for(int i=1;i<=200;i++){ t[i][0]=0; for(int j=1;j<=200;j++){ t[i][j]=t[i][j-1]; if(gcd(i,j)==1) t[i][j]++; } } for(int i=200;i>=0;i--){ for(int j=200;j>=1;j--){ tank[i][j]=tank[i+1][j]+t[i][j]; } } } int main(){ //freopen("input.txt","r",stdin); int T; int x,y;; scanf("%d",&T); prepare(); for(int Tcase=1;Tcase<=T;Tcase++){ memset(a,0,sizeof(a)); scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d%d",&x,&y); a[x][y]=1; } for(int i=200;i>=1;i--){ for(int j=200;j>=1;j--){ U[i][j]=a[i][j]==0?0:U[i][j+1]+1; R[i][j]=a[i][j]==0?0:R[i+1][j]+1; } } LL ans1=0,ans2=0; for(int i=200;i>=1;i--){ for(int j=200;j>=1;j--){ p[i][j]=0; if(!a[i][j]) p[i][j]=0; else{ for(int aa=1;aa<=R[i][j]-1;aa++){ p[i][j]+=t[aa][U[i][j]-1]; } } px[i][j]=px[i][j+1]+p[i][j]; py[i][j]=py[i+1][j]+p[i][j]; sum[i][j]=sum[i+1][j+1]+px[i][j]+py[i][j]-p[i][j]; ans2+=p[i][j]*p[i][j]; //if(p[i][j]>0) printf("p[%d][%d]:%d\n",i,j,p[i][j]); } } ans1=sum[1][1]*sum[1][1]; //printf("ans2:%I64d\n",ans2); LL tmp=0; for(int i=200;i>=1;i--){ for(int j=200;j>=1;j--){ tmp=0; for(int aa=1;aa<=R[i][j]-1;aa++){ //ans2+=(py[i+1][j]-py[i+aa+1][j])*t[aa][U[i][j]-1]; tmp+=(py[i+1][j]-py[i+aa+1][j])*t[aa][U[i][j]-1]; } for(int bb=1;bb<=U[i][j]-1;bb++){ //ans2+=(px[i][j+1]-px[i][j+bb+1])*t[bb][R[i][j]-1]; tmp+=(px[i][j+1]-px[i][j+bb+1])*t[bb][R[i][j]-1]; } ans2+=tmp*2; //if(tmp>0) printf("i:%d j:%d tmp:%I64d\n",i,j,tmp); } } //printf("ans2:%I64d\n",ans2); LL res1,res2; for(int i=200;i>=1;i--){ for(int j=200;j>=1;j--){ if(a[i][j]==0) continue; res1=0;res2=0; for(int aa=1;a[i-aa][j]==1;aa++){ res1+=-tank[R[i-aa][j]][U[i-aa][j]-1]+tank[aa][U[i-aa][j]-1]; } for(int bb=1;a[i][j-bb]==1;bb++){ res2+=tank[bb][R[i][j-bb]-1]-tank[U[i][j-bb]][R[i][j-bb]-1]; } ans2+=res1*res2*2; } } LL ans=ans1-ans2; printf("Case #%d: ",Tcase); printf("%I64d\n",ans); //printf("ans1:%I64d ans2:%I64d\n",ans1,ans2); } return 0; }
[ "15307130191@fudan.edu.cn" ]
15307130191@fudan.edu.cn
7876c16595f0dab1a0254b3c634a799bdeae5d46
6fac50aa19020566f2e01595a6a0632a42ba3da3
/Ligh OJ/L-1093.cpp
4481ebd7772c9d25ac6c043541be70e53bd19519
[]
no_license
sayemimtiaz/competitive-programming
c36905ee99b1cfeb578c2b47367eff901a5e444f
58ff86e0d3804bd072d733e5fa491d6c192e4345
refs/heads/master
2023-01-27T14:47:06.767566
2023-01-08T21:50:49
2023-01-08T21:50:49
36,745,247
0
0
null
null
null
null
UTF-8
C++
false
false
2,201
cpp
#include<cstdio> #include<algorithm> #include<vector> #include<cstring> #include<iostream> #include<math.h> #include<cstdlib> #include<queue> #include<stack> #include<sstream> #include<set> #include<cctype> #include<string> #include<map> #include<fstream> #include<iomanip> using namespace std; #define S1(a) scanf("%d",&a) #define S2(a,b) scanf("%d %d",&a,&b) #define S3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pb push_back #define PI acos(-1.0) #define INT_MX 2147483647 #define INT_MN -2147483647 #define SIZE 100000 #define i64 int #define dle double #define rep(i,a,b) for(i=a;i<=b;i++) #define repb(i,a,b) for(i=a;i>=b;i--) #define sq(a) a*a #define eps 1e-9 #define mems(x) memset(x,0,sizeof(x)) #define swap(a,b) a^=b,b^=a,a^=b #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) int xx[]={0,0,1,-1,1,-1,1,-1}; int yy[]={1,-1,0,0,1,-1,-1,1}; struct Point { dle x,y; }; typedef vector<int>vi; typedef queue<int>qi; typedef stack<int>si; typedef pair<int,int>pii; inline i64 MAX(i64 a,i64 b) {return (a>b)?a:b;} inline i64 MIN(i64 a,i64 b) {return (a>b)?b:a;} inline dle dis(Point a,Point b) {return ((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));} i64 pwr(i64 x,i64 n) { if(n==0) return 1; if(n==1) return x; i64 a=pwr(x,n/2); a=a*a; if(n%2) a*=x; return a; } struct SS { i64 Mx,Mn; }S[300009]; i64 A[100009]; void init(i64 b,i64 e,i64 n) { if(b==e) S[n].Mx=S[n].Mn=A[b]; else{ i64 m=(b+e)/2; init(b,m,2*n);init(m+1,e,2*n+1); S[n].Mx=MAX(S[2*n].Mx,S[2*n+1].Mx); S[n].Mn=MIN(S[2*n].Mn,S[2*n+1].Mn); } } SS Query(i64 b,i64 e,i64 i,i64 j,i64 n) { SS T1={INT_MN,INT_MX}; if(e<i||b>j) return T1; if(b>=i&&e<=j) return S[n]; i64 m=(b+e)/2; T1=Query(b,m,i,j,2*n); SS T2=Query(m+1,e,i,j,2*n+1); SS T= {MAX(T1.Mx,T2.Mx),MIN(T1.Mn,T2.Mn)}; return T; } int main() { i64 a,b,q,n,i,j,kase,kas=0,d,R; S1(kase); while(kase--) { S2(n,d); rep(i,1,n) S1(A[i]); init(1,n,1); printf("Case %d: ",++kas); SS T; R=0; rep(i,1,n-d+1){ T=Query(1,n,i,i+d-1,1); R=MAX(R,T.Mx-T.Mn); } printf("%d\n",R); } return 0; }
[ "imtiaz.cuet@gmail.com" ]
imtiaz.cuet@gmail.com
1290a4cadd557610b94b5b41ea3b58a628765348
35e377af65e4a14baaacfcb5223400b1d9b76ef5
/TypeCasting/Source.cpp
596cff987a1e611813bce4bf32bf11fa131558ad
[]
no_license
olegdubakov/cscill
bf4efa327b519ddf6a402b546d28778b66a15f39
06a3e4901add39b228825a69ee146832c37d2b68
refs/heads/master
2021-06-18T20:20:25.607812
2019-07-02T13:05:21
2019-07-02T13:05:21
136,362,448
0
0
null
2019-07-02T13:09:23
2018-06-06T17:23:28
C++
UTF-8
C++
false
false
2,448
cpp
#include <iostream> #include <string> #include <list> using namespace std; // explicit void TestExplicit() { char ea = 'a'; double eb = 6.6; int ec = (int)ea + (int)eb; cout << "explicit casting result: " << ec << endl; } // implicit void TestImplicit() { double ia = 1.2; short ib = 3; int ic = ia + ib; cout << "implicit casting result: " << ic << endl; } // dynamic_cast class DynamicCastA { public: virtual void test() { cout << "test from DynamicCastA" << endl; } }; class DynamicCastB : public DynamicCastA { public: virtual void test() { cout << "test from DynamicCastB" << endl; } }; void TestDynamicCast() { DynamicCastA* dynamicCastA_1 = new DynamicCastB; dynamicCastA_1->test(); DynamicCastA* dynamicCastA_2 = new DynamicCastA; dynamicCastA_2->test(); DynamicCastA* dynamicCastB_1 = dynamic_cast<DynamicCastA*>(dynamicCastA_1); dynamicCastB_1->test(); DynamicCastA* dynamicCastB_2 = dynamic_cast<DynamicCastA*>(dynamicCastA_1); dynamicCastB_2->test(); } // static_cast (Converts between types using a combination of implicit and user-defined conversions. ) class StaticCastA { public: int m = 0; virtual void test() { cout << "test from StaticCastA" << endl; } }; class StaticCastB : public StaticCastA { public: virtual void test() { cout << "test from StaticCastB" << endl; } }; enum staticCastEnum { ONE = 1, TWO, THREE }; void TestStaticCast() { float sc_float = 3.333; int sc_int_1 = 0; sc_int_1 = static_cast<int>(sc_float); cout << "result of static_cast<int>(float): " << sc_int_1 << endl; int sc_int_2 = 2; staticCastEnum sc_num = static_cast<staticCastEnum>(sc_int_2); cout << "result of static_cast<enum>(int): "; switch (sc_num) { case ONE: cout << "ONE" << endl; break; case TWO: cout << "TWO" << endl; break; case THREE: cout << "THREE" << endl; break; } } // reinterpret_cast void TestReinterpretCast() { int *first_int = new int(51); void *ptr_to_int = reinterpret_cast<void*>(first_int); int *first_int_again = reinterpret_cast<int*>(ptr_to_int); std::cout << "result of reinterpret_cast: " << *first_int_again << endl; } // const_cast void TestConstCast() { int i = 33; const int& ci = i; const_cast<int&>(ci) = 4; std::cout << "result of const_cast: " << i << endl; } void main() { TestExplicit(); TestImplicit(); TestDynamicCast(); TestStaticCast(); TestReinterpretCast(); TestConstCast(); }
[ "oleg.dubakov@WS303" ]
oleg.dubakov@WS303
a08ea350331479128be0f57f522aa51ef6b7cb8b
95626140b639c93a5bc7d86c5ed7cead4d27372a
/algorithm And Data Structure/Link lIst AtoZ/Insert N position.cpp
2d0a079ca4fd31cd54c861efbe6119f8d3048b58
[]
no_license
asad-shuvo/ACM
059bed7f91261af385d1be189e544fe240da2ff2
2dea0ef7378d831097efdf4cae25fbc6f34b8064
refs/heads/master
2022-06-08T13:03:04.294916
2022-05-13T12:22:50
2022-05-13T12:22:50
211,629,208
0
0
null
null
null
null
UTF-8
C++
false
false
2,951
cpp
#include <bits/stdc++.h> using namespace std; int fx4[] = {1 , -1 , 0 , 0}; int fy4[] = {0 , 0 , 1 , -1}; int Kfx[]= {-2,-2,2,2,1,1,-1,-1}; ///knight move x - exis int Kfy[]= {1,-1,1,-1,2,-2,2,-2}; ///knight move y- exis int fx8[]= {1,1,1,0,0,-1,-1,-1}; int fy8[]= {0,1,-1,1,-1,0,1,-1}; #define ll long long int #define pii pair<int,int> #define llu unsigned long long #define inf 1<<28 #define gama 0.57721566490 #define PI acos(-1.0) #define INF 0x7fffffff #define MOD 1000000007 #define EPS 1e-7 #define all(r)(r).begin(),(r).end() /* bool status[mx]; void sieve(){ long long int i,j; for(i=2;i<=mx;i++) { status[i]=0; } for( i=2;i<=sqrt(mx);i++){ if(status[i]==0) { for(j=i*i;j<=mx;j+=i){ status[j]=1; } } } }*/ ll BM( ll a , ll b , ll m ) { if ( b == 0 ) return 1 ; ll x = BM(a,b/2,m); x = (( x % m) * (x % m))%m; if( b % 2 ) x = (( x % m) * (a %m)) % m ; return x ; } #define dd double #define sc scanf #define pr printf #define VI vector<int> #define VS vector<string> #define VC vector<char> #define VLL vector<long long int> #define FILE freopen("input.txt","rt",stdin); freopen("output.txt","w",stdout); #define p_b push_back #define mem(x,y) memset(x,y,sizeof(x)) #define F(i,a,b) for(i=a;i<=b;i++) #define sc1(a) scanf("%d",&a) #define scL1(a) scanf("%lld",&a) #define scL2(a,b) scanf("%lld%lld",&a,&b) #define sc2(a,b) scanf("%d%d",&a,&b) #define sc3(a,b,c) scanf("%d%d%d",&a,&b,&c) #define scL3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define fori(N) for(int i = 0; i<(N); i++) #define forj(N) for(int j = 0; j<(N); j++) #define fork(N) for(int k = 0; k<(N); k++) #define forl(N) for(int l = 0; l<(N); l++) #define ford(N) for(int d = 0; d<(N); d++) #define fori1(N) for(int i = 1; i<=(N); i++) #define forj1(N) for(int j = 1; j<=(N); j++) #define fork1(N) for(int k = 1; k<=(N); k++) #define ford1(N) for(int d = 1; d<=(N); d++) #define sqr(x) (x)*(x) #define TEST int test,te=0;sc1(test); #define segment_tree int l=(n*2),r=(n*2)+1,mid=(l+r)/2 #define Mx 100005 #define mx 10005 struct node{ int data; node* next; }; node* head; void Insert(int pos,int x) { node* temp1=new node(); temp1->data=x; temp1->next=NULL; if(pos==1){ temp1->next=head; head=temp1; return; } node* temp2=head; for(int i=0;i<pos-2;i++){ temp2=temp2->next; } temp1->next=temp2->next; temp2->next=temp1; } void print() { node* temp=head; while(temp!=NULL){ printf("%d ",temp->data); temp=temp->next; } pr("\n"); } int main() { head=NULL; int n; cin>>n; for(int i=1;i<=n;i++){ int x; cin>>x; int pos; cin>>pos; Insert(pos,x); print(); } }
[ "asad.shuvo.cse@gmail.com" ]
asad.shuvo.cse@gmail.com
faf77d97380e7a3cdad5aae709c1d57b928cce73
1a7aeed44aa642bdca6a1976824a0fd4f6bede1c
/calculator/calculator.cpp
04f1c388eda7036c230a7513cf43048fe5d23375
[]
no_license
begusibrahim000/cpp
43475d075dfe68175916b0d2b3efa6742a6d8c64
c5ebbba905f497e6c24f05c005f29a62758a5b75
refs/heads/master
2020-07-26T03:14:56.960000
2019-09-17T07:28:34
2019-09-17T07:28:34
208,516,875
1
0
null
null
null
null
UTF-8
C++
false
false
2,906
cpp
#include <iostream> using namespace std; // fungsi int kali(int a, int b){ int c; c = a * b; return c; } int bagi(int a, int b){ int c; c = a / b; return c; } int tambah(int a, int b){ int c; c = a + b; return c; } int kurang(int a, int b) { int c; c = a - b; return c; } int modul(int a, int b){ int c; c = a % b; return c; } int main() { char ulang; do { int masukan,hasil,a,b; cout << "# Begus Ibrahim | FullStack Developer #" << endl; cout << "========== APLIKASI KALKULATOR ==========" << endl; cout << "1. Perkalian" << endl; cout << "2. Pembagian" << endl; cout << "3. Pertambahan" << endl; cout << "4. Pengurangan" << endl; cout << "5. Modulus" << endl; cout << "Pilih fungsi yang mana (1/2/3/4/5) : "; cin >> masukan; if(masukan == 1){ cout << "* Perkalian *" << endl; cout << "Masukan angka ke-1 = "; cin >> a; cout << "Masukan angka ke-2 = "; cin >> b; hasil = kali(a,b); cout << "Hasil dari " << a << " x " << b << " = " << hasil << endl; }else if(masukan == 2){ cout << "/ Pembagian /" << endl; cout << "Masukan angka ke-1 = "; cin >> a; cout << "Masukan angka ke-2 = "; cin >> b; hasil = bagi(a,b); cout << "Hasil dari " << a << " / " << b << " = " << hasil << endl; }else if(masukan == 3){ cout << "+ Pertambahan + " << endl; cout << "Masukan angka ke-1 = "; cin >> a; cout << "Masukan angka ke-2 = "; cin >> b; hasil = tambah(a,b); cout << "Hasil dari " << a << " + " << b << " = " << hasil << endl; }else if(masukan == 4){ cout << "- Pengurangan -" << endl; cout << "Masukan angka ke-1 = "; cin >> a; cout << "Masukan angka ke-2 = "; cin >> b; hasil = kurang(a,b); cout << "Hasil dari " << a << " - " << b << " = " << hasil << endl; }else if(masukan == 5){ cout << "% Modulus %" << endl; cout << "Masukan angka ke-1 = "; cin >> a; cout << "Masukan angka ke-2 = "; cin >> b; hasil = modul(a,b); cout << "Hasil dari " << a << " % " << b << " = " << hasil << endl; } else{ cout << "=======================================" << endl; cout << "WARNING :: TIDAK ADA PILIHAN YANG TEPAT" << endl; cout << "=======================================" << endl; } cout << "Mau mengulang program kembali (y/n) : "; cin >> ulang; }while(ulang == 'Y' || ulang == 'y'); cin.get(); return 0; }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
a53c4551b32b83c39de339522b957646d23526a4
0aaa072fdc32bfa260f19e32f253e03a37592307
/scripts/ADMB/ADMBexp/NEFSC129/NEFSC129.cpp
63f4256f123516ca32931837fba9faccc743f78d
[]
no_license
BenjaminHCCarr/Collapse
b0a9a4e228407b5820e621feaeef05628828169b
1738c1271beefe6f307d28459c1db678e7021eee
refs/heads/master
2020-04-09T15:27:06.368121
2014-08-25T22:53:58
2014-08-25T22:53:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,639
cpp
#include <admodel.h> #include <admodel.h> #include <contrib.h> extern "C" { void ad_boundf(int i); } #include <NEFSC129.htp> model_data::model_data(int argc,char * argv[]) : ad_comm(argc,argv) { nobs.allocate("nobs"); maxB.allocate("maxB"); data.allocate(1,nobs,1,2,"data"); landings.allocate(1,nobs); biomass.allocate(1,nobs); iter=0; } model_parameters::model_parameters(int sz,int argc,char * argv[]) : model_data(argc,argv) , function_minimizer(sz) { initializationfunction(); lnK.allocate(-10000.,maxB,"lnK"); lnMSY.allocate("lnMSY"); n.allocate(0.1,30.,-2,"n"); f.allocate("f"); prior_function_value.allocate("prior_function_value"); likelihood_function_value.allocate("likelihood_function_value"); z.allocate("z"); #ifndef NO_AD_INITIALIZE z.initialize(); #endif zMSY.allocate("zMSY"); #ifndef NO_AD_INITIALIZE zMSY.initialize(); #endif meanP.allocate("meanP"); #ifndef NO_AD_INITIALIZE meanP.initialize(); #endif sig.allocate("sig"); #ifndef NO_AD_INITIALIZE sig.initialize(); #endif K.allocate("K"); #ifndef NO_AD_INITIALIZE K.initialize(); #endif MSY.allocate("MSY"); #ifndef NO_AD_INITIALIZE MSY.initialize(); #endif SSQ.allocate("SSQ"); #ifndef NO_AD_INITIALIZE SSQ.initialize(); #endif BMSY.allocate("BMSY"); #ifndef NO_AD_INITIALIZE BMSY.initialize(); #endif FMSY.allocate("FMSY"); #ifndef NO_AD_INITIALIZE FMSY.initialize(); #endif halfk.allocate("halfk"); #ifndef NO_AD_INITIALIZE halfk.initialize(); #endif epsilon.allocate(1,nobs-1,"epsilon"); #ifndef NO_AD_INITIALIZE epsilon.initialize(); #endif Ppred.allocate(1,nobs-1,"Ppred"); #ifndef NO_AD_INITIALIZE Ppred.initialize(); #endif Pobs.allocate(1,nobs-1,"Pobs"); #ifndef NO_AD_INITIALIZE Pobs.initialize(); #endif sd_sig.allocate("sd_sig"); } void model_parameters::preliminary_calculations(void) { #if defined(USE_ADPVM) admaster_slave_variable_interface(*this); #endif // get the data out of the columns of the data matrix landings=column(data,1); biomass=column(data,2); // calculate observed surplus production (Pobs) for(int i=1;i<=nobs-1;i++) { Pobs(i)=biomass(i+1)-biomass(i)+landings(i); } // set starting values lnMSY=log(0.6*max(Pobs)); lnK=log(max(biomass)); n=2; } void model_parameters::userfunction(void) { f =0.0; //*******MAIN PROGRAM******** init_states(); calc_residuals(); calc_ref_points(); calc_obj_fun(); sd_sig=sig; ofstream ofs("par.mcmc",ios::app); if(mceval_phase()) mcmc_stuff(); //****************************** } void model_parameters::init_states(void) { K=mfexp(lnK); halfk = K/2; MSY=mfexp(lnMSY); // calc z, zMSY, and meanP z=(1/(n-1))*pow(n,(n/(n-1))); zMSY=z*MSY; meanP=mean(Pobs); } void model_parameters::calc_residuals(void) { for(int j=1;j<=nobs-1;j++) { Ppred(j)=zMSY*((biomass(j)/K) - pow(biomass(j)/K,n)); } epsilon=Pobs-Ppred; sig=sqrt(norm2(epsilon)/(nobs-1)); SSQ=norm2(epsilon); } void model_parameters::calc_ref_points(void) { BMSY=pow(n,(1/(1-n)))*K; FMSY=MSY/BMSY; } void model_parameters::calc_obj_fun(void) { f=dnorm(epsilon,sig); } void model_parameters::report(const dvector& gradients) { adstring ad_tmp=initial_params::get_reportfile_name(); ofstream report((char*)(adprogram_name + ad_tmp)); if (!report) { cerr << "error trying to open report file" << adprogram_name << ".rep"; return; } report<<BMSY<<"\n"<<halfk<<"\n"<<maxB<<endl; } void model_parameters::mcmc_stuff(void) { if(iter==0){ ofstream ofs("par.mcmc"); ofs<<"K\t"<<"MSY\t"<<"n\t"<<endl; cout<<iter<<endl; } iter++; ofstream ofs("par.mcmc",ios::app); ofs<<K<<"\t"<<MSY<<"\t"<<n<<endl; } model_data::~model_data() {} model_parameters::~model_parameters() {} void model_parameters::final_calcs(void){} void model_parameters::set_runtime(void){} #ifdef _BORLANDC_ extern unsigned _stklen=10000U; #endif #ifdef __ZTC__ extern unsigned int _stack=10000U; #endif long int arrmblsize=0; int main(int argc,char * argv[]) { ad_set_new_handler(); ad_exit=&ad_boundf; gradient_structure::set_NO_DERIVATIVES(); gradient_structure::set_YES_SAVE_VARIABLES_VALUES(); if (!arrmblsize) arrmblsize=15000000; model_parameters mp(arrmblsize,argc,argv); mp.iprint=10; mp.preliminary_calculations(); mp.computations(argc,argv); return 0; } extern "C" { void ad_boundf(int i) { /* so we can stop here */ exit(i); } }
[ "bencarr@bu.edu" ]
bencarr@bu.edu
377bfcb203878210090b2cf7715c19cc031964c3
ec68c973b7cd3821dd70ed6787497a0f808e18e1
/Cpp/SDK/Widget_CheckpointNotification_parameters.h
4df3f3953e950d9cf3c3d139523562533f90e727
[]
no_license
Hengle/zRemnant-SDK
05be5801567a8cf67e8b03c50010f590d4e2599d
be2d99fb54f44a09ca52abc5f898e665964a24cb
refs/heads/main
2023-07-16T04:44:43.113226
2021-08-27T14:26:40
2021-08-27T14:26:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
h
#pragma once // Name: Remnant, Version: 1.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function Widget_CheckpointNotification.Widget_CheckpointNotification_C.Construct struct UWidget_CheckpointNotification_C_Construct_Params { }; // Function Widget_CheckpointNotification.Widget_CheckpointNotification_C.RemoveSelf struct UWidget_CheckpointNotification_C_RemoveSelf_Params { }; // Function Widget_CheckpointNotification.Widget_CheckpointNotification_C.StartCountdown struct UWidget_CheckpointNotification_C_StartCountdown_Params { }; // Function Widget_CheckpointNotification.Widget_CheckpointNotification_C.ExecuteUbergraph_Widget_CheckpointNotification struct UWidget_CheckpointNotification_C_ExecuteUbergraph_Widget_CheckpointNotification_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
88db5f31f6e46832d86efedb12a16ce76aa7c9f0
96ab18b237681c5c01bf3d0fce187740e5038bb8
/ asdk/Source/客户端/代码/otchkclient/FinSmith/FlatSplitterWnd.h
64f064765e109b06e262fe9fd46c172a285af09e
[]
no_license
radtek/asdk
43fd7bfeb31028ef6392be4117e5de4c908af8e5
4f9a3bd80f6cc58db02a4ed0f67bc5ee03cedb01
refs/heads/master
2020-06-09T04:28:16.485493
2012-05-10T10:30:00
2012-05-10T10:30:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,813
h
/* * File: FlatSplitterWnd.h * * Author: Marc Richarme <devix@devix.cjb.net> * * Created: 28 Jan. 2001 * Modified: 28 Jan. 2001 * * Use as much as you want, wherever you want... * Claim you coded it, I don't mind. * */ #if !defined(AFX_FLATSPLITTERWND_H__61D2F7E7_7AAA_11D1_9F4C_008029E98A75__INCLUDED_) #define AFX_FLATSPLITTERWND_H__61D2F7E7_7AAA_11D1_9F4C_008029E98A75__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 ///////////////////////////////////////////////////////////////////////////// // CFlatSplitterWnd class CFlatSplitterWnd : public CSplitterWnd { public: CFlatSplitterWnd(); virtual ~CFlatSplitterWnd(); virtual void OnDrawSplitter(CDC* pDC, ESplitType nType, const CRect& rectArg); virtual void RecalcLayout(); // call after changing sizes static void DeferClientPos(AFX_SIZEPARENTPARAMS* lpLayout, CWnd* pWnd, int x, int y, int cx, int cy, BOOL bScrollBar); static void LayoutRowCol(CSplitterWnd::CRowColInfo* pInfoArray, int nMax, int nSize, int nSizeSplitter); //code for hide protected: int m_nHidedCol; public: void ShowColumn(); void HideColumn(int c_colHide); //code for hide end // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFlatSplitterWnd) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CFlatSplitterWnd) //}}AFX_MSG DECLARE_MESSAGE_MAP() public: afx_msg void OnSize(UINT nType, int cx, int cy); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FLATSPLITTERWND_H__61D2F7E7_7AAA_11D1_9F4C_008029E98A75__INCLUDED_)
[ "He.Reyter@gmail.com@195b811d-50ba-3ccd-8b31-a51a91d0a79c" ]
He.Reyter@gmail.com@195b811d-50ba-3ccd-8b31-a51a91d0a79c
b4a7df9e896bb8e33b56d4802b3a67fb56e14c99
1cece0d71f79fe991ede775181767e1a697ac374
/third_party/mlir/include/mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h
d2f416b35fe9760e2ed5a9bec545aa843f90ff28
[ "Apache-2.0" ]
permissive
microsoft/tensorflow-directml
18d95a3f9ea0909fde8c1c245973eaa891e11348
3800a8e1cdeea062b9dac8584fb6303be7395b06
refs/heads/directml
2023-08-24T03:21:52.097089
2022-12-21T22:39:00
2022-12-21T22:39:00
291,217,084
459
43
Apache-2.0
2022-12-21T22:39:02
2020-08-29T06:44:33
C++
UTF-8
C++
false
false
3,724
h
//===- ConvertStandardToLLVMPass.h - Pass entrypoint ------------*- C++ -*-===// // // Copyright 2019 The MLIR Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= #ifndef MLIR_CONVERSION_STANDARDTOLLVM_CONVERTSTANDARDTOLLVMPASS_H_ #define MLIR_CONVERSION_STANDARDTOLLVM_CONVERTSTANDARDTOLLVMPASS_H_ #include "llvm/ADT/STLExtras.h" #include <memory> #include <vector> namespace llvm { class Module; } // namespace llvm namespace mlir { class DialectConversion; class FuncOp; class LLVMTypeConverter; struct LogicalResult; class MLIRContext; class ModuleOp; class ModulePassBase; class RewritePattern; class Type; // Owning list of rewriting patterns. class OwningRewritePatternList; /// Type for a callback constructing the owning list of patterns for the /// conversion to the LLVMIR dialect. The callback is expected to append /// patterns to the owning list provided as the second argument. using LLVMPatternListFiller = std::function<void(LLVMTypeConverter &, OwningRewritePatternList &)>; /// Type for a callback constructing the type converter for the conversion to /// the LLVMIR dialect. The callback is expected to return an instance of the /// converter. using LLVMTypeConverterMaker = std::function<std::unique_ptr<LLVMTypeConverter>(MLIRContext *)>; /// Collect a set of patterns to convert from the Standard dialect to LLVM. void populateStdToLLVMConversionPatterns(LLVMTypeConverter &converter, OwningRewritePatternList &patterns); /// Creates a pass to convert the Standard dialect into the LLVMIR dialect. std::unique_ptr<ModulePassBase> createConvertToLLVMIRPass(); /// Creates a pass to convert operations to the LLVMIR dialect. The conversion /// is defined by a list of patterns and a type converter that will be obtained /// during the pass using the provided callbacks. std::unique_ptr<ModulePassBase> createConvertToLLVMIRPass(LLVMPatternListFiller patternListFiller, LLVMTypeConverterMaker typeConverterMaker); /// Creates a pass to convert operations to the LLVMIR dialect. The conversion /// is defined by a list of patterns obtained during the pass using the provided /// callback and an optional type conversion class, an instance is created /// during the pass. template <typename TypeConverter = LLVMTypeConverter> std::unique_ptr<ModulePassBase> createConvertToLLVMIRPass(LLVMPatternListFiller patternListFiller) { return createConvertToLLVMIRPass(patternListFiller, [](MLIRContext *context) { return std::make_unique<TypeConverter>(context); }); } namespace LLVM { /// Make argument-taking successors of each block distinct. PHI nodes in LLVM /// IR use the predecessor ID to identify which value to take. They do not /// support different values coming from the same predecessor. If a block has /// another block as a successor more than once with different values, insert /// a new dummy block for LLVM PHI nodes to tell the sources apart. void ensureDistinctSuccessors(ModuleOp m); } // namespace LLVM } // namespace mlir #endif // MLIR_CONVERSION_STANDARDTOLLVM_CONVERTSTANDARDTOLLVMPASS_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
9ec1289516134137499236bb4c74ab89c9503189
3448a43cf0635866b25e5d513dd60fb003f47e29
/src/xrGame/ai/monsters/basemonster/base_monster_feel.cpp
2f15410cec2cf55d2747c11841caab0eaa66e196
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
xrLil-Batya/cordisproject
49632acc5e68bea9847d001d82fb049703d223c2
24275a382fec62a4e58d11579bf497b894f220ba
refs/heads/master
2023-03-19T01:17:25.170059
2020-11-17T14:22:06
2020-11-17T14:22:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,025
cpp
//////////////////////////////////////////////////////////////////////////// // Module : base_monster_feel.cpp // Created : 26.05.2003 // Modified : 26.05.2003 // Author : Serge Zhem // Description : Visibility and look for all the biting monsters //////////////////////////////////////////////////////////////////////////// #include "pch_script.h" #include "base_monster.h" #include "Actor.h" #include "ActorEffector.h" #include "ai/monsters/ai_monster_effector.h" #include "KinematicsAnimated.h" #include "sound_player.h" #include "Level.h" #include "xrScriptEngine/script_callback_ex.h" #include "script_game_object.h" #include "game_object_space.h" #include "ai_monster_space.h" #include "ai/monsters/control_animation_base.h" #include "UIGameCustom.h" #include "xrUICore/Static/UIStatic.h" #include "xrAICore/Navigation/ai_object_location.h" #include "xrEngine/profiler.h" #include "ActorEffector.h" #include "xrEngine/CameraBase.h" void CBaseMonster::feel_sound_new( IGameObject* who, int eType, CSound_UserDataPtr user_data, const Fvector& Position, float power) { if (!g_Alive()) return; // ignore my sounds if (this == who) return; if (user_data) user_data->accept(sound_user_data_visitor()); // ignore unknown sounds if (eType == 0xffffffff) return; // ignore distant sounds Fvector center; Center(center); float dist = center.distance_to(Position); if (dist > db().m_max_hear_dist) return; // ignore sounds if not from enemies and not help sounds CEntityAlive* entity = smart_cast<CEntityAlive*>(who); // ignore sound if enemy drop a weapon on death if (!entity && ((eType & SOUND_TYPE_ITEM_HIDING) == SOUND_TYPE_ITEM_HIDING)) return; if (entity && (!EnemyMan.is_enemy(entity))) { SoundMemory.check_help_sound(eType, entity->ai_location().level_vertex_id()); return; } if ((eType & SOUND_TYPE_WEAPON_SHOOTING) == SOUND_TYPE_WEAPON_SHOOTING) power = 1.f; if (((eType & SOUND_TYPE_WEAPON_BULLET_HIT) == SOUND_TYPE_WEAPON_BULLET_HIT) && (dist < 2.f)) HitMemory.add_hit(who, eSideFront); // execute callback sound_callback(who, eType, Position, power); // register in sound memory if (power >= db().m_fSoundThreshold) { SoundMemory.HearSound(who, eType, Position, power, Device.dwTimeGlobal); } } #define MAX_LOCK_TIME 2.f void CBaseMonster::HitEntity( const CEntity* pEntity, float fDamage, float impulse, Fvector& dir, ALife::EHitType hit_type, bool draw_hit_marks) { if (!g_Alive()) return; if (!pEntity || pEntity->getDestroy()) return; if (!EnemyMan.get_enemy()) return; if (EnemyMan.get_enemy() == pEntity) { Fvector position_in_bone_space; position_in_bone_space.set(0.f, 0.f, 0.f); // перевод из локальных координат в мировые вектора направления импульса Fvector hit_dir; XFORM().transform_dir(hit_dir, dir); hit_dir.normalize(); CEntity* pEntityNC = const_cast<CEntity*>(pEntity); VERIFY(pEntityNC); NET_Packet l_P; SHit HS; HS.GenHeader(GE_HIT, pEntityNC->ID()); // u_EventGen (l_P,GE_HIT, pEntityNC->ID()); HS.whoID = (ID()); // l_P.w_u16 (ID()); HS.weaponID = (ID()); // l_P.w_u16 (ID()); HS.dir = (hit_dir); // l_P.w_dir (hit_dir); HS.power = (fDamage); // l_P.w_float (fDamage); HS.boneID = (smart_cast<IKinematics*>(pEntityNC->Visual()) ->LL_GetBoneRoot()); // l_P.w_s16 //(smart_cast<IKinematics*>(pEntityNC->Visual())->LL_GetBoneRoot()); HS.p_in_bone_space = (position_in_bone_space); // l_P.w_vec3 (position_in_bone_space); HS.impulse = (impulse); // l_P.w_float (impulse); HS.hit_type = hit_type; // l_P.w_u16 ( u16(ALife::eHitTypeWound) ); HS.Write_Packet(l_P); u_EventSend(l_P); if (pEntityNC == Actor() && draw_hit_marks) { START_PROFILE("BaseMonster/Animation/HitEntity"); StaticDrawableWrapper* s = CurrentGameUI()->AddCustomStatic("monster_claws", false); float h1, p1; Device.vCameraDirection.getHP(h1, p1); Fvector hd = hit_dir; hd.mul(-1); float d = -h1 + hd.getH(); s->wnd()->SetHeading(d); Fvector2 wnd_pos = s->wnd()->GetWndPos(); wnd_pos.y += 400.0f * _cos(d); wnd_pos.x += 500.0f * _sin(d); s->wnd()->SetWndPos(wnd_pos); STOP_PROFILE; // SetAttackEffector (); float time_to_lock = fDamage * MAX_LOCK_TIME; clamp(time_to_lock, 0.f, MAX_LOCK_TIME); Actor()->lock_accel_for(int(time_to_lock * 1000)); ////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// CEffectorCam* ce = Actor()->Cameras().GetCamEffector((ECamEffectorType)effBigMonsterHit); if (!ce) { const shared_str& eff_sect = pSettings->r_string(cNameSect(), "actor_hit_effect"); if (eff_sect.c_str()) { int id = -1; Fvector cam_pos, cam_dir, cam_norm; Actor()->cam_Active()->Get(cam_pos, cam_dir, cam_norm); cam_dir.normalize_safe(); dir.normalize_safe(); float ang_diff = angle_difference(cam_dir.getH(), dir.getH()); Fvector cp; cp.crossproduct(cam_dir, dir); bool bUp = (cp.y > 0.0f); Fvector cross; cross.crossproduct(cam_dir, dir); VERIFY(ang_diff >= 0.0f && ang_diff <= PI); float _s1 = PI_DIV_8; float _s2 = _s1 + PI_DIV_4; float _s3 = _s2 + PI_DIV_4; float _s4 = _s3 + PI_DIV_4; if (ang_diff <= _s1) { id = 2; } else { if (ang_diff > _s1 && ang_diff <= _s2) { id = (bUp) ? 5 : 7; } else if (ang_diff > _s2 && ang_diff <= _s3) { id = (bUp) ? 3 : 1; } else if (ang_diff > _s3 && ang_diff <= _s4) { id = (bUp) ? 4 : 6; } else if (ang_diff > _s4) { id = 0; } else { VERIFY(0); } } string64 sect_name; xr_sprintf(sect_name, "%s_%d", eff_sect.c_str(), id); AddEffector(Actor(), effBigMonsterHit, sect_name, fDamage); } } ////////////////////////////////////////////////////////////////////////// } Morale.on_attack_success(); m_time_last_attack_success = Device.dwTimeGlobal; } } bool CBaseMonster::feel_vision_isRelevant(IGameObject* O) { if (!g_Alive()) return false; if (0 == smart_cast<CEntity*>(O)) return false; if ((O->GetSpatialData().type & STYPE_VISIBLEFORAI) != STYPE_VISIBLEFORAI) return false; // если спит, то ничего не видит if (m_bSleep) return false; // если не враг - не видит CEntityAlive* entity = smart_cast<CEntityAlive*>(O); if (entity && entity->g_Alive()) { if (!EnemyMan.is_enemy(entity)) { // если видит друга - проверить наличие у него врагов CBaseMonster* monster = smart_cast<CBaseMonster*>(entity); if (monster && !m_skip_transfer_enemy) EnemyMan.transfer_enemy(monster); return false; } } return true; } void CBaseMonster::HitSignal(float amount, Fvector& vLocalDir, IGameObject* who, s16 element) { if (!g_Alive()) return; feel_sound_new(who, SOUND_TYPE_WEAPON_SHOOTING, 0, who->Position(), 1.f); if (g_Alive()) sound().play(MonsterSound::eMonsterSoundTakeDamage); if (element < 0) return; // Определить направление хита (перед || зад || лево || право) float yaw, pitch; vLocalDir.getHP(yaw, pitch); yaw = angle_normalize(yaw); EHitSide hit_side = eSideFront; if ((yaw >= PI_DIV_4) && (yaw <= 3 * PI_DIV_4)) hit_side = eSideLeft; else if ((yaw >= 3 * PI_DIV_4) && (yaw <= 5 * PI_DIV_4)) hit_side = eSideBack; else if ((yaw >= 5 * PI_DIV_4) && (yaw <= 7 * PI_DIV_4)) hit_side = eSideRight; anim().FX_Play(hit_side, 1.0f); HitMemory.add_hit(who, hit_side); Morale.on_hit(); // Lord - [Script] Re-write // callback(GameObject::eHit)( // lua_game_object(), amount, vLocalDir, smart_cast<const CGameObject*>(who)->lua_game_object(), element); this->GetScriptBinderObject()->hit_callback(this->lua_game_object(), amount, vLocalDir, (smart_cast<const CGameObject*>(who))->lua_game_object(), element); // если нейтрал - добавить как врага CEntityAlive* obj = smart_cast<CEntityAlive*>(who); if (obj && (tfGetRelationType(obj) == ALife::eRelationTypeNeutral)) EnemyMan.add_enemy(obj); } void CBaseMonster::SetAttackEffector() { CActor* pA = smart_cast<CActor*>(Level().CurrentEntity()); if (pA) { Actor()->Cameras().AddCamEffector( new CMonsterEffectorHit(db().m_attack_effector.ce_time, db().m_attack_effector.ce_amplitude, db().m_attack_effector.ce_period_number, db().m_attack_effector.ce_power)); Actor()->Cameras().AddPPEffector(new CMonsterEffector(db().m_attack_effector.ppi, db().m_attack_effector.time, db().m_attack_effector.time_attack, db().m_attack_effector.time_release)); } } void CBaseMonster::Hit_Psy(IGameObject* object, float value) { NET_Packet P; SHit HS; HS.GenHeader(GE_HIT, object->ID()); // // u_EventGen (P,GE_HIT, object->ID()); // HS.whoID = (ID()); // own // P.w_u16 (ID()); // own HS.weaponID = (ID()); // own // P.w_u16 (ID()); // own HS.dir = (Fvector().set( 0.f, 1.f, 0.f)); // direction // P.w_dir (Fvector().set(0.f,1.f,0.f)); // direction HS.power = (value); // hit value // P.w_float (value); // hit value HS.boneID = (BI_NONE); // bone // P.w_s16 (BI_NONE); // bone HS.p_in_bone_space = (Fvector().set(0.f, 0.f, 0.f)); // P.w_vec3 (Fvector().set(0.f,0.f,0.f)); HS.impulse = (0.f); // P.w_float (0.f); HS.hit_type = (ALife::eHitTypeTelepatic); // P.w_u16 (u16(ALife::eHitTypeTelepatic)); HS.Write_Packet(P); u_EventSend(P); } void CBaseMonster::Hit_Wound(IGameObject* object, float value, const Fvector& dir, float impulse) { NET_Packet P; SHit HS; HS.GenHeader(GE_HIT, object->ID()); // u_EventGen (P,GE_HIT, object->ID()); HS.whoID = (ID()); // P.w_u16 (ID()); HS.weaponID = (ID()); // P.w_u16 (ID()); HS.dir = (dir); // P.w_dir (dir); HS.power = (value); // P.w_float (value); HS.boneID = (smart_cast<IKinematics*>(object->Visual()) ->LL_GetBoneRoot()); // P.w_s16 (smart_cast<IKinematics*>(object->Visual())->LL_GetBoneRoot()); HS.p_in_bone_space = (Fvector().set(0.f, 0.f, 0.f)); // P.w_vec3 (Fvector().set(0.f,0.f,0.f)); HS.impulse = (impulse); // P.w_float (impulse); HS.hit_type = (ALife::eHitTypeWound); // P.w_u16 (u16(ALife::eHitTypeWound)); HS.Write_Packet(P); u_EventSend(P); } bool CBaseMonster::critical_wound_external_conditions_suitable() { if (!control().check_start_conditions(ControlCom::eControlSequencer)) return false; if (!anim().IsStandCurAnim()) return false; return true; } void CBaseMonster::critical_wounded_state_start() { VERIFY(m_critical_wound_type != u32(-1)); LPCSTR anim = 0; switch (m_critical_wound_type) { case critical_wound_type_head: anim = m_critical_wound_anim_head; break; case critical_wound_type_torso: anim = m_critical_wound_anim_torso; break; case critical_wound_type_legs: anim = m_critical_wound_anim_legs; break; } VERIFY(anim); com_man().critical_wound(anim); }
[ "phantom1020@yandex.ru" ]
phantom1020@yandex.ru
d97119ba4cab7f8d237f007d89927fbf1a0cb72a
e3162c9933bd6d8b9d10054f09eccabd7648fc26
/CVector/cvector.cpp
93e5f8a472fa21ffda5cd3e1009b42a88a82e1b3
[]
no_license
Tismoney/warehouse
21622e16572434cb6bec8ae26a81e241c9e8757f
b1d7868e7ce23a69a86933d8a20733a158993bf4
refs/heads/master
2021-01-17T09:07:02.617921
2017-03-14T21:47:26
2017-03-14T21:47:26
42,769,218
0
1
null
2016-04-16T20:48:56
2015-09-19T10:39:50
C++
UTF-8
C++
false
false
3,065
cpp
#include <iostream> #include <cassert> #define type template <typename T> using namespace std; const int MAX_SIZE = 32; type class CVector { private: int size_; T data_[MAX_SIZE]; public: CVector(int _size); ~CVector(); int Vsize() { return size_; } CVector<T> operator + (CVector<T>& val) { assert(size_ == val.Vsize()); CVector<T> exp(size_); int i; for(i = 0; i < size_; i++) exp[i] = data_[i] + val[i]; return exp; } T& operator [] (int index) { assert(0 <= index && index < size_); return data_[index]; } T operator ^ (CVector<T>& val) // scalar product { assert(size_ == val.Vsize()); T exp = 0; int i; for(i = 0; i < size_; i++) exp += data_[i] * val[i]; return exp; } void VDump(); class iter { private: T* data_; public: iter(T* dt) { data_ = dt; } void operator ++ () { data_ += 1; return; } T operator * () { return *data_; } bool operator != (iter now) { if(data_ != now.data_) return true; else return false; } }; iter begin() { return iter(&data_[0]); } iter end() { return iter(&data_[size_ - 1]); } }; type CVector<T>::CVector(int _size) { size_ = _size; int i; for(i = 0; i < size_; i++) data_[i] = 0; } type CVector<T>::~CVector() { int i; for(i = 0; i < size_; i++) data_[i] = 0xBAD; size_ = -1; } type void CVector<T>::VDump() { int i; cout<<"("; for(i = 0; i < size_ - 1; i++) cout << data_[i] << ", "; cout <<data_[i]<<")"<< endl; } template <> CVector<bool> CVector<bool>::operator + (CVector<bool>& val) { assert(size_ == val.Vsize()); CVector<bool> exp(size_); int i; for(i = 0; i < size_; i++) exp[i] = (data_[i] + val[i]) % 2; return exp; } int main() { CVector<double> V(5), V1(5), V2(5); int i; for(i = 0; i < V.Vsize(); i++) { V1[i] = i + 0.5; V2[i] = i + 1; } V1.VDump(); V2.VDump(); V.VDump(); V = V1 + V2; V.VDump(); double sk = V1 ^ V2; cout << "scalar product = "<< sk << endl; CVector<bool> V3(5), V4(5), V5(5); for(i = 0; i < V.Vsize(); i++) { V3[i] = (7 * i + 1) % 2; V4[i] = (5 * i + 6) % 2; } V3.VDump(); V4.VDump(); V5 = V3 + V4; V5.VDump(); for(/*CVector<double>:: iter*/auto it = V.begin(); it != V.end(); ++it) { cout << *it << " "; } cout << *V.end()<< endl; return 0; }
[ "tismoney@mail.ru" ]
tismoney@mail.ru
0ddd007f2778e6ce6a76cbb452c83e30c56e602e
2c210b74c6eded787c30f6841b72f5e099b71249
/Revive/CompositorVk.h
21eaad38c7efb2d6d350fd7039fedc0e6f48e8d9
[ "BSD-3-Clause", "MIT", "BSD-2-Clause" ]
permissive
kant/Revive
abbc6b1de6e963f45e3c161fe566ff1810f1de9b
f055d4f05331d27ab80fdf65913da0adfad15e53
refs/heads/master
2022-02-02T01:24:50.738724
2019-07-20T15:31:06
2019-07-20T15:31:22
198,011,240
0
0
NOASSERTION
2019-07-21T04:19:13
2019-07-21T04:19:13
null
UTF-8
C++
false
false
805
h
#pragma once #include "CompositorBase.h" class CompositorVk : public CompositorBase { public: CompositorVk(VkPhysicalDevice physicalDevice, VkInstance instance); virtual ~CompositorVk(); virtual vr::ETextureType GetAPI() { return vr::TextureType_Vulkan; } virtual void Flush() { } virtual TextureBase* CreateTexture(); virtual void RenderTextureSwapChain(vr::EVREye eye, ovrTextureSwapChain swapChain, ovrTextureSwapChain sceneChain, ovrRecti viewport, vr::VRTextureBounds_t bounds, vr::HmdVector4_t quad); virtual void RenderMirrorTexture(ovrMirrorTexture mirrorTexture); void SetDevice(VkDevice device) { m_device = device; } void SetQueue(VkQueue queue) { m_queue = queue; } private: VkDevice m_device; VkPhysicalDevice m_physicalDevice; VkInstance m_instance; VkQueue m_queue; };
[ "jules.blok@gmail.com" ]
jules.blok@gmail.com
42af1f8cfcbcfbbecfd3b2b1be08e1fa5c7e5a7d
8c2461b55a516bcbcd011b014cc0fd6ff30e1a4a
/CodeForces/234A - Lefthanders and Righthanders.cpp
7a89ff4a9bfbbd05acb2c943a77734ffee4498ba
[]
no_license
Abhiramon/ioi-training
602bfd29f93f3d93143a1f54b93623b7df014f07
6f17829f2ea7fca60e719d1f67db4095012a9632
refs/heads/master
2021-01-22T05:50:42.627764
2015-06-18T02:13:46
2015-06-18T02:13:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
937
cpp
//10997782 2015-05-04 19:52:12 Hiasat98 234A - Lefthanders and Righthanders GNU C++ Accepted 30 ms 200 KB #include <iostream> #include <stdio.h> #include <vector> using namespace std; int main(){ int n; string r; freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); cin >> n; char a[101]; for(int i=0;i<n;i++){ cin>>a[i]; r += a[i]; } vector< pair<int,string> > p; for(int i = 1 ; i < n + 1;i++){ string x = ""; x += r.at(i - 1); p.push_back( pair<int,string>(i,x)); } for(int i = 0 ; i < n/2 ;i++){ pair<int,string> x = p[i]; pair<int,string> x1 =p[n/2 + i]; if(x.second == "R" && x1.second == "L"){ cout << x1.first << " " << x.first << endl; }else{ cout << x.first << " " << x1.first << endl; } } return 0; }
[ "hiasat00@gmail.com" ]
hiasat00@gmail.com
85d4a0bfabc39e8fbc2eede7ef328edcc7a2be79
f05fb433924b6ad56d71258d25101280c52ee205
/Src/lunaui/cards/emulation/PixmapButton.cpp
ee13b70e046f18b27a3fc25e50bfb08941a5d60c
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
webOS-ports/LunaCE
e0612d328ce29b413f0e2815788ee53d1a6995a0
f69124d4b57f77bae0d492f1669a907e9c6dad75
refs/heads/master
2021-01-16T00:17:04.402518
2018-05-11T08:20:44
2018-05-11T08:20:44
4,824,892
0
1
null
2013-12-12T19:00:21
2012-06-28T19:54:59
C++
UTF-8
C++
false
false
5,983
cpp
/* @@@LICENSE * * Copyright (c) 2010-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "Common.h" #include <glib.h> #include <string> #include "PixmapButton.h" #include <QGraphicsSceneMouseEvent> #include <QPainter> #include <QGraphicsObject> PixmapButton::PixmapButton (const QPixmap& off, const QPixmap& pressed) { m_isToggleButton = false; m_offPixmap = off; m_pressedPixmap = pressed; m_active = false; m_pressed = false; prepareGeometryChange(); m_bounds = QRectF(0, 0, pressed.width(), pressed.height()); setPixmap(m_offPixmap); m_pExpandedHitTarget = 0; } // constructor for toggle button PixmapButton::PixmapButton (QPixmap& off, QPixmap pressed, QPixmap& on) { m_isToggleButton = true; m_onPixmap = on; m_offPixmap = off; m_pressedPixmap = pressed; m_active = false; m_pressed = false; prepareGeometryChange(); m_bounds = QRectF(0, 0, pressed.width(), pressed.height()); setPixmap(m_offPixmap); m_pExpandedHitTarget = 0; } PixmapButton::PixmapButton(const QPixmap& composite,const QRect& offCoords,const QRect& pressedCoords) { m_isToggleButton = true; m_offPixmap = composite.copy(offCoords); m_pressedPixmap = composite.copy(pressedCoords); m_active = false; m_pressed = false; prepareGeometryChange(); m_bounds = QRectF(0, 0, m_pressedPixmap.width(), m_pressedPixmap.height()); setPixmap(m_offPixmap); m_pExpandedHitTarget = 0; } PixmapButton::~PixmapButton() { if (m_pExpandedHitTarget) delete m_pExpandedHitTarget; } void PixmapButton::setActive(bool active) { if(m_active == active) return; toggle(); } void PixmapButton::toggle() { if(m_active) { m_active = false; if(!m_pressed) setPixmap(m_offPixmap); } else { m_active = true; if(!m_pressed) setPixmap(m_onPixmap); } } void PixmapButton::mousePressEvent(QGraphicsSceneMouseEvent* event) { if(!isVisible()) return; m_pressed = true; setPixmap(m_pressedPixmap); update(); Q_EMIT clickOn(); } void PixmapButton::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if(!isVisible()) return; if(m_pressed && !isUnderMouse()) { m_pressed = false; if(m_active) setPixmap(m_onPixmap); else setPixmap(m_offPixmap); update(); ungrabMouse(); Q_EMIT clickComplete(); } } void PixmapButton::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { if(!isVisible()) return; const bool emitComplete = m_pressed; //m_pressed will be false if a moveEvent happened before m_pressed = false; if(m_active) setPixmap(m_onPixmap); else setPixmap(m_offPixmap); update(); if (emitComplete) { Q_EMIT clickComplete(); } } //virtual void PixmapButton::createLargerHitTargetRect(quint32 width,quint32 height) { if (m_pExpandedHitTarget) return; m_pExpandedHitTarget = new PixmapButtonHitTarget(QRectF(-(qreal)width/2.0,-(qreal)height/2.0,(qreal)width,(qreal)height),this); m_pExpandedHitTarget->setParentItem(this); m_pExpandedHitTarget->setPos(boundingRect().center()); m_pExpandedHitTarget->setVisible(true); } void PixmapButton::removeLargerHitTargetRect(quint32 width,quint32 height) { if (m_pExpandedHitTarget) { delete m_pExpandedHitTarget; m_pExpandedHitTarget = 0; } } void PixmapButton::enableLargerHitTargetRect() { if (m_pExpandedHitTarget) m_pExpandedHitTarget->setVisible(true); } void PixmapButton::disableLargerHitTargetRect() { if (m_pExpandedHitTarget) m_pExpandedHitTarget->setVisible(false); } //reimplemented trivially so it can be a slot void PixmapButton::setVisible(bool visible) { QGraphicsPixmapItem::setVisible(visible); if (m_pExpandedHitTarget) m_pExpandedHitTarget->setVisible(visible); } void PixmapButton::show() { setVisible(true); } void PixmapButton::hide() { setVisible(false); } void PixmapButton::setManualMode(bool manualModeEnabled) { if (manualModeEnabled) { ungrabMouse(); if (m_pExpandedHitTarget) { m_pExpandedHitTarget->ungrabMouse(); } } else { if (m_pExpandedHitTarget) { m_pExpandedHitTarget->grabMouse(); } else { grabMouse(); } } } void PixmapButton::simulateClick() { //This class never actually uses the contents of the event. QGraphicsSceneMouseEvent evt; mousePressEvent(&evt); mouseReleaseEvent(&evt); } PixmapButtonHitTarget::PixmapButtonHitTarget(const QRectF& hitRect,PixmapButton * pButton) : QObject() , QGraphicsItem(pButton) , m_boundingRect(hitRect) , m_qpButton(pButton) { setFlag(QGraphicsItem::ItemHasNoContents); } //virtual void PixmapButtonHitTarget::paint(QPainter* painter, const QStyleOptionGraphicsItem* options, QWidget* widget) { //DEBUG - uncomment to draw red outline on bound rect (i.e. the effective hit area) painter->save(); painter->setPen(Qt::red); painter->drawRect(m_boundingRect); painter->restore(); } #include <QDebug> void PixmapButtonHitTarget::mousePressEvent(QGraphicsSceneMouseEvent* event) { if (m_qpButton.isNull()) { event->ignore(); return; } PixmapButton ungrabMouse(); m_qpButton->grabMouse(); m_qpButton->mousePressEvent(event); //careful if PixmapButton's mousePressEvent() //ever needs to consider event's coordinates - they'll be in the wrong //coordinate space } void PixmapButtonHitTarget::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { //should never get this event->ignore(); } void PixmapButtonHitTarget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { //should never get this event->ignore(); }
[ "patrick@silentbluesystems.com" ]
patrick@silentbluesystems.com
7c0f16d9eb06bc9000ec3536a0e5b15eb00b4075
e0c5313b68b7592cb9ee848f9a7eabccf5246423
/RpcL2MuonSA/RpcDispPreparator.h
fe4d1b895430799d8cd1f1d341f91bfc5731aa78
[]
no_license
ktaniguc/RpcL2MuonSA
ab59d843f81ebbc027738010a5c135780e6a6d46
252a61335ad55d07856dd028e290153c384c6253
refs/heads/master
2021-06-22T04:32:05.021172
2021-03-01T03:46:40
2021-03-01T03:46:40
194,240,403
0
0
null
null
null
null
UTF-8
C++
false
false
4,647
h
#ifndef RpcDispPreparator_h #define RpcDispPreparator_h #include <TH2.h> #include <TStyle.h> #include <TCanvas.h> #include <iostream> #include "TH1F.h" #include "TF1.h" #include "TH2F.h" #include "TH3F.h" #include "TROOT.h" #include "TFile.h" #include "THStack.h" #include "TStyle.h" #include "TLatex.h" #include "TTree.h" #include "TChain.h" #include "TMath.h" #include "TString.h" #include "TProfile.h" #include "TColor.h" #include "TLegend.h" #include "TLegendEntry.h" #include "TPaveText.h" #include "TText.h" #include "TLatex.h" #include "TGraphErrors.h" #include "TApplication.h" #include "TVector3.h" #include <vector> #include <iostream> #include <stdlib.h> class RpcDispPreparator { public : RpcDispPreparator(); void SetParameter_rpcFit(//bool isTag, int NTrigChain, float* rpcFitInn, float* rpcFitMid, float* rpcFitOut, float rpcFitMidPhi, float rpcFitMidSlope, float rpcFitMidOffset, float rpcFitOutPhi, float rpcFitOutSlope, float rpcFitOutOffset ); void RpcHitSetter(const Int_t& nRPC, int& NTrigChain, vector<vector<double>>*& mesSA_rpcHitStationNumber, vector<vector<double>>*& mesSA_rpcHitR, vector<vector<double>>*& mesSA_rpcHitEta, vector<vector<double>>*& mesSA_rpcHitPhi, vector<vector<uint32_t>>*& mesSA_rpcHitLayer, vector<vector<uint32_t>>*& mesSA_rpcHitMeasuresPhi, vector < vector < float > >*& mesSA_rpcHitDistEtaRO, //ktaniguc trial add vector < vector < float > >*& mesSA_rpcHitDistPhiRO, vector < vector < float > >*& mesSA_rpcHitX, vector < vector < float > >*& mesSA_rpcHitY, vector < vector < float > >*& mesSA_rpcHitZ, //ktaniguc trial add end vector<vector<float>>& setRpc1HitEta, vector<vector<float>>& setRpc2HitEta, vector<vector<float>>& setRpc3HitEta, vector<vector<float>>& setRpc1HitPhi, vector<vector<float>>& setRpc2HitPhi, vector<vector<float>>& setRpc3HitPhi, vector < vector < float > >& setRpc1HitDistEtaRO, //ktaniguc trial add vector < vector < float > >& setRpc1HitDistPhiRO, vector < vector < float > >& setRpc2HitDistEtaRO, //ktaniguc trial add vector < vector < float > >& setRpc2HitDistPhiRO, vector < vector < float > >& setRpc3HitDistEtaRO, //ktaniguc trial add vector < vector < float > >& setRpc3HitDistPhiRO, vector<vector<uint32_t>>& setRpc1HitLayer, vector<vector<uint32_t>>& setRpc2HitLayer, vector<vector<uint32_t>>& setRpc3HitLayer, vector<vector<uint32_t>>& setRpc1HitMeasuresPhi, vector<vector<uint32_t>>& setRpc2HitMeasuresPhi, vector<vector<uint32_t>>& setRpc3HitMeasuresPhi ); void SetEta_rpcFit( int address, float* rpcFitInn, float* rpcFitMid, float* rpcFitOut, float& rpcFitInnEta, float& rpcFitMidEta, float& rpcFitOutEta); float SetR_rpcFit(double address); float calcRpcFitEta(float rpcFitSlope, float rpcFitOffset, float rpcFitR); void setGraphRpcStrip(bool isTag, TGraphErrors& gr_rpcEtaPhi, vector<float>& rpcHitEta, vector<float>& rpcHitPhi, vector<uint32_t>& rpcHitLayer, vector<uint32_t>& rpcHitMeasuresPhi); void setGraphRpcStripLayer(bool isTag, TGraphErrors& gr_rpcEtaPhi, vector<float>& rpcHitEta, vector<float>& rpcHitPhi, vector<uint32_t>& rpcHitLayer, vector<uint32_t>& rpcHitMeasuresPhi); bool isLowerLayer(uint32_t rpcHitLayer); }; #endif
[ "guchiwo7@gmail.com" ]
guchiwo7@gmail.com
63ca33de6dcb02400237c37871cf2f7a0c08da9c
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/include/functions/mpower.hpp
d8cf48f0efce0fc3ab172469fa297cae67793f09
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
160
hpp
#ifndef NT2_INCLUDE_FUNCTIONS_MPOWER_HPP_INCLUDED #define NT2_INCLUDE_FUNCTIONS_MPOWER_HPP_INCLUDED #include <nt2/linalg/include/functions/mpower.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
71870ff8147f52e1be89714a66f37157f20348c7
e5a37a543ca382ed3eaab28c37d267b04ad667c0
/probrems/AOJ0197.cpp
8319b51b6896710fc2f31c3800a2d0273d64b571
[]
no_license
akawashiro/competitiveProgramming
6dfbe626c2e2433d5e702e9431ee9de2c41337ed
ee8a582c80dbd5716ae900a02e8ea67ff8daae4b
refs/heads/master
2018-09-02T19:49:22.460865
2018-06-30T05:45:51
2018-06-30T05:45:51
71,694,415
0
0
null
null
null
null
UTF-8
C++
false
false
265
cpp
#include <stdio.h> #include <algorithm> using namespace std; int main(){ while(1){ int x,y; scanf("%d%d",&x,&y); if(!x&&!y) break; if(x<y) swap(x,y); int i; for(i=0;y!=0;i++){ x=x%y; swap(x,y); } printf("%d %d\n",x,i); } return 0; }
[ "akira@akiraMacBookPro.local" ]
akira@akiraMacBookPro.local
7724ccb8abbd26673120b6985d72a45e6da47d67
40e0e01bad8c36699ddbec72d489010f1a2907d8
/pizza/pizza/DataMager.h
66c952b093b32435eca92b7b90ad83adaeea7e91
[]
no_license
kimyongghwa/SoSuGeonGong
6dfd04c0c553380067f312ffcec3450688f4d1b5
0b2a7c513f2e0d2f2fa22b3b2ede3eb1804cd6c1
refs/heads/master
2023-01-21T10:33:00.930264
2020-11-26T07:37:30
2020-11-26T07:37:30
286,414,769
0
0
null
null
null
null
TIS-620
C++
false
false
359
h
#pragma once #include<fstream> #include<string> #define DataMgr DataMager::instance() using namespace std; class DataMager { private: string name = "วรทนภฬพ๎"; int level = 37; int exp = 1000000; public: DataMager() { } static DataMager* instance() { static DataMager inst; return &inst; } int getLevel() { return level; } };
[ "conna335@gmail.com" ]
conna335@gmail.com
a892ba71bd685d12139dee3380e24fc9f145e27b
b679b84463f625bd4da3c8ca75bb0b4ea8d11b2c
/libsg/interaction/InteractFrameSurfSampled.cpp
a3d7296f193a1d22e5f70ffbdb1965dd5569166e
[ "MIT" ]
permissive
msavva/pigraphs
bb99aad460d006d27dc1d93268ca7e67a576c7b0
ee794f3acef4eac418ca0f69bb410fef34b99246
refs/heads/master
2021-01-22T15:16:16.622222
2019-10-27T23:38:21
2019-10-27T23:38:21
59,326,524
42
5
null
null
null
null
UTF-8
C++
false
false
14,502
cpp
#include "common.h" // NOLINT #include "interaction/InteractFrameSurfSampled.h" // ReSharper disable once CppUnusedIncludeDirective #include <ext-boost/serialization.h> #include "core/Model.h" #include "core/ModelInstance.h" #include "core/OccupancyGrid.h" #include "core/Scan.h" #include "interaction/SkeletonInteraction.h" // ReSharper disable once CppUnusedIncludeDirective #include "util/eigen_boost_serialization.h" #include "util/timer.h" #include "vis/vis.h" #include "vis/ColorIndex.h" namespace sg { namespace interaction { using geo::Vec3f; using geo::Matrix3f; using geo::OBB; const string InteractionFrame::kSkeletonId = "Skeleton"; BOOST_BINARY_SERIALIZABLE_IMPL(InteractionFrame) InteractionFrame::InteractionFrame(const Vec3f& halfDims /*= Vec3f(1, 1, 1)*/, int numBinsPerDim /*= 10*/) : m_halfDims(halfDims) , m_numBinsPerDim(numBinsPerDim) , m_binDim(m_halfDims[0] * 2.f / m_numBinsPerDim) , m_invBinSize(1.f / m_binDim) , m_numBinsPerDimSq(m_numBinsPerDim * m_numBinsPerDim) , m_obb(Vec3f::Zero(), m_halfDims, Matrix3f::Identity()) , m_bins(m_numBinsPerDim * m_numBinsPerDimSq) { } void InteractionFrame::addPoint(const string& id, const Vec3f& worldPoint, bool boundChecks /*= false*/) { const auto localPoint = m_obb.worldToLocal() * worldPoint; const int idx = binIndex(localPoint); if (idx < 0 && boundChecks) { cerr << "[InteractionFrame] Warning: point outside range: " << localPoint << endl; } else if (idx >= 0) { m_bins[idx].inc(id); m_points[id].push_back(localPoint); m_observationsCount.inc(id); } else { // No bounds checking and index out of bounds so just ignore point } } void InteractionFrame::addPoint(const string& id, const ml::vec3f& worldPoint, bool boundChecks /*= false*/) { addPoint(id, geo::vec3f(worldPoint), boundChecks); } void InteractionFrame::reposition(const Skeleton& skel) { const Vec3f bn = geo::vec3f(skel.bodyPlaneNormal), front = Vec3f(bn[0], bn[1], 0).normalized(), right = front.cross(Vec3f::UnitZ()), centroid = geo::vec3f(skel.centerOfMass()); Matrix3f R; R.col(0) = right; R.col(1) = front; R.col(2) = Vec3f::UnitZ(); m_obb = OBB(centroid, m_halfDims, R); } void InteractionFrame::recenter(const Vec3f& center) { m_obb = OBB(center, m_halfDims, Matrix3f::Identity()); } vec<ml::vec3f> InteractionFrame::getWorldPoints(const string& id) const { if (m_points.count(id) == 0) { return vec<ml::vec3f>(); } const auto& obbPoints = m_points.at(id); const size_t numPoints = obbPoints.size(); vec<ml::vec3f> worldPoints(numPoints); const auto& worldT = m_obb.localToWorld(); for (size_t iPoint = 0; iPoint < numPoints; ++iPoint) { worldPoints[iPoint] = geo::to<ml::vec3f>(worldT * obbPoints[iPoint]); } return worldPoints; } void InteractionFrame::clearPoints() { m_points.clear(); m_bins.clear(); m_bins.resize(m_numBinsPerDim * m_numBinsPerDimSq); } void InteractionFrame::clearPoints(const string& id) { if (m_points.count(id) > 0) { m_points.at(id).clear(); } for (auto& bin : m_bins) { bin.resetCount(id); } } vec<InteractionFrame::Bin> InteractionFrame::getBins() const { vec<Bin> bins; for (int iBin = 0; iBin < m_bins.size(); ++iBin) { if (m_bins[iBin].totalCount() > 0) { // TODO(MS): Cache counting if performance issue bins.push_back({m_bins[iBin], binCenter(iBin)}); } } return bins; } // helper for selecting only major joints bool isMajorJoint(int i) { using J = core::Skeleton::JointGroupLR; return (i == J::JointGroupLR_Head || i == J::JointGroupLR_Hips || i == J::JointGroupLR_Torso || i == J::JointGroupLR_FootL || i == J::JointGroupLR_FootR || i == J::JointGroupLR_HandL || i == J::JointGroupLR_HandR || i == J::JointGroupLR_Gaze); }; void InteractionFrame::getWeightedColorBins(const vis::IFVisParams& p, ColoredBinGrid* out, bool dropLowWeightBins /*= true*/) const { util::Timer timer("getWeightedColorBins"); vis::ColorIndex cIndex; // Populate some information about each label struct LabelInfo { string id; string type; double weight; double normalization; ml::vec4f color; }; std::unordered_map<string, LabelInfo> labelTypeMap; vec<string> jointNames(kSkelParams.kNumJoints); for (int iJoint = 0; iJoint < kSkelParams.kNumJoints; iJoint++) { const string& jointId = kSkelParams.kJointNames[iJoint]; jointNames[iJoint] = jointId; } double normSkel = (p.renderSkelPts)? 1.0 / static_cast<double>(getBinWithMaxTotalCount(kSkeletonId).second) : 1.0; double normOcc = (p.renderOccupancy)? 1.0 / static_cast<double>(getBinWithMaxTotalCount({"OCC", "FREE", "UNK"}).second) : 1.0; for (int iJoint = 0; iJoint < kSkelParams.kNumJoints; iJoint++) { const string& jointId = kSkelParams.kJointNames[iJoint]; double weight = 1.0; if (p.pJointWeights) { const int wgi = Skeleton::kJointGroupLRToJointGroup.at(iJoint); // TODO(MS): Assumes kSkelParams is using JointGroupLR weight = p.pJointWeights[wgi]; } double normJoint = (p.renderJointPts)? 1.0 / static_cast<double>(getBinWithMaxTotalCount(jointId).second) : 1.0; labelTypeMap[jointId] = { jointId, "Joint", weight, normJoint, kSkelParams.kJointColors[iJoint] }; } labelTypeMap[kSkeletonId] = { kSkeletonId, kSkeletonId, 1.0, normSkel, cIndex.color(kSkeletonId, true).toVec4f() }; labelTypeMap["OCC"] = { "OCC", "Occupancy", 1.0, normOcc, cIndex.color("OCC", true).toVec4f() }; labelTypeMap["FREE"] = { "FREE", "Occupancy", 1.0, normOcc, cIndex.color("FREE", true).toVec4f() }; labelTypeMap["UNK"] = { "UNK", "Occupancy", 1.0, normOcc, cIndex.color("UNK", true).toVec4f() }; const auto& totalsCounter = getTotalsCounter(); const auto addPoint = [&] (int iBin, const stats::Counter<string>& bin, const ml::vec3f& pos, const string& id) { const auto& labelInfo = labelTypeMap[id]; const size_t count = bin.count(id); //const float ratio = count * totalCountInv; //const int numSamplesPerObservation = 1000; // TODO(MS): this really shouldn't be here //const float ratio = static_cast<float>(count) / totalsCounter.count(id) * numSamplesPerObservation; //const float binWeight2 = static_cast<float>(labelInfo.weight * ratio); const float binWeight = static_cast<float>(10 * labelInfo.weight * count * labelInfo.normalization); if (!dropLowWeightBins || binWeight > p.minBinWeight) { const float w = math::clamp((binWeight - p.minBinWeight) / (1 - p.minBinWeight), 0.f, 1.f); //cout << "bin " << iBin << " " << w << ", "<< binWeight << ", " << binWeight2 << endl; const auto c = labelInfo.color; const auto val = ml::vec4f(c.x, c.y, c.z, w); (*out)[binIndexToCoords(iBin)].emplace_back(ColoredBin{pos, val}); } }; const auto maxObjectLabelBin = getBinWithMaxTotalCount([&](const string& label) { return labelTypeMap.count(label) == 0; }); double normObjectLabel = (p.renderOccupancy)? 1.0 / static_cast<double>(maxObjectLabelBin.second) : 1.0; for (int iBin = 0; iBin < m_bins.size(); ++iBin) { const auto& bin = m_bins[iBin]; const auto pos = geo::to<ml::vec3f>(binCenter(iBin)); //const float totalCountInv = 1.f / bin.counter.totalCount(); // helper for adding entry to binCenters and binColors if (p.renderJointPts) { for (int iJoint = 0; iJoint < kSkelParams.kNumJoints; ++iJoint) { if (isMajorJoint(iJoint)) { const string jointName = kSkelParams.kJointNames[iJoint]; addPoint(iBin, bin, pos, jointName); } } } if (p.renderSkelPts) { addPoint(iBin, bin, pos, kSkeletonId); } if (p.renderOccupancy) { //addPoint(iBin, bin, pos, "FREE"); addPoint(iBin, bin, pos, "OCC"); addPoint(iBin, bin, pos, "UNK"); } if (p.renderObjectLabels) { for (const auto& it : bin) { const string& label = it.first; const size_t count = it.second; bool hasLabelInfo = labelTypeMap.count(label); bool isObjLabel = !hasLabelInfo || labelTypeMap.at(label).type == "ObjectLabel"; if (isObjLabel) { if (!hasLabelInfo) { const ml::RGBColor& crgb = cIndex.color(label, true); ml::vec4f c = crgb.toVec4f(); labelTypeMap[label] = { label, "ObjectLabel", 1.0, normObjectLabel, c}; SG_LOG_INFO << "Adding object label " << label; } addPoint(iBin, bin, pos, label); } } } } } void InteractionFrame::getBinWorldCentroids(vec<geo::Vec3f>* out) const { if (out->size() != m_bins.size()) { out->resize(m_bins.size()); } for (int iBin = 0; iBin < m_bins.size(); ++iBin) { (*out)[iBin] = m_obb.localToWorld() * binCenter(iBin); } } std::pair<int, size_t> InteractionFrame::getBinWithMaxTotalCount() const { pair<int, size_t> maxBin = {-1, 0}; for (int iBin = 0; iBin < m_bins.size(); ++iBin) { const auto& bin = m_bins[iBin]; const auto c = bin.totalCount(); if (c > maxBin.second) { maxBin.first = iBin; maxBin.second = c; } } return maxBin; } std::pair<int, size_t> InteractionFrame::getBinWithMaxTotalCount(const vec<string>& labels) const { pair<int, size_t> maxBin = {-1, 0}; for (int iBin = 0; iBin < m_bins.size(); ++iBin) { const auto& bin = m_bins[iBin]; size_t c = 0; for (const string& label : labels) { c += bin.count(label); } if (c > maxBin.second) { maxBin.first = iBin; maxBin.second = c; } } return maxBin; } std::pair<int, size_t> InteractionFrame::getBinWithMaxTotalCount(std::function<bool(const string&)> filterFn) const { pair<int, size_t> maxBin = {-1, 0}; for (int iBin = 0; iBin < m_bins.size(); ++iBin) { const auto& bin = m_bins[iBin]; size_t c = 0; for (const auto& p : bin) { if (filterFn(p.first)) { c += p.second; } } if (c > maxBin.second) { maxBin.first = iBin; maxBin.second = c; } } return maxBin; } double InteractionFrame::support(const Skeleton& skel, const core::Scan* pScan) { if (!pScan) { return 0.0; } const ml::BinaryGrid3& scanVoxelGrid = pScan->getOccupancyGrid().unknownOrOccupied(); const ml::mat4f& worldToGrid = pScan->getOccupancyGrid().worldToGrid(); return support(skel, scanVoxelGrid, worldToGrid, true); } double InteractionFrame::support(const Skeleton& skel, const core::ModelInstance& modelInstance) { const ml::BinaryGrid3& voxelGrid = modelInstance.model.solidVoxels; const ml::mat4f worldToModel = geo::to<ml::mat4f>(modelInstance.getParentToLocal()); const ml::mat4f worldToGrid = modelInstance.model.modelToVoxel * worldToModel; return support(skel, voxelGrid, worldToGrid, false); } double InteractionFrame::support(const Skeleton& skel, const ml::BinaryGrid3& voxelGrid, const ml::mat4f& worldToGrid, bool skipIfOutsideGrid) { vec<double> jointSupport(kSkelParams.kNumJoints, 0); double skelSupport = 0; vec<size_t> jointBinCounts(kSkelParams.kNumJoints, 0); size_t skelBinCount = 0; // TODO: Have boolean indicating if this repositioning needs to be done reposition(skel); // Get all nonempty frame bins and scan's voxel grid const auto bins = getBins(); size_t numOutsideVoxelGrid = 0; size_t numBins = bins.size(); for (const auto& bin : bins) { // Get bin center in voxel grid coords const auto binCenterWorld = m_obb.localToWorld() * bin.center; const ml::vec3f binCenterVoxel = worldToGrid * geo::to<ml::vec3f>(binCenterWorld); const ml::vec3i voxelCoord(static_cast<int>(binCenterVoxel.x), static_cast<int>(binCenterVoxel.y), static_cast<int>(binCenterVoxel.z)); bool isValidVoxel = voxelGrid.isValidCoordinate(voxelCoord.x, voxelCoord.y, voxelCoord.z); if (!isValidVoxel) { numOutsideVoxelGrid++; // Skip if outside scan voxelization if (skipIfOutsideGrid) { continue; } } const bool voxelOccupied = isValidVoxel && voxelGrid.isVoxelSet(voxelCoord.x, voxelCoord.y, voxelCoord.z); //const double totalCountInv = 1.0 / bin.counter.totalCount(); // If voxel set and joint interaction presence, add to support for (size_t iJoint = 0; iJoint < kSkelParams.kNumJoints; ++iJoint) { const string& jointId = kSkelParams.kJointNames[iJoint]; const size_t jointC = bin.counter.count(jointId); if (jointC == 0) { // No count for this joint continue; } const double sup = voxelOccupied ? jointC : 0.0; // Good if occupied, bad if empty // TODO(MS): weight this jointSupport[iJoint] += sup; jointBinCounts[iJoint]++; } // If voxel occupied and skeleton presence in frame, subtract from support const size_t skelC = bin.counter.count(kSkeletonId); if (skelC > 0) { skelSupport += voxelOccupied ? 0.0 : 1.0; // Bad if occupied, good if empty skelBinCount++; } } //const double skelWeight = 0.1, totalJointWeight = 1 - skelWeight; // Add up total support double totalJointSupport = 0.0, totalSkelSupport = 0.0, totalSupport = 0.0; int numJointsContributing = 0; for (size_t iJoint = 0; iJoint < kSkelParams.kNumJoints; ++iJoint) { //const size_t jointCount = jointBinCounts[iJoint]; const size_t jointCount = m_observationsCount.count(kSkelParams.kJointNames[iJoint]); if (jointCount == 0) { continue; } totalJointSupport += jointSupport[iJoint] / jointCount; numJointsContributing++; } if (skelBinCount > 0) { totalSkelSupport += skelSupport / skelBinCount; } if (numJointsContributing == 0) { totalSupport = totalSkelSupport; } else { totalSupport = totalSkelSupport + totalJointSupport / numJointsContributing; } SG_LOG_DEBUG << "IV numBins=" << numBins << ", numOutsideVoxelGrid=" << numOutsideVoxelGrid; SG_LOG_DEBUG << "IV totalSupport: " << totalSupport << " with totalSkelSupport=" << totalSkelSupport << " totalJointSupport=" << totalJointSupport << " numJointsContributing=" << numJointsContributing; return totalSupport; } } // namespace interaction } // namespace sg
[ "manolis.savva@gmail.com" ]
manolis.savva@gmail.com
0e5b577826987df8b248f711fb82f5eb082f11fe
ab1c643f224197ca8c44ebd562953f0984df321e
/wmi/wbem/winmgmt/provsubsys/decoupledclient/include/globals.h
f5f723d707ec8ddd771972f31c27588992f6d8be
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_admin
e162e0452fb2067f0675745f2273d5c569798709
d36e522f16bd866384bec440517f954a1a5c4a4d
refs/heads/master
2023-04-12T13:25:45.807158
2021-04-13T16:33:59
2021-04-13T16:33:59
357,613,696
0
1
null
null
null
null
UTF-8
C++
false
false
2,372
h
/*++ Copyright (C) 1996-2001 Microsoft Corporation Module Name: Globals.h Abstract: History: --*/ #ifndef _Globals_H #define _Globals_H #include <pssException.h> #include <Allocator.h> #include <BasicTree.h> #include <Cache.h> /****************************************************************************** * * Name: * * * Description: * * *****************************************************************************/ class DecoupledProviderSubSystem_Globals { public: static WmiAllocator *s_Allocator ; static LONG s_LocksInProgress ; static LONG s_ObjectsInProgress ; static LONG s_CServerClassFactory_ObjectsInProgress ; static LONG s_CServerObject_ProviderRegistrar_ObjectsInProgress ; static LONG s_CServerObject_ProviderEvents_ObjectsInProgress ; static LONG s_CInterceptor_DecoupledClient_ObjectsInProgress ; static LONG s_CDecoupled_IWbemSyncObjectSink_ObjectsInProgress ; static LONG s_CDecoupled_Batching_IWbemSyncObjectSink_ObjectsInProgress ; static LONG s_CInterceptor_IWbemDecoupledUnboundObjectSink_ObjectsInProgress ; static HRESULT Global_Startup () ; static HRESULT Global_Shutdown () ; static HRESULT BeginThreadImpersonation ( IUnknown *&a_OldContext , IServerSecurity *&a_OldSecurity , BOOL &a_Impersonating ) ; static HRESULT EndThreadImpersonation ( IUnknown *a_OldContext , IServerSecurity *a_OldSecurity , BOOL a_Impersonating ) ; static HRESULT Begin_IdentifyCall_PrvHost ( WmiInternalContext a_InternalContext , BOOL &a_Impersonating , IUnknown *&a_OldContext , IServerSecurity *&a_OldSecurity ) ; static HRESULT End_IdentifyCall_PrvHost ( WmiInternalContext a_InternalContext , IUnknown *&a_OldContext , IServerSecurity *&a_OldSecurity , BOOL &a_Impersonating ) ; static HRESULT Begin_IdentifyCall_SvcHost ( WmiInternalContext a_InternalContext , BOOL &a_Impersonating , IUnknown *&a_OldContext , IServerSecurity *&a_OldSecurity ) ; static HRESULT End_IdentifyCall_SvcHost ( WmiInternalContext a_InternalContext , IUnknown *&a_OldContext , IServerSecurity *&a_OldSecurity , BOOL &a_Impersonating ) ; static HRESULT AdjustSecurityDescriptorWithSystemSid ( SECURITY_DESCRIPTOR *&a_SecurityDescriptor , SECURITY_DESCRIPTOR *&a_AlteredSecurityDescriptor ) ; static HRESULT OpenTokenToSystem () ; } ; #endif // _Globals_H
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
1f84ca94c65fa17a4bd3a093e81a96d267da2ebf
f1d0f8140af5ccf5408513719345775e5e5d1a75
/src/debugger/debugger.h
d06ea663c88e8b9951dbdafd1c91fb872e78effc
[]
no_license
annulment/w_vr3
f08c41f2405c970ca2aa0c826ec1f3f11a3d35f1
2d1a265faf8ba38710f7528973cafc5d2541bc5c
refs/heads/master
2023-03-22T13:20:06.032628
2021-03-13T17:56:49
2021-03-13T17:56:49
345,869,170
0
0
null
null
null
null
UTF-8
C++
false
false
442
h
#ifndef _W_VR3_DEBUGGER_H #define _W_VR3_DEBUGGER_H #include "../w_vr3/w_vr3.h" namespace w_vr3 { class debugger { w_vr3::w_vr3_debug_level debug_level; public: debugger(w_vr3::w_vr3_debug_level debug_level); void debug(const char* msg); void debug(const char* msg, uint32_t error_code); void error(const char* msg); void error(const char* msg, uint32_t error_code); ~debugger(); }; } #endif // !_W_VR3_DEBUGGER_H
[ "minecon14@bk.ru" ]
minecon14@bk.ru
58e0c869f24177590378dcc7732be8e2e8c2fce8
f3bcc29738c2d0b3761550f58901ee39557a4a15
/ftrl/src/ftrl_train.h
4ba6e21a03e79a3a5f9a8a1c3bea87460f67c89d
[]
no_license
onejune/ftrl_model
3f1b433fdc074337d092a6102e88d786a3af8bb8
bad4e9862fa5dbcd72076b7406300918a86b0f78
refs/heads/master
2021-01-02T22:52:22.249299
2017-08-07T01:10:53
2017-08-07T01:10:53
99,408,626
0
0
null
null
null
null
UTF-8
C++
false
false
20,050
h
// Copyright (c) 2014-2015 The AsyncFTRL Project // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef SRC_FTRL_TRAIN_H #define SRC_FTRL_TRAIN_H #include <algorithm> #include <cstdint> #include <fstream> #include <string> #include <utility> #include <vector> #include "src/fast_ftrl_solver.h" #include "src/file_parser.h" #include "src/ftrl_solver.h" #include "src/stopwatch.h" template<typename T> size_t read_problem_info( const char* train_file, bool read_cache, size_t& line_cnt, size_t num_threads = 0); template<typename T, class Func> T evaluate_file(const char* path, const Func& func_predict, size_t num_threads = 0); template<typename T> T calc_loss(T y, T pred) { T max_sigmoid = static_cast<T>(MAX_SIGMOID); T min_sigmoid = static_cast<T>(MIN_SIGMOID); T one = 1.; pred = std::max(std::min(pred, max_sigmoid), min_sigmoid); T loss = y > 0 ? -log(pred) : -log(std::max(one - pred, min_sigmoid)); return loss; } template<typename T> class FtrlTrainer { public: FtrlTrainer(); virtual ~FtrlTrainer(); bool Initialize(size_t epoch, bool cache_feature_num = true); bool Train( T alpha, T beta, T l1, T l2, T dropout, size_t feat_num, const char* model_file, const char* train_file, const char* test_file = NULL); bool Train( const char* last_model, const char* model_file, const char* train_file, const char* test_file = NULL); protected: bool TrainImpl( const char* model_file, const char* train_file, size_t line_cnt, const char* test_file = NULL); private: size_t epoch_; bool cache_feature_num_; FtrlSolver<T> solver_; bool init_; bool read_stdin_; }; template<typename T> class LockFreeFtrlTrainer { public: LockFreeFtrlTrainer(); virtual ~LockFreeFtrlTrainer(); bool Initialize( size_t epoch, size_t num_threads, bool cache_feature_num = true); bool Train( T alpha, T beta, T l1, T l2, T dropout, const char* model_file, const char* train_file, const char* test_file = NULL); bool Train( const char* last_model, const char* model_file, const char* train_file, const char* test_file = NULL); protected: bool TrainImpl( const char* model_file, const char* train_file, size_t line_cnt, const char* test_file = NULL); private: size_t epoch_; bool cache_feature_num_; FtrlSolver<T> solver_; size_t num_threads_; bool init_; }; template<typename T> class FastFtrlTrainer { public: FastFtrlTrainer(); virtual ~FastFtrlTrainer(); bool Initialize( size_t epoch, size_t num_threads = 0, bool cache_feature_num = true, T burn_in = 0, size_t push_step = kPushStep, size_t fetch_step = kFetchStep); bool Train( T alpha, T beta, T l1, T l2, T dropout, const char* model_file, const char* train_file, const char* test_file = NULL); bool Train( const char* last_model, const char* model_file, const char* train_file, const char* test_file = NULL); protected: bool TrainImpl( const char* model_file, const char* train_file, size_t line_cnt, const char* test_file = NULL); private: size_t epoch_; bool cache_feature_num_; size_t push_step_; size_t fetch_step_; T burn_in_; FtrlParamServer<T> param_server_; size_t num_threads_; bool init_; }; template<typename T> FtrlTrainer<T>::FtrlTrainer() : epoch_(0), cache_feature_num_(false), init_(false), read_stdin_(false) { } template<typename T> FtrlTrainer<T>::~FtrlTrainer() { } template<typename T> bool FtrlTrainer<T>::Initialize(size_t epoch, bool cache_feature_num) { epoch_ = epoch; cache_feature_num_ = cache_feature_num; init_ = true; return init_; } template<typename T> bool FtrlTrainer<T>::Train( T alpha, T beta, T l1, T l2, T dropout, size_t feat_num, const char* model_file, const char* train_file, const char* test_file) { if (!init_) return false; if (strcmp(train_file, "stdin") == 0) { read_stdin_ = true; epoch_ = 1; cache_feature_num_ = false; } size_t line_cnt = 0; if (!read_stdin_) { feat_num = read_problem_info<T>(train_file, cache_feature_num_, line_cnt); } if (feat_num == 0) { printf("Usage: ./ftrl_train -f input_file -m model_file [options]\n" "options:\n" "--feat-num num : when use stdin as input_file, set feature num, default is 0\n" ); return false; } if (!solver_.Initialize(alpha, beta, l1, l2, feat_num, dropout)) { return false; } return TrainImpl(model_file, train_file, line_cnt, test_file); } template<typename T> bool FtrlTrainer<T>::Train( const char* last_model, const char* model_file, const char* train_file, const char* test_file) { if (!init_) return false; if (strcmp(train_file, "stdin") == 0) { read_stdin_ = true; epoch_ = 1; cache_feature_num_ = false; } size_t line_cnt = 0; if (!read_stdin_) { size_t feat_num = read_problem_info<T>(train_file, cache_feature_num_, line_cnt); if (feat_num == 0) return false; } if (!solver_.Initialize(last_model)) { return false; } return TrainImpl(model_file, train_file, line_cnt, test_file); } template<typename T> bool FtrlTrainer<T>::TrainImpl( const char* model_file, const char* train_file, size_t line_cnt, const char* test_file) { if (!init_) return false; fprintf( stdout, "params={alpha:%.2f, beta:%.2f, l1:%.2f, l2:%.2f, dropout:%.2f, epoch:%zu}\n", static_cast<float>(solver_.alpha()), static_cast<float>(solver_.beta()), static_cast<float>(solver_.l1()), static_cast<float>(solver_.l2()), static_cast<float>(solver_.dropout()), epoch_); auto predict_func = [&] (const std::vector<std::pair<size_t, T> >& x) { return solver_.Predict(x); }; StopWatch timer; double last_time = 0; for (size_t iter = 0; iter < epoch_; ++iter) { FileParser<T> file_parser; file_parser.OpenFile(train_file); std::vector<std::pair<size_t, T> > x; T y; size_t cur_cnt = 0, last_cnt = 0; T loss = 0; while (file_parser.ReadSample(y, x)) { T pred = solver_.Update(x, y); loss += calc_loss(y, pred); ++cur_cnt; if (cur_cnt - last_cnt > 100000 && timer.StopTimer() - last_time > 0.5) { if (!read_stdin_ && line_cnt > 0) { fprintf( stdout, "epoch=%zu processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\r", iter, cur_cnt * 100 / static_cast<float>(line_cnt), timer.ElapsedTime(), static_cast<float>(loss) / cur_cnt); } else { fprintf( stdout, "epoch=%zu processed=[%zu] time=[%.2f] train-loss=[%.6f]\r", iter, cur_cnt, timer.ElapsedTime(), static_cast<float>(loss) / cur_cnt); } fflush(stdout); last_cnt = cur_cnt; last_time = timer.ElapsedTime(); } } if (!read_stdin_ && line_cnt > 0) { fprintf( stdout, "epoch=%zu processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\n", iter, cur_cnt * 100 / static_cast<float>(line_cnt), timer.ElapsedTime(), static_cast<float>(loss) / cur_cnt); } else { fprintf( stdout, "epoch=%zu processed=[%zu] time=[%.2f] train-loss=[%.6f]\n", iter, cur_cnt, timer.ElapsedTime(), static_cast<float>(loss) / cur_cnt); } file_parser.CloseFile(); if (test_file) { T eval_loss = evaluate_file<T>(test_file, predict_func); printf("validation-loss=[%lf]\n", static_cast<double>(eval_loss)); } } return solver_.SaveModelAll(model_file); } template<typename T> LockFreeFtrlTrainer<T>::LockFreeFtrlTrainer() : epoch_(0), cache_feature_num_(false), num_threads_(0), init_(false) { } template<typename T> LockFreeFtrlTrainer<T>::~LockFreeFtrlTrainer() { } template<typename T> bool LockFreeFtrlTrainer<T>::Initialize( size_t epoch, size_t num_threads, bool cache_feature_num) { epoch_ = epoch; cache_feature_num_ = cache_feature_num; num_threads_ = num_threads; init_ = true; return init_; } template<typename T> bool LockFreeFtrlTrainer<T>::Train( T alpha, T beta, T l1, T l2, T dropout, const char* model_file, const char* train_file, const char* test_file) { if (!init_) return false; size_t line_cnt = 0; size_t feat_num = read_problem_info<T>(train_file, cache_feature_num_, line_cnt, num_threads_); if (feat_num == 0) return false; if (!solver_.Initialize(alpha, beta, l1, l2, feat_num, dropout)) { return false; } return TrainImpl(model_file, train_file, line_cnt, test_file); } template<typename T> bool LockFreeFtrlTrainer<T>::Train( const char* last_model, const char* model_file, const char* train_file, const char* test_file) { if (!init_) return false; size_t line_cnt = 0; size_t feat_num = read_problem_info<T>(train_file, cache_feature_num_, line_cnt, num_threads_); if (feat_num == 0) return false; if (!solver_.Initialize(last_model)) { return false; } return TrainImpl(model_file, train_file, line_cnt, test_file); } template<typename T> bool LockFreeFtrlTrainer<T>::TrainImpl( const char* model_file, const char* train_file, size_t line_cnt, const char* test_file) { if (!init_) return false; fprintf( stdout, "params={alpha:%.2f, beta:%.2f, l1:%.2f, l2:%.2f, dropout:%.2f, epoch:%zu}\n", static_cast<float>(solver_.alpha()), static_cast<float>(solver_.beta()), static_cast<float>(solver_.l1()), static_cast<float>(solver_.l2()), static_cast<float>(solver_.dropout()), epoch_); auto predict_func = [&] (const std::vector<std::pair<size_t, T> >& x) { return solver_.Predict(x); }; StopWatch timer; for (size_t iter = 0; iter < epoch_; ++iter) { FileParser<T> file_parser; file_parser.OpenFile(train_file); size_t count = 0; T loss = 0; SpinLock lock; auto worker_func = [&] (size_t i) { std::vector<std::pair<size_t, T> > x; T y; size_t local_count = 0; T local_loss = 0; while (1) { if (!file_parser.ReadSampleMultiThread(y, x)) { break; } T pred = solver_.Update(x, y); local_loss += calc_loss(y, pred); ++local_count; if (i == 0 && local_count % 10000 == 0) { size_t tmp_cnt = std::min(local_count * num_threads_, line_cnt); fprintf( stdout, "epoch=%zu processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\r", iter, tmp_cnt * 100 / static_cast<float>(line_cnt), timer.StopTimer(), static_cast<float>(local_loss) / local_count); fflush(stdout); } } { std::lock_guard<SpinLock> lockguard(lock); count += local_count; loss += local_loss; } }; util_parallel_run(worker_func, num_threads_); file_parser.CloseFile(); fprintf( stdout, "epoch=%zu processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\n", iter, count * 100 / static_cast<float>(line_cnt), timer.StopTimer(), static_cast<float>(loss) / count); if (test_file) { T eval_loss = evaluate_file<T>(test_file, predict_func); printf("validation-loss=[%lf]\n", static_cast<double>(eval_loss)); } } return solver_.SaveModelAll(model_file); } template<typename T> FastFtrlTrainer<T>::FastFtrlTrainer() : epoch_(0), cache_feature_num_(false), push_step_(0), fetch_step_(0), param_server_(), num_threads_(0), init_(false) { } template<typename T> FastFtrlTrainer<T>::~FastFtrlTrainer() { } template<typename T> bool FastFtrlTrainer<T>::Initialize( size_t epoch, size_t num_threads, bool cache_feature_num, T burn_in, size_t push_step, size_t fetch_step) { epoch_ = epoch; cache_feature_num_ = cache_feature_num; push_step_ = push_step; fetch_step_ = fetch_step; if (num_threads == 0) { num_threads_ = std::thread::hardware_concurrency(); } else { num_threads_ = num_threads; } burn_in_ = burn_in; init_ = true; return init_; } template<typename T> size_t read_problem_info( const char* train_file, bool read_cache, size_t& line_cnt, size_t num_threads) { size_t feat_num = 0; line_cnt = 0; SpinLock lock; FileParser<T> parser; auto read_from_cache = [&](const char* path) { std::fstream fin; fin.open(path, std::ios::in); fin >> line_cnt >> feat_num; if (!fin || fin.eof()) { feat_num = 0; line_cnt = 0; } fin.close(); }; auto write_to_cache = [&](const char* path) { std::fstream fout; fout.open(path, std::ios::out); fout << line_cnt << "\t" << feat_num << "\n"; fout.close(); }; auto read_problem_worker = [&](size_t i) { size_t local_max_feat = 0; size_t local_count = 0; std::vector<std::pair<size_t, T> > local_x; T local_y; while (1) { if (!parser.ReadSampleMultiThread(local_y, local_x)) break; for (auto& item : local_x) { if (item.first + 1 > local_max_feat) local_max_feat = item.first + 1; } ++local_count; } { std::lock_guard<SpinLock> lockguard(lock); line_cnt += local_count; if (local_max_feat > feat_num) feat_num = local_max_feat; } }; std::string cache_file = std::string(train_file) + ".cache"; bool cache_exists = FileParserBase<T>::FileExists(cache_file.c_str()); if (read_cache && cache_exists) { read_from_cache(cache_file.c_str()); } else { parser.OpenFile(train_file); fprintf(stdout, "loading..."); fflush(stdout); util_parallel_run(read_problem_worker, num_threads); parser.CloseFile(); } fprintf(stdout, "\rinstances=[%zu] features=[%zu]\n", line_cnt, feat_num); if (read_cache && !cache_exists) { write_to_cache(cache_file.c_str()); } return feat_num; } template<typename T> bool FastFtrlTrainer<T>::Train( T alpha, T beta, T l1, T l2, T dropout, const char* model_file, const char* train_file, const char* test_file) { if (!init_) return false; size_t line_cnt = 0; size_t feat_num = read_problem_info<T>(train_file, cache_feature_num_, line_cnt, num_threads_); if (feat_num == 0) return false; if (!param_server_.Initialize(alpha, beta, l1, l2, feat_num, dropout)) { return false; } return TrainImpl(model_file, train_file, line_cnt, test_file); } template<typename T> bool FastFtrlTrainer<T>::Train( const char* last_model, const char* model_file, const char* train_file, const char* test_file) { if (!init_) return false; size_t line_cnt = 0; size_t feat_num = read_problem_info<T>(train_file, cache_feature_num_, line_cnt, num_threads_); if (feat_num == 0) return false; if (!param_server_.Initialize(last_model)) { return false; } return TrainImpl(model_file, train_file, line_cnt, test_file); } template<typename T> bool FastFtrlTrainer<T>::TrainImpl( const char* model_file, const char* train_file, size_t line_cnt, const char* test_file) { if (!init_) return false; fprintf( stdout, "params={alpha:%.2f, beta:%.2f, l1:%.2f, l2:%.2f, dropout:%.2f, epoch:%zu}\n", static_cast<float>(param_server_.alpha()), static_cast<float>(param_server_.beta()), static_cast<float>(param_server_.l1()), static_cast<float>(param_server_.l2()), static_cast<float>(param_server_.dropout()), epoch_); FtrlWorker<T>* solvers = new FtrlWorker<T>[num_threads_]; for (size_t i = 0; i < num_threads_; ++i) { solvers[i].Initialize(&param_server_, push_step_, fetch_step_); } auto predict_func = [&] (const std::vector<std::pair<size_t, T> >& x) { return param_server_.Predict(x); }; StopWatch timer; for (size_t iter = 0; iter < epoch_; ++iter) { FileParser<T> file_parser; file_parser.OpenFile(train_file); size_t count = 0; T loss = 0; SpinLock lock; auto worker_func = [&] (size_t i) { std::vector<std::pair<size_t, T> > x; T y; size_t local_count = 0; T local_loss = 0; while (1) { if (!file_parser.ReadSampleMultiThread(y, x)) { break; } T pred = solvers[i].Update(x, y, &param_server_); local_loss += calc_loss(y, pred); ++local_count; if (i == 0 && local_count % 10000 == 0) { size_t tmp_cnt = std::min(local_count * num_threads_, line_cnt); fprintf( stdout, "epoch=%zu processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\r", iter, tmp_cnt * 100 / static_cast<float>(line_cnt), timer.StopTimer(), static_cast<float>(local_loss) / local_count); fflush(stdout); } } { std::lock_guard<SpinLock> lockguard(lock); count += local_count; loss += local_loss; } solvers[i].PushParam(&param_server_); }; if (iter == 0 && util_greater(burn_in_, (T)0)) { size_t burn_in_cnt = (size_t) (burn_in_ * line_cnt); std::vector<std::pair<size_t, T> > x; T y; T local_loss = 0; for (size_t i = 0; i < burn_in_cnt; ++i) { if (!file_parser.ReadSample(y, x)) { break; } T pred = param_server_.Update(x, y); local_loss += calc_loss(y, pred); if (i % 10000 == 0) { fprintf( stdout, "burn-in processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\r", (i + 1) * 100 / static_cast<float>(line_cnt), timer.StopTimer(), static_cast<float>(local_loss) / (i + 1)); fflush(stdout); } } fprintf( stdout, "burn-in processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\n", burn_in_cnt * 100 / static_cast<float>(line_cnt), timer.StopTimer(), static_cast<float>(local_loss) / burn_in_cnt); if (util_equal(burn_in_, (T)1)) continue; } for (size_t i = 0; i < num_threads_; ++i) { solvers[i].Reset(&param_server_); } util_parallel_run(worker_func, num_threads_); file_parser.CloseFile(); fprintf( stdout, "epoch=%zu processed=[%.2f%%] time=[%.2f] train-loss=[%.6f]\n", iter, count * 100 / static_cast<float>(line_cnt), timer.StopTimer(), static_cast<float>(loss) / count); if (test_file) { T eval_loss = evaluate_file<T>(test_file, predict_func, num_threads_); printf("validation-loss=[%lf]\n", static_cast<double>(eval_loss)); } } delete [] solvers; return param_server_.SaveModelAll(model_file); } template<typename T, class Func> T evaluate_file(const char* path, const Func& func_predict, size_t num_threads) { FileParser<T> parser; parser.OpenFile(path); size_t count = 0; T loss = 0; SpinLock lock; auto predict_worker = [&](size_t i) { size_t local_count = 0; T local_loss = 0; std::vector<std::pair<size_t, T> > local_x; T local_y; while (1) { bool res = parser.ReadSampleMultiThread(local_y, local_x); if (!res) break; local_loss += calc_loss(local_y, func_predict(local_x)); ++local_count; } { std::lock_guard<SpinLock> lockguard(lock); count += local_count; loss += local_loss; } }; util_parallel_run(predict_worker, num_threads); parser.CloseFile(); if (count > 0) loss /= count; return loss; } #endif // SRC_FTRL_TRAIN_H /* vim: set ts=4 sw=4 tw=0 noet :*/
[ "onejune@126.com" ]
onejune@126.com
5781140ebca70dd0b831809f5fa7f4890d35d226
fd215a59f1de02982e57457f99a992cc325e9a33
/datalog.h
49c065603dbc7e9047b2705ebbf4ed30b6d58924
[ "Apache-2.0" ]
permissive
asaparov/parser
6d4eca276d9c16fc89c939ab7ea399c03b14aaa2
28058ac13e825dba0646d6ac2e57f108880ea48c
refs/heads/master
2022-05-01T21:37:31.939206
2022-04-05T19:41:01
2022-04-05T19:41:01
93,598,703
29
4
null
null
null
null
UTF-8
C++
false
false
546,481
h
/** * datalog.h * * Created on: Jul 1, 2016 * Author: asaparov */ #ifndef DATALOG_H_ #define DATALOG_H_ #include <core/lex.h> #include <grammar/morphology.h> #include <limits.h> #include <type_traits> #include <atomic> #include <cctype> using namespace core; constexpr unsigned int DATALOG_LABEL_WILDCARD = UINT_MAX; constexpr unsigned int DATALOG_LABEL_EMPTY = UINT_MAX - 1; constexpr unsigned int DATALOG_LABEL_NOT = UINT_MAX - 2; constexpr char DATALOG_STRING_LABEL_WILDCARD = (char) -1; constexpr unsigned int PREDICATE_ANSWER = 1; constexpr unsigned int PREDICATE_COUNT = 2; constexpr unsigned int PREDICATE_SUM = 3; constexpr unsigned int PREDICATE_HIGHEST = 4; constexpr unsigned int PREDICATE_LOWEST = 5; constexpr unsigned int PREDICATE_HEIGHT = 6; constexpr unsigned int PREDICATE_LONGEST = 7; constexpr unsigned int PREDICATE_SHORTEST = 8; constexpr unsigned int PREDICATE_LENGTH = 9; constexpr unsigned int PREDICATE_LARGEST = 10; constexpr unsigned int PREDICATE_SMALLEST = 11; constexpr unsigned int PREDICATE_MOST = 12; constexpr unsigned int PREDICATE_FEWEST = 13; constexpr unsigned int PREDICATE_NOT = 14; constexpr unsigned int NUM_PREDICATES = 14; constexpr unsigned int PREDICATE_PARSE = 15; constexpr unsigned int DIRECTION_FORWARD = 16; constexpr unsigned int DIRECTION_BACKWARD = 17; constexpr unsigned int DIRECTION_BOTH = 18; constexpr unsigned int DIRECTION_SELF = 19; constexpr unsigned int DIRECTION_NONE = 20; constexpr unsigned int DIRECTION_PREDICATE = 21; constexpr unsigned int DIRECTION_CONSTANT = 22; constexpr unsigned int ARITY_ZERO = 23; constexpr unsigned int ARITY_ONE = 24; constexpr unsigned int ARITY_TWO = 25; constexpr unsigned int ARITY_THREE = 26; constexpr unsigned int ARITY_NULL = 27; constexpr unsigned int ARG_OTHER = 28; constexpr unsigned int DATALOG_TRUE = 29; constexpr unsigned int PREDICATE_LOC = 30; constexpr unsigned int PREDICATE_CONST = 31; constexpr unsigned int PREDICATE_ATTR = 32; constexpr unsigned int PREDICATE_OBJECT = 33; constexpr unsigned int NUMBER_OFFSET = 34; constexpr unsigned int INFLECTION_OFFSET = 34 + grammatical_number_count - 1; enum datalog_expression_type { DATALOG_PREDICATE = INFLECTION_OFFSET + 1, DATALOG_FUNCTION = INFLECTION_OFFSET + 2, DATALOG_TUPLE = INFLECTION_OFFSET + 3, DATALOG_LIST = INFLECTION_OFFSET + 4, DATALOG_VARIABLE = INFLECTION_OFFSET + 5, DATALOG_CONSTANT = INFLECTION_OFFSET + 6, DATALOG_INTEGER = INFLECTION_OFFSET + 7, DATALOG_STRING = INFLECTION_OFFSET + 8, DATALOG_EMPTY = INFLECTION_OFFSET + 9, DATALOG_ANY = INFLECTION_OFFSET + 10, DATALOG_NON_EMPTY = INFLECTION_OFFSET + 11 }; struct datalog_token_scribe { }; template<typename Stream> inline bool print(const string& str, Stream& out, const datalog_token_scribe& printer) { for (unsigned int i = 0; i < str.length; i++) { if (std::isspace(str[i]) || str[i] == '.') { return print('\'', out) && print(str, out) && print('\'', out); } } return print(str, out); } /** * Code for tokenizing/lexing Datalog data. */ bool populate_name_map(hash_map<string, unsigned int>& names) { bool success = true; success &= names.put("parse", PREDICATE_PARSE); success &= names.put("answer", PREDICATE_ANSWER); success &= names.put("count", PREDICATE_COUNT); success &= names.put("sum", PREDICATE_SUM); success &= names.put("highest", PREDICATE_HIGHEST); success &= names.put("lowest", PREDICATE_LOWEST); success &= names.put("height", PREDICATE_HEIGHT); success &= names.put("longest", PREDICATE_LONGEST); success &= names.put("shortest", PREDICATE_SHORTEST); success &= names.put("length", PREDICATE_LENGTH); success &= names.put("largest", PREDICATE_LARGEST); success &= names.put("smallest", PREDICATE_SMALLEST); success &= names.put("most", PREDICATE_MOST); success &= names.put("fewest", PREDICATE_FEWEST); success &= names.put("not", PREDICATE_NOT); success &= names.put("direction_forward", DIRECTION_FORWARD); success &= names.put("direction_backward", DIRECTION_BACKWARD); success &= names.put("direction_both", DIRECTION_BOTH); success &= names.put("direction_self", DIRECTION_SELF); success &= names.put("direction_none", DIRECTION_NONE); success &= names.put("direction_predicate", DIRECTION_PREDICATE); success &= names.put("direction_constant", DIRECTION_CONSTANT); success &= names.put("arity_zero", ARITY_ZERO); success &= names.put("arity_unary", ARITY_ONE); success &= names.put("arity_binary", ARITY_TWO); success &= names.put("arity_three", ARITY_THREE); success &= names.put("arity_null", ARITY_NULL); success &= names.put("arg_other", ARG_OTHER); success &= names.put("true", DATALOG_TRUE); success &= names.put("loc", PREDICATE_LOC); success &= names.put("const", PREDICATE_CONST); success &= names.put("attr", PREDICATE_ATTR); success &= names.put("object", PREDICATE_OBJECT); success &= names.put("sg", NUMBER_OFFSET + NUMBER_SINGULAR - 1); success &= names.put("pl", NUMBER_OFFSET + NUMBER_PLURAL - 1); success &= names.put("uncountable", NUMBER_OFFSET + NUMBER_UNCOUNTABLE - 1); success &= names.put("non_sg", NUMBER_OFFSET + NUMBER_NON_SINGULAR - 1); success &= names.put("non_pl", NUMBER_OFFSET + NUMBER_NON_PLURAL - 1); success &= names.put("all_numbers", NUMBER_OFFSET + NUMBER_ALL - 1); success &= names.put("no_number", NUMBER_OFFSET + NUMBER_NONE - 1); success &= names.put("past_participle", INFLECTION_OFFSET + INFLECTION_PAST_PARTICIPLE - 1); success &= names.put("present_participle", INFLECTION_OFFSET + INFLECTION_PRESENT_PARTICIPLE - 1); success &= names.put("infinitive", INFLECTION_OFFSET + INFLECTION_INFINITIVE - 1); success &= names.put("default_tense", INFLECTION_OFFSET + INFLECTION_OTHER_VERB - 1); success &= names.put("noun", INFLECTION_OFFSET + INFLECTION_NOUN - 1); success &= names.put("adjective", INFLECTION_OFFSET + INFLECTION_ADJECTIVE - 1); success &= names.put("comparative", INFLECTION_OFFSET + INFLECTION_COMPARATIVE - 1); success &= names.put("superlative", INFLECTION_OFFSET + INFLECTION_SUPERLATIVE - 1); success &= names.put("no_inflection", INFLECTION_OFFSET + INFLECTION_NONE - 1); success &= names.put("type_predicate", DATALOG_PREDICATE); success &= names.put("type_function", DATALOG_FUNCTION); success &= names.put("type_tuple", DATALOG_TUPLE); success &= names.put("type_list", DATALOG_LIST); success &= names.put("type_variable", DATALOG_VARIABLE); success &= names.put("type_constant", DATALOG_CONSTANT); success &= names.put("type_integer", DATALOG_INTEGER); success &= names.put("type_string", DATALOG_STRING); success &= names.put("type_empty", DATALOG_EMPTY); success &= names.put("type_any", DATALOG_ANY); success &= names.put("type_non_empty", DATALOG_NON_EMPTY); return success; } enum datalog_token_type { DATALOG_TOKEN_LBRACKET, DATALOG_TOKEN_RBRACKET, DATALOG_TOKEN_LPAREN, DATALOG_TOKEN_RPAREN, DATALOG_TOKEN_COMMA, DATALOG_TOKEN_PERIOD, DATALOG_TOKEN_IDENTIFIER, DATALOG_TOKEN_STRING, DATALOG_TOKEN_SLASH_PLUS, DATALOG_TOKEN_TAB }; typedef lexical_token<datalog_token_type> datalog_token; template<typename Stream> inline bool print(datalog_token_type type, Stream& stream) { switch (type) { case DATALOG_TOKEN_LBRACKET: return print('[', stream); case DATALOG_TOKEN_RBRACKET: return print(']', stream); case DATALOG_TOKEN_LPAREN: return print('(', stream); case DATALOG_TOKEN_RPAREN: return print(')', stream); case DATALOG_TOKEN_COMMA: return fprintf(stream, "COMMA") > 0; case DATALOG_TOKEN_PERIOD: return print('.', stream); case DATALOG_TOKEN_IDENTIFIER: return fprintf(stream, "IDENTIFIER") > 0; case DATALOG_TOKEN_STRING: return fprintf(stream, "STRING") > 0; case DATALOG_TOKEN_SLASH_PLUS: return fprintf(stream, "\\+") > 0; case DATALOG_TOKEN_TAB: return print('\t', stream); } fprintf(stderr, "print ERROR: Unknown datalog_token_type.\n"); return false; } enum datalog_lexer_state { DATALOG_LEXER_START, DATALOG_LEXER_IDENTIFIER, DATALOG_LEXER_QUOTE, DATALOG_LEXER_COMMENT }; bool datalog_emit_symbol(array<datalog_token>& tokens, const position& start, char symbol) { switch (symbol) { case ',': return emit_token(tokens, start, start + 1, DATALOG_TOKEN_COMMA); case '.': return emit_token(tokens, start, start + 1, DATALOG_TOKEN_PERIOD); case '(': return emit_token(tokens, start, start + 1, DATALOG_TOKEN_LPAREN); case ')': return emit_token(tokens, start, start + 1, DATALOG_TOKEN_RPAREN); case '[': return emit_token(tokens, start, start + 1, DATALOG_TOKEN_LBRACKET); case ']': return emit_token(tokens, start, start + 1, DATALOG_TOKEN_RBRACKET); case '\t': return emit_token(tokens, start, start + 1, DATALOG_TOKEN_TAB); default: fprintf(stderr, "datalog_emit_symbol ERROR: Unexpected symbol.\n"); return false; } } template<bool TokenizeTabs = true> bool datalog_lex(array<datalog_token>& tokens, FILE* input) { position start = position(1, 1); position current = position(1, 1); datalog_lexer_state state = DATALOG_LEXER_START; array<char> token = array<char>(1024); int prev = 0, next = fgetc(input); bool new_line = false; bool found_tab = TokenizeTabs; while (next != -1) { switch (state) { case DATALOG_LEXER_QUOTE: if (next == '\\') { /* escape character */ next = fgetc(input); current.column++; if (next == -1) { read_error("Unexpected end of stream", current); return false; } if (!token.add(next)) return false; } else if (next == '\'') { if (!emit_token(tokens, token, start, current, DATALOG_TOKEN_STRING)) return false; state = DATALOG_LEXER_START; token.clear(); } else { if (!token.add(next)) return false; } break; case DATALOG_LEXER_IDENTIFIER: if (next == ',' || next == '.' || next == '(' || next == ')' || next == '[' || next == ']' || (TokenizeTabs && next == '\t')) { if (TokenizeTabs && next == '\t') found_tab = true; if (!emit_token(tokens, token, start, current, DATALOG_TOKEN_IDENTIFIER) || !datalog_emit_symbol(tokens, current, next)) return false; state = DATALOG_LEXER_START; token.clear(); } else if (next == '\'') { read_error("Unexpected quote after identifier", current); return false; } else if (next == '\\') { read_error("Unexpected backslash after identifier", current); return false; } else if (next == ' ' || next == '\t' || next == '\n' || next == '\r') { if (!emit_token(tokens, token, start, current, DATALOG_TOKEN_IDENTIFIER)) return false; state = DATALOG_LEXER_START; token.clear(); new_line = (next == '\n'); } else { if (!token.add(next)) return false; } break; case DATALOG_LEXER_START: if (next == '\'' && found_tab) { state = DATALOG_LEXER_QUOTE; start = current; } else if (next == ',' || next == '.' || next == '(' || next == ')' || next == '[' || next == ']' || (TokenizeTabs && next == '\t')) { if (!datalog_emit_symbol(tokens, current, next)) return false; } else if (next == '\\') { next = fgetc(input); if (next != '+') { read_error("Expected '+'", current); return false; } if (!emit_token(tokens, current, current + 1, DATALOG_TOKEN_SLASH_PLUS)) return false; current.column++; } else if (next == ' ' || next == '\t' || next == '\n' || next == '\r') { new_line = (next == '\n'); } else if (next == '/') { next = fgetc(input); if (next != '*') { read_error("Expected '*'", current); return false; } state = DATALOG_LEXER_COMMENT; } else { if (!token.add(next)) return false; state = DATALOG_LEXER_IDENTIFIER; start = current; } break; case DATALOG_LEXER_COMMENT: if (prev == '*' && next == '/') { state = DATALOG_LEXER_START; } else if (next == '\n') { new_line = true; } break; } if (new_line) { current.line++; current.column = 1; found_tab = TokenizeTabs; new_line = false; } else current.column++; prev = next; next = fgetc(input); } if (state == DATALOG_LEXER_QUOTE) { read_error("Expected closing quote", current); return false; } else if (state == DATALOG_LEXER_IDENTIFIER) { return emit_token(tokens, token, start, current, DATALOG_TOKEN_IDENTIFIER); } return true; } /** * Recursive-descent parser for tokenized Datalog data. */ struct datalog_expression; bool datalog_interpret_expression( const array<datalog_token>& tokens, unsigned int& index, datalog_expression& exp, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables); inline bool exclude(unsigned int*& excluded, unsigned int& excluded_count, const unsigned int* to_exclude, unsigned int to_exclude_count) { unsigned int* excluded_union = (unsigned int*) malloc( sizeof(unsigned int) * (excluded_count + to_exclude_count)); if (excluded_union == NULL) { fprintf(stderr, "exclude ERROR: Out of memory.\n"); return false; } unsigned int excluded_union_count = 0; set_union(excluded_union, excluded_union_count, excluded, excluded_count, to_exclude, to_exclude_count); if (excluded_union_count == 0) { core::free(excluded_union); return true; } else if (excluded_count > 0) core::free(excluded); excluded = excluded_union; excluded_count = excluded_union_count; return true; } struct datalog_predicate { static constexpr unsigned int ARG_COUNT = 3; unsigned int function; unsigned int* excluded; unsigned int excluded_count; datalog_expression* args[ARG_COUNT]; inline bool is_excluded(unsigned int value) const { return index_of(value, excluded, excluded_count) < excluded_count; } inline bool ensure_excluded_capacity(unsigned int capacity) { if (excluded_count == 0) excluded = NULL; if (!resize(excluded, capacity)) { fprintf(stderr, "datalog_predicate.ensure_excluded_capacity ERROR: Unable to expand excluded array.\n"); return false; } return true; } bool exclude(const unsigned int* items, unsigned int count) { return ::exclude(excluded, excluded_count, items, count); } static inline void free(datalog_predicate& pred); }; struct datalog_function { unsigned int function; unsigned int* excluded; unsigned int excluded_count; unsigned int vars[2]; datalog_expression* arg; inline bool is_excluded(unsigned int value) const { return index_of(value, excluded, excluded_count) < excluded_count; } inline bool ensure_excluded_capacity(unsigned int capacity) { excluded = NULL; if (!resize(excluded, capacity)) { fprintf(stderr, "datalog_function.ensure_excluded_capacity ERROR: Unable to expand excluded array.\n"); return false; } return true; } bool exclude(const unsigned int* items, unsigned int count) { return ::exclude(excluded, excluded_count, items, count); } static inline void free(datalog_function& func); }; enum tuple_position { POSITION_LEFT, POSITION_RIGHT, POSITION_EXACT }; struct datalog_tuple { array<datalog_expression*> elements; tuple_position position; static inline void free(datalog_tuple& tuple); }; struct datalog_list { array<datalog_expression*> elements; static inline void free(datalog_list& list); }; struct datalog_literal { unsigned int label; unsigned int* excluded; unsigned int excluded_count; inline bool is_excluded(unsigned int value) const { return index_of(value, excluded, excluded_count) < excluded_count; } inline bool ensure_excluded_capacity(unsigned int capacity) { excluded = NULL; if (!resize(excluded, capacity)) { fprintf(stderr, "datalog_function.ensure_excluded_capacity ERROR: Unable to expand excluded array.\n"); return false; } return true; } bool exclude(const unsigned int* items, unsigned int count) { return ::exclude(excluded, excluded_count, items, count); } static inline void move(const datalog_literal& src, datalog_literal& dst) { dst.label = src.label; dst.excluded = src.excluded; dst.excluded_count = src.excluded_count; } static inline unsigned int hash(const datalog_literal& key) { unsigned int hash_value = default_hash(key.label); if (key.excluded_count > 0) hash_value ^= default_hash(key.excluded, key.excluded_count); return hash_value; } static inline bool is_empty(const datalog_literal& key) { return key.label == 0; } static inline void free(datalog_literal& literal); }; inline bool operator < (const datalog_literal& first, const datalog_literal& second) { if (first.label < second.label) return true; else if (first.label > second.label) return false; else if (first.excluded_count < second.excluded_count) return true; else if (first.excluded_count > second.excluded_count) return false; for (unsigned int i = 0; i < first.excluded_count; i++) { if (first.excluded[i] < second.excluded[i]) return true; else if (first.excluded[i] > second.excluded[i]) return false; } /* the literals are identical */ return false; } struct datalog_expression { datalog_expression_type type; unsigned int reference_count; union { datalog_predicate pred; datalog_function func; datalog_tuple tuple; datalog_list list; datalog_literal constant; unsigned int variable; int integer; string str; }; datalog_expression() : type(DATALOG_ANY), reference_count(1) { } datalog_expression(datalog_expression_type type) : type(type), reference_count(1) { } datalog_expression(const datalog_expression& src) : reference_count(1) { if (!initialize(src)) exit(EXIT_FAILURE); } ~datalog_expression() { free(); } inline void operator = (const datalog_expression& src) { reference_count = 1; if (!initialize(src)) exit(EXIT_FAILURE); } inline void recompute_hash() const { } static inline void move(const datalog_expression& src, datalog_expression& dst) { dst.type = src.type; dst.reference_count = src.reference_count; switch (src.type) { case DATALOG_PREDICATE: dst.pred.function = src.pred.function; dst.pred.excluded = src.pred.excluded; dst.pred.excluded_count = src.pred.excluded_count; for (unsigned int i = 0; i < array_length(src.pred.args); i++) dst.pred.args[i] = src.pred.args[i]; return; case DATALOG_FUNCTION: dst.func.function = src.func.function; dst.func.excluded = src.func.excluded; dst.func.excluded_count = src.func.excluded_count; dst.func.arg = src.func.arg; for (unsigned int i = 0; i < array_length(src.func.vars); i++) dst.func.vars[i] = src.func.vars[i]; return; case DATALOG_TUPLE: core::move(src.tuple.elements, dst.tuple.elements); dst.tuple.position = src.tuple.position; return; case DATALOG_LIST: core::move(src.list.elements, dst.list.elements); return; case DATALOG_VARIABLE: dst.variable = src.variable; return; case DATALOG_CONSTANT: dst.constant.label = src.constant.label; dst.constant.excluded = src.constant.excluded; dst.constant.excluded_count = src.constant.excluded_count; return; case DATALOG_INTEGER: dst.integer = src.integer; return; case DATALOG_STRING: string::move(src.str, dst.str); return; case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: return; } fprintf(stderr, "datalog_expression.move ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } static inline void swap(datalog_expression& first, datalog_expression& second) { char* first_data = (char*) &first; char* second_data = (char*) &second; for (unsigned int i = 0; i < sizeof(datalog_expression); i++) core::swap(first_data[i], second_data[i]); } static inline bool is_empty(const datalog_expression& key) { return key.reference_count == 0; } static inline unsigned int hash(const datalog_expression& key) { unsigned int hash_value; switch (key.type) { case DATALOG_PREDICATE: hash_value = default_hash(key.pred.function); if (key.pred.excluded_count > 0) hash_value ^= default_hash(key.pred.excluded, key.pred.excluded_count); for (unsigned int i = 0; i < array_length(key.pred.args); i++) { if (key.pred.args[i] == NULL) continue; hash_value ^= hash(*key.pred.args[i]); } return 0 + 11 * hash_value; case DATALOG_FUNCTION: hash_value = default_hash(key.func.function); if (key.func.excluded_count > 0) hash_value ^= default_hash(key.func.excluded, key.func.excluded_count); if (key.func.arg != NULL) hash_value ^= hash(*key.func.arg); for (unsigned int i = 0; i < array_length(key.func.vars); i++) { if (key.func.vars[i] == 0) break; hash_value ^= default_hash(key.func.vars[i]); } return 1 + 11 * hash_value; case DATALOG_TUPLE: hash_value = default_hash(key.tuple.position); for (unsigned int i = 0; i < key.tuple.elements.length; i++) hash_value ^= hash(*key.tuple.elements[i]); return 2 + 11 * hash_value; case DATALOG_LIST: hash_value = 0; for (unsigned int i = 0; i < key.list.elements.length; i++) hash_value ^= hash(*key.list.elements[i]); return 3 + 11 * hash_value; case DATALOG_VARIABLE: return 4 + 11 * default_hash(key.variable); case DATALOG_CONSTANT: return 5 + 11 * datalog_literal::hash(key.constant); case DATALOG_INTEGER: return 6 + 11 * default_hash(key.integer); case DATALOG_STRING: return 7 + 11 * string::hash(key.str); case DATALOG_EMPTY: return 8; case DATALOG_ANY: return 9; case DATALOG_NON_EMPTY: return 10; } fprintf(stderr, "datalog_expression.hash ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } static inline void free(datalog_expression& exp) { exp.free(); } private: template<typename... Args> inline bool initialize(const datalog_expression& src, Args&&... args); inline void free() { reference_count--; if (reference_count == 0) { switch (type) { case DATALOG_PREDICATE: core::free(pred); break; case DATALOG_FUNCTION: core::free(func); break; case DATALOG_TUPLE: core::free(tuple); break; case DATALOG_LIST: core::free(list); break; case DATALOG_VARIABLE: core::free(variable); break; case DATALOG_CONSTANT: core::free(constant); break; case DATALOG_INTEGER: core::free(integer); break; case DATALOG_STRING: core::free(str); break; case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: break; } } } template<typename... Args> friend bool init(datalog_expression&, const datalog_expression&, Args&&...); }; struct datalog_expression_root { /* semantic information */ datalog_expression root; /* syntactic information */ grammatical_number index; grammatical_number concord; inflection inf; datalog_expression_root() : index(NUMBER_ANY), concord(NUMBER_ANY), inf(INFLECTION_ANY) { } datalog_expression_root(const datalog_expression_root& src) : root(src.root), index(src.index), concord(src.concord), inf(src.inf) { } inline void operator = (const datalog_expression_root& src) { root = src.root; index = src.index; concord = src.concord; inf = src.inf; } inline void recompute_hash() const { root.recompute_hash(); } static inline void move(const datalog_expression_root& src, datalog_expression_root& dst) { datalog_expression::move(src.root, dst.root); dst.index = src.index; dst.concord = src.concord; dst.inf = src.inf; } static inline void swap(datalog_expression_root& first, datalog_expression_root& second) { datalog_expression::swap(first.root, second.root); core::swap(first.index, second.index); core::swap(first.concord, second.concord); core::swap(first.inf, second.inf); } static inline bool is_empty(const datalog_expression_root& key) { return datalog_expression::is_empty(key.root); } static inline unsigned int hash(const datalog_expression_root& key) { return datalog_expression::hash(key.root) ^ default_hash(key.index) ^ default_hash(key.concord) ^ default_hash(key.inf); } static inline void free(datalog_expression_root& exp) { datalog_expression::free(exp.root); } enum feature { FEATURE_NULL = 0, FEATURE_FUNCTION = 1, FEATURE_FUNCTION_ONLY = 2, FEATURE_FUNCTION_ANSWER = 3, FEATURE_HAS_FUNCTION = 4, FEATURE_HAS_FUNCTION_NOT = 5, FEATURE_HAS_FUNCTION_COUNT_NOT = 6, FEATURE_HAS_FUNCTION_ANSWER = 7, FEATURE_PREDICATE = 8, FEATURE_PREDICATE_ONLY = 9, FEATURE_FIRST_PREDICATE = 10, FEATURE_SECOND_PREDICATE = 11, FEATURE_THIRD_PREDICATE = 12, FEATURE_LAST_PREDICATE = 13, FEATURE_DIRECTION = 14, FEATURE_DIRECTION_ROOT = 15, FEATURE_CONSTANT = 16, FEATURE_PREDICATE_ARITY = 17, FEATURE_ARG1 = 18, FEATURE_ARG2 = 19, FEATURE_ARG3 = 20, FEATURE_ARG1_ONLY = 21, FEATURE_ARG2_ONLY = 22, FEATURE_ARG3_ONLY = 23, FEATURE_ARG2_ARITY = 24, FEATURE_NUMBER = 25, FEATURE_INFLECTION = 26 }; enum function_type { FUNCTION_EMPTY = 0, FUNCTION_IDENTITY = 1, FUNCTION_IDENTITY_COORD = 2, FUNCTION_NULL = 3, FUNCTION_SELECT_LEFT = 4, FUNCTION_SELECT_LEFT_COORD = 5, FUNCTION_SELECT_LEFT_DELETE_FEATURES = 6, FUNCTION_SELECT_LEFT_CONCORD_SINGULAR = 7, FUNCTION_SELECT_LEFT_DISJOINT = 8, FUNCTION_SELECT_LEFT_DISJOINT_COORD = 9, FUNCTION_SELECT_LEFT2 = 10, FUNCTION_SELECT_LEFT2_DELETE_FEATURES = 11, FUNCTION_SELECT_LEFT2_DISJOINT = 12, FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR = 13, FUNCTION_SELECT_LEFT2_DISJOINT_COORD = 14, FUNCTION_SELECT_LEFT3_DISJOINT = 15, FUNCTION_SELECT_LEFT4_DISJOINT = 16, FUNCTION_SELECT_LEFT5_DISJOINT = 17, FUNCTION_SELECT_LEFT6_DISJOINT = 18, FUNCTION_SELECT_LEFT7_DISJOINT = 19, FUNCTION_SELECT_LEFT_KEEP_FUNCTION = 20, FUNCTION_SELECT_LEFT_KEEP_FUNCTION_DISJOINT = 21, FUNCTION_SELECT_LEFT2_KEEP_FUNCTION = 22, FUNCTION_SELECT_LEFT2_KEEP_FUNCTION_DISJOINT = 23, FUNCTION_SELECT_LEFT3_KEEP_FUNCTION = 24, FUNCTION_SELECT_LEFT_DELETE_HEAD = 25, FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR = 26, FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT = 27, FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD = 28, FUNCTION_SELECT_LEFT_DELETE_FUNCTION = 29, FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES = 30, FUNCTION_SELECT_LEFT_DELETE_ANSWER = 31, FUNCTION_SELECT_LEFT2_DELETE_ANSWER = 32, FUNCTION_SELECT_LEFT3_DELETE_ANSWER = 33, FUNCTION_SELECT_LEFT3_DELETE_ANSWER_DISJOINT = 34, FUNCTION_SELECT_LEFT5_DELETE_ANSWER_DISJOINT = 35, FUNCTION_SELECT_LEFT_DELETE_ANSWER_HEAD = 36, FUNCTION_SELECT_LEFT_DELETE_COUNT_ANSWER = 37, FUNCTION_SELECT_LEFT2_DELETE_COUNT_ANSWER = 38, FUNCTION_SELECT_LEFT3_DELETE_COUNT_ANSWER = 39, FUNCTION_SELECT_LEFT_DELETE_FUNCTION_ANSWER = 40, FUNCTION_SELECT_LEFT2_DELETE_FUNCTION_ANSWER = 41, FUNCTION_SELECT_LEFT3_DELETE_FUNCTION_ANSWER = 42, FUNCTION_SELECT_LEFT_DELETE_NOT = 43, FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES = 44, FUNCTION_SELECT_RIGHT = 45, FUNCTION_SELECT_RIGHT2 = 46, FUNCTION_SELECT_RIGHT2_SINGULAR = 47, FUNCTION_SELECT_RIGHT2_DISJOINT = 48, FUNCTION_SELECT_RIGHT3_DISJOINT = 49, FUNCTION_SELECT_RIGHT4_DISJOINT = 50, FUNCTION_SELECT_RIGHT5_DISJOINT = 51, FUNCTION_SELECT_RIGHT6_DISJOINT = 52, FUNCTION_SELECT_RIGHT7_DISJOINT = 53, FUNCTION_SELECT_RIGHT_DELETE_HEAD = 54, FUNCTION_SELECT_RIGHT_DELETE_FUNCTION = 55, FUNCTION_SELECT_RIGHT2_DELETE_ANSWER = 56, FUNCTION_SELECT_FUNCTION = 57, FUNCTION_SELECT_FUNCTION_DELETE_FEATURES = 58, FUNCTION_SELECT_FUNCTION_DELETE_HEAD = 59, FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES = 60, FUNCTION_DELETE_LEFT = 61, FUNCTION_DELETE_LEFT_COORD = 62, FUNCTION_DELETE_LEFT_FEATURES = 63, FUNCTION_DELETE_LEFT_DISJOINT = 64, FUNCTION_DELETE_LEFT_DISJOINT_COORD = 65, FUNCTION_DELETE_LEFT2 = 66, FUNCTION_DELETE_LEFT2_DISJOINT = 67, FUNCTION_DELETE_LEFT2_DISJOINT_COORD = 68, FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES = 201, FUNCTION_DELETE_LEFT3_DISJOINT = 69, FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES = 202, FUNCTION_DELETE_LEFT4_DISJOINT = 70, FUNCTION_DELETE_LEFT5_DISJOINT = 71, FUNCTION_DELETE_LEFT6_DISJOINT = 72, FUNCTION_DELETE_LEFT7_DISJOINT = 73, FUNCTION_DELETE_LEFT_HEAD = 74, FUNCTION_DELETE_LEFT_HEAD_FEATURES = 75, FUNCTION_DELETE_LEFT2_HEAD = 76, FUNCTION_DELETE_LEFT2_HEAD_FEATURES = 77, FUNCTION_DELETE_LEFT_FUNCTION = 78, FUNCTION_DELETE_LEFT_FUNCTION_DISJOINT = 79, FUNCTION_DELETE_LEFT2_FUNCTION = 80, FUNCTION_DELETE_LEFT2_FUNCTION_DISJOINT = 81, FUNCTION_DELETE_LEFT_FUNCTION_HEAD = 82, FUNCTION_DELETE_LEFT3_FUNCTION_HEAD = 83, FUNCTION_DELETE_LEFT_KEEP_ANSWER = 84, FUNCTION_DELETE_LEFT_KEEP_FUNCTION = 85, FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION = 86, FUNCTION_DELETE_LEFT_HEAD_KEEP_FUNCTION = 87, FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION = 88, FUNCTION_DELETE_LEFT_HEAD_KEEP_NOT = 89, FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT = 90, FUNCTION_DELETE_LEFT_ANSWER = 91, FUNCTION_DELETE_LEFT2_ANSWER = 92, FUNCTION_DELETE_LEFT3_ANSWER = 93, FUNCTION_DELETE_LEFT3_ANSWER_DISJOINT = 94, FUNCTION_DELETE_LEFT5_ANSWER_DISJOINT = 95, FUNCTION_DELETE_LEFT_ANSWER_HEAD = 96, FUNCTION_DELETE_LEFT_COUNT_ANSWER = 97, FUNCTION_DELETE_LEFT2_COUNT_ANSWER = 98, FUNCTION_DELETE_LEFT3_COUNT_ANSWER = 99, FUNCTION_DELETE_LEFT_FUNCTION_ANSWER = 100, FUNCTION_DELETE_LEFT2_FUNCTION_ANSWER = 101, FUNCTION_DELETE_LEFT3_FUNCTION_ANSWER = 102, FUNCTION_DELETE_LEFT_ANSWER_KEEP_FUNCTION = 103, FUNCTION_DELETE_LEFT_ANSWER_HEAD_KEEP_FUNCTION = 104, FUNCTION_DELETE_LEFT2_ANSWER_KEEP_FUNCTION = 105, FUNCTION_DELETE_LEFT2_ANSWER_HEAD_KEEP_FUNCTION = 106, FUNCTION_DELETE_LEFT3_ANSWER_KEEP_FUNCTION = 107, FUNCTION_DELETE_LEFT3_ANSWER_HEAD_KEEP_FUNCTION = 108, FUNCTION_DELETE_RIGHT = 109, FUNCTION_DELETE_RIGHT2 = 110, FUNCTION_DELETE_RIGHT2_DISJOINT = 111, FUNCTION_DELETE_RIGHT3_DISJOINT = 112, FUNCTION_DELETE_RIGHT4_DISJOINT = 113, FUNCTION_DELETE_RIGHT5_DISJOINT = 114, FUNCTION_DELETE_RIGHT6_DISJOINT = 115, FUNCTION_DELETE_RIGHT7_DISJOINT = 116, FUNCTION_DELETE_RIGHT_HEAD = 117, FUNCTION_DELETE_RIGHT_HEAD_KEEP_FUNCTION = 118, FUNCTION_DELETE_RIGHT2_ANSWER = 119, FUNCTION_DELETE_COUNT = 120, FUNCTION_DELETE_COUNT_HEAD = 121, FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL = 122, FUNCTION_DELETE_COUNT_ANSWER = 123, FUNCTION_DELETE_NOT = 124, FUNCTION_DELETE_NOT_FEATURES = 125, FUNCTION_DELETE_NOT_INFINITIVE = 126, FUNCTION_DELETE_LEFT_NOT_HEAD = 127, FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES = 128, FUNCTION_DELETE_FUNCTION = 129, FUNCTION_DELETE_FUNCTION_HEAD = 130, FUNCTION_DELETE_FUNCTION_FEATURES = 131, FUNCTION_DELETE_ANSWER = 132, FUNCTION_DELETE_ANSWER_HAS_LOC = 133, FUNCTION_SELECT_ARG1 = 134, FUNCTION_SELECT_ARG1_SINGULAR = 235, FUNCTION_SELECT_ARG1_PLURAL = 236, FUNCTION_SELECT_ARG1_ONLY = 234, FUNCTION_SELECT_ARG1_DELETE_FEATURES = 237, FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES = 243, FUNCTION_SELECT_ARG2 = 136, FUNCTION_SELECT_ARG2_ONLY = 244, FUNCTION_SELECT_ARG2_DELETE_FEATURES = 238, FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES = 245, FUNCTION_SELECT_ARG3 = 137, FUNCTION_SELECT_ARG3_ONLY = 246, FUNCTION_SELECT_ARG3_DELETE_FEATURES = 138, FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES = 247, FUNCTION_DELETE_ARG1 = 139, FUNCTION_DELETE_ARG1_SINGULAR = 239, FUNCTION_DELETE_ARG1_PLURAL = 240, FUNCTION_DELETE_ARG1_FEATURES = 241, FUNCTION_DELETE_ARG2 = 140, FUNCTION_DELETE_ARG2_FEATURES = 242, FUNCTION_DELETE_ARG3 = 141, FUNCTION_DELETE_ARGS = 142, FUNCTION_DELETE_ARGS_CONCORD_SINGULAR = 143, FUNCTION_DELETE_ARGS_KEEP_PLURAL = 144, FUNCTION_HEAD_ARG1_SELECT_ARG2 = 145, FUNCTION_HEAD_ARG1_SELECT_ARG2_ONLY = 146, FUNCTION_EMPTY_TUPLE = 147, FUNCTION_EMPTY_TUPLE_ONLY = 148, FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR = 149, FUNCTION_KEEP_NULL = 249, FUNCTION_EMPTY_ARG2 = 150, FUNCTION_EMPTY_ARGS = 248, FUNCTION_ARG2_ZERO_ARITY = 250, FUNCTION_LOC = 151, FUNCTION_TWO_PREDICATES = 152, /* functions that relate to syntactic information */ FUNCTION_SINGULAR = 153, FUNCTION_PLURAL = 154, FUNCTION_UNCOUNTABLE = 155, FUNCTION_CONCORD_SINGULAR = 156, FUNCTION_CONCORD_PLURAL = 157, FUNCTION_CONCORD_UNCOUNTABLE = 158, FUNCTION_CONCORD_NON_SINGULAR = 159, FUNCTION_CONCORD_NON_PLURAL = 160, FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR = 252, FUNCTION_CONCORD_ALL = 161, FUNCTION_KEEP_CONCORD_SINGULAR = 251, FUNCTION_KEEP_CONCORD_PLURAL = 253, FUNCTION_KEEP_CONCORD_UNCOUNTABLE = 254, FUNCTION_DELETE_NOT_CONCORD_SINGULAR = 162, FUNCTION_DELETE_NOT_CONCORD_PLURAL = 163, FUNCTION_KEEP_SINGULAR = 164, FUNCTION_KEEP_PLURAL = 165, FUNCTION_KEEP_UNCOUNTABLE = 166, FUNCTION_INFINITIVE = 167, FUNCTION_PRESENT_PARTICIPLE = 168, FUNCTION_PAST_PARTICIPLE = 169, FUNCTION_KEEP_PRESENT_PARTICIPLE = 170, FUNCTION_KEEP_PAST_PARTICIPLE = 171, FUNCTION_FLIP_PREDICATE = 172, FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE = 173, FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE = 174, FUNCTION_KEEP_FEATURES = 175, FUNCTION_DELETE_FEATURES = 176 }; struct function { function_type type; constexpr function(const function_type& type) : type(type) { } static inline unsigned int hash(const function& f) { return default_hash(f.type); } static inline bool is_empty(const function& f) { return f.type == FUNCTION_EMPTY; } static inline void set_empty(function& f) { f.type = FUNCTION_EMPTY; } }; static constexpr function default_function() { return function(FUNCTION_NULL); } template<typename Stream> static inline bool read(feature& f, Stream& stream) { unsigned char c; if (!core::read(c, stream)) return false; f = static_cast<datalog_expression_root::feature>(c); return true; } template<typename Stream> static inline bool write(const feature& f, Stream& stream) { return core::write((unsigned char) f, stream); } static bool interpret(feature& f, const string& name) { if (name == "function") { f = datalog_expression_root::FEATURE_FUNCTION; } else if (name == "function_only") { f = datalog_expression_root::FEATURE_FUNCTION_ONLY; } else if (name == "function_answer") { f = datalog_expression_root::FEATURE_FUNCTION_ANSWER; } else if (name == "has_function") { f = datalog_expression_root::FEATURE_HAS_FUNCTION; } else if (name == "has_function_answer") { f = datalog_expression_root::FEATURE_HAS_FUNCTION_ANSWER; } else if (name == "has_function_not") { f = datalog_expression_root::FEATURE_HAS_FUNCTION_NOT; } else if (name == "has_function_count_not") { f = datalog_expression_root::FEATURE_HAS_FUNCTION_COUNT_NOT; } else if (name == "predicate") { f = datalog_expression_root::FEATURE_PREDICATE; } else if (name == "predicate_only") { f = datalog_expression_root::FEATURE_PREDICATE_ONLY; } else if (name == "first_predicate") { f = datalog_expression_root::FEATURE_FIRST_PREDICATE; } else if (name == "second_predicate") { f = datalog_expression_root::FEATURE_SECOND_PREDICATE; } else if (name == "third_predicate") { f = datalog_expression_root::FEATURE_THIRD_PREDICATE; } else if (name == "last_predicate") { f = datalog_expression_root::FEATURE_LAST_PREDICATE; } else if (name == "direction") { f = datalog_expression_root::FEATURE_DIRECTION; } else if (name == "direction_root") { f = datalog_expression_root::FEATURE_DIRECTION_ROOT; } else if (name == "constant") { f = datalog_expression_root::FEATURE_CONSTANT; } else if (name == "arity") { f = datalog_expression_root::FEATURE_PREDICATE_ARITY; } else if (name == "arg1") { f = datalog_expression_root::FEATURE_ARG1; } else if (name == "arg2") { f = datalog_expression_root::FEATURE_ARG2; } else if (name == "arg3") { f = datalog_expression_root::FEATURE_ARG3; } else if (name == "arg1_only") { f = datalog_expression_root::FEATURE_ARG1_ONLY; } else if (name == "arg2_only") { f = datalog_expression_root::FEATURE_ARG2_ONLY; } else if (name == "arg3_only") { f = datalog_expression_root::FEATURE_ARG3_ONLY; } else if (name == "arg2_arity") { f = datalog_expression_root::FEATURE_ARG2_ARITY; } else if (name == "number") { f = datalog_expression_root::FEATURE_NUMBER; } else if (name == "inflection") { f = datalog_expression_root::FEATURE_INFLECTION; } else { core::print("parse ERROR: Unrecognized semantic feature name '", stderr); core::print(name, stderr); core::print("'.\n", stderr); return false; } return true; } template<typename Stream> static bool print(const feature& f, Stream& out) { switch (f) { case datalog_expression_root::FEATURE_NULL: return core::print("null", out); case datalog_expression_root::FEATURE_FUNCTION: return core::print("function", out); case datalog_expression_root::FEATURE_FUNCTION_ONLY: return core::print("function_only", out); case datalog_expression_root::FEATURE_FUNCTION_ANSWER: return core::print("function_answer", out); case datalog_expression_root::FEATURE_HAS_FUNCTION: return core::print("has_function", out); case datalog_expression_root::FEATURE_HAS_FUNCTION_NOT: return core::print("has_function_not", out); case datalog_expression_root::FEATURE_HAS_FUNCTION_COUNT_NOT: return core::print("has_function_count_not", out); case datalog_expression_root::FEATURE_HAS_FUNCTION_ANSWER: return core::print("has_function_answer", out); case datalog_expression_root::FEATURE_PREDICATE: return core::print("predicate", out); case datalog_expression_root::FEATURE_PREDICATE_ONLY: return core::print("predicate_only", out); case datalog_expression_root::FEATURE_FIRST_PREDICATE: return core::print("first_predicate", out); case datalog_expression_root::FEATURE_SECOND_PREDICATE: return core::print("second_predicate", out); case datalog_expression_root::FEATURE_THIRD_PREDICATE: return core::print("third_predicate", out); case datalog_expression_root::FEATURE_LAST_PREDICATE: return core::print("last_predicate", out); case datalog_expression_root::FEATURE_DIRECTION: return core::print("direction", out); case datalog_expression_root::FEATURE_DIRECTION_ROOT: return core::print("direction_root", out); case datalog_expression_root::FEATURE_CONSTANT: return core::print("constant", out); case datalog_expression_root::FEATURE_PREDICATE_ARITY: return core::print("arity", out); case datalog_expression_root::FEATURE_ARG1: return core::print("arg1", out); case datalog_expression_root::FEATURE_ARG2: return core::print("arg2", out); case datalog_expression_root::FEATURE_ARG3: return core::print("arg3", out); case datalog_expression_root::FEATURE_ARG1_ONLY: return core::print("arg1_only", out); case datalog_expression_root::FEATURE_ARG2_ONLY: return core::print("arg2_only", out); case datalog_expression_root::FEATURE_ARG3_ONLY: return core::print("arg3_only", out); case datalog_expression_root::FEATURE_ARG2_ARITY: return core::print("arg2_arity", out); case datalog_expression_root::FEATURE_NUMBER: return core::print("number", out); case datalog_expression_root::FEATURE_INFLECTION: return core::print("inflection", out); } fprintf(stderr, "print ERROR: Unrecognized semantic feature.\n"); return false; } template<typename Stream> static inline bool read(function& f, Stream& stream) { unsigned char c; if (!core::read(c, stream)) return false; f.type = static_cast<datalog_expression_root::function_type>(c); return true; } template<typename Stream> static inline bool write(const function& f, Stream& stream) { return core::write((unsigned char) f.type, stream); } template<typename T, typename Stream> static inline bool read(T* array, Stream& stream, unsigned int length) { for (unsigned int i = 0; i < length; i++) if (!read(array[i], stream)) return false; return true; } template<typename T, typename Stream> static inline bool write(const T* array, Stream& stream, unsigned int length) { for (unsigned int i = 0; i < length; i++) if (!write(array[i], stream)) return false; return true; } static bool interpret(function& f, const string& name) { if (name == "identity") { f.type = datalog_expression_root::FUNCTION_IDENTITY; } else if (name == "identity_coord") { f.type = datalog_expression_root::FUNCTION_IDENTITY_COORD; } else if (name == "null") { f.type = datalog_expression_root::FUNCTION_NULL; } else if (name == "select_left") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT; } else if (name == "select_left_coord") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_COORD; } else if (name == "select_left_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FEATURES; } else if (name == "select_left_concord_singular") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_CONCORD_SINGULAR; } else if (name == "select_left_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT; } else if (name == "select_left_disjoint_coord") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT_COORD; } else if (name == "select_left2") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2; } else if (name == "select_left2_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FEATURES; } else if (name == "select_left2_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT; } else if (name == "select_left2_disjoint_concord_singular") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR; } else if (name == "select_left2_disjoint_coord") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_COORD; } else if (name == "select_left3_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT3_DISJOINT; } else if (name == "select_left4_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT4_DISJOINT; } else if (name == "select_left5_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT5_DISJOINT; } else if (name == "select_left6_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT6_DISJOINT; } else if (name == "select_left7_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT7_DISJOINT; } else if (name == "select_left_delete_head") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD; } else if (name == "select_left_delete_head_concord_singular") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR; } else if (name == "select_left_delete_head_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT; } else if (name == "select_left_delete_head_disjoint_coord") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD; } else if (name == "select_left_keep_function") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION; } else if (name == "select_left_keep_function_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION_DISJOINT; } else if (name == "select_left2_keep_function") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION; } else if (name == "select_left2_keep_function_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION_DISJOINT; } else if (name == "select_left3_keep_function") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT3_KEEP_FUNCTION; } else if (name == "select_left_delete_function") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION; } else if (name == "select_left_delete_function_features") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES; } else if (name == "select_left_delete_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER; } else if (name == "select_left2_delete_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_ANSWER; } else if (name == "select_left3_delete_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER; } else if (name == "select_left3_delete_answer_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER_DISJOINT; } else if (name == "select_left5_delete_answer_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT5_DELETE_ANSWER_DISJOINT; } else if (name == "select_left_delete_answer_head") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER_HEAD; } else if (name == "select_left_delete_count_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_COUNT_ANSWER; } else if (name == "select_left2_delete_count_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_COUNT_ANSWER; } else if (name == "select_left3_delete_count_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_COUNT_ANSWER; } else if (name == "select_left_delete_function_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_ANSWER; } else if (name == "select_left2_delete_function_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FUNCTION_ANSWER; } else if (name == "select_left3_delete_function_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_FUNCTION_ANSWER; } else if (name == "select_left_delete_not") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT; } else if (name == "select_left_delete_not_features") { f.type = datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES; } else if (name == "select_right") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT; } else if (name == "select_right2") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT2; } else if (name == "select_right2_singular") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT2_SINGULAR; } else if (name == "select_right2_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT2_DISJOINT; } else if (name == "select_right3_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT3_DISJOINT; } else if (name == "select_right4_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT4_DISJOINT; } else if (name == "select_right5_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT5_DISJOINT; } else if (name == "select_right6_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT6_DISJOINT; } else if (name == "select_right7_disjoint") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT7_DISJOINT; } else if (name == "select_right_delete_head") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_HEAD; } else if (name == "select_right_delete_function") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_FUNCTION; } else if (name == "select_right2_delete_answer") { f.type = datalog_expression_root::FUNCTION_SELECT_RIGHT2_DELETE_ANSWER; } else if (name == "select_function") { f.type = datalog_expression_root::FUNCTION_SELECT_FUNCTION; } else if (name == "select_function_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_FEATURES; } else if (name == "select_function_delete_head") { f.type = datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD; } else if (name == "select_function_delete_head_features") { f.type = datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES; } else if (name == "delete_left") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT; } else if (name == "delete_left_features") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES; } else if (name == "delete_left_coord") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_COORD; } else if (name == "delete_left_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT; } else if (name == "delete_left_disjoint_coord") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT_COORD; } else if (name == "delete_left2") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2; } else if (name == "delete_left2_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT; } else if (name == "delete_left2_disjoint_coord") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_COORD; } else if (name == "delete_left2_disjoint_features") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES; } else if (name == "delete_left3_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT; } else if (name == "delete_left3_disjoint_features") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES; } else if (name == "delete_left4_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT4_DISJOINT; } else if (name == "delete_left5_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT5_DISJOINT; } else if (name == "delete_left6_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT6_DISJOINT; } else if (name == "delete_left7_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT7_DISJOINT; } else if (name == "delete_left_head") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD; } else if (name == "delete_left_head_features") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES; } else if (name == "delete_left2_head") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD; } else if (name == "delete_left2_head_features") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD_FEATURES; } else if (name == "delete_left_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION; } else if (name == "delete_left_function_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_DISJOINT; } else if (name == "delete_left2_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION; } else if (name == "delete_left2_function_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_DISJOINT; } else if (name == "delete_left_function_head") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_HEAD; } else if (name == "delete_left3_function_head") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_HEAD; } else if (name == "delete_left_keep_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_ANSWER; } else if (name == "delete_left_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_FUNCTION; } else if (name == "delete_left_features_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION; } else if (name == "delete_left_head_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_FUNCTION; } else if (name == "delete_left_head_features_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION; } else if (name == "delete_left_head_keep_not") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_NOT; } else if (name == "delete_left_head_features_keep_not") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT; } else if (name == "delete_left_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER; } else if (name == "delete_left2_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER; } else if (name == "delete_left3_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER; } else if (name == "delete_left3_answer_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_DISJOINT; } else if (name == "delete_left5_answer_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT5_ANSWER_DISJOINT; } else if (name == "delete_left_answer_head") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD; } else if (name == "delete_left_count_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_COUNT_ANSWER; } else if (name == "delete_left2_count_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_COUNT_ANSWER; } else if (name == "delete_left3_count_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_COUNT_ANSWER; } else if (name == "delete_left_function_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_ANSWER; } else if (name == "delete_left2_function_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_ANSWER; } else if (name == "delete_left3_function_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_ANSWER; } else if (name == "delete_left_answer_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_KEEP_FUNCTION; } else if (name == "delete_left_answer_head_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD_KEEP_FUNCTION; } else if (name == "delete_left2_answer_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_KEEP_FUNCTION; } else if (name == "delete_left2_answer_head_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_HEAD_KEEP_FUNCTION; } else if (name == "delete_left3_answer_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_KEEP_FUNCTION; } else if (name == "delete_left3_answer_head_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_HEAD_KEEP_FUNCTION; } else if (name == "delete_right") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT; } else if (name == "delete_right2") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT2; } else if (name == "delete_right2_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT2_DISJOINT; } else if (name == "delete_right3_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT3_DISJOINT; } else if (name == "delete_right4_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT4_DISJOINT; } else if (name == "delete_right5_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT5_DISJOINT; } else if (name == "delete_right6_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT6_DISJOINT; } else if (name == "delete_right7_disjoint") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT7_DISJOINT; } else if (name == "delete_right_head") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD; } else if (name == "delete_right_head_keep_function") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD_KEEP_FUNCTION; } else if (name == "delete_right2_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_RIGHT2_ANSWER; } else if (name == "delete_function") { f.type = datalog_expression_root::FUNCTION_DELETE_FUNCTION; } else if (name == "delete_function_head") { f.type = datalog_expression_root::FUNCTION_DELETE_FUNCTION_HEAD; } else if (name == "delete_function_features") { f.type = datalog_expression_root::FUNCTION_DELETE_FUNCTION_FEATURES; } else if (name == "delete_count") { f.type = datalog_expression_root::FUNCTION_DELETE_COUNT; } else if (name == "delete_count_head") { f.type = datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD; } else if (name == "delete_count_head_concord_plural") { f.type = datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL; } else if (name == "delete_count_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_COUNT_ANSWER; } else if (name == "delete_not") { f.type = datalog_expression_root::FUNCTION_DELETE_NOT; } else if (name == "delete_not_features") { f.type = datalog_expression_root::FUNCTION_DELETE_NOT_FEATURES; } else if (name == "delete_not_infinitive") { f.type = datalog_expression_root::FUNCTION_DELETE_NOT_INFINITIVE; } else if (name == "delete_left_not_head") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD; } else if (name == "delete_left_not_head_features") { f.type = datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES; } else if (name == "delete_answer") { f.type = datalog_expression_root::FUNCTION_DELETE_ANSWER; } else if (name == "delete_answer_has_loc") { f.type = datalog_expression_root::FUNCTION_DELETE_ANSWER_HAS_LOC; } else if (name == "select_arg1") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG1; } else if (name == "select_arg1_singular") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG1_SINGULAR; } else if (name == "select_arg1_plural") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG1_PLURAL; } else if (name == "select_arg1_only") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY; } else if (name == "select_arg1_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG1_DELETE_FEATURES; } else if (name == "select_arg1_only_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES; } else if (name == "select_arg2") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG2; } else if (name == "select_arg2_only") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY; } else if (name == "select_arg2_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG2_DELETE_FEATURES; } else if (name == "select_arg2_only_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES; } else if (name == "select_arg3") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG3; } else if (name == "select_arg3_only") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY; } else if (name == "select_arg3_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG3_DELETE_FEATURES; } else if (name == "select_arg3_only_delete_features") { f.type = datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES; } else if (name == "delete_arg1") { f.type = datalog_expression_root::FUNCTION_DELETE_ARG1; } else if (name == "delete_arg1_singular") { f.type = datalog_expression_root::FUNCTION_DELETE_ARG1_SINGULAR; } else if (name == "delete_arg1_plural") { f.type = datalog_expression_root::FUNCTION_DELETE_ARG1_PLURAL; } else if (name == "delete_arg1_features") { f.type = datalog_expression_root::FUNCTION_DELETE_ARG1_FEATURES; } else if (name == "delete_arg2") { f.type = datalog_expression_root::FUNCTION_DELETE_ARG2; } else if (name == "delete_arg2_features") { f.type = datalog_expression_root::FUNCTION_DELETE_ARG2_FEATURES; } else if (name == "delete_arg3") { f.type = datalog_expression_root::FUNCTION_DELETE_ARG3; } else if (name == "delete_args") { f.type = datalog_expression_root::FUNCTION_DELETE_ARGS; } else if (name == "delete_args_concord_singular") { f.type = datalog_expression_root::FUNCTION_DELETE_ARGS_CONCORD_SINGULAR; } else if (name == "delete_args_keep_plural") { f.type = datalog_expression_root::FUNCTION_DELETE_ARGS_KEEP_PLURAL; } else if (name == "head_arg1_select_arg2") { f.type = datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2; } else if (name == "head_arg1_select_arg2_only") { f.type = datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2_ONLY; } else if (name == "empty_tuple") { f.type = datalog_expression_root::FUNCTION_EMPTY_TUPLE; } else if (name == "empty_tuple_only") { f.type = datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY; } else if (name == "empty_tuple_only_keep_concord_singular") { f.type = datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR; } else if (name == "keep_null") { f.type = datalog_expression_root::FUNCTION_KEEP_NULL; } else if (name == "empty_arg2") { f.type = datalog_expression_root::FUNCTION_EMPTY_ARG2; } else if (name == "empty_args") { f.type = datalog_expression_root::FUNCTION_EMPTY_ARGS; } else if (name == "arg2_zero_arity") { f.type = datalog_expression_root::FUNCTION_ARG2_ZERO_ARITY; } else if (name == "loc") { f.type = datalog_expression_root::FUNCTION_LOC; } else if (name == "two_predicates") { f.type = datalog_expression_root::FUNCTION_TWO_PREDICATES; } else if (name == "singular") { f.type = datalog_expression_root::FUNCTION_SINGULAR; } else if (name == "plural") { f.type = datalog_expression_root::FUNCTION_PLURAL; } else if (name == "uncountable") { f.type = datalog_expression_root::FUNCTION_UNCOUNTABLE; } else if (name == "concord_singular") { f.type = datalog_expression_root::FUNCTION_CONCORD_SINGULAR; } else if (name == "concord_plural") { f.type = datalog_expression_root::FUNCTION_CONCORD_PLURAL; } else if (name == "concord_uncountable") { f.type = datalog_expression_root::FUNCTION_CONCORD_UNCOUNTABLE; } else if (name == "concord_non_singular") { f.type = datalog_expression_root::FUNCTION_CONCORD_NON_SINGULAR; } else if (name == "concord_non_plural") { f.type = datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL; } else if (name == "concord_non_plural_keep_singular") { f.type = datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR; } else if (name == "concord_all") { f.type = datalog_expression_root::FUNCTION_CONCORD_ALL; } else if (name == "keep_concord_singular") { f.type = datalog_expression_root::FUNCTION_KEEP_CONCORD_SINGULAR; } else if (name == "keep_concord_plural") { f.type = datalog_expression_root::FUNCTION_KEEP_CONCORD_PLURAL; } else if (name == "keep_concord_uncountable") { f.type = datalog_expression_root::FUNCTION_KEEP_CONCORD_UNCOUNTABLE; } else if (name == "delete_not_concord_singular") { f.type = datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_SINGULAR; } else if (name == "delete_not_concord_plural") { f.type = datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_PLURAL; } else if (name == "keep_singular") { f.type = datalog_expression_root::FUNCTION_KEEP_SINGULAR; } else if (name == "keep_plural") { f.type = datalog_expression_root::FUNCTION_KEEP_PLURAL; } else if (name == "keep_uncountable") { f.type = datalog_expression_root::FUNCTION_KEEP_UNCOUNTABLE; } else if (name == "infinitive") { f.type = datalog_expression_root::FUNCTION_INFINITIVE; } else if (name == "present_participle") { f.type = datalog_expression_root::FUNCTION_PRESENT_PARTICIPLE; } else if (name == "past_participle") { f.type = datalog_expression_root::FUNCTION_PAST_PARTICIPLE; } else if (name == "keep_present_participle") { f.type = datalog_expression_root::FUNCTION_KEEP_PRESENT_PARTICIPLE; } else if (name == "keep_past_participle") { f.type = datalog_expression_root::FUNCTION_KEEP_PAST_PARTICIPLE; } else if (name == "flip_predicate") { f.type = datalog_expression_root::FUNCTION_FLIP_PREDICATE; } else if (name == "flip_predicate_past_participle") { f.type = datalog_expression_root::FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE; } else if (name == "flip_predicate_keep_past_participle") { f.type = datalog_expression_root::FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE; } else if (name == "keep_features") { f.type = datalog_expression_root::FUNCTION_KEEP_FEATURES; } else if (name == "delete_features") { f.type = datalog_expression_root::FUNCTION_DELETE_FEATURES; } else { fprintf(stderr, "parse ERROR: Unrecognized semantic transformation function name.\n"); return false; } return true; } template<typename Stream> static bool print(const function& f, Stream& out) { switch (f.type) { case datalog_expression_root::FUNCTION_EMPTY: return core::print("empty", out); case datalog_expression_root::FUNCTION_IDENTITY: return core::print("identity", out); case datalog_expression_root::FUNCTION_IDENTITY_COORD: return core::print("identity_coord", out); case datalog_expression_root::FUNCTION_NULL: return core::print("null", out); case datalog_expression_root::FUNCTION_SELECT_LEFT: return core::print("select_left", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_COORD: return core::print("select_left_coord", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FEATURES: return core::print("select_left_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_CONCORD_SINGULAR: return core::print("select_left_concord_singular", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT: return core::print("select_left_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT_COORD: return core::print("select_left_disjoint_coord", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2: return core::print("select_left2", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FEATURES: return core::print("select_left2_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT: return core::print("select_left2_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR: return core::print("select_left2_disjoint_concord_singular", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_COORD: return core::print("select_left2_disjoint_coord", out); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DISJOINT: return core::print("select_left3_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT4_DISJOINT: return core::print("select_left4_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT5_DISJOINT: return core::print("select_left5_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT6_DISJOINT: return core::print("select_left6_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT7_DISJOINT: return core::print("select_left7_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD: return core::print("select_left_delete_head", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR: return core::print("select_left_delete_head_concord_singular", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT: return core::print("select_left_delete_head_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD: return core::print("select_left_delete_head_disjoint_coord", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION: return core::print("select_left_keep_function", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION_DISJOINT: return core::print("select_left_keep_function_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION: return core::print("select_left2_keep_function", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION_DISJOINT: return core::print("select_left2_keep_function_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT3_KEEP_FUNCTION: return core::print("select_left3_keep_function", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION: return core::print("select_left_delete_function", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES: return core::print("select_left_delete_function_features", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER: return core::print("select_left_delete_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_ANSWER: return core::print("select_left2_delete_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER: return core::print("select_left3_delete_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER_DISJOINT: return core::print("select_left3_delete_answer_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT5_DELETE_ANSWER_DISJOINT: return core::print("select_left5_delete_answer_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER_HEAD: return core::print("select_left_delete_answer_head", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_COUNT_ANSWER: return core::print("select_left_delete_count_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_COUNT_ANSWER: return core::print("select_left2_delete_count_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_COUNT_ANSWER: return core::print("select_left3_delete_count_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_ANSWER: return core::print("select_left_delete_function_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FUNCTION_ANSWER: return core::print("select_left2_delete_function_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_FUNCTION_ANSWER: return core::print("select_left3_delete_function_answer", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT: return core::print("select_left_delete_not", out); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES: return core::print("select_left_delete_not_features", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT: return core::print("select_right", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT2: return core::print("select_right2", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT2_SINGULAR: return core::print("select_right2_singular", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DISJOINT: return core::print("select_right2_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT3_DISJOINT: return core::print("select_right3_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT4_DISJOINT: return core::print("select_right4_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT5_DISJOINT: return core::print("select_right5_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT6_DISJOINT: return core::print("select_right6_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT7_DISJOINT: return core::print("select_right7_disjoint", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_HEAD: return core::print("select_right_delete_head", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_FUNCTION: return core::print("select_right_delete_function", out); case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DELETE_ANSWER: return core::print("select_right2_delete_answer", out); case datalog_expression_root::FUNCTION_SELECT_FUNCTION: return core::print("select_function", out); case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_FEATURES: return core::print("select_function_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD: return core::print("select_function_delete_head", out); case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES: return core::print("select_function_delete_head_features", out); case datalog_expression_root::FUNCTION_DELETE_LEFT: return core::print("delete_left", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_COORD: return core::print("delete_left_coord", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES: return core::print("delete_left_features", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT: return core::print("delete_left_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT_COORD: return core::print("delete_left_disjoint_coord", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2: return core::print("delete_left2", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT: return core::print("delete_left2_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_COORD: return core::print("delete_left2_disjoint_coord", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES: return core::print("delete_left2_disjoint_features", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT: return core::print("delete_left3_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES: return core::print("delete_left3_disjoint_features", out); case datalog_expression_root::FUNCTION_DELETE_LEFT4_DISJOINT: return core::print("delete_left4_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT5_DISJOINT: return core::print("delete_left5_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT6_DISJOINT: return core::print("delete_left6_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT7_DISJOINT: return core::print("delete_left7_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD: return core::print("delete_left_head", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES: return core::print("delete_left_head_features", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD: return core::print("delete_left2_head", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD_FEATURES: return core::print("delete_left2_head_features", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION: return core::print("delete_left_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_DISJOINT: return core::print("delete_left_function_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION: return core::print("delete_left2_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_DISJOINT: return core::print("delete_left2_function_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_HEAD: return core::print("delete_left_function_head", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_HEAD: return core::print("delete_left3_function_head", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_ANSWER: return core::print("delete_left_keep_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_FUNCTION: return core::print("delete_left_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION: return core::print("delete_left_features_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_FUNCTION: return core::print("delete_left_head_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION: return core::print("delete_left_head_features_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_NOT: return core::print("delete_left_head_keep_not", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT: return core::print("delete_left_head_features_keep_not", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER: return core::print("delete_left_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER: return core::print("delete_left2_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER: return core::print("delete_left3_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_DISJOINT: return core::print("delete_left3_answer_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT5_ANSWER_DISJOINT: return core::print("delete_left5_answer_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD: return core::print("delete_left_answer_head", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_COUNT_ANSWER: return core::print("delete_left_count_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_COUNT_ANSWER: return core::print("delete_left2_count_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_COUNT_ANSWER: return core::print("delete_left3_count_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_ANSWER: return core::print("delete_left_function_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_ANSWER: return core::print("delete_left2_function_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_ANSWER: return core::print("delete_left3_function_answer", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_KEEP_FUNCTION: return core::print("delete_left_answer_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD_KEEP_FUNCTION: return core::print("delete_left_answer_head_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_KEEP_FUNCTION: return core::print("delete_left2_answer_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_HEAD_KEEP_FUNCTION: return core::print("delete_left2_answer_head_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_KEEP_FUNCTION: return core::print("delete_left3_answer_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_HEAD_KEEP_FUNCTION: return core::print("delete_left3_answer_head_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT: return core::print("delete_right", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT2: return core::print("delete_right2", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT2_DISJOINT: return core::print("delete_right2_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT3_DISJOINT: return core::print("delete_right3_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT4_DISJOINT: return core::print("delete_right4_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT5_DISJOINT: return core::print("delete_right5_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT6_DISJOINT: return core::print("delete_right6_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT7_DISJOINT: return core::print("delete_right7_disjoint", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD: return core::print("delete_right_head", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD_KEEP_FUNCTION: return core::print("delete_right_head_keep_function", out); case datalog_expression_root::FUNCTION_DELETE_RIGHT2_ANSWER: return core::print("delete_right2_answer", out); case datalog_expression_root::FUNCTION_DELETE_COUNT: return core::print("delete_count", out); case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD: return core::print("delete_count_head", out); case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL: return core::print("delete_count_head_concord_plural", out); case datalog_expression_root::FUNCTION_DELETE_COUNT_ANSWER: return core::print("delete_count_answer", out); case datalog_expression_root::FUNCTION_DELETE_NOT: return core::print("delete_not", out); case datalog_expression_root::FUNCTION_DELETE_NOT_FEATURES: return core::print("delete_not_features", out); case datalog_expression_root::FUNCTION_DELETE_NOT_INFINITIVE: return core::print("delete_not_infinitive", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD: return core::print("delete_left_not_head", out); case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES: return core::print("delete_left_not_head_features", out); case datalog_expression_root::FUNCTION_DELETE_FUNCTION: return core::print("delete_function", out); case datalog_expression_root::FUNCTION_DELETE_FUNCTION_HEAD: return core::print("delete_function_head", out); case datalog_expression_root::FUNCTION_DELETE_FUNCTION_FEATURES: return core::print("delete_function_features", out); case datalog_expression_root::FUNCTION_DELETE_ANSWER: return core::print("delete_answer", out); case datalog_expression_root::FUNCTION_DELETE_ANSWER_HAS_LOC: return core::print("delete_answer_has_loc", out); case datalog_expression_root::FUNCTION_SELECT_ARG1: return core::print("select_arg1", out); case datalog_expression_root::FUNCTION_SELECT_ARG1_SINGULAR: return core::print("select_arg1_singular", out); case datalog_expression_root::FUNCTION_SELECT_ARG1_PLURAL: return core::print("select_arg1_plural", out); case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY: return core::print("select_arg1_only", out); case datalog_expression_root::FUNCTION_SELECT_ARG1_DELETE_FEATURES: return core::print("select_arg1_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES: return core::print("select_arg1_only_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_ARG2: return core::print("select_arg2", out); case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY: return core::print("select_arg2_only", out); case datalog_expression_root::FUNCTION_SELECT_ARG2_DELETE_FEATURES: return core::print("select_arg2_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES: return core::print("select_arg2_only_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_ARG3: return core::print("select_arg3", out); case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY: return core::print("select_arg3_only", out); case datalog_expression_root::FUNCTION_SELECT_ARG3_DELETE_FEATURES: return core::print("select_arg3_delete_features", out); case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES: return core::print("select_arg3_only_delete_features", out); case datalog_expression_root::FUNCTION_DELETE_ARG1: return core::print("delete_arg1", out); case datalog_expression_root::FUNCTION_DELETE_ARG1_SINGULAR: return core::print("delete_arg1_singular", out); case datalog_expression_root::FUNCTION_DELETE_ARG1_PLURAL: return core::print("delete_arg1_plural", out); case datalog_expression_root::FUNCTION_DELETE_ARG1_FEATURES: return core::print("delete_arg1_features", out); case datalog_expression_root::FUNCTION_DELETE_ARG2: return core::print("delete_arg2", out); case datalog_expression_root::FUNCTION_DELETE_ARG2_FEATURES: return core::print("delete_arg2_features", out); case datalog_expression_root::FUNCTION_DELETE_ARG3: return core::print("delete_arg3", out); case datalog_expression_root::FUNCTION_DELETE_ARGS: return core::print("delete_args", out); case datalog_expression_root::FUNCTION_DELETE_ARGS_CONCORD_SINGULAR: return core::print("delete_args_concord_singular", out); case datalog_expression_root::FUNCTION_DELETE_ARGS_KEEP_PLURAL: return core::print("delete_args_keep_plural", out); case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2: return core::print("head_arg1_select_arg2", out); case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2_ONLY: return core::print("head_arg1_select_arg2_only", out); case datalog_expression_root::FUNCTION_EMPTY_TUPLE: return core::print("empty_tuple", out); case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY: return core::print("empty_tuple_only", out); case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR: return core::print("empty_tuple_only_keep_concord_singular", out); case datalog_expression_root::FUNCTION_KEEP_NULL: return core::print("keep_null", out); case datalog_expression_root::FUNCTION_EMPTY_ARG2: return core::print("empty_arg2", out); case datalog_expression_root::FUNCTION_EMPTY_ARGS: return core::print("empty_args", out); case datalog_expression_root::FUNCTION_ARG2_ZERO_ARITY: return core::print("arg2_zero_arity", out); case datalog_expression_root::FUNCTION_LOC: return core::print("loc", out); case datalog_expression_root::FUNCTION_TWO_PREDICATES: return core::print("two_predicates", out); case datalog_expression_root::FUNCTION_SINGULAR: return core::print("singular", out); case datalog_expression_root::FUNCTION_PLURAL: return core::print("plural", out); case datalog_expression_root::FUNCTION_UNCOUNTABLE: return core::print("uncountable", out); case datalog_expression_root::FUNCTION_CONCORD_SINGULAR: return core::print("concord_singular", out); case datalog_expression_root::FUNCTION_CONCORD_PLURAL: return core::print("concord_plural", out); case datalog_expression_root::FUNCTION_CONCORD_UNCOUNTABLE: return core::print("concord_uncountable", out); case datalog_expression_root::FUNCTION_CONCORD_NON_SINGULAR: return core::print("concord_non_singular", out); case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL: return core::print("concord_non_plural", out); case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR: return core::print("concord_non_plural_keep_singular", out); case datalog_expression_root::FUNCTION_CONCORD_ALL: return core::print("concord_all", out); case datalog_expression_root::FUNCTION_KEEP_CONCORD_SINGULAR: return core::print("keep_concord_singular", out); case datalog_expression_root::FUNCTION_KEEP_CONCORD_PLURAL: return core::print("keep_concord_plural", out); case datalog_expression_root::FUNCTION_KEEP_CONCORD_UNCOUNTABLE: return core::print("keep_concord_uncountable", out); case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_SINGULAR: return core::print("delete_not_concord_singular", out); case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_PLURAL: return core::print("delete_not_concord_plural", out); case datalog_expression_root::FUNCTION_KEEP_SINGULAR: return core::print("keep_singular", out); case datalog_expression_root::FUNCTION_KEEP_PLURAL: return core::print("keep_plural", out); case datalog_expression_root::FUNCTION_KEEP_UNCOUNTABLE: return core::print("keep_uncountable", out); case datalog_expression_root::FUNCTION_INFINITIVE: return core::print("infinitive", out); case datalog_expression_root::FUNCTION_PRESENT_PARTICIPLE: return core::print("present_participle", out); case datalog_expression_root::FUNCTION_PAST_PARTICIPLE: return core::print("past_participle", out); case datalog_expression_root::FUNCTION_KEEP_PRESENT_PARTICIPLE: return core::print("keep_present_participle", out); case datalog_expression_root::FUNCTION_KEEP_PAST_PARTICIPLE: return core::print("keep_past_participle", out); case datalog_expression_root::FUNCTION_FLIP_PREDICATE: return core::print("flip_predicate", out); case datalog_expression_root::FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE: return core::print("flip_predicate_past_participle", out); case datalog_expression_root::FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE: return core::print("flip_predicate_keep_past_participle", out); case datalog_expression_root::FUNCTION_KEEP_FEATURES: return core::print("keep_features", out); case datalog_expression_root::FUNCTION_DELETE_FEATURES: return core::print("delete_features", out); } fprintf(stderr, "print ERROR: Unrecognized semantic transformation function.\n"); return false; } static bool is_feature_pruneable(feature f) { switch (f) { case datalog_expression_root::FEATURE_SECOND_PREDICATE: case datalog_expression_root::FEATURE_THIRD_PREDICATE: case datalog_expression_root::FEATURE_LAST_PREDICATE: case datalog_expression_root::FEATURE_DIRECTION: case datalog_expression_root::FEATURE_DIRECTION_ROOT: case datalog_expression_root::FEATURE_ARG1: case datalog_expression_root::FEATURE_ARG1_ONLY: case datalog_expression_root::FEATURE_ARG2: case datalog_expression_root::FEATURE_ARG2_ONLY: case datalog_expression_root::FEATURE_ARG3: case datalog_expression_root::FEATURE_ARG3_ONLY: case datalog_expression_root::FEATURE_NUMBER: case datalog_expression_root::FEATURE_INFLECTION: return false; case datalog_expression_root::FEATURE_FIRST_PREDICATE: case datalog_expression_root::FEATURE_FUNCTION: case datalog_expression_root::FEATURE_FUNCTION_ONLY: case datalog_expression_root::FEATURE_FUNCTION_ANSWER: case datalog_expression_root::FEATURE_HAS_FUNCTION: case datalog_expression_root::FEATURE_HAS_FUNCTION_NOT: case datalog_expression_root::FEATURE_HAS_FUNCTION_COUNT_NOT: case datalog_expression_root::FEATURE_HAS_FUNCTION_ANSWER: case datalog_expression_root::FEATURE_PREDICATE_ARITY: case datalog_expression_root::FEATURE_ARG2_ARITY: case datalog_expression_root::FEATURE_PREDICATE: case datalog_expression_root::FEATURE_PREDICATE_ONLY: case datalog_expression_root::FEATURE_CONSTANT: return true; case datalog_expression_root::FEATURE_NULL: break; } fprintf(stderr, "datalog_expression_root.is_feature_pruneable ERROR: Unrecognized semantic feature.\n"); exit(EXIT_FAILURE); } }; /* forward declarations */ bool apply(datalog_expression_root::function, const datalog_expression&, datalog_expression&); bool apply(datalog_expression_root::function, const datalog_expression_root&, datalog_expression_root&); bool intersect( datalog_expression&, const datalog_expression*, const datalog_expression*, array<unsigned int>&, array<unsigned int>&, array<unsigned int>&); bool operator == (const datalog_expression&, const datalog_expression&); bool operator != (const datalog_expression&, const datalog_expression&); thread_local datalog_expression DATALOG_ANY_TREE; thread_local datalog_expression DATALOG_NON_EMPTY_TREE(DATALOG_NON_EMPTY); inline bool new_expression(datalog_expression*& expression) { expression = (datalog_expression*) malloc(sizeof(datalog_expression)); if (expression == NULL) { fprintf(stderr, "new_expression ERROR: Out of memory.\n"); return false; } return expression; } inline bool init(unsigned int& variable, unsigned int src) { variable = src; return true; } inline bool init(unsigned int& variable, unsigned int src, int offset) { variable = src + offset; return true; } inline bool initialize_any(datalog_expression& exp) { exp.type = DATALOG_ANY; exp.reference_count = 1; return true; } inline bool initialize_any(datalog_expression_root& exp) { if (!initialize_any(exp.root)) return false; exp.index = NUMBER_ANY; exp.concord = NUMBER_ANY; exp.inf = INFLECTION_ANY; return true; } inline bool ensure_variable_map_capacity(array<unsigned int>& variable_map, unsigned int variable) { unsigned int old_capacity = variable_map.capacity; if (!variable_map.ensure_capacity(variable + 1)) return false; memset(variable_map.data + old_capacity, 0, sizeof(unsigned int) * (variable_map.capacity - old_capacity)); return true; } inline bool init(unsigned int& variable, unsigned int src, array<unsigned int>& src_variable_map, array<unsigned int>& dst_variable_map) { if (!ensure_variable_map_capacity(src_variable_map, src)) return false; else if (src_variable_map[src] != 0) { variable = src_variable_map[src]; if (!ensure_variable_map_capacity(dst_variable_map, variable)) return false; if (dst_variable_map[variable] == 0) dst_variable_map[variable] = 1; return true; } unsigned int i; for (i = src - 1; i > 0; i--) if (src_variable_map[i] != 0) break; unsigned int first = src_variable_map[i] + src - i; for (unsigned int j = src_variable_map[i] + 1; j < first; j++) { if (!ensure_variable_map_capacity(dst_variable_map, j + 1)) return false; else if (dst_variable_map[j]) first++; } if (!ensure_variable_map_capacity(dst_variable_map, first)) return false; while (dst_variable_map[first]) { first++; if (!ensure_variable_map_capacity(dst_variable_map, first)) return false; } src_variable_map[src] = first; dst_variable_map[first] = 1; variable = first; return true; } inline bool init(unsigned int& variable, unsigned int src, const array_map<unsigned int, unsigned int>& variable_map) { variable = variable_map.get(src); return true; } template<typename... Args> inline bool init(datalog_expression*& expression, datalog_expression* src, Args&&... args) { if (!new_expression(expression)) return false; if (!init(*expression, *src, std::forward<Args>(args)...)) { free(expression); return false; } return true; } template<> inline bool init<>(datalog_expression*& expression, datalog_expression* src) { expression = src; src->reference_count++; return true; } inline bool init(datalog_expression_root*& expression, datalog_expression* src, grammatical_number index = NUMBER_ALL, grammatical_number concord = NUMBER_NONE, inflection inf = INFLECTION_NONE) { expression = (datalog_expression_root*) malloc(sizeof(datalog_expression_root)); if (expression == NULL) { fprintf(stderr, "init ERROR: Insufficient memory for datalog_expression_root.\n"); return false; } else if (!init(expression->root, *src)) { free(expression); return false; } expression->index = index; expression->concord = concord; expression->inf = inf; return true; } template<typename... Args> inline bool init(datalog_expression**& args, datalog_expression* const* const expressions, unsigned int count, Args&&... optional_args) { for (unsigned int i = 0; i < count; i++) { if (!init(args[i], expressions[i], std::forward<Args>(optional_args)...)) { for (unsigned int j = 0; j < i; j++) { free(*args[i]); if (args[i]->reference_count == 0) free(args[i]); } return false; } } return true; } template<typename... Args> inline bool init(array<datalog_expression*>& args, datalog_expression* const* const expressions, unsigned int count, Args&&... optional_args) { if (!array_init(args, max(1u, count))) { return false; } else if (!init(args.data, expressions, count, std::forward<Args>(optional_args)...)) { free(args); return false; } args.length = count; return true; } inline bool init(datalog_function& func) { func.excluded_count = 0; func.arg = NULL; return true; } inline bool init_excluded(unsigned int*& excluded, const unsigned int* src, unsigned int src_count) { excluded = (unsigned int*) malloc(sizeof(unsigned int) * src_count); if (excluded == NULL) { fprintf(stderr, "init_excluded ERROR: Out of memory.\n"); return false; } memcpy(excluded, src, sizeof(unsigned int) * src_count); return true; } template<typename... Args> inline bool init(datalog_function& func, const datalog_function& src, Args&&... args) { func.function = src.function; if (src.excluded_count > 0 && !init_excluded(func.excluded, src.excluded, src.excluded_count)) return false; func.excluded_count = src.excluded_count; for (unsigned int i = 0; i < array_length(src.vars); i++) { if (src.vars[i] == 0) func.vars[i] = 0; else if (!init(func.vars[i], src.vars[i], std::forward<Args>(args)...)) return false; } if (!init(func.arg, src.arg, std::forward<Args>(args)...)) { if (func.excluded_count > 0) free(func.excluded); return false; } return true; } inline bool init(datalog_predicate& pred) { pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(pred.args); i++) pred.args[i] = NULL; return true; } template<typename... Args> inline bool init(datalog_predicate& pred, const datalog_predicate& src, Args&&... args) { pred.function = src.function; if (src.excluded_count > 0 && !init_excluded(pred.excluded, src.excluded, src.excluded_count)) return false; pred.excluded_count = src.excluded_count; for (unsigned int i = 0; i < array_length(src.args); i++) pred.args[i] = NULL; for (unsigned int i = 0; i < array_length(src.args); i++) { if (src.args[i] != NULL && !init(pred.args[i], src.args[i], std::forward<Args>(args)...)) { free(pred); return false; } } return true; } inline bool init(datalog_tuple& tuple, tuple_position position, unsigned int initial_capacity = 4) { tuple.position = position; return array_init(tuple.elements, initial_capacity); } template<typename... Args> inline bool init( datalog_tuple& tuple, tuple_position position, datalog_expression* const* const expressions, unsigned int count, Args&&... args) { tuple.position = position; return init(tuple.elements, expressions, count, std::forward<Args>(args)...); } template<typename... Args> inline bool init(datalog_tuple& tuple, const datalog_tuple& src, Args&&... args) { tuple.position = src.position; return init(tuple.elements, src.elements.data, src.elements.length, std::forward<Args>(args)...); } template<unsigned int Capacity, tuple_position Position> inline bool init_tuple(datalog_expression& exp) { if (!init(exp.tuple, Position, Capacity)) { fprintf(stderr, "init_tuple ERROR: Unable to initialize tuple.\n"); return false; } exp.type = DATALOG_TUPLE; exp.reference_count = 1; return true; } template<unsigned int Capacity, tuple_position Position> inline bool init_tuple(datalog_expression*& exp) { exp = (datalog_expression*) malloc(sizeof(datalog_expression)); if (exp == NULL) { fprintf(stderr, "init_tuple ERROR: Out of memory.\n"); return false; } else if (!init_tuple<Capacity, Position>(*exp)) { free(exp); return false; } return true; } inline bool init_tuple(datalog_expression& exp, tuple_position position, unsigned int capacity) { if (!init(exp.tuple, position, max(1u, capacity))) { fprintf(stderr, "init_tuple ERROR: Unable to initialize tuple.\n"); return false; } exp.type = DATALOG_TUPLE; exp.reference_count = 1; return true; } inline bool init_tuple(datalog_expression*& exp, tuple_position position, unsigned int capacity) { exp = (datalog_expression*) malloc(sizeof(datalog_expression)); if (exp == NULL) { fprintf(stderr, "init_tuple ERROR: Out of memory.\n"); return false; } else if (!init_tuple(*exp, position, capacity)) { free(exp); return false; } return true; } inline bool init(datalog_list& list) { return array_init(list.elements, 8); } template<typename... Args> inline bool init(datalog_list& list, const datalog_list& src, Args&&... args) { return init(list.elements, src.elements.data, src.elements.length, std::forward<Args>(args)...); } inline bool init(datalog_literal& literal, const datalog_literal& src) { literal.label = src.label; if (src.excluded_count > 0 && !init_excluded(literal.excluded, src.excluded, src.excluded_count)) return false; literal.excluded_count = src.excluded_count; return true; } template<typename... Args> inline bool datalog_expression::initialize(const datalog_expression& src, Args&&... args) { switch (src.type) { case DATALOG_PREDICATE: if (!init(pred, src.pred, std::forward<Args>(args)...)) return false; break; case DATALOG_FUNCTION: if (!init(func, src.func, std::forward<Args>(args)...)) return false; break; case DATALOG_TUPLE: if (!init(tuple, src.tuple, std::forward<Args>(args)...)) return false; break; case DATALOG_LIST: if (!init(list, src.list, std::forward<Args>(args)...)) return false; break; case DATALOG_VARIABLE: if (!init(variable, src.variable, std::forward<Args>(args)...)) return false; break; case DATALOG_CONSTANT: if (!init(constant, src.constant)) return false; break; case DATALOG_INTEGER: integer = src.integer; break; case DATALOG_STRING: if (!init(str, src.str)) return false; break; case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: break; } type = src.type; return true; } template<typename... Args> bool init(datalog_expression& e, const datalog_expression& src, Args&&... args) { e.reference_count = 1; return e.initialize(src, std::forward<Args>(args)...); } template<typename... Args> inline bool init(datalog_expression*& exp, const datalog_expression& src, Args&&... args) { if (!new_expression(exp)) return false; else if (!init(*exp, src, std::forward<Args>(args)...)) { free(exp); return false; } return true; } inline void datalog_predicate::free(datalog_predicate& pred) { for (unsigned int i = 0; i < array_length(pred.args); i++) { if (pred.args[i] != NULL) { core::free(*pred.args[i]); if (pred.args[i]->reference_count == 0) core::free(pred.args[i]); } } if (pred.excluded_count > 0) core::free(pred.excluded); } inline void datalog_function::free(datalog_function& func) { if (func.arg != NULL) { core::free(*func.arg); if (func.arg->reference_count == 0) core::free(func.arg); } if (func.excluded_count > 0) core::free(func.excluded); } inline void datalog_tuple::free(datalog_tuple& tuple) { for (unsigned int i = 0; i < tuple.elements.length; i++) { core::free(*tuple.elements[i]); if (tuple.elements[i]->reference_count == 0) core::free(tuple.elements[i]); } core::free(tuple.elements); } inline void datalog_list::free(datalog_list& list) { for (unsigned int i = 0; i < list.elements.length; i++) { core::free(*list.elements[i]); if (list.elements[i]->reference_count == 0) core::free(list.elements[i]); } core::free(list.elements); } inline void datalog_literal::free(datalog_literal& literal) { if (literal.excluded_count > 0) core::free(literal.excluded); } template<int Offset = 0> inline bool build_variable_map(unsigned int src, array<unsigned int>& src_variable_map, array<unsigned int>& dst_variable_map) { if (!ensure_variable_map_capacity(src_variable_map, src) || !ensure_variable_map_capacity(dst_variable_map, src + Offset)) return false; else if (src_variable_map[src] != 0) return true; src_variable_map[src] = src + Offset; dst_variable_map[src + Offset] = 1; return true; } template<int Offset = 0> inline bool build_variable_map(unsigned int variable, array_map<unsigned int, unsigned int>& variable_map) { if (!variable_map.ensure_capacity(variable_map.size + 1)) return false; unsigned int index = variable_map.index_of(variable); if (index < variable_map.size) { return true; } else { variable_map.keys[index] = variable; variable_map.values[index] = variable_map.size + 1; variable_map.size++; return true; } } template<int Offset = 0, typename... Args> bool build_variable_map(const datalog_expression& exp, Args&&... args) { switch (exp.type) { case DATALOG_PREDICATE: for (unsigned int i = 0; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) break; if (!build_variable_map<Offset>(*exp.pred.args[i], std::forward<Args>(args)...)) return false; } return true; case DATALOG_FUNCTION: for (unsigned int i = 0; i < array_length(exp.func.vars); i++) { if (exp.func.vars[i] == 0) break; if (!build_variable_map<Offset>(exp.func.vars[i], std::forward<Args>(args)...)) return false; } return build_variable_map<Offset>(*exp.func.arg, std::forward<Args>(args)...); case DATALOG_TUPLE: for (datalog_expression* arg : exp.tuple.elements) if (!build_variable_map<Offset>(*arg, std::forward<Args>(args)...)) return false; return true; case DATALOG_LIST: for (datalog_expression* arg : exp.list.elements) if (!build_variable_map<Offset>(*arg, std::forward<Args>(args)...)) return false; return true; case DATALOG_VARIABLE: return build_variable_map<Offset>(exp.variable, std::forward<Args>(args)...); case DATALOG_CONSTANT: case DATALOG_INTEGER: case DATALOG_STRING: case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: return true; } fprintf(stderr, "build_variable_map ERROR: Unrecognized expression type.\n"); return false; } inline void apply_variable_map(unsigned int& variable, const array<unsigned int>& variable_map) { variable = variable_map[variable]; } template<typename... Args> void apply_variable_map(datalog_expression& exp, const Args&... variable_map) { switch (exp.type) { case DATALOG_PREDICATE: for (unsigned int i = 0; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) break; apply_variable_map(*exp.pred.args[i], variable_map...); } return; case DATALOG_FUNCTION: for (unsigned int i = 0; i < array_length(exp.func.vars); i++) { if (exp.func.vars[i] == 0) break; apply_variable_map(exp.func.vars[i], variable_map...); } apply_variable_map(*exp.func.arg, variable_map...); return; case DATALOG_TUPLE: for (datalog_expression* arg : exp.tuple.elements) apply_variable_map(*arg, variable_map...); return; case DATALOG_LIST: for (datalog_expression* arg : exp.list.elements) apply_variable_map(*arg, variable_map...); return; case DATALOG_VARIABLE: apply_variable_map(exp.variable, variable_map...); return; case DATALOG_CONSTANT: case DATALOG_INTEGER: case DATALOG_STRING: case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: return; } fprintf(stderr, "apply_variable_map ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } inline void apply_variable_map(array<unsigned int>& src_variable_map, const array<unsigned int>& to_apply) { for (unsigned int i = 0; i < src_variable_map.capacity; i++) if (src_variable_map[i] != 0) apply_variable_map(src_variable_map[i], to_apply); } inline void compress_variable_map(array<unsigned int>& variable_map) { unsigned int sum = 0; for (unsigned int i = 1; i < variable_map.capacity; i++) { sum += variable_map[i]; variable_map[i] = sum; } } template<unsigned int EmptyVariable, unsigned int AnyVariable, typename Function> unsigned int map_variables(const datalog_expression& exp, Function func) { unsigned int count = EmptyVariable; switch (exp.type) { case DATALOG_PREDICATE: if (exp.pred.args[0] != NULL) count = func(count, map_variables<EmptyVariable, AnyVariable>(*exp.pred.args[0], func)); for (unsigned int i = 1; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) break; count = func(count, map_variables<EmptyVariable, AnyVariable>(*exp.pred.args[i], func)); } return count; case DATALOG_FUNCTION: for (unsigned int i = 0; i < array_length(exp.func.vars); i++) { if (exp.func.vars[i] == 0) break; count = func(count, exp.func.vars[i]); } return func(count, map_variables<EmptyVariable, AnyVariable>(*exp.func.arg, func)); case DATALOG_TUPLE: if (exp.tuple.position != POSITION_EXACT) count = func(count, AnyVariable); for (datalog_expression* arg : exp.tuple.elements) count = func(count, map_variables<EmptyVariable, AnyVariable>(*arg, func)); return count; case DATALOG_LIST: for (datalog_expression* arg : exp.list.elements) count = func(count, map_variables<EmptyVariable, AnyVariable>(*arg, func)); return count; case DATALOG_VARIABLE: return func(count, exp.variable); case DATALOG_CONSTANT: case DATALOG_INTEGER: case DATALOG_STRING: case DATALOG_EMPTY: return func(count, EmptyVariable); case DATALOG_ANY: case DATALOG_NON_EMPTY: return func(count, AnyVariable); } fprintf(stderr, "map_variables ERROR: Unrecognized expression type.\n"); return false; } inline unsigned int choose_head(unsigned int first, unsigned int second) { if (first == 1 || second == 1) return 1; if (first == DATALOG_LABEL_WILDCARD || second == DATALOG_LABEL_WILDCARD) return DATALOG_LABEL_WILDCARD; return min(first, second); } inline unsigned int get_head(const datalog_expression& exp) { return map_variables<DATALOG_LABEL_EMPTY, DATALOG_LABEL_WILDCARD>(exp, choose_head); } inline unsigned int min_variable(const datalog_expression& exp) { static auto min_func = [] (unsigned int a, unsigned int b) { return min(a, b); }; return map_variables<UINT_MAX, UINT_MAX>(exp, min_func); } inline unsigned int max_variable(const datalog_expression& exp) { static auto max_func = [] (unsigned int a, unsigned int b) { return max(a, b); }; return map_variables<0, 0>(exp, max_func); } inline unsigned int variable_count(const datalog_expression& exp) { unsigned int max_var = max_variable(exp); if (max_var == 0) return 0; else return max_var - min_variable(exp) + 1; } bool is_ambiguous(const datalog_expression& exp) { switch (exp.type) { case DATALOG_PREDICATE: if (exp.pred.function == DATALOG_LABEL_WILDCARD) return true; for (unsigned int i = 0; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) break; if (is_ambiguous(*exp.pred.args[i])) return true; } return false; case DATALOG_FUNCTION: if (exp.func.function == DATALOG_LABEL_WILDCARD) return true; return is_ambiguous(*exp.func.arg); case DATALOG_TUPLE: if (exp.tuple.position != POSITION_EXACT) return true; for (datalog_expression* arg : exp.tuple.elements) if (is_ambiguous(*arg)) return true; return false; case DATALOG_LIST: for (datalog_expression* arg : exp.list.elements) if (is_ambiguous(*arg)) return true; return false; case DATALOG_CONSTANT: return (exp.constant.label == DATALOG_LABEL_WILDCARD); case DATALOG_VARIABLE: case DATALOG_INTEGER: case DATALOG_EMPTY: return false; case DATALOG_STRING: return exp.str.length == 1 && exp.str[0] == DATALOG_STRING_LABEL_WILDCARD; case DATALOG_ANY: case DATALOG_NON_EMPTY: return true; } fprintf(stderr, "is_ambiguous ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } inline bool is_ambiguous(const datalog_expression_root& exp) { return is_ambiguous(exp.root); } bool valid_variable_scope(const datalog_expression& exp, array<unsigned int>& variables) { switch (exp.type) { case DATALOG_PREDICATE: for (unsigned int i = 0; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) continue; if (!valid_variable_scope(*exp.pred.args[i], variables)) return false; } return true; case DATALOG_FUNCTION: if (exp.func.function == PREDICATE_COUNT || exp.func.function == PREDICATE_SUM) { if (!ensure_variable_map_capacity(variables, exp.func.vars[0])) exit(EXIT_FAILURE); if (variables[exp.func.vars[0]] == 1) { /* this variable appeared before the function */ return false; } } else if (exp.func.function == PREDICATE_MOST || exp.func.function == PREDICATE_FEWEST) { if (!ensure_variable_map_capacity(variables, exp.func.vars[1])) exit(EXIT_FAILURE); if (variables[exp.func.vars[1]] == 1) { /* this variable appeared before the function */ return false; } } if (!valid_variable_scope(*exp.func.arg, variables)) return false; if (exp.func.function == PREDICATE_COUNT || exp.func.function == PREDICATE_SUM) variables[exp.func.vars[0]] = 2; else if (exp.func.function == PREDICATE_MOST || exp.func.function == PREDICATE_FEWEST) variables[exp.func.vars[1]] = 2; return true; case DATALOG_TUPLE: for (datalog_expression* arg : exp.tuple.elements) if (!valid_variable_scope(*arg, variables)) return false; return true; case DATALOG_LIST: for (datalog_expression* arg : exp.list.elements) if (!valid_variable_scope(*arg, variables)) return false; return true; case DATALOG_VARIABLE: if (!ensure_variable_map_capacity(variables, exp.variable)) exit(EXIT_FAILURE); if (variables[exp.variable] == 0) { /* this is a new variable */ variables[exp.variable] = 1; } else if (variables[exp.variable] == 2) { /* this variable is out of scope */ return false; } return true; case DATALOG_CONSTANT: case DATALOG_INTEGER: case DATALOG_STRING: case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: return true; } fprintf(stderr, "valid_variable_scope ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } inline bool valid_variable_scope(const datalog_expression& exp) { array<unsigned int> variables = array<unsigned int>(8); memset(variables.data, 0, sizeof(unsigned int) * variables.capacity); return valid_variable_scope(exp, variables); } template<unsigned int Predicate> bool has_predicate(const datalog_expression& exp) { switch (exp.type) { case DATALOG_PREDICATE: if (exp.pred.function == DATALOG_LABEL_WILDCARD) { if (!exp.pred.is_excluded(Predicate)) return true; } else if (exp.pred.function == Predicate) return true; for (unsigned int i = 0; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) continue; if (has_predicate<Predicate>(*exp.pred.args[i])) return true; } return false; case DATALOG_FUNCTION: return has_predicate<Predicate>(*exp.func.arg); case DATALOG_TUPLE: for (datalog_expression* arg : exp.tuple.elements) if (has_predicate<Predicate>(*arg)) return true; return false; case DATALOG_LIST: for (datalog_expression* arg : exp.list.elements) if (has_predicate<Predicate>(*arg)) return true; return false; case DATALOG_VARIABLE: case DATALOG_CONSTANT: case DATALOG_INTEGER: case DATALOG_STRING: case DATALOG_EMPTY: return false; case DATALOG_ANY: case DATALOG_NON_EMPTY: return true; } fprintf(stderr, "has_predicate ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } constexpr bool operator == ( const datalog_expression_root::function& first, const datalog_expression_root::function& second) { return first.type == second.type; } constexpr bool operator != ( const datalog_expression_root::function& first, const datalog_expression_root::function& second) { return first.type != second.type; } constexpr bool operator < ( const datalog_expression_root::function& first, const datalog_expression_root::function& second) { return first.type < second.type; } inline bool operator == (const datalog_literal& first, const datalog_literal& second) { if (first.label != second.label || first.excluded_count != second.excluded_count) return false; for (unsigned int i = 0; i < first.excluded_count; i++) if (first.excluded[i] != second.excluded[i]) return false; return true; } bool operator == (const datalog_expression& first, const datalog_expression& second) { if (first.type != second.type) return false; switch (first.type) { case DATALOG_PREDICATE: if (first.pred.function != second.pred.function || first.pred.excluded_count != second.pred.excluded_count) return false; for (unsigned int i = 0; i < first.pred.excluded_count; i++) if (first.pred.excluded[i] != second.pred.excluded[i]) return false; for (unsigned int i = 0; i < array_length(first.pred.args); i++) { if (first.pred.args[i] == NULL) { if (second.pred.args[i] == NULL) continue; else return false; } else if (second.pred.args[i] == NULL) { return false; } else if (first.pred.args[i] != second.pred.args[i] && *first.pred.args[i] != *second.pred.args[i]) return false; } return true; case DATALOG_FUNCTION: if (first.func.function != second.func.function || first.func.excluded_count != second.func.excluded_count) return false; for (unsigned int i = 0; i < first.func.excluded_count; i++) if (first.func.excluded[i] != second.func.excluded[i]) return false; if (first.func.arg == NULL) { if (second.func.arg == NULL) return true; else return false; } else if (second.func.arg == NULL) { return false; } else if (first.func.arg != second.func.arg && *first.func.arg != *second.func.arg) return false; return true; case DATALOG_TUPLE: if (first.tuple.position != second.tuple.position || first.tuple.elements.length != second.tuple.elements.length) return false; for (unsigned int i = 0; i < first.tuple.elements.length; i++) if (first.tuple.elements[i] != second.tuple.elements[i] && *first.tuple.elements[i] != *second.tuple.elements[i]) return false; return true; case DATALOG_LIST: if (first.list.elements.length != second.list.elements.length) return false; for (unsigned int i = 0; i < first.list.elements.length; i++) if (first.list.elements[i] != second.list.elements[i] && *first.list.elements[i] != *second.list.elements[i]) return false; return true; case DATALOG_VARIABLE: return first.variable == second.variable; case DATALOG_CONSTANT: return first.constant == second.constant; case DATALOG_INTEGER: return first.integer == second.integer; case DATALOG_STRING: return first.str == second.str; case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: return true; } fprintf(stderr, "datalog_expression operator == ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } inline bool operator != (const datalog_expression& first, const datalog_expression& second) { return !(first == second); } inline bool operator == (const datalog_expression_root& first, const datalog_expression_root& second) { return first.index == second.index && first.concord == second.concord && first.inf == second.inf && first.root == second.root; } inline bool operator != (const datalog_expression_root& first, const datalog_expression_root& second) { return first.index != second.index || first.concord != second.concord || first.inf != second.inf || first.root != second.root; } /* forward declarations */ bool canonicalize(const datalog_expression& src, datalog_expression& dst, const array_map<const datalog_expression*, array<const datalog_expression*>>& maximal_scope); struct canonicalizer { }; inline bool less_than( const datalog_expression& first, const datalog_expression& second, const canonicalizer& sorter) { if (first.type < second.type) return true; else if (first.type > second.type) return false; switch (first.type) { case DATALOG_PREDICATE: if (first.pred.function < second.pred.function) return true; else if (first.pred.function > second.pred.function) return false; else if (first.pred.excluded_count < second.pred.excluded_count) return true; else if (first.pred.excluded_count > second.pred.excluded_count) return false; for (unsigned int i = 0; i < first.pred.excluded_count; i++) { if (first.pred.excluded[i] < second.pred.excluded[i]) return true; else if (first.pred.excluded[i] > second.pred.excluded[i]) return false; } for (unsigned int i = 0; i < array_length(first.pred.args); i++) { if (first.pred.args[i] == NULL) { if (second.pred.args[i] == NULL) { continue; } else { return true; } } else { if (second.pred.args[i] == NULL) { return false; } else if (less_than(*first.pred.args[i], *second.pred.args[i], sorter)) { return true; } else if (less_than(*second.pred.args[i], *first.pred.args[i], sorter)) { return false; } } } return false; case DATALOG_FUNCTION: if (first.func.function < second.func.function) return true; else if (first.func.function > second.func.function) return false; else if (first.func.excluded_count < second.func.excluded_count) return true; else if (first.func.excluded_count > second.func.excluded_count) return false; else if (first.func.arg == NULL) { if (second.func.arg == NULL) { return false; } else { return true; } } else { if (second.func.arg == NULL) { return true; } else { return less_than(*first.func.arg, *second.func.arg, sorter); } } case DATALOG_TUPLE: if (first.tuple.position < second.tuple.position) return true; else if (first.tuple.position > second.tuple.position) return false; else if (first.tuple.elements.length < second.tuple.elements.length) return true; else if (first.tuple.elements.length > second.tuple.elements.length) return false; for (unsigned int i = 0; i < first.tuple.elements.length; i++) { if (less_than(*first.tuple.elements[i], *second.tuple.elements[i], sorter)) { return true; } else if (less_than(*second.tuple.elements[i], *first.tuple.elements[i], sorter)) { return false; } } return false; case DATALOG_LIST: if (first.list.elements.length < second.list.elements.length) return true; else if (first.list.elements.length > second.list.elements.length) return false; for (unsigned int i = 0; i < first.list.elements.length; i++) { if (less_than(*first.list.elements[i], *second.list.elements[i], sorter)) { return true; } else if (less_than(*second.list.elements[i], *first.list.elements[i], sorter)) { return false; } } return false; case DATALOG_CONSTANT: return first.constant < second.constant; case DATALOG_INTEGER: return first.integer < second.integer; case DATALOG_STRING: return first.str < second.str; case DATALOG_VARIABLE: case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: return true; } fprintf(stderr, "less_than ERROR: Unrecognized expression type during canonicalization.\n"); exit(EXIT_FAILURE); } inline bool less_than( const datalog_expression* first, const datalog_expression* second, const canonicalizer& sorter) { return less_than(*first, *second, sorter); } struct datalog_scope { const datalog_expression* exp; array<unsigned int>* variables; }; inline bool process_maximal_scope(const datalog_expression* child_expression, const array_map<unsigned int, datalog_scope>& available_scopes, array_map<const datalog_expression*, array<const datalog_expression*>>& maximal_scope, array<const datalog_expression*>& root_scope, const array<unsigned int>& child_variables) { datalog_scope* scope = NULL; for (unsigned int i = available_scopes.size; i > 0; i--) { if (child_variables.contains(available_scopes.keys[i - 1])) { scope = &available_scopes.values[i - 1]; break; } } if (scope == NULL) { return root_scope.add(child_expression); } else { array<unsigned int>& variables = *scope->variables; if (!variables.ensure_capacity(variables.length + child_variables.length)) return false; for (unsigned int child_variable : child_variables) { if (variables.contains(child_variable)) continue; variables[variables.length] = child_variable; variables.length++; } return maximal_scope.get(scope->exp).add(child_expression); } } bool compute_maximal_scope(const datalog_expression& src, array_map<unsigned int, datalog_scope>& available_scopes, array_map<const datalog_expression*, array<const datalog_expression*>>& maximal_scope, array<const datalog_expression*>& root_scope, array<unsigned int>& variables) { unsigned int old_maximal_scope_count; unsigned int old_available_scope_count = available_scopes.size; array<unsigned int> child_variables = array<unsigned int>(8); array_map<unsigned int, datalog_scope> child_scopes = array_map<unsigned int, datalog_scope>(8); array<const datalog_expression*> child_root_scope = array<const datalog_expression*>(8); switch (src.type) { case DATALOG_PREDICATE: for (unsigned int i = 0; i < array_length(src.pred.args); i++) { if (src.pred.args[i] == NULL) continue; /* arguments of predicates can't be moved outside */ if (!maximal_scope.ensure_capacity(maximal_scope.size + 1)) return false; old_maximal_scope_count = maximal_scope.size; maximal_scope.keys[old_maximal_scope_count] = src.pred.args[i]; if (!array_init(maximal_scope.values[old_maximal_scope_count], 4)) return false; maximal_scope.size++; /* recursively compute the variables of the child expression */ if (!compute_maximal_scope(*src.pred.args[i], child_scopes, maximal_scope, child_root_scope, child_variables) || !process_maximal_scope(src.pred.args[i], child_scopes, maximal_scope, child_root_scope, child_variables) || !maximal_scope.values[old_maximal_scope_count].append(child_root_scope.data, child_root_scope.length) || !variables.append(child_variables.data, child_variables.length)) return false; child_scopes.clear(); child_root_scope.clear(); child_variables.clear(); } return true; case DATALOG_FUNCTION: if (!maximal_scope.ensure_capacity(maximal_scope.size + 1) || !available_scopes.ensure_capacity(available_scopes.size + array_length(src.func.vars))) return false; for (unsigned int i = 0; i < array_length(src.func.vars); i++) { if (src.func.vars[i] == 0) continue; else if (!variables.add(src.func.vars[i])) return false; available_scopes.keys[available_scopes.size] = src.func.vars[i]; available_scopes.values[available_scopes.size] = {src.func.arg, &variables}; available_scopes.size++; } old_maximal_scope_count = maximal_scope.size; maximal_scope.keys[old_maximal_scope_count] = src.func.arg; if (!array_init(maximal_scope.values[old_maximal_scope_count], 4)) return false; maximal_scope.size++; if (src.func.function == PREDICATE_ANSWER || src.func.function == PREDICATE_NOT) { /* negation and lambda terms block movement */ for (unsigned int i = 0; i < array_length(src.func.vars); i++) { if (src.func.vars[i] == 0) continue; child_scopes.keys[i] = src.func.vars[i]; child_scopes.values[i] = {src.func.arg, &variables}; child_scopes.size++; } /* recursively compute the variables of the child expression */ if (!compute_maximal_scope(*src.func.arg, child_scopes, maximal_scope, child_root_scope, child_variables) || !process_maximal_scope(src.func.arg, child_scopes, maximal_scope, child_root_scope, child_variables) || !maximal_scope.values[old_maximal_scope_count].append(child_root_scope.data, child_root_scope.length)) return false; } else { /* recursively compute the variables of the child expression */ if (!compute_maximal_scope(*src.func.arg, available_scopes, maximal_scope, root_scope, child_variables) || !process_maximal_scope(src.func.arg, available_scopes, maximal_scope, root_scope, child_variables)) return false; } available_scopes.size = old_available_scope_count; return true; case DATALOG_TUPLE: for (unsigned int i = 0; i < src.tuple.elements.length; i++) { if (!compute_maximal_scope(*src.tuple.elements[i], available_scopes, maximal_scope, root_scope, child_variables) || !process_maximal_scope(src.tuple.elements[i], available_scopes, maximal_scope, root_scope, child_variables)) return false; child_variables.clear(); } /* since all elements of a tuple are "moved" to a higher scope, the tuple becomes vacuous, so don't mark it for movement */ return true; case DATALOG_LIST: /* lists block all movement */ for (unsigned int i = 0; i < src.tuple.elements.length; i++) { if (maximal_scope.ensure_capacity(maximal_scope.size + 1)) return false; old_maximal_scope_count = maximal_scope.size; maximal_scope.keys[old_maximal_scope_count] = src.tuple.elements[i]; if (!array_init(maximal_scope.values[old_maximal_scope_count], 4)) return false; maximal_scope.size++; /* recursively compute the variables of the child expression */ if (!compute_maximal_scope(*src.tuple.elements[i], child_scopes, maximal_scope, child_root_scope, child_variables) || !process_maximal_scope(src.tuple.elements[i], child_scopes, maximal_scope, child_root_scope, child_variables) || !maximal_scope.values[old_maximal_scope_count].append(child_root_scope.data, child_root_scope.length)) return false; child_scopes.clear(); child_root_scope.clear(); child_variables.clear(); } return true; case DATALOG_VARIABLE: return variables.add(src.variable); case DATALOG_CONSTANT: case DATALOG_INTEGER: case DATALOG_STRING: case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: return true; } fprintf(stderr, "compute_maximal_scope ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } inline bool compute_maximal_scope(const datalog_expression& src, array_map<const datalog_expression*, array<const datalog_expression*>>& maximal_scope) { array<unsigned int> variables = array<unsigned int>(8); array_map<unsigned int, datalog_scope> available_scopes = array_map<unsigned int, datalog_scope>(8); array<const datalog_expression*> root_scope = array<const datalog_expression*>(8); return compute_maximal_scope(src, available_scopes, maximal_scope, root_scope, variables); } inline bool canonicalize_scope(const datalog_expression* src_scope, datalog_expression& dst, const array_map<const datalog_expression*, array<const datalog_expression*>>& maximal_scope) { const array<const datalog_expression*>& moved_expressions = maximal_scope.get(src_scope); tuple_position position = (src_scope->type == DATALOG_TUPLE) ? src_scope->tuple.position : POSITION_EXACT; if (position == POSITION_RIGHT) position = POSITION_LEFT; if (moved_expressions.length == 1 && position == POSITION_EXACT) { return canonicalize(*moved_expressions[0], dst, maximal_scope); } else { if (!init_tuple(dst, position, moved_expressions.length)) return false; for (unsigned int i = 0; i < moved_expressions.length; i++) { if (!new_expression(dst.tuple.elements[i])) { free(dst); return false; } else if (!canonicalize(*moved_expressions[i], *dst.tuple.elements[i], maximal_scope)) { free(dst.tuple.elements[i]); free(dst); return false; } dst.tuple.elements.length++; } /* remove any vacuous elements */ for (unsigned int i = 0; i < dst.tuple.elements.length; i++) { if (dst.tuple.elements[i]->type == DATALOG_TUPLE && dst.tuple.elements[i]->tuple.elements.length == 0) { if (dst.tuple.elements[i]->tuple.position != POSITION_EXACT) dst.tuple.position = POSITION_LEFT; free(*dst.tuple.elements[i]); free(dst.tuple.elements[i]); dst.tuple.elements.remove(i); i--; } } if (dst.tuple.elements.length > 1) { /* sort the tuple elements */ sort(dst.tuple.elements, canonicalizer()); /* remove duplicate elements */ unsigned int dst_index = 0; for (unsigned int i = 1; i < dst.tuple.elements.length; i++) { if (dst.tuple.elements[dst_index] != dst.tuple.elements[i]) { dst.tuple.elements[++dst_index] = dst.tuple.elements[i]; } else { free(*dst.tuple.elements[i]); free(dst.tuple.elements[i]); } } dst.tuple.elements.length = dst_index + 1; } /* if only one element remains, simplify the tuple */ if (dst.tuple.elements.length == 1 && dst.tuple.position == POSITION_EXACT) { datalog_expression* singleton = dst.tuple.elements[0]; singleton->reference_count++; free(dst); dst = *singleton; free(*singleton); if (singleton->reference_count == 0) free(singleton); } return true; } return true; } bool canonicalize(const datalog_predicate& pred, datalog_expression& dst, const array_map<const datalog_expression*, array<const datalog_expression*>>& maximal_scope) { dst.pred.function = pred.function; if (pred.excluded_count > 0 && !init_excluded(dst.pred.excluded, pred.excluded, pred.excluded_count)) return false; dst.pred.excluded_count = pred.excluded_count; for (unsigned int i = 0; i < array_length(pred.args); i++) dst.pred.args[i] = NULL; for (unsigned int i = 0; i < array_length(pred.args); i++) { if (pred.args[i] == NULL) { continue; } else if (!new_expression(dst.pred.args[i])) { free(dst.pred); return false; } else if (!canonicalize_scope(pred.args[i], *dst.pred.args[i], maximal_scope)) { free(dst.pred.args[i]); dst.pred.args[i] = NULL; free(dst.pred); return false; } } dst.type = DATALOG_PREDICATE; dst.reference_count = 1; return true; } bool canonicalize(const datalog_expression& src, datalog_expression& dst, const array_map<const datalog_expression*, array<const datalog_expression*>>& maximal_scope) { switch (src.type) { case DATALOG_PREDICATE: return canonicalize(src.pred, dst, maximal_scope); case DATALOG_FUNCTION: if (!new_expression(dst.func.arg)) return false; dst.func.function = src.func.function; if (src.func.excluded_count > 0 && !init_excluded(dst.func.excluded, src.func.excluded, src.func.excluded_count)) { free(dst.func.arg); return false; } dst.func.excluded_count = src.func.excluded_count; dst.type = DATALOG_FUNCTION; dst.reference_count = 1; for (unsigned int i = 0; i < array_length(src.func.vars); i++) dst.func.vars[i] = src.func.vars[i]; return canonicalize_scope(src.func.arg, *dst.func.arg, maximal_scope); case DATALOG_TUPLE: return init_tuple(dst, src.tuple.position, 1); case DATALOG_LIST: if (!array_init(dst.list.elements, src.list.elements.length)) return false; dst.type = DATALOG_LIST; dst.reference_count = 1; for (unsigned int i = 0; i < src.list.elements.length; i++) { if (!new_expression(dst.list.elements[i])) { free(dst); return false; } else if (!canonicalize_scope(src.list.elements[i], *dst.list.elements[i], maximal_scope)) { free(dst.list.elements[i]); free(dst); return false; } dst.list.elements.length++; } return true; case DATALOG_CONSTANT: if (!init(dst.constant, src.constant)) return false; dst.type = DATALOG_CONSTANT; dst.reference_count = 1; return true; case DATALOG_INTEGER: dst.integer = src.integer; dst.type = DATALOG_INTEGER; dst.reference_count = 1; return true; case DATALOG_STRING: dst.str = src.str; dst.type = DATALOG_STRING; dst.reference_count = 1; return true; case DATALOG_VARIABLE: dst.variable = src.variable; dst.type = DATALOG_VARIABLE; dst.reference_count = 1; return true; case DATALOG_EMPTY: case DATALOG_ANY: case DATALOG_NON_EMPTY: dst.type = src.type; dst.reference_count = 1; return true; } fprintf(stderr, "canonicalize ERROR: Unrecognized expression type.\n"); exit(EXIT_FAILURE); } template<typename K, typename V> void free_values(array_map<K, V>& map) { for (auto entry : map) free(entry.value); } bool equivalent(const datalog_expression& first, const datalog_expression& second) { array_map<const datalog_expression*, array<const datalog_expression*>> first_maximal_scope(8), second_maximal_scope(8); if (!compute_maximal_scope(first, first_maximal_scope) || !compute_maximal_scope(second, second_maximal_scope)) { free_values(first_maximal_scope); free_values(second_maximal_scope); return false; } /* canonicalize the logical form structure (modulo variables) */ datalog_expression first_canonical; datalog_expression second_canonical; if (!canonicalize(first, first_canonical, first_maximal_scope) || !canonicalize(second, second_canonical, second_maximal_scope)) { free_values(first_maximal_scope); free_values(second_maximal_scope); free(first_canonical); exit(EXIT_FAILURE); } free_values(first_maximal_scope); free_values(second_maximal_scope); /* relabel variables in prefix order */ datalog_expression first_relabeled; datalog_expression second_relabeled; array_map<unsigned int, unsigned int> first_variable_map = array_map<unsigned int, unsigned int>(8); array_map<unsigned int, unsigned int> second_variable_map = array_map<unsigned int, unsigned int>(8); if (!build_variable_map(first_canonical, first_variable_map) || !build_variable_map(second_canonical, second_variable_map) || !init(first_relabeled, first_canonical, first_variable_map) || !init(second_relabeled, second_canonical, second_variable_map)) { free(first_canonical); free(second_canonical); free(first_relabeled); exit(EXIT_FAILURE); } free(first_canonical); free(second_canonical); bool are_equivalent = (first_relabeled == second_relabeled); free(first_relabeled); free(second_relabeled); return are_equivalent; } inline bool equivalent(const datalog_expression_root& first, const datalog_expression_root& second) { return first.index == second.index && first.concord == second.concord && first.inf == second.inf && equivalent(first.root, second.root); } template<typename Stream> inline bool print_variable(unsigned int variable, Stream& out) { if (variable == 0) return print('0', out); else return print((char) ('A' + variable - 1), out); } template<typename Stream, typename... Printer> bool print(const datalog_function& func, Stream& out, Printer&&... printer) { if (func.function == DATALOG_LABEL_WILDCARD) { return print("*(", out) && print(*func.arg, out, std::forward<Printer>(printer)...) && print(')', out); } if (func.function != PREDICATE_NOT && (!print(func.function, out, std::forward<Printer>(printer)...) || !print('(', out))) return false; switch (func.function) { case PREDICATE_COUNT: case PREDICATE_SUM: if (!print_variable(func.vars[0], out)) return false; if (!print(',', out) || !print(*func.arg, out, std::forward<Printer>(printer)...) || !print(',', out)) return false; return print_variable(func.vars[1], out) && print(')', out); case PREDICATE_ANSWER: case PREDICATE_HIGHEST: case PREDICATE_LOWEST: case PREDICATE_LONGEST: case PREDICATE_SHORTEST: case PREDICATE_LARGEST: case PREDICATE_SMALLEST: if (!print_variable(func.vars[0], out)) return false; return print(',', out) && print(*func.arg, out, std::forward<Printer>(printer)...) && print(')', out); case PREDICATE_MOST: case PREDICATE_FEWEST: if (!print_variable(func.vars[0], out) || !print(',', out) || !print_variable(func.vars[1], out)) return false; return print(',', out) && print(*func.arg, out, std::forward<Printer>(printer)...) && print(')', out); case PREDICATE_NOT: return print("\\+", out) && print(*func.arg, out, std::forward<Printer>(printer)...); default: fprintf(stderr, "print ERROR: Unrecognized datalog_function predicate.\n"); return false; } } template<typename Stream, typename... Printer> bool print(const datalog_tuple& tuple, Stream& out, Printer&&... printer) { if (tuple.elements.length == 0) { if (tuple.position == POSITION_EXACT) return print("()", out); else return print("(...)", out); } if (!print('(', out)) return false; if (tuple.position == POSITION_RIGHT && !print("...,", out)) return false; if (!print(*tuple.elements[0], out, std::forward<Printer>(printer)...)) return false; for (unsigned int i = 1; i < tuple.elements.length; i++) { if (!print(',', out) || !print(*tuple.elements[i], out, std::forward<Printer>(printer)...)) return false; } if (tuple.position == POSITION_LEFT && !print(",...", out)) return false; return print(')', out); } template<typename Stream, typename... Printer> bool print(const datalog_expression& exp, Stream& out, Printer&&... printer) { switch (exp.type) { case DATALOG_PREDICATE: if (!print(exp.pred.function, out, std::forward<Printer>(printer)...) || !print('(', out)) return false; for (unsigned int i = 0; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) break; if (i > 0 && !print(',', out)) return false; if (!print(*exp.pred.args[i], out, std::forward<Printer>(printer)...)) return false; } return print(')', out); case DATALOG_FUNCTION: return print(exp.func, out, std::forward<Printer>(printer)...); case DATALOG_TUPLE: return print(exp.tuple, out, std::forward<Printer>(printer)...); case DATALOG_LIST: if (!print('[', out)) return false; for (unsigned int i = 0; i < exp.tuple.elements.length; i++) { if (i > 0 && !print(',', out)) return false; if (!print(*exp.tuple.elements[i], out, std::forward<Printer>(printer)...)) return false; } return print(']', out); case DATALOG_VARIABLE: return print_variable(exp.variable, out); case DATALOG_CONSTANT: return print(exp.constant.label, out, std::forward<Printer>(printer)...); case DATALOG_INTEGER: return print(exp.integer, out); case DATALOG_STRING: if (exp.str.length == 1 && exp.str[0] == DATALOG_STRING_LABEL_WILDCARD) return print("<any string>", out); return print('"', out) && print(exp.str, out) && print('"', out); case DATALOG_EMPTY: return print("<empty>", out); case DATALOG_ANY: case DATALOG_NON_EMPTY: return print('*', out); } fprintf(stderr, "print ERROR: Unrecognized datalog_expression type.\n"); exit(EXIT_FAILURE); } template<typename Stream, typename... Printer> bool print(const datalog_expression_root& exp, Stream& out, Printer&&... printer) { if (!print(exp.root, out, std::forward<Printer>(printer)...)) return false; unsigned int index = 0; if (exp.index != NUMBER_ALL) { if (index == 0 && !print('[', out)) return false; if (!print("index:", out) || !print(exp.index, out)) return false; index++; } if (exp.concord != NUMBER_NONE) { if (index == 0 && !print('[', out)) return false; if (index != 0 && !print(',', out)) return false; if (!print("concord:", out) || !print(exp.concord, out)) return false; index++; } if (exp.inf != INFLECTION_NONE) { if (index == 0 && !print('[', out)) return false; if (index != 0 && !print(',', out)) return false; if (!print(exp.inf, out)) return false; index++; } return (index == 0 || print(']', out)); } bool datalog_interpret_args( const array<datalog_token>& tokens, unsigned int& index, array<datalog_expression*>& args, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables) { while (true) { if (!args.ensure_capacity(args.length + 1)) return false; datalog_expression*& next_arg = args[(unsigned int) args.length]; if (!new_expression(next_arg) || !datalog_interpret_expression(tokens, index, *next_arg, names, variables)) { if (next_arg != NULL) free(next_arg); return false; } args.length++; if (next_arg->type == DATALOG_EMPTY) { free(next_arg); next_arg = NULL; } if (index >= tokens.length) { fprintf(stderr, "ERROR: Unexpected end of input.\n"); return false; } else if (tokens[index].type != DATALOG_TOKEN_COMMA) { /* this is the end of the list, so return */ return true; } index++; } } template<datalog_token_type ClosingSymbol, const char* SymbolDescription> bool datalog_interpret_comma_list( const array<datalog_token>& tokens, unsigned int& index, array<datalog_expression*>& args, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables) { if (tokens[index].type == ClosingSymbol) { /* this function has no arguments */ index++; return true; } else { if (!datalog_interpret_args(tokens, index, args, names, variables)) return false; if (!expect_token(tokens, index, ClosingSymbol, SymbolDescription)) return false; index++; return true; } } char bracket_description[] = "closing bracket in list"; char parenthesis_description[] = "closing parenthesis in function call"; inline bool datalog_interpret_list( const array<datalog_token>& tokens, unsigned int& index, array<datalog_expression*>& args, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables) { return datalog_interpret_comma_list <DATALOG_TOKEN_RBRACKET, bracket_description>(tokens, index, args, names, variables); } inline bool datalog_interpret_tuple( const array<datalog_token>& tokens, unsigned int& index, array<datalog_expression*>& args, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables) { return datalog_interpret_comma_list <DATALOG_TOKEN_RPAREN, parenthesis_description>(tokens, index, args, names, variables); } bool datalog_interpret_function( unsigned int predicate, datalog_expression& exp, array<datalog_expression*>& args, const position& pos) { if (!init(exp.func)) return false; exp.func.function = predicate; exp.type = DATALOG_FUNCTION; unsigned int var_index = 0; for (datalog_expression* arg : args) { switch (arg->type) { case DATALOG_VARIABLE: if (var_index == array_length(exp.func.vars)) { read_error("Too many variable arguments to function", pos); free(exp.func); return false; } exp.func.vars[var_index] = arg->variable; var_index++; break; default: if (exp.func.arg != NULL) { read_error("Too many non-variable arguments to function", pos); free(exp.func); return false; } exp.func.arg = arg; arg->reference_count++; break; } } for (; var_index < array_length(exp.func.vars); var_index++) exp.func.vars[var_index] = 0; return true; } bool datalog_interpret_predicate( unsigned int predicate, datalog_expression& exp, array<datalog_expression*>& args, const position& pos) { if (!init(exp.pred)) return false; exp.pred.function = predicate; exp.type = DATALOG_PREDICATE; unsigned int index = 0; for (datalog_expression* arg : args) { if (index == array_length(exp.pred.args)) { read_error("Too many arguments to predicate instance", pos); free(exp.pred); return false; } exp.pred.args[index] = arg; if (arg != NULL) arg->reference_count++; index++; } return true; } bool datalog_interpret_expression( const array<datalog_token>& tokens, unsigned int& index, datalog_expression& exp, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables) { if (index >= tokens.length) { fprintf(stderr, "ERROR: Unexpected end of input.\n"); return false; } else if (tokens[index].type == DATALOG_TOKEN_IDENTIFIER || tokens[index].type == DATALOG_TOKEN_STRING) { const datalog_token& identifier = tokens[index]; index++; if (index >= tokens.length) { fprintf(stderr, "ERROR: Unexpected end of input.\n"); return false; } else if (tokens[index].type == DATALOG_TOKEN_LPAREN) { /* this is a higher-order function or predicate instance */ index++; exp.reference_count = 1; unsigned int predicate; if (!get_token(identifier.text, predicate, names)) { free(exp); return false; } /* parse the function/predicate arguments */ array<datalog_expression*> args = array<datalog_expression*>(4); if (!datalog_interpret_tuple(tokens, index, args, names, variables)) { for (datalog_expression* arg : args) { free(*arg); free(arg); } free(exp); return false; } bool failed = (predicate <= NUM_PREDICATES && !datalog_interpret_function(predicate, exp, args, identifier.end)) || (predicate > NUM_PREDICATES && !datalog_interpret_predicate(predicate, exp, args, identifier.end)); for (datalog_expression* arg : args) { if (arg == NULL) continue; free(*arg); if (arg->reference_count == 0) free(arg); } return !failed; } else { exp.reference_count = 1; if (identifier.type == DATALOG_TOKEN_STRING) { /* this is a constant */ exp.type = DATALOG_CONSTANT; if (!get_token(identifier.text, exp.constant.label, names)) return false; exp.constant.excluded_count = 0; } else if ((identifier.text.length == 1 && identifier.text[0] >= 'A' && identifier.text[0] <= 'Z') || (identifier.text.length == 2 && identifier.text[0] >= 'A' && identifier.text[0] <= 'Z' && isdigit(identifier.text[1]))) { /* this is a variable */ exp.type = DATALOG_VARIABLE; if (!get_token(identifier.text, exp.variable, variables)) return false; } else if (identifier.text.length > 1 && identifier.text[0] == '_') { /* this is also a variable */ exp.type = DATALOG_VARIABLE; if (!get_token(identifier.text, exp.variable, variables)) return false; } else if (identifier.text.length == 1 && identifier.text[0] == '_') { exp.type = DATALOG_EMPTY; return true; } else { if (parse_int(identifier.text, exp.integer)) { /* this is an integer */ exp.type = DATALOG_INTEGER; } else { /* this is a constant */ exp.type = DATALOG_CONSTANT; if (!get_token(identifier.text, exp.constant.label, names)) return false; exp.constant.excluded_count = 0; } } } } else if (tokens[index].type == DATALOG_TOKEN_SLASH_PLUS) { /* this is a negation */ index++; if (!init(exp.func)) return false; if (!new_expression(exp.func.arg) || !datalog_interpret_expression(tokens, index, *exp.func.arg, names, variables)) { if (exp.func.arg != NULL) free(exp.func.arg); return false; } for (unsigned int i = 0; i < array_length(exp.func.vars); i++) exp.func.vars[i] = 0; exp.func.function = PREDICATE_NOT; exp.type = DATALOG_FUNCTION; exp.reference_count = 1; } else if (tokens[index].type == DATALOG_TOKEN_LBRACKET) { /* this is a list */ index++; if (!init(exp.list)) return false; exp.type = DATALOG_LIST; exp.reference_count = 1; if (!datalog_interpret_list(tokens, index, exp.list.elements, names, variables)) { free(exp.list); return false; } } else if (tokens[index].type == DATALOG_TOKEN_LPAREN) { /* this is a tuple */ index++; if (!init(exp.tuple, POSITION_EXACT, 1)) { fprintf(stderr, "datalog_interpret_expression ERROR: Unable to initialize tuple.\n"); return false; } exp.type = DATALOG_TUPLE; exp.reference_count = 1; if (!datalog_interpret_tuple(tokens, index, exp.tuple.elements, names, variables)) { free(exp.tuple); return false; } } else { read_error("Unexpected symbol at beginning of expression", tokens[index].start); return false; } return true; } bool datalog_interpret( const array<datalog_token>& tokens, array<datalog_expression_root*>& expressions, hash_map<string, unsigned int>& names) { unsigned int index = 0; while (index < tokens.length) { if (!expressions.ensure_capacity(expressions.length + 1)) return false; hash_map<string, unsigned int> variables = hash_map<string, unsigned int>(16); datalog_expression_root*& next_expression = expressions[(unsigned int) expressions.length]; next_expression = (datalog_expression_root*) malloc(sizeof(datalog_expression_root)); if (next_expression == NULL) { fprintf(stderr, "datalog_interpret ERROR: Out of memory.\n"); return false; } next_expression->index = NUMBER_ALL; next_expression->concord = NUMBER_NONE; next_expression->inf = INFLECTION_NONE; if (!datalog_interpret_expression(tokens, index, next_expression->root, names, variables)) return false; for (auto entry : variables) free(entry.key); expressions.length++; if (!expect_token(tokens, index, DATALOG_TOKEN_PERIOD, "period at end of statement")) return false; index++; } return true; } /** * Below is code for parsing a variable-free variant of Datalog. */ #include <grammar/tree_semantics.h> /* forward declarations */ bool variable_free_interpret_expression( const array<datalog_token>& tokens, unsigned int& index, tree_semantics& expression, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables); bool datalog_interpret_sentence( const array<datalog_token>& tokens, unsigned int& index, array<array<unsigned int>>& sentences, hash_map<string, unsigned int>& names) { if (!sentences.ensure_capacity(sentences.length + 1) || !array_init(sentences[(unsigned int) sentences.length], 16)) return false; sentences.length++; array<unsigned int>& sentence = sentences.last(); while (true) { if (!sentence.ensure_capacity(sentence.length + 1)) return false; if (index >= tokens.length) { fprintf(stderr, "ERROR: Unexpected end of input.\n"); return false; } else if (tokens[index].type == DATALOG_TOKEN_TAB) { index++; return true; } else if (tokens[index].type == DATALOG_TOKEN_PERIOD) { if (!get_token(".", sentence[(unsigned int) sentence.length], names)) return false; sentence.length++; index++; } else if (tokens[index].type == DATALOG_TOKEN_IDENTIFIER || tokens[index].type == DATALOG_TOKEN_STRING) { if (!get_token(tokens[index].text, sentence[(unsigned int) sentence.length], names)) return false; sentence.length++; index++; } else { read_error("Expected a sentence token or tab", tokens[index].start); return false; } } } bool variable_free_interpret_args( const array<datalog_token>& tokens, unsigned int& index, tree_semantics& expression, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables) { expression.left_child = (tree_semantics*) malloc(sizeof(tree_semantics)); if (expression.left_child == NULL) { fprintf(stderr, "variable_free_interpret_args ERROR: Out of memory.\n"); return false; } if (!variable_free_interpret_expression(tokens, index, *expression.left_child, names, variables)) return false; if (index >= tokens.length || tokens[index].type != DATALOG_TOKEN_COMMA) return true; index++; expression.right_child = (tree_semantics*) malloc(sizeof(tree_semantics)); if (expression.right_child == NULL) { fprintf(stderr, "variable_free_interpret_args ERROR: Out of memory.\n"); return false; } return variable_free_interpret_expression(tokens, index, *expression.right_child, names, variables); } bool variable_free_interpret_expression( const array<datalog_token>& tokens, unsigned int& index, tree_semantics& expression, hash_map<string, unsigned int>& names, hash_map<string, unsigned int>& variables) { expression.left_child = NULL; expression.right_child = NULL; expression.excluded_count = 0; expression.reference_count = 1; if (!expect_token(tokens, index, DATALOG_TOKEN_IDENTIFIER, "identifier at beginning of variable-free expression")) return false; if (!get_token(tokens[index].text, expression.label, names)) return false; index++; if (index >= tokens.length) { fprintf(stderr, "ERROR: Unexpected end of input.\n"); return false; } else if (tokens[index].type == DATALOG_TOKEN_LPAREN) { index++; if (!variable_free_interpret_args(tokens, index, expression, names, variables)) return false; if (!expect_token(tokens, index, DATALOG_TOKEN_RPAREN, "Closing right parenthesis")) return false; index++; } return true; } bool variable_free_interpret( const array<datalog_token>& tokens, array<array<unsigned int>>& sentences, array<tree_semantics>& expressions, hash_map<string, unsigned int>& names) { unsigned int index = 0; hash_map<string, unsigned int> dummy = hash_map<string, unsigned int>(1); while (index < tokens.length) { if (!expressions.ensure_capacity(expressions.length + 1)) return false; tree_semantics& expression = expressions[(unsigned int) expressions.length]; if (!datalog_interpret_sentence(tokens, index, sentences, names) || !variable_free_interpret_expression(tokens, index, expression, names, dummy)) return false; expressions.length++; } for (auto entry : dummy) free(entry.key); return true; } /** * Some routines for initializing derivation trees. */ template<typename Distribution> bool sample_preterminal( const grammar<datalog_expression, Distribution>& G, const sequence& terminal, unsigned int& sample) { array<unsigned int> preterminals = array<unsigned int>(G.nonterminals.length); for (unsigned int i = 0; i < G.nonterminals.length; i++) { if (!G.nonterminals[i].is_preterminal) continue; auto& terminal_prior = G.nonterminals[i].rule_distribution.h.pi.terminal_prior; if (terminal_prior.probability(terminal) > 0.0) preterminals.add(G.nonterminals[i].id); } if (preterminals.length == 0) return false; sample = sample_uniform(preterminals); return true; } template<typename Distribution> bool sample_nonterminal(const grammar<datalog_expression, Distribution>& G, unsigned int& sample) { array<unsigned int> nonterminals = array<unsigned int>(G.nonterminals.length); for (unsigned int i = 0; i < G.nonterminals.length; i++) { if (!G.nonterminals[i].is_preterminal) nonterminals.add(G.nonterminals[i].id); } if (nonterminals.length == 0) return false; sample = sample_uniform(nonterminals); return true; } template<typename RulePrior> inline bool sentence_starts_with( const RulePrior& rule_prior, const sequence& sentence, unsigned int earliest_end, unsigned int latest_end, unsigned int earliest_start, unsigned int& found) { unsigned int start = earliest_start; for (unsigned int end = earliest_end; end < latest_end + 1; end++) { rule<datalog_expression_root> r = rule<datalog_expression_root>({sentence.tokens + start, end - start}); if (rule_prior.probability(r) > 0.0) { found = end; return true; } } return false; } template<typename RulePrior> inline bool sentence_ends_with( const RulePrior& rule_prior, const sequence& sentence, unsigned int end, unsigned int earliest_start, unsigned int& found) { for (unsigned int start = earliest_start; start < end; start++) { rule<datalog_expression_root> r = rule<datalog_expression_root>({sentence.tokens + start, end - start}); if (rule_prior.probability(r) > 0.0) { found = end; return true; } } return false; } template<typename RulePrior> inline bool sentence_matches( const RulePrior& rule_prior, const sequence& sentence, unsigned int earliest_end, unsigned int latest_end, unsigned int earliest_start, unsigned int& found) { for (unsigned int end = earliest_end; end < latest_end + 1; end++) { if (sentence_ends_with(rule_prior, sentence, end, earliest_start, found)) return true; } return false; } template<typename Distribution> bool rule_matches(const grammar<datalog_expression_root, Distribution>& G, const rule<datalog_expression_root>& r, const sequence& sentence) { if (r.nt.length > sentence.length) return false; unsigned int prev = 0; for (unsigned int k = 0; k < r.nt.length; k++) { const auto& child_nonterminal = G.nonterminals[r.nt.nonterminals[k] - 1]; const auto& rule_prior = child_nonterminal.rule_distribution.h.pi; if (child_nonterminal.is_preterminal) { /* find the earliest end position for this preterminal */ unsigned int earliest_start = prev; unsigned int earliest_end = prev + 1; unsigned int latest_end = sentence.length - r.nt.length + k + 1; if (k == 0) { if (!sentence_starts_with(rule_prior, sentence, earliest_end, latest_end, earliest_start, prev)) return false; } else if (k + 1 == r.nt.length) { if (!sentence_ends_with(rule_prior, sentence, latest_end, earliest_start, prev)) return false; } else { if (!sentence_matches(rule_prior, sentence, earliest_end, latest_end, earliest_start, prev)) return false; } } else { prev++; } } return true; } /* checks if the given logical form can be associated with the given nonterminal (by checking whether the semantic feature functions can be evaluated) */ template<typename Distribution> bool is_nonterminal_valid(const grammar<datalog_expression, Distribution>& G, const datalog_expression& logical_form, unsigned int nonterminal) { const auto& N = G.nonterminals[nonterminal - 1]; unsigned int* excluded; unsigned int value, excluded_count; for (unsigned int i = 0; i < N.feature_count; i++) if (!get_feature(N.feature_sequence[i], logical_form, value, excluded, excluded_count)) return false; return true; } template<typename Distribution> bool initialize_tree( const grammar<datalog_expression_root, Distribution>& G, syntax_node<datalog_expression_root>*& tree, const sequence& sentence, const datalog_expression_root& logical_form, unsigned int nonterminal = 1) { if (!is_nonterminal_valid(G, logical_form, nonterminal)) return false; const auto& rule_prior = G.nonterminals[nonterminal - 1].rule_distribution.h.pi; tree = (syntax_node<datalog_expression_root>*) malloc(sizeof(syntax_node<datalog_expression_root>)); if (tree == NULL) { exit(EXIT_FAILURE); } if (G.nonterminals[nonterminal - 1].is_preterminal) { /* this is a terminal */ if (!init(*tree, sentence)) exit(EXIT_FAILURE); return true; } /* pick a random production rule */ array<unsigned int> available_rules = array<unsigned int>(8); for (unsigned int i = 0; i < rule_prior.rules.capacity; i++) { const rule<datalog_expression_root>& r = rule_prior.rules.keys[i]; if (is_empty(r)) continue; if (rule_matches(G, r, sentence)) { if (!available_rules.add(i)) exit(EXIT_FAILURE); } } if (available_rules.length == 0) { free(tree); tree = NULL; return false; } const rule<datalog_expression_root>& selected_rule = rule_prior.rules.keys[sample_uniform(available_rules)]; if (!init(*tree, selected_rule)) exit(EXIT_FAILURE); unsigned int prev = 0; for (unsigned int k = 0; k < selected_rule.nt.length; k++) { /* pick a random split point from {prev + 1, ..., n - K + k} */ unsigned int start, next; if (k + 1 == selected_rule.nt.length) start = sentence.length; else start = prev + 1; const auto& child_nonterminal = G.nonterminals[selected_rule.nt.nonterminals[k] - 1]; if (child_nonterminal.is_preterminal) { array<unsigned int> available_next = array<unsigned int>(8); for (unsigned int i = start; i < sentence.length - selected_rule.nt.length + k + 2; i++) { const auto& rule_prior = child_nonterminal.rule_distribution.h.pi; rule<datalog_expression_root> r = rule<datalog_expression_root>({sentence.tokens + prev, i - prev}); if (rule_prior.probability(r) > 0.0 && !available_next.add(i)) exit(EXIT_FAILURE); } if (available_next.length == 0) { free(*tree); free(tree); tree = NULL; return false; } next = sample_uniform(available_next); } else { next = sample_uniform(sentence.length - selected_rule.nt.length + k - start + 2) + start; } datalog_expression_root child; if (!apply(selected_rule.nt.transformations[k], logical_form, child)) { free(*tree); free(tree); tree = NULL; return false; } if (!initialize_tree(G, tree->children[k], {sentence.tokens + prev, next - prev}, child, selected_rule.nt.nonterminals[k])) { free(child); free(*tree); free(tree); tree = NULL; return false; } free(child); prev = next; } return true; } inline bool can_be_empty(const datalog_expression& exp) { if (exp.type == DATALOG_NON_EMPTY) { return false; } if (exp.type == DATALOG_ANY || exp.type == DATALOG_EMPTY) { return true; } else if (exp.type == DATALOG_CONSTANT) { if (exp.constant.label == DATALOG_LABEL_EMPTY) return true; else if (exp.constant.label != DATALOG_LABEL_WILDCARD) return false; return !exp.constant.is_excluded(DATALOG_LABEL_EMPTY); } else if (exp.type == DATALOG_PREDICATE) { if (exp.pred.function == DATALOG_LABEL_EMPTY) return true; else if (exp.pred.function != DATALOG_LABEL_WILDCARD) return false; return !exp.pred.is_excluded(DATALOG_LABEL_EMPTY); } return false; } /** * Semantic transformation functions and their inverses. */ template<unsigned int FieldCount> inline bool select_any(datalog_expression& dst) { if (FieldCount == 1) { initialize_any(dst); } else { if (!init(dst.tuple, POSITION_EXACT, FieldCount)) return false; for (unsigned int i = 0; i < FieldCount; i++) dst.tuple.elements[i] = &DATALOG_ANY_TREE; dst.tuple.elements.length = FieldCount; DATALOG_ANY_TREE.reference_count += FieldCount; dst.type = DATALOG_TUPLE; dst.reference_count = 1; } return true; } template<unsigned int FieldCount> inline bool delete_any(datalog_expression& dst) { initialize_any(dst); return true; } template<unsigned int FieldCount, bool KeepHead> inline bool select_left(const datalog_expression& src, datalog_expression& dst, array<unsigned int>& src_variable_map, array<unsigned int>& dst_variable_map, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { if (src.type == DATALOG_PREDICATE && FieldCount == 1) { unsigned int head = get_head(src); parent_head = choose_head(parent_head, head); child_head = choose_head(child_head, head); if (KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head != child_head) return false; if (!KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head == child_head) return false; return init(dst, src, KeepHead ? 0 : -1); } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return select_any<FieldCount>(dst); } else if (src.type != DATALOG_TUPLE || (src.tuple.position != POSITION_LEFT && src.tuple.elements.length < FieldCount)) { return false; } else { /* check that the head variable of the child is correct */ for (unsigned int i = 0; i < min(FieldCount, (unsigned int) src.tuple.elements.length); i++) { unsigned int head = get_head(*src.tuple.elements[i]); child_head = choose_head(child_head, head); parent_head = choose_head(parent_head, head); } if (src.tuple.position != POSITION_EXACT && child_head != 1) child_head = DATALOG_LABEL_WILDCARD; for (unsigned int i = FieldCount; i < src.tuple.elements.length; i++) parent_head = choose_head(parent_head, get_head(*src.tuple.elements[i])); if (src.tuple.position != POSITION_EXACT && parent_head != 1) parent_head = DATALOG_LABEL_WILDCARD; if (KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head != child_head) return false; if (!KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head == child_head) return false; /* create the child logical form */ if (FieldCount == 1) { if (src.tuple.elements.length == 0) { dst.type = DATALOG_ANY; dst.reference_count = 1; } else { if (!init(dst, *src.tuple.elements[0], src_variable_map, dst_variable_map)) return false; compress_variable_map(dst_variable_map); apply_variable_map(dst, dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); } } else { if (!init(dst.tuple, POSITION_EXACT, FieldCount)) return false; else if (!init(dst.tuple.elements.data, src.tuple.elements.data, min(FieldCount, (unsigned int) src.tuple.elements.length), src_variable_map, dst_variable_map)) { free(dst.tuple); return false; } for (unsigned int i = src.tuple.elements.length; i < FieldCount; i++) { dst.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } dst.tuple.elements.length = FieldCount; dst.type = DATALOG_TUPLE; dst.reference_count = 1; compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < min(FieldCount, (unsigned int) src.tuple.elements.length); i++) apply_variable_map(*dst.tuple.elements[i], dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); } } return true; } template<unsigned int FieldCount, bool KeepHead> inline bool select_left(const datalog_expression& src, datalog_expression& dst, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; return select_left<FieldCount, KeepHead>(src, dst, src_variable_map, dst_variable_map, parent_head, child_head); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> inline bool delete_left(const datalog_expression& src, datalog_expression& dst, array<unsigned int>& src_variable_map, array<unsigned int>& dst_variable_map, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { if (src.type == DATALOG_PREDICATE && FieldCount == 1) { unsigned int head = get_head(src); parent_head = choose_head(parent_head, head); if (KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head != child_head) return false; if (!KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head == child_head) return false; if (!init(dst.tuple, POSITION_EXACT, 1)) return false; dst.type = DATALOG_TUPLE; } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_any<FieldCount>(dst); } else if (src.type != DATALOG_TUPLE || (src.tuple.position != POSITION_LEFT && src.tuple.elements.length < FieldCount)) { return false; } else { /* check that the head variable of the child is correct */ for (unsigned int i = FieldCount; i < src.tuple.elements.length; i++) { unsigned int head = get_head(*src.tuple.elements[i]); child_head = choose_head(child_head, head); parent_head = choose_head(parent_head, head); } if (src.tuple.position != POSITION_EXACT && child_head != 1) child_head = DATALOG_LABEL_WILDCARD; for (unsigned int i = 0; i < min(FieldCount, (unsigned int) src.tuple.elements.length); i++) parent_head = choose_head(parent_head, get_head(*src.tuple.elements[i])); if (src.tuple.position != POSITION_EXACT && parent_head != 1) parent_head = DATALOG_LABEL_WILDCARD; if (KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head != child_head) return false; if (!KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head == child_head) return false; if (FieldCount >= src.tuple.elements.length) { if (src.tuple.position == POSITION_EXACT) { if (!init(dst.tuple, POSITION_EXACT, 1)) return false; dst.type = DATALOG_TUPLE; } else { dst.type = DATALOG_ANY; } } else if (src.tuple.elements.length - FieldCount == 1 && src.tuple.position == POSITION_EXACT) { if (!init(dst, *src.tuple.elements[FieldCount], src_variable_map, dst_variable_map)) return false; /* TODO: i think we only need to compress and apply the variable map if MergeVariables = true */ compress_variable_map(dst_variable_map); apply_variable_map(dst, dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); return true; } else { if (!init(dst.tuple, src.tuple.position, src.tuple.elements.data + FieldCount, src.tuple.elements.length - FieldCount, src_variable_map, dst_variable_map)) return false; dst.type = DATALOG_TUPLE; /* TODO: i think we only need to compress and apply the variable map if MergeVariables = true */ compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < dst.tuple.elements.length; i++) apply_variable_map(*dst.tuple.elements[i], dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); } } dst.reference_count = 1; return true; } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> inline bool delete_left(const datalog_expression& src, datalog_expression& dst, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; return delete_left<FieldCount, KeepHead, MergeVariables>(src, dst, src_variable_map, dst_variable_map, parent_head, child_head); } template<unsigned int FieldCount, bool KeepHead> inline bool select_right(const datalog_expression& src, datalog_expression& dst, array<unsigned int>& src_variable_map, array<unsigned int>& dst_variable_map, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { if (src.type == DATALOG_PREDICATE && FieldCount == 1) { return init(dst, src); } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return select_any<FieldCount>(dst); } else if (src.type != DATALOG_TUPLE || (src.tuple.position != POSITION_RIGHT && src.tuple.elements.length < FieldCount)) { return false; } else { /* check that the head variable of the child is correct */ for (unsigned int i = max(FieldCount, (unsigned int) src.tuple.elements.length) - FieldCount; i < src.tuple.elements.length; i++) { unsigned int head = get_head(*src.tuple.elements[i]); child_head = choose_head(child_head, head); parent_head = choose_head(parent_head, head); } if (src.tuple.position != POSITION_EXACT && child_head != 1) child_head = DATALOG_LABEL_WILDCARD; for (unsigned int i = 0; i < src.tuple.elements.length - FieldCount; i++) parent_head = choose_head(parent_head, get_head(*src.tuple.elements[i])); if (src.tuple.position != POSITION_EXACT && parent_head != 1) parent_head = DATALOG_LABEL_WILDCARD; if (KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head != child_head) return false; if (!KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head == child_head) return false; if (FieldCount == 1) { if (src.tuple.elements.length == 0) { dst.type = DATALOG_ANY; dst.reference_count = 1; } else { if (!init(dst, *src.tuple.elements.last(), src_variable_map, dst_variable_map)) return false; compress_variable_map(dst_variable_map); apply_variable_map(dst, dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); } } else { if (!init(dst.tuple, POSITION_EXACT, FieldCount)) return false; if (src.tuple.elements.length < FieldCount) { if (!init(dst.tuple.elements.data, src.tuple.elements.data, src.tuple.elements.length, src_variable_map, dst_variable_map)) { free(dst.tuple); return false; } for (unsigned int i = 0; i < FieldCount - src.tuple.elements.length; i++) dst.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += FieldCount - src.tuple.elements.length; } else { if (!init(dst.tuple.elements.data, src.tuple.elements.data + src.tuple.elements.length - FieldCount, FieldCount, src_variable_map, dst_variable_map)) { free(dst.tuple); return false; } } dst.tuple.elements.length = FieldCount; dst.type = DATALOG_TUPLE; dst.reference_count = 1; compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < dst.tuple.elements.length; i++) apply_variable_map(*dst.tuple.elements[i], dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); } } return true; } template<unsigned int FieldCount, bool KeepHead> inline bool select_right(const datalog_expression& src, datalog_expression& dst, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; return select_right<FieldCount, KeepHead>(src, dst, src_variable_map, dst_variable_map, parent_head, child_head); } template<unsigned int FieldCount, bool KeepHead> inline bool delete_right(const datalog_expression& src, datalog_expression& dst, array<unsigned int>& src_variable_map, array<unsigned int>& dst_variable_map, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { if (src.type == DATALOG_PREDICATE && FieldCount == 1) { unsigned int head = get_head(src); parent_head = choose_head(parent_head, head); if (KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head != child_head) return false; if (!KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head == child_head) return false; if (!init(dst.tuple, POSITION_EXACT, 1)) return false; dst.type = DATALOG_TUPLE; } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_any<FieldCount>(dst); } else if (src.type != DATALOG_TUPLE || (src.tuple.position != POSITION_RIGHT && src.tuple.elements.length < FieldCount)) { return false; } else { /* check that the head variable of the child is correct */ for (unsigned int i = 0; i < max(FieldCount, (unsigned int) src.tuple.elements.length) - FieldCount; i++) { unsigned int head = get_head(*src.tuple.elements[i]); child_head = choose_head(child_head, head); parent_head = choose_head(parent_head, head); } if (src.tuple.position != POSITION_EXACT && child_head != 1) child_head = DATALOG_LABEL_WILDCARD; for (unsigned int i = max(FieldCount, (unsigned int) src.tuple.elements.length) - FieldCount; i < src.tuple.elements.length; i++) parent_head = choose_head(parent_head, get_head(*src.tuple.elements[i])); if (src.tuple.position != POSITION_EXACT && parent_head != 1) parent_head = DATALOG_LABEL_WILDCARD; if (KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head != child_head) return false; if (!KeepHead && parent_head != DATALOG_LABEL_WILDCARD && child_head != DATALOG_LABEL_WILDCARD && parent_head == child_head) return false; if (FieldCount >= src.tuple.elements.length) { if (src.tuple.position == POSITION_EXACT) { if (!init(dst.tuple, POSITION_EXACT, 1)) return false; dst.type = DATALOG_TUPLE; } else { dst.type = DATALOG_ANY; } } else if (src.tuple.elements.length - FieldCount == 1 && src.tuple.position == POSITION_EXACT) { if (!init(dst, *src.tuple.elements[0], src_variable_map, dst_variable_map)) return false; compress_variable_map(dst_variable_map); apply_variable_map(dst, dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); return true; } else { if (!init(dst.tuple, src.tuple.position, src.tuple.elements.data, src.tuple.elements.length - FieldCount, src_variable_map, dst_variable_map)) return false; dst.type = DATALOG_TUPLE; compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < dst.tuple.elements.length; i++) apply_variable_map(*dst.tuple.elements[i], dst_variable_map); apply_variable_map(src_variable_map, dst_variable_map); } } dst.reference_count = 1; return true; } template<unsigned int FieldCount, bool KeepHead> inline bool delete_right(const datalog_expression& src, datalog_expression& dst, unsigned int parent_head = DATALOG_LABEL_EMPTY, unsigned int child_head = DATALOG_LABEL_EMPTY) { array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; return delete_right<FieldCount, KeepHead>(src, dst, src_variable_map, dst_variable_map, parent_head, child_head); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool select_left_keep_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_FUNCTION) { if (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate) return false; } else if (src.type != DATALOG_ANY && src.type != DATALOG_NON_EMPTY) return false; if (!init(dst.func)) return false; dst.func.arg = (datalog_expression*) malloc(sizeof(datalog_expression)); if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { if (dst.func.arg == NULL || !select_any<FieldCount>(*dst.func.arg)) { if (dst.func.arg != NULL) free(dst.func.arg); return false; } for (unsigned int i = 0; i < array_length(dst.func.vars); i++) dst.func.vars[i] = 0; dst.func.function = DATALOG_LABEL_WILDCARD; } else { array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; unsigned int head = DATALOG_LABEL_EMPTY; for (unsigned int i = 0; i < array_length(dst.func.vars); i++) { if (src.func.vars[i] == 0) { dst.func.vars[i] = 0; } else { if (!KeepHead && src.func.vars[i] == 1) { free(dst.func.arg); return false; } dst.func.vars[i] = src.func.vars[i] - (KeepHead ? 0 : 1); head = choose_head(head, src.func.vars[i]); src_variable_map[src.func.vars[i]] = dst.func.vars[i]; dst_variable_map[dst.func.vars[i]] = 1; } } if (dst.func.arg == NULL || !select_left<FieldCount, KeepHead>( *src.func.arg, *dst.func.arg, src_variable_map, dst_variable_map, head, head)) { if (dst.func.arg != NULL) free(dst.func.arg); return false; } dst.func.function = src.func.function; if (src.func.excluded_count > 0 && !init_excluded(dst.func.excluded, src.func.excluded, src.func.excluded_count)) { free(*dst.func.arg); free(dst.func.arg); return false; } dst.func.excluded_count = src.func.excluded_count; } dst.type = DATALOG_FUNCTION; dst.reference_count = 1; return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool delete_left_keep_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_FUNCTION) { if (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate) return false; } else if (src.type != DATALOG_ANY && src.type != DATALOG_NON_EMPTY && !(src.type == DATALOG_TUPLE && src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT)) return false; if (!init(dst.func)) return false; dst.func.arg = (datalog_expression*) malloc(sizeof(datalog_expression)); if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY || (src.type == DATALOG_TUPLE && src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT)) { if (dst.func.arg == NULL || !delete_any<FieldCount>(*dst.func.arg)) { if (dst.func.arg != NULL) free(dst.func.arg); return false; } for (unsigned int i = 0; i < array_length(dst.func.vars); i++) dst.func.vars[i] = 0; dst.func.function = DATALOG_LABEL_WILDCARD; } else { array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; unsigned int head = DATALOG_LABEL_EMPTY; for (unsigned int i = 0; i < array_length(dst.func.vars); i++) { if (src.func.vars[i] == 0) { dst.func.vars[i] = 0; } else { if (!KeepHead && src.func.vars[i] == 1) { free(dst.func.arg); return false; } dst.func.vars[i] = src.func.vars[i] - (KeepHead ? 0 : 1); head = choose_head(head, src.func.vars[i]); src_variable_map[src.func.vars[i]] = dst.func.vars[i]; dst_variable_map[dst.func.vars[i]] = 1; } } if (dst.func.arg == NULL || !delete_left<FieldCount, KeepHead>( *src.func.arg, *dst.func.arg, src_variable_map, dst_variable_map, head, head)) { if (dst.func.arg != NULL) free(dst.func.arg); return false; } dst.func.function = src.func.function; if (src.func.excluded_count > 0 && !init_excluded(dst.func.excluded, src.func.excluded, src.func.excluded_count)) { free(*dst.func.arg); free(dst.func.arg); return false; } dst.func.excluded_count = src.func.excluded_count; } dst.type = DATALOG_FUNCTION; dst.reference_count = 1; return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool delete_right_keep_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_FUNCTION) { if (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate) return false; } else if (src.type != DATALOG_ANY && src.type != DATALOG_NON_EMPTY) return false; if (!init(dst.func)) return false; dst.func.arg = (datalog_expression*) malloc(sizeof(datalog_expression)); if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { if (dst.func.arg == NULL || !delete_any<FieldCount>(*dst.func.arg)) { if (dst.func.arg != NULL) free(dst.func.arg); return false; } for (unsigned int i = 0; i < array_length(dst.func.vars); i++) dst.func.vars[i] = 0; dst.func.function = DATALOG_LABEL_WILDCARD; } else { array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; unsigned int head = DATALOG_LABEL_EMPTY; for (unsigned int i = 0; i < array_length(dst.func.vars); i++) { if (src.func.vars[i] == 0) { dst.func.vars[i] = 0; } else { if (!KeepHead && src.func.vars[i] == 1) { free(dst.func.arg); return false; } dst.func.vars[i] = src.func.vars[i] - (KeepHead ? 0 : 1); head = choose_head(head, src.func.vars[i]); src_variable_map[src.func.vars[i]] = dst.func.vars[i]; dst_variable_map[dst.func.vars[i]] = 1; } } if (dst.func.arg == NULL || !delete_right<FieldCount, KeepHead>( *src.func.arg, *dst.func.arg, src_variable_map, dst_variable_map, head, head)) { if (dst.func.arg != NULL) free(dst.func.arg); return false; } dst.func.function = src.func.function; if (src.func.excluded_count > 0 && !init_excluded(dst.func.excluded, src.func.excluded, src.func.excluded_count)) { free(*dst.func.arg); free(dst.func.arg); return false; } dst.func.excluded_count = src.func.excluded_count; } dst.type = DATALOG_FUNCTION; dst.reference_count = 1; return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool delete_left_answer_keep_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_left_keep_function<FieldCount, Predicate, KeepHead>(DATALOG_ANY_TREE, dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return delete_left_keep_function<FieldCount, Predicate, KeepHead>(*src.func.arg, dst); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool select_left_delete_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return select_any<FieldCount>(dst); } else if (src.type == DATALOG_TUPLE && src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT) { dst.type = DATALOG_ANY; dst.reference_count = 1; return true; } else if (src.type != DATALOG_FUNCTION || (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate)) return false; unsigned int parent_head = DATALOG_LABEL_EMPTY; for (unsigned int i = 0; i < array_length(src.func.vars); i++) if (src.func.vars[i] != 0) parent_head = choose_head(parent_head, src.func.vars[i]); return select_left<FieldCount, KeepHead>(*src.func.arg, dst, parent_head); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool select_right_delete_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return select_any<FieldCount>(dst); } else if (src.type != DATALOG_FUNCTION || (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate)) return false; unsigned int parent_head = DATALOG_LABEL_EMPTY; for (unsigned int i = 0; i < array_length(src.func.vars); i++) if (src.func.vars[i] != 0) parent_head = choose_head(parent_head, src.func.vars[i]); return select_right<FieldCount, KeepHead>(*src.func.arg, dst, parent_head); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool delete_left_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_any<FieldCount>(dst); } else if (src.type != DATALOG_FUNCTION || (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate)) return false; unsigned int parent_head = DATALOG_LABEL_EMPTY; for (unsigned int i = 0; i < array_length(src.func.vars); i++) if (src.func.vars[i] != 0) parent_head = choose_head(parent_head, src.func.vars[i]); return delete_left<FieldCount, KeepHead>(*src.func.arg, dst, parent_head); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> bool select_left_delete_function_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return select_left_delete_function<FieldCount, Predicate, KeepHead>(DATALOG_ANY_TREE, dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return select_left_delete_function<FieldCount, Predicate, KeepHead>(*src.func.arg, dst); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> bool delete_left_function_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_left_function<FieldCount, Predicate, KeepHead>(DATALOG_ANY_TREE, dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return delete_left_function<FieldCount, Predicate, KeepHead>(*src.func.arg, dst); } template<unsigned int FieldCount, bool KeepHead> bool select_left_delete_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return select_any<FieldCount>(dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return select_left<FieldCount, KeepHead>(*src.func.arg, dst); } template<unsigned int FieldCount, bool KeepHead> bool select_right_delete_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return select_any<FieldCount>(dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return select_right<FieldCount, KeepHead>(*src.func.arg, dst); } template<unsigned int FieldCount, bool KeepHead> bool delete_left_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_any<FieldCount>(dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return delete_left<FieldCount, KeepHead>(*src.func.arg, dst); } template<unsigned int FieldCount, bool KeepHead> bool delete_right_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_any<FieldCount>(dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return delete_right<FieldCount, KeepHead>(*src.func.arg, dst); } inline bool delete_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { initialize_any(dst); return true; } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return init(dst, *src.func.arg); } template<unsigned int Predicate, bool KeepHead> inline bool select_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_FUNCTION) { if (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate) return false; } else if (src.type != DATALOG_ANY && src.type != DATALOG_NON_EMPTY) return false; if (!init(dst.func)) return false; dst.func.arg = (datalog_expression*) malloc(sizeof(datalog_expression)); if (dst.func.arg == NULL || !init(dst.func.arg->tuple, POSITION_EXACT, 1)) { if (dst.func.arg != NULL) free(dst.func.arg); return false; } dst.func.arg->type = DATALOG_TUPLE; dst.func.arg->reference_count = 1; if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { for (unsigned int i = 0; i < array_length(dst.func.vars); i++) dst.func.vars[i] = 0; dst.func.function = DATALOG_LABEL_WILDCARD; } else { unsigned int src_head = DATALOG_LABEL_EMPTY; for (unsigned int i = 0; i < array_length(dst.func.vars); i++) { if (src.func.vars[i] == 0) { dst.func.vars[i] = 0; } else if (src.func.vars[i] == 1 && !KeepHead) { free(*dst.func.arg); free(dst.func.arg); return false; } else { src_head = choose_head(src_head, src.func.vars[i]); dst.func.vars[i] = src.func.vars[i] - (KeepHead ? 0 : 1); } } if (KeepHead && src_head != 1 && src_head != DATALOG_LABEL_EMPTY) { free(*dst.func.arg); free(dst.func.arg); return false; } dst.func.function = src.func.function; if (src.func.excluded_count > 0 && !init_excluded(dst.func.excluded, src.func.excluded, src.func.excluded_count)) { free(*dst.func.arg); free(dst.func.arg); return false; } dst.func.excluded_count = src.func.excluded_count; } dst.type = DATALOG_FUNCTION; dst.reference_count = 1; return true; } template<unsigned int Predicate, bool KeepHead> inline bool delete_function(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { initialize_any(dst); return true; } else if (src.type == DATALOG_TUPLE && src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT) { return init(dst, src); } else if (src.type != DATALOG_FUNCTION || (Predicate != DATALOG_LABEL_WILDCARD && src.func.function != DATALOG_LABEL_WILDCARD && src.func.function != Predicate)) return false; unsigned int child_head = get_head(*src.func.arg); if (KeepHead && child_head != DATALOG_LABEL_WILDCARD && child_head != 1) return false; if (!KeepHead && child_head != DATALOG_LABEL_WILDCARD && child_head == 1) return false; array<unsigned int> src_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(src_variable_map.data, 0, sizeof(unsigned int) * src_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); src_variable_map[KeepHead ? 1 : 2] = 1; dst_variable_map[1] = 1; if (!init(dst, *src.func.arg, src_variable_map, dst_variable_map)) return false; if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); apply_variable_map(dst, dst_variable_map); return true; } template<unsigned int Predicate, bool KeepHead> bool delete_function_answer(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return delete_function<Predicate, KeepHead>(DATALOG_ANY_TREE, dst); } else if (src.type != DATALOG_FUNCTION || src.func.function != PREDICATE_ANSWER) return false; return delete_function<Predicate, KeepHead>(*src.func.arg, dst); } template<unsigned int FieldIndex, bool OtherArgsEmpty> inline bool select_arg(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { initialize_any(dst); return true; } else if (src.type == DATALOG_TUPLE && src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT) { initialize_any(dst); return true; } else if (src.type != DATALOG_PREDICATE || FieldIndex >= array_length(src.pred.args)) return false; if (OtherArgsEmpty) { for (unsigned int i = 0; i < array_length(src.pred.args); i++) { if (i == FieldIndex) continue; if (src.pred.args[i] != NULL && !can_be_empty(*src.pred.args[i])) return false; } } if (src.pred.args[FieldIndex] == NULL) { dst.type = DATALOG_EMPTY; return true; } return init(dst, *src.pred.args[FieldIndex]); } template<unsigned int FieldIndex> inline bool delete_arg(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY || (src.type == DATALOG_TUPLE && src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT)) { dst.type = DATALOG_PREDICATE; dst.reference_count = 1; dst.pred.function = DATALOG_LABEL_WILDCARD; dst.pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(dst.pred.args); i++) dst.pred.args[i] = &DATALOG_ANY_TREE; dst.pred.args[FieldIndex] = NULL; DATALOG_ANY_TREE.reference_count += (array_length(dst.pred.args) - 1); } else if (src.type != DATALOG_PREDICATE) { return false; } else { if (FieldIndex >= array_length(src.pred.args) || src.pred.args[FieldIndex] == NULL) return false; dst.type = DATALOG_PREDICATE; dst.reference_count = 1; dst.pred.function = src.pred.function; if (src.pred.excluded_count > 0 && !init_excluded(dst.pred.excluded, src.pred.excluded, src.pred.excluded_count)) { return false; } dst.pred.excluded_count = src.pred.excluded_count; for (unsigned int i = 0 ; i < array_length(dst.pred.args); i++) { if (i == FieldIndex) continue; dst.pred.args[i] = src.pred.args[i]; if (src.pred.args[i] != NULL) src.pred.args[i]->reference_count++; } dst.pred.args[FieldIndex] = NULL; } return true; } inline bool delete_args(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { dst.type = DATALOG_PREDICATE; dst.reference_count = 1; dst.pred.function = DATALOG_LABEL_WILDCARD; dst.pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(dst.pred.args); i++) dst.pred.args[i] = NULL; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.position == POSITION_RIGHT || src.tuple.elements.length != 1) return false; else return delete_args(*src.tuple.elements[0], dst); } else if (src.type != DATALOG_PREDICATE) { return false; } else { dst.type = DATALOG_PREDICATE; dst.reference_count = 1; dst.pred.function = src.pred.function; if (src.pred.excluded_count > 0 && !init_excluded(dst.pred.excluded, src.pred.excluded, src.pred.excluded_count)) { return false; } dst.pred.excluded_count = src.pred.excluded_count; for (unsigned int i = 0 ; i < array_length(dst.pred.args); i++) dst.pred.args[i] = NULL; } return true; } template<unsigned int HeadIndex, unsigned int SelectIndex, bool OtherArgsEmpty> inline bool head_arg_select_arg(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { initialize_any(dst); return true; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.elements.length == 0) { if (src.tuple.position == POSITION_EXACT) return false; initialize_any(dst); return true; } else if (src.tuple.elements.length > 1) { return false; } else { return head_arg_select_arg<HeadIndex, SelectIndex, OtherArgsEmpty>(*src.tuple.elements[0], dst); } } else if (src.type != DATALOG_PREDICATE || HeadIndex >= array_length(src.pred.args)) return false; if (src.pred.args[HeadIndex] == NULL || src.pred.args[SelectIndex] == NULL) return false; if (src.pred.args[HeadIndex]->type != DATALOG_ANY && src.pred.args[HeadIndex]->type != DATALOG_NON_EMPTY && (src.pred.args[HeadIndex]->type != DATALOG_VARIABLE || src.pred.args[HeadIndex]->variable != 1)) return false; for (unsigned int i = 0; OtherArgsEmpty && i < array_length(src.pred.args); i++) { if (i == HeadIndex || i == SelectIndex) continue; if (src.pred.args[i] != NULL && !can_be_empty(*src.pred.args[i])) return false; } return select_arg<SelectIndex, false>(src, dst); } template<unsigned int Predicate> inline bool check_predicate(const datalog_expression& src) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return true; } else if (src.type == DATALOG_PREDICATE) { if (src.pred.function == DATALOG_LABEL_WILDCARD) { if (src.pred.is_excluded(Predicate)) return false; } else if (src.pred.function != Predicate) return false; if (src.pred.args[0] == NULL || src.pred.args[1] == NULL) return false; if (src.pred.args[0]->type != DATALOG_ANY && src.pred.args[0]->type != DATALOG_NON_EMPTY && (src.pred.args[0]->type != DATALOG_VARIABLE || src.pred.args[0]->variable != 2)) return false; if (src.pred.args[1]->type != DATALOG_ANY && src.pred.args[1]->type != DATALOG_NON_EMPTY && (src.pred.args[1]->type != DATALOG_VARIABLE || src.pred.args[1]->variable != 1)) return false; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.position == POSITION_RIGHT) return false; else if (src.tuple.elements.length == 0) return src.tuple.position == POSITION_LEFT; return check_predicate<Predicate>(*src.tuple.elements[0]); } else { return false; } return true; } template<unsigned int Predicate> inline bool check_predicate_answer(const datalog_expression& src) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { return true; } else if (src.type == DATALOG_FUNCTION) { if (src.func.function == DATALOG_LABEL_WILDCARD) { if (src.func.is_excluded(PREDICATE_ANSWER)) return false; } else if (src.func.function != PREDICATE_ANSWER) return false; return check_predicate<Predicate>(*src.func.arg); } else { return false; } return true; } template<unsigned int Length> inline bool tuple_length(const datalog_expression& src, datalog_expression& dst) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { if (!init(dst.tuple, POSITION_EXACT, Length)) return false; for (unsigned int i = 0; i < Length; i++) dst.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += Length; dst.tuple.elements.length = Length; dst.type = DATALOG_TUPLE; dst.reference_count = 1; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.elements.length > Length) return false; if (!init(dst.tuple, POSITION_EXACT, Length)) return false; if (src.tuple.position == POSITION_LEFT) { for (unsigned int i = 0; i < src.tuple.elements.length; i++) { dst.tuple.elements[i] = src.tuple.elements[i]; src.tuple.elements[i]->reference_count++; } for (unsigned int i = src.tuple.elements.length; i < Length; i++) dst.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += (Length - src.tuple.elements.length); } else if (src.tuple.position == POSITION_RIGHT) { for (unsigned int i = 0; i < Length - src.tuple.elements.length; i++) dst.tuple.elements[i] = &DATALOG_ANY_TREE; unsigned int offset = Length - src.tuple.elements.length; for (unsigned int i = offset; i < Length; i++) { dst.tuple.elements[i] = src.tuple.elements[i - offset]; src.tuple.elements[i - offset]->reference_count++; } DATALOG_ANY_TREE.reference_count += offset; } else { if (src.tuple.elements.length != Length) { free(dst.tuple); return false; } for (unsigned int i = 0; i < Length; i++) { dst.tuple.elements[i] = src.tuple.elements[i]; src.tuple.elements[i]->reference_count++; } } dst.tuple.elements.length = Length; dst.type = DATALOG_TUPLE; dst.reference_count = 1; } else { return false; } return true; } inline bool flip_predicate(datalog_predicate& pred) { if (pred.args[0] == NULL || pred.args[1] == NULL || (pred.args[0]->type != DATALOG_ANY && pred.args[0]->type != DATALOG_NON_EMPTY && pred.args[0]->type != DATALOG_VARIABLE) || (pred.args[1]->type != DATALOG_ANY && pred.args[1]->type != DATALOG_NON_EMPTY && pred.args[1]->type != DATALOG_VARIABLE)) return false; for (unsigned int i = 2; i < array_length(pred.args); i++) { if (pred.args[i] == NULL) continue; if (!can_be_empty(*pred.args[i])) return false; free(*pred.args[i]); if (pred.args[i]->reference_count == 0) free(pred.args[i]); pred.args[i] = NULL; } swap(pred.args[0], pred.args[1]); return true; } template<bool InsideTuple = false> inline bool flip_predicate(datalog_expression& exp) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { if (InsideTuple) { exp.type = DATALOG_PREDICATE; exp.reference_count = 1; } else { if (!init_tuple(exp, POSITION_LEFT, 1) || !new_expression(exp.tuple.elements[0])) return false; exp.tuple.elements[0]->type = DATALOG_PREDICATE; exp.tuple.elements[0]->reference_count = 1; exp.tuple.elements.length = 1; } datalog_predicate& pred = InsideTuple ? exp.pred : exp.tuple.elements[0]->pred; pred.function = DATALOG_LABEL_WILDCARD; pred.excluded_count = 0; pred.args[0] = &DATALOG_ANY_TREE; pred.args[1] = &DATALOG_ANY_TREE; for (unsigned int i = 2; i < array_length(pred.args); i++) pred.args[i] = NULL; DATALOG_ANY_TREE.reference_count += 2; return true; } else if (exp.type == DATALOG_TUPLE) { if (exp.tuple.position == POSITION_RIGHT) { return false; } else if (exp.tuple.elements.length == 0) { if (exp.tuple.position == POSITION_EXACT) return false; else if (!exp.tuple.elements.ensure_capacity(1) || !new_expression(exp.tuple.elements[0])) exit(EXIT_FAILURE); exp.tuple.elements[0]->type = DATALOG_PREDICATE; exp.tuple.elements[0]->reference_count = 1; exp.tuple.elements.length = 1; datalog_predicate& pred = exp.tuple.elements[0]->pred; pred.function = DATALOG_LABEL_WILDCARD; pred.excluded_count = 0; pred.args[0] = &DATALOG_ANY_TREE; pred.args[1] = &DATALOG_ANY_TREE; for (unsigned int i = 2; i < array_length(pred.args); i++) pred.args[i] = NULL; DATALOG_ANY_TREE.reference_count += 2; return true; } else { datalog_expression* arg; if (exp.tuple.elements[0]->reference_count == 1) { arg = exp.tuple.elements[0]; } else { if (!init(arg, *exp.tuple.elements[0])) exit(EXIT_FAILURE); free(*exp.tuple.elements[0]); exp.tuple.elements[0] = arg; } return flip_predicate<true>(*arg); } } else if (exp.type == DATALOG_PREDICATE) { return flip_predicate(exp.pred); } else { return false; } } bool apply(datalog_expression_root::function function, const datalog_expression_root& src, datalog_expression_root& dst) { /* first apply the syntactic features */ if (function.type == datalog_expression_root::FUNCTION_NULL || function.type == datalog_expression_root::FUNCTION_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_FUNCTION_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG2_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG3_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_ARG1_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_ARG2_FEATURES) { dst.index = NUMBER_ALL; dst.concord = NUMBER_NONE; dst.inf = INFLECTION_NONE; } else if (function.type == datalog_expression_root::FUNCTION_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_RIGHT2_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_SINGULAR || function.type == datalog_expression_root::FUNCTION_DELETE_ARG1_SINGULAR) { dst.index = NUMBER_SINGULAR; dst.concord = src.concord; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_PLURAL || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_ARG1_PLURAL) { dst.index = NUMBER_PLURAL; dst.concord = src.concord; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_UNCOUNTABLE) { dst.index = NUMBER_UNCOUNTABLE; dst.concord = src.concord; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_DELETE_ARGS_CONCORD_SINGULAR) { dst.index = src.index; dst.concord = NUMBER_SINGULAR; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL) { dst.index = src.index; dst.concord = NUMBER_PLURAL; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_UNCOUNTABLE) { dst.index = src.index; dst.concord = NUMBER_UNCOUNTABLE; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_NON_SINGULAR) { dst.index = src.index; dst.concord = NUMBER_NON_SINGULAR; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL) { dst.index = src.index; dst.concord = NUMBER_NON_PLURAL; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR) { if (src.index != NUMBER_SINGULAR) return false; dst.index = src.index; dst.concord = NUMBER_NON_PLURAL; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_ALL) { if (src.index == NUMBER_SINGULAR) return false; dst.index = src.index; dst.concord = NUMBER_ALL; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR) { if (src.concord != NUMBER_SINGULAR && src.concord != NUMBER_NON_PLURAL && src.concord != NUMBER_ALL && src.concord != NUMBER_ANY) return false; dst.index = src.index; dst.concord = NUMBER_SINGULAR; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_CONCORD_PLURAL) { if (src.concord != NUMBER_PLURAL && src.concord != NUMBER_NON_SINGULAR && src.concord != NUMBER_ALL && src.concord != NUMBER_ANY) return false; dst.index = src.index; dst.concord = NUMBER_PLURAL; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_CONCORD_UNCOUNTABLE) { if (src.concord != NUMBER_UNCOUNTABLE && src.concord != NUMBER_NON_SINGULAR && src.concord != NUMBER_NON_PLURAL && src.concord != NUMBER_ALL && src.concord != NUMBER_ANY) return false; dst.index = src.index; dst.concord = NUMBER_UNCOUNTABLE; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_SINGULAR) { if (src.index != NUMBER_SINGULAR && src.index != NUMBER_NON_PLURAL && src.index != NUMBER_ANY) return false; dst.index = NUMBER_SINGULAR; dst.concord = src.concord; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_ARGS_KEEP_PLURAL) { if (src.index != NUMBER_PLURAL && src.index != NUMBER_NON_SINGULAR && src.index != NUMBER_ANY) return false; dst.index = NUMBER_PLURAL; dst.concord = src.concord; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_UNCOUNTABLE) { if (src.index != NUMBER_UNCOUNTABLE && src.index != NUMBER_NON_SINGULAR && src.index != NUMBER_NON_PLURAL && src.index != NUMBER_ANY) return false; dst.index = NUMBER_UNCOUNTABLE; dst.concord = src.concord; dst.inf = src.inf; } else if (function.type == datalog_expression_root::FUNCTION_PRESENT_PARTICIPLE) { dst.index = src.index; dst.concord = src.concord; dst.inf = INFLECTION_PRESENT_PARTICIPLE; } else if (function.type == datalog_expression_root::FUNCTION_PAST_PARTICIPLE || function.type == datalog_expression_root::FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE) { dst.index = src.index; dst.concord = src.concord; dst.inf = INFLECTION_PAST_PARTICIPLE; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_PRESENT_PARTICIPLE) { if (src.inf != INFLECTION_PRESENT_PARTICIPLE && src.inf != INFLECTION_ANY && src.inf != INFLECTION_NONE) return false; dst.index = src.index; dst.concord = src.concord; dst.inf = INFLECTION_PRESENT_PARTICIPLE; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_PAST_PARTICIPLE || function.type == datalog_expression_root::FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE) { if (src.inf != INFLECTION_PAST_PARTICIPLE && src.inf != INFLECTION_ANY && src.inf != INFLECTION_NONE) return false; dst.index = src.index; dst.concord = src.concord; dst.inf = INFLECTION_PAST_PARTICIPLE; } else if (function.type == datalog_expression_root::FUNCTION_INFINITIVE || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_INFINITIVE) { dst.index = src.index; dst.concord = src.concord; dst.inf = INFLECTION_INFINITIVE; } else if (function.type == datalog_expression_root::FUNCTION_IDENTITY_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_COORD || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_COORD) { if (src.concord == NUMBER_NONE || (src.index == NUMBER_SINGULAR && src.concord == NUMBER_PLURAL)) return false; dst.concord = src.concord; dst.index = src.concord; dst.inf = src.inf; } else { dst.index = src.index; dst.concord = src.concord; dst.inf = src.inf; } dst.root.reference_count = 1; switch (function.type) { case datalog_expression_root::FUNCTION_IDENTITY: case datalog_expression_root::FUNCTION_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SINGULAR: case datalog_expression_root::FUNCTION_PLURAL: case datalog_expression_root::FUNCTION_UNCOUNTABLE: case datalog_expression_root::FUNCTION_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_CONCORD_UNCOUNTABLE: case datalog_expression_root::FUNCTION_CONCORD_NON_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL: case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_ALL: case datalog_expression_root::FUNCTION_KEEP_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_KEEP_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_KEEP_CONCORD_UNCOUNTABLE: case datalog_expression_root::FUNCTION_KEEP_SINGULAR: case datalog_expression_root::FUNCTION_KEEP_PLURAL: case datalog_expression_root::FUNCTION_KEEP_UNCOUNTABLE: case datalog_expression_root::FUNCTION_PRESENT_PARTICIPLE: case datalog_expression_root::FUNCTION_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_KEEP_PRESENT_PARTICIPLE: case datalog_expression_root::FUNCTION_KEEP_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_INFINITIVE: case datalog_expression_root::FUNCTION_IDENTITY_COORD: return init(dst.root, src.root); case datalog_expression_root::FUNCTION_NULL: case datalog_expression_root::FUNCTION_KEEP_FEATURES: dst.root.type = DATALOG_EMPTY; return true; case datalog_expression_root::FUNCTION_SELECT_LEFT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_LEFT_COORD: case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT_COORD: return select_left<1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_COORD: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR: return select_left<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DISJOINT: return select_left<3, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT4_DISJOINT: return select_left<4, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT5_DISJOINT: return select_left<5, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT6_DISJOINT: return select_left<6, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT7_DISJOINT: return select_left<7, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD: return select_left<1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION_DISJOINT: return select_left_keep_function<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION_DISJOINT: return select_left_keep_function<2, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_KEEP_FUNCTION: return select_left_keep_function<3, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES: return select_left_delete_function<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER: return select_left_delete_answer<1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_ANSWER: return select_left_delete_answer<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER_DISJOINT: return select_left_delete_answer<3, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT5_DELETE_ANSWER_DISJOINT: return select_left_delete_answer<5, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER_HEAD: return select_left_delete_answer<1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_COUNT_ANSWER: return select_left_delete_function_answer<1, PREDICATE_COUNT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_COUNT_ANSWER: return select_left_delete_function_answer<2, PREDICATE_COUNT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_COUNT_ANSWER: return select_left_delete_function_answer<3, PREDICATE_COUNT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_ANSWER: return select_left_delete_function_answer<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FUNCTION_ANSWER: return select_left_delete_function_answer<2, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_FUNCTION_ANSWER: return select_left_delete_function_answer<3, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES: return select_left_delete_function<1, PREDICATE_NOT, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT: return select_right<1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT2: case datalog_expression_root::FUNCTION_SELECT_RIGHT2_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DISJOINT: return select_right<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT3_DISJOINT: return select_right<3, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT4_DISJOINT: return select_right<4, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT5_DISJOINT: return select_right<5, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT6_DISJOINT: return select_right<6, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT7_DISJOINT: return select_right<7, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_HEAD: return select_right<1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_FUNCTION: return select_right_delete_function<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DELETE_ANSWER: return select_right_delete_answer<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_FEATURES: return select_function<DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD: case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES: return select_function<DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT: case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES: case datalog_expression_root::FUNCTION_DELETE_LEFT_COORD: return delete_left<1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT_COORD: return delete_left<1, true, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2: return delete_left<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_COORD: case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES: return delete_left<2, true, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES: return delete_left<3, true, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT4_DISJOINT: return delete_left<4, true, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT5_DISJOINT: return delete_left<5, true, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT6_DISJOINT: return delete_left<6, true, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT7_DISJOINT: return delete_left<7, true, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES: return delete_left<1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD_FEATURES: return delete_left<2, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_DISJOINT: return delete_left_function<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_DISJOINT: return delete_left_function<2, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_HEAD: return delete_left_function<1, DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_HEAD: return delete_left_function<3, DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_ANSWER: return delete_left_keep_function<1, PREDICATE_ANSWER, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION: return delete_left_keep_function<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION: return delete_left_keep_function<1, DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_NOT: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT: return delete_left_keep_function<1, PREDICATE_NOT, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER: return delete_left_answer<1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER: return delete_left_answer<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_DISJOINT: return delete_left_answer<3, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT5_ANSWER_DISJOINT: return delete_left_answer<5, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD: return delete_left_answer<1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_COUNT_ANSWER: return delete_left_function_answer<1, PREDICATE_COUNT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_COUNT_ANSWER: return delete_left_function_answer<2, PREDICATE_COUNT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_COUNT_ANSWER: return delete_left_function_answer<3, PREDICATE_COUNT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_ANSWER: return delete_left_function_answer<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_ANSWER: return delete_left_function_answer<2, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_ANSWER: return delete_left_function_answer<3, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_KEEP_FUNCTION: return delete_left_answer_keep_function<1, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD_KEEP_FUNCTION: return delete_left_answer_keep_function<1, DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_KEEP_FUNCTION: return delete_left_answer_keep_function<2, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_HEAD_KEEP_FUNCTION: return delete_left_answer_keep_function<2, DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_KEEP_FUNCTION: return delete_left_answer_keep_function<3, DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_HEAD_KEEP_FUNCTION: return delete_left_answer_keep_function<3, DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT: return delete_right<1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT2: case datalog_expression_root::FUNCTION_DELETE_RIGHT2_DISJOINT: return delete_right<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT3_DISJOINT: return delete_right<3, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT4_DISJOINT: return delete_right<4, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT5_DISJOINT: return delete_right<5, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT6_DISJOINT: return delete_right<6, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT7_DISJOINT: return delete_right<7, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD: return delete_right<1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD_KEEP_FUNCTION: return delete_right_keep_function<1, DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT2_ANSWER: return delete_right_answer<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_COUNT: return delete_function<PREDICATE_COUNT, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD: case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL: return delete_function<PREDICATE_COUNT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_COUNT_ANSWER: return delete_function_answer<PREDICATE_COUNT, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_NOT: case datalog_expression_root::FUNCTION_DELETE_NOT_FEATURES: case datalog_expression_root::FUNCTION_DELETE_NOT_INFINITIVE: case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_PLURAL: return delete_function<PREDICATE_NOT,true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES: return delete_left_function<1, PREDICATE_NOT, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_FUNCTION_FEATURES: return delete_function<DATALOG_LABEL_WILDCARD, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_FUNCTION_HEAD: return delete_function<DATALOG_LABEL_WILDCARD, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_ANSWER: return delete_answer(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_ANSWER_HAS_LOC: if (!has_predicate<PREDICATE_LOC>(src.root)) return false; return delete_answer(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_ARG1: case datalog_expression_root::FUNCTION_SELECT_ARG1_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_ARG1_PLURAL: case datalog_expression_root::FUNCTION_SELECT_ARG1_DELETE_FEATURES: return select_arg<0, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES: return select_arg<0, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_ARG2: case datalog_expression_root::FUNCTION_SELECT_ARG2_DELETE_FEATURES: return select_arg<1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES: return select_arg<1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_ARG3: case datalog_expression_root::FUNCTION_SELECT_ARG3_DELETE_FEATURES: return select_arg<2, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES: return select_arg<2, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_ARG1: case datalog_expression_root::FUNCTION_DELETE_ARG1_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_ARG1_PLURAL: case datalog_expression_root::FUNCTION_DELETE_ARG1_FEATURES: return delete_arg<0>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_ARG2: case datalog_expression_root::FUNCTION_DELETE_ARG2_FEATURES: return delete_arg<1>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_ARG3: return delete_arg<2>(src.root, dst.root); case datalog_expression_root::FUNCTION_DELETE_ARGS: case datalog_expression_root::FUNCTION_DELETE_ARGS_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_ARGS_KEEP_PLURAL: return delete_args(src.root, dst.root); case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2: return head_arg_select_arg<0, 1, false>(src.root, dst.root); case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2_ONLY: return head_arg_select_arg<0, 1, true>(src.root, dst.root); case datalog_expression_root::FUNCTION_EMPTY_TUPLE: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY || src.root.type == DATALOG_TUPLE || src.root.type == DATALOG_PREDICATE || src.root.type == DATALOG_FUNCTION) { if (!init(dst.root.tuple, POSITION_EXACT, 1)) return false; dst.root.type = DATALOG_TUPLE; dst.root.reference_count = 1; } else return false; return true; case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY: case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY || src.root.type == DATALOG_EMPTY || (src.root.type == DATALOG_TUPLE && src.root.tuple.elements.length == 0)) { if (!init(dst.root.tuple, POSITION_EXACT, 1)) return false; dst.root.type = DATALOG_TUPLE; dst.root.reference_count = 1; } else return false; return true; case datalog_expression_root::FUNCTION_KEEP_NULL: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY || src.root.type == DATALOG_EMPTY) { dst.root.type = DATALOG_EMPTY; dst.root.reference_count = 1; } else return false; return true; case datalog_expression_root::FUNCTION_EMPTY_ARG2: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY) { dst.root.pred.function = DATALOG_LABEL_WILDCARD; dst.root.pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(dst.root.pred.args); i++) if (i != 1) dst.root.pred.args[i] = &DATALOG_ANY_TREE; dst.root.pred.args[1] = NULL; DATALOG_ANY_TREE.reference_count += array_length(dst.root.pred.args) - 1; } else if (src.root.type == DATALOG_PREDICATE) { if (src.root.pred.args[1] != NULL && !can_be_empty(*src.root.pred.args[1])) return false; if (!init(dst.root.pred, src.root.pred)) return false; if (dst.root.pred.args[1] != NULL) { free(*dst.root.pred.args[1]); if (dst.root.pred.args[1]->reference_count == 0) free(dst.root.pred.args[1]); dst.root.pred.args[1] = NULL; } } else return false; dst.root.type = DATALOG_PREDICATE; dst.root.reference_count = 1; return true; case datalog_expression_root::FUNCTION_EMPTY_ARGS: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY) { dst.root.pred.function = DATALOG_LABEL_WILDCARD; dst.root.pred.excluded_count = 0; } else if (src.root.type == DATALOG_PREDICATE) { for (unsigned int i = 0; i < array_length(src.root.pred.args); i++) { if (src.root.pred.args[i] != NULL && !can_be_empty(*src.root.pred.args[i])) return false; } dst.root.pred.function = src.root.pred.function; if (src.root.pred.excluded_count > 0 && !init_excluded(dst.root.pred.excluded, src.root.pred.excluded, src.root.pred.excluded_count)) return false; dst.root.pred.excluded_count = src.root.pred.excluded_count; } else return false; for (unsigned int i = 0; i < array_length(dst.root.pred.args); i++) dst.root.pred.args[i] = NULL; dst.root.type = DATALOG_PREDICATE; dst.root.reference_count = 1; return dst.root.pred.function != DATALOG_LABEL_WILDCARD || dst.root.pred.exclude(&DATALOG_LABEL_EMPTY, 1); case datalog_expression_root::FUNCTION_ARG2_ZERO_ARITY: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY) { dst.root.pred.function = DATALOG_LABEL_WILDCARD; dst.root.pred.excluded_count = 0; if (!new_expression(dst.root.pred.args[1])) return false; datalog_expression& arg = *dst.root.pred.args[1]; arg.type = DATALOG_PREDICATE; arg.reference_count = 1; arg.pred.function = DATALOG_LABEL_WILDCARD; arg.pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(arg.pred.args); i++) arg.pred.args[i] = NULL; for (unsigned int i = 0; i < array_length(dst.root.pred.args); i++) if (i != 1) dst.root.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += array_length(dst.root.pred.args) - 1; } else if (src.root.type == DATALOG_PREDICATE) { if (src.root.pred.args[1] == NULL) { dst.root.pred.args[1] = NULL; } else if (src.root.pred.args[1]->type == DATALOG_ANY) { if (!new_expression(dst.root.pred.args[1])) return false; datalog_expression& arg = *dst.root.pred.args[1]; arg.type = DATALOG_PREDICATE; arg.reference_count = 1; arg.pred.function = DATALOG_LABEL_WILDCARD; arg.pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(arg.pred.args); i++) arg.pred.args[i] = NULL; } else if (src.root.pred.args[1]->type == DATALOG_NON_EMPTY) { if (!new_expression(dst.root.pred.args[1])) return false; datalog_expression& arg = *dst.root.pred.args[1]; arg.type = DATALOG_PREDICATE; arg.reference_count = 1; arg.pred.function = DATALOG_LABEL_WILDCARD; arg.pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(arg.pred.args); i++) arg.pred.args[i] = NULL; if (!init_excluded(arg.pred.excluded, &DATALOG_LABEL_EMPTY, 1)) return false; arg.pred.excluded_count = 1; } else if (src.root.pred.args[1]->type == DATALOG_PREDICATE) { datalog_expression& src_arg = *src.root.pred.args[1]; for (unsigned int i = 0; i < array_length(src_arg.pred.args); i++) { if (src_arg.pred.args[i] != NULL && !can_be_empty(*src_arg.pred.args[i])) return false; } if (!new_expression(dst.root.pred.args[1])) return false; datalog_expression& dst_arg = *dst.root.pred.args[1]; dst_arg.type = DATALOG_PREDICATE; dst_arg.reference_count = 1; dst_arg.pred.function = src_arg.pred.function; if (src_arg.pred.excluded_count > 0 && !init_excluded(dst_arg.pred.excluded, src_arg.pred.excluded, src_arg.pred.excluded_count)) { free(dst.root.pred.args[1]); return false; } dst_arg.pred.excluded_count = src_arg.pred.excluded_count; for (unsigned int i = 0; i < array_length(dst_arg.pred.args); i++) dst_arg.pred.args[i] = NULL; } else { return false; } /* initialize the root predicate */ dst.root.pred.function = src.root.pred.function; if (src.root.pred.excluded_count > 0 && !init_excluded(dst.root.pred.excluded, src.root.pred.excluded, src.root.pred.excluded_count)) { if (dst.root.pred.args[1] != NULL) { free(*dst.root.pred.args[1]); free(dst.root.pred.args[1]); } return false; } dst.root.pred.excluded_count = src.root.pred.excluded_count; for (unsigned int i = 0; i < array_length(src.root.pred.args); i++) { if (i == 1) continue; dst.root.pred.args[i] = src.root.pred.args[i]; if (dst.root.pred.args[i] != NULL) dst.root.pred.args[i]->reference_count++; } } else { return false; } dst.root.type = DATALOG_PREDICATE; dst.root.reference_count = 1; return dst.root.pred.function != DATALOG_LABEL_WILDCARD || dst.root.pred.exclude(&DATALOG_LABEL_EMPTY, 1); case datalog_expression_root::FUNCTION_LOC: if (!check_predicate_answer<PREDICATE_LOC>(src.root)) return false; dst.root.type = DATALOG_EMPTY; dst.root.reference_count = 1; return true; case datalog_expression_root::FUNCTION_TWO_PREDICATES: return tuple_length<2>(src.root, dst.root); case datalog_expression_root::FUNCTION_FLIP_PREDICATE: case datalog_expression_root::FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE: if (!init(dst.root, src.root)) { return false; } else if (!flip_predicate(dst.root)) { free(dst); return false; } return true; case datalog_expression_root::FUNCTION_EMPTY: break; } fprintf(stderr, "apply ERROR: Unrecognized transformation function.\n"); return false; } inline bool copy_array( const unsigned int* src, unsigned int src_length, unsigned int*& dst, unsigned int& dst_length) { dst = (unsigned int*) malloc(sizeof(unsigned int) * src_length); if (dst == nullptr) { fprintf(stderr, "copy_array ERROR: Out of memory.\n"); return false; } memcpy(dst, src, sizeof(unsigned int) * src_length); dst_length = src_length; return true; } template<bool HigherOrderOnly> inline bool get_function(const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { if (src.type == DATALOG_PREDICATE || src.type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; excluded_count = 0; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT) value = DATALOG_LABEL_WILDCARD; else value = DATALOG_LABEL_EMPTY; excluded_count = 0; } else if (src.type == DATALOG_FUNCTION) { if (HigherOrderOnly) { if (src.func.arg != NULL) { if (src.func.arg->type == DATALOG_PREDICATE || (src.func.arg->type == DATALOG_TUPLE && src.func.arg->tuple.elements.length > 0)) return false; } } value = src.func.function; if (src.func.excluded_count != 0 && !copy_array(src.func.excluded, src.func.excluded_count, excluded, excluded_count)) return false; } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else { return false; } return true; } inline bool has_function( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { if (src.type == DATALOG_PREDICATE || src.type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT) value = DATALOG_LABEL_WILDCARD; else value = DATALOG_LABEL_EMPTY; } else if (src.type == DATALOG_FUNCTION) { value = DATALOG_TRUE; } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; } else { return false; } excluded_count = 0; return true; } /* NOTE: this function assumes 'named_functions' is sorted */ template<size_t N> inline bool has_function( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count, const unsigned int (&named_functions)[N]) { if (src.type == DATALOG_PREDICATE || src.type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.elements.length == 0 && src.tuple.position != POSITION_EXACT) value = DATALOG_LABEL_WILDCARD; else value = DATALOG_LABEL_EMPTY; } else if (src.type == DATALOG_FUNCTION) { if (src.func.function == DATALOG_LABEL_WILDCARD) { unsigned int intersection_size = 0; auto count = [&](unsigned int i, unsigned int j) { intersection_size++; }; set_intersect(count, src.func.excluded, src.func.excluded_count, named_functions, N); if (intersection_size == N) value = DATALOG_TRUE; else value = DATALOG_LABEL_WILDCARD; } else { for (unsigned int i = 0; i < N; i++) { if (src.func.function == named_functions[i]) { value = named_functions[i]; excluded_count = 0; return true; } } value = DATALOG_TRUE; } } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; } else { return false; } excluded_count = 0; return true; } inline bool get_predicate( const datalog_expression& term, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { if (term.type == DATALOG_PREDICATE) { if (term.pred.excluded_count != 0 && !copy_array(term.pred.excluded, term.pred.excluded_count, excluded, excluded_count)) return false; value = term.pred.function; } else if (term.type == DATALOG_FUNCTION) { if (term.func.excluded_count != 0 && !copy_array(term.func.excluded, term.func.excluded_count, excluded, excluded_count)) return false; value = term.func.function; } else if (term.type == DATALOG_ANY || term.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else { return false; } return true; } template<unsigned int Index, bool Preterminal, bool AllowFunction> bool get_predicate( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { static_assert(Index == 0 || !Preterminal, "If Preterminal is true, Index must be zero"); if (src.type == DATALOG_TUPLE) { if (Preterminal && src.tuple.elements.length > 1) return false; if (src.tuple.position == POSITION_RIGHT) { if (Preterminal) { if (src.tuple.elements.length == 0) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else { return get_predicate(*src.tuple.elements[0], value, excluded, excluded_count); } } else { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } } else if (Index >= src.tuple.elements.length) { value = (src.tuple.position == POSITION_LEFT) ? DATALOG_LABEL_WILDCARD : DATALOG_LABEL_EMPTY; excluded_count = 0; } else return get_predicate(*src.tuple.elements[Index], value, excluded, excluded_count); } else if (src.type == DATALOG_PREDICATE) { if (Index != 0) { value = DATALOG_LABEL_EMPTY; excluded_count = 0; return true; } if (src.pred.excluded_count != 0 && !copy_array(src.pred.excluded, src.pred.excluded_count, excluded, excluded_count)) return false; value = src.pred.function; } else if (src.type == DATALOG_FUNCTION) { if (!AllowFunction) return false; return get_predicate<Index, Preterminal, true>(*src.func.arg, value, excluded, excluded_count); } else if (src.type == DATALOG_STRING) { value = DATALOG_STRING; excluded_count = 0; } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else if (src.type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; excluded_count = 0; } else { return false; } return true; } template<unsigned int Index> bool get_right_predicate( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { if (src.type == DATALOG_TUPLE) { if (src.tuple.position == POSITION_LEFT) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else if (Index >= src.tuple.elements.length) { value = (src.tuple.position == POSITION_RIGHT) ? DATALOG_LABEL_WILDCARD : DATALOG_LABEL_EMPTY; excluded_count = 0; } else return get_predicate(*src.tuple.elements[src.tuple.elements.length - Index - 1], value, excluded, excluded_count); } else if (src.type == DATALOG_PREDICATE) { if (Index != 0) { value = DATALOG_LABEL_EMPTY; excluded_count = 0; return true; } if (src.pred.excluded_count != 0 && !copy_array(src.pred.excluded, src.pred.excluded_count, excluded, excluded_count)) return false; value = src.pred.function; } else if (src.type == DATALOG_FUNCTION) { return get_right_predicate<Index>(*src.func.arg, value, excluded, excluded_count); } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else if (src.type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; excluded_count = 0; } else { return false; } return true; } template<bool Preterminal> bool get_direction(const datalog_expression& src, unsigned int& value) { if (src.type == DATALOG_PREDICATE) { if (src.pred.args[2] != NULL && !can_be_empty(*src.pred.args[2])) { return false; } else if (src.pred.args[0] == NULL) { value = DIRECTION_NONE; return true; } else if (src.pred.args[0]->type == DATALOG_ANY || src.pred.args[0]->type == DATALOG_NON_EMPTY) { if (src.pred.args[1] == NULL) { value = DIRECTION_SELF; } else if (src.pred.args[1]->type == DATALOG_ANY || src.pred.args[1]->type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; } else { return false; /* prune search paths where the excluded directions is supposed to be non-empty */ } return true; } else if (src.pred.args[0]->type != DATALOG_VARIABLE) { return false; } else if (src.pred.args[1] == NULL) { value = DIRECTION_SELF; /* this predicate is unary */ return true; } else if (src.pred.args[1]->type == DATALOG_ANY || src.pred.args[1]->type == DATALOG_NON_EMPTY) { return false; /* prune search paths where the excluded directions is supposed to be non-empty */ } else if (!Preterminal && src.pred.args[1]->type == DATALOG_PREDICATE) { value = DIRECTION_PREDICATE; return true; } else if (!Preterminal && src.pred.args[1]->type == DATALOG_CONSTANT) { value = DIRECTION_CONSTANT; return true; } else if (src.pred.args[1]->type != DATALOG_VARIABLE) { return false; } unsigned int first_head = src.pred.args[0]->variable; unsigned int second_head = src.pred.args[1]->variable; if (first_head < second_head) value = DIRECTION_FORWARD; else if (first_head > second_head) value = DIRECTION_BACKWARD; else value = DIRECTION_BOTH; } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; } else if (src.type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; } else if (src.type == DATALOG_FUNCTION) { return get_direction<Preterminal>(*src.func.arg, value); } else if (src.type == DATALOG_TUPLE) { if (src.tuple.position == POSITION_RIGHT) { return false; /* we prune this part of the search space */ } else if (src.tuple.position == POSITION_LEFT) { if (src.tuple.elements.length == 0) { value = DATALOG_LABEL_WILDCARD; } else { return get_direction<Preterminal>(*src.tuple.elements[0], value); } } else { if (src.tuple.elements.length == 0) { value = DATALOG_LABEL_EMPTY; } else { return get_direction<Preterminal>(*src.tuple.elements[0], value); } } } else { return false; } return true; } template<bool ConstantOnly> inline bool get_constant( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else if (src.type == DATALOG_PREDICATE) { if (ConstantOnly) return false; value = src.pred.function; if (src.pred.excluded_count != 0 && !copy_array(src.pred.excluded, src.pred.excluded_count, excluded, excluded_count)) return false; } else if (src.type == DATALOG_STRING && src.str.length > 0) { if (ConstantOnly) return false; value = DATALOG_STRING; excluded_count = 0; } else if (src.type != DATALOG_CONSTANT) { if (ConstantOnly) return false; value = DATALOG_LABEL_EMPTY; excluded_count = 0; } else { value = src.constant.label; if (src.constant.excluded_count != 0 && !copy_array(src.constant.excluded, src.constant.excluded_count, excluded, excluded_count)) return false; } return true; } inline bool get_predicate_arity( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { static unsigned int excluded_arities_zero_one[] = { ARITY_TWO, ARITY_THREE, ARITY_NULL }; static unsigned int excluded_arities_zero_two[] = { ARITY_THREE, ARITY_NULL }; static unsigned int excluded_arities_zero_three[] = { ARITY_NULL }; static unsigned int excluded_arities_one_two[] = { ARITY_ZERO, ARITY_THREE, ARITY_NULL }; static unsigned int excluded_arities_one_three[] = { ARITY_ZERO, ARITY_NULL }; static unsigned int excluded_arities_two_three[] = { ARITY_ZERO, ARITY_ONE, ARITY_NULL }; excluded_count = 0; if (src.type == DATALOG_TUPLE) { if (src.tuple.elements.length == 0) { if (src.tuple.position == POSITION_EXACT) value = DATALOG_LABEL_EMPTY; else value = DATALOG_LABEL_WILDCARD; /* the arity could either be DATALOG_LABEL_EMPTY, ARITY_NULL, or the arity of the singleton predicate */ } else if (src.tuple.elements.length == 1) { if (src.tuple.position == POSITION_EXACT) return get_predicate_arity(*src.tuple.elements[0], value, excluded, excluded_count); else value = DATALOG_LABEL_WILDCARD; /* the arity could be ARITY_NULL or the arity of the singleton predicate */ } else value = ARITY_NULL; } else if (src.type == DATALOG_PREDICATE) { unsigned int min_arity = array_length(src.pred.args); unsigned int max_arity = array_length(src.pred.args); while (min_arity > 0) { if (src.pred.args[min_arity - 1] != NULL && !can_be_empty(*src.pred.args[min_arity - 1])) break; min_arity--; } while (max_arity > min_arity) { if (src.pred.args[max_arity - 1] != NULL) break; max_arity--; } if (min_arity > 3 || max_arity > 3) { fprintf(stderr, "get_feature ERROR: Unrecognized arity.\n"); return false; } value = DATALOG_LABEL_WILDCARD; if (min_arity == 0) { if (max_arity == 0) value = ARITY_ZERO; else if (max_arity == 1) { if (!copy_array(excluded_arities_zero_one, array_length(excluded_arities_zero_one), excluded, excluded_count)) return false; } else if (max_arity == 2) { if (!copy_array(excluded_arities_zero_two, array_length(excluded_arities_zero_two), excluded, excluded_count)) return false; } else if (max_arity == 3) { if (!copy_array(excluded_arities_zero_three, array_length(excluded_arities_zero_three), excluded, excluded_count)) return false; } } else if (min_arity == 1) { if (max_arity == 1) value = ARITY_ONE; else if (max_arity == 2) { if (!copy_array(excluded_arities_one_two, array_length(excluded_arities_one_two), excluded, excluded_count)) return false; } else if (max_arity == 3) { if (!copy_array(excluded_arities_one_three, array_length(excluded_arities_one_three), excluded, excluded_count)) return false; } } else if (min_arity == 2) { if (max_arity == 2) value = ARITY_TWO; else if (max_arity == 3) { if (!copy_array(excluded_arities_two_three, array_length(excluded_arities_two_three), excluded, excluded_count)) return false; } } else if (min_arity == 3) { if (max_arity == 3) value = ARITY_THREE; } } else if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; } else if (src.type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; } else { return false; } return true; } template<unsigned int Index, bool ConstantOnly> inline bool get_arg_constant( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else if (!ConstantOnly && src.type == DATALOG_TUPLE) { if (src.tuple.position == POSITION_RIGHT) { return false; /* prune this region of the search */ } else if (src.tuple.elements.length == 0) { if (src.tuple.position == POSITION_EXACT) value = ARG_OTHER; else value = DATALOG_LABEL_WILDCARD; } else { return get_arg_constant<Index, ConstantOnly>(*src.tuple.elements[0], value, excluded, excluded_count); } excluded_count = 0; } else if (src.type != DATALOG_PREDICATE) { if (ConstantOnly) return false; value = ARG_OTHER; excluded_count = 0; } else if (src.pred.args[Index] == NULL || src.pred.args[Index]->type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; excluded_count = 0; } else { return get_constant<ConstantOnly>(*src.pred.args[Index], value, excluded, excluded_count); } return true; } template<unsigned int Index> inline bool get_arg_arity( const datalog_expression& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { if (src.type == DATALOG_ANY || src.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else if (src.type == DATALOG_TUPLE) { if (src.tuple.position == POSITION_RIGHT) { return false; /* prune this region of the search */ } else if (src.tuple.elements.length == 0) { if (src.tuple.position == POSITION_EXACT) value = ARG_OTHER; else value = DATALOG_LABEL_WILDCARD; } else { return get_arg_arity<Index>(*src.tuple.elements[0], value, excluded, excluded_count); } excluded_count = 0; } else if (src.type != DATALOG_PREDICATE) { value = ARG_OTHER; excluded_count = 0; } else if (src.pred.args[Index] == NULL || src.pred.args[Index]->type == DATALOG_EMPTY) { value = DATALOG_LABEL_EMPTY; excluded_count = 0; } else { return get_predicate_arity(*src.pred.args[Index], value, excluded, excluded_count); } return true; } bool get_feature( datalog_expression_root::feature feature, const datalog_expression_root& src, unsigned int& value, unsigned int*& excluded, unsigned int& excluded_count) { static constexpr unsigned int PREDICATES_NOT[] = {PREDICATE_NOT}; static constexpr unsigned int PREDICATES_COUNT_NOT[] = {PREDICATE_COUNT, PREDICATE_NOT}; static unsigned int NUMBERS_SINGULAR[] = {NUMBER_OFFSET + NUMBER_SINGULAR - 1}; static unsigned int NUMBERS_PLURAL[] = {NUMBER_OFFSET + NUMBER_PLURAL - 1}; switch (feature) { case datalog_expression_root::FEATURE_FUNCTION: return get_function<false>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_FUNCTION_ONLY: return get_function<true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_FUNCTION_ANSWER: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; return true; } else if (src.root.type == DATALOG_FUNCTION) { if (src.root.func.function == DATALOG_LABEL_WILDCARD) { if (src.root.func.is_excluded(PREDICATE_ANSWER)) return false; } else if (src.root.func.function != PREDICATE_ANSWER) return false; return get_function<false>(*src.root.func.arg, value, excluded, excluded_count); } else return false; case datalog_expression_root::FEATURE_HAS_FUNCTION: return has_function(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_HAS_FUNCTION_NOT: return has_function(src.root, value, excluded, excluded_count, PREDICATES_NOT); case datalog_expression_root::FEATURE_HAS_FUNCTION_COUNT_NOT: return has_function(src.root, value, excluded, excluded_count, PREDICATES_COUNT_NOT); case datalog_expression_root::FEATURE_HAS_FUNCTION_ANSWER: if (src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; return true; } else if (src.root.type == DATALOG_FUNCTION) { if (src.root.func.function == DATALOG_LABEL_WILDCARD) { if (src.root.func.is_excluded(PREDICATE_ANSWER)) return false; } else if (src.root.func.function != PREDICATE_ANSWER) return false; return has_function(*src.root.func.arg, value, excluded, excluded_count); } else return false; case datalog_expression_root::FEATURE_PREDICATE: return get_predicate<0, true, true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_PREDICATE_ONLY: return get_predicate<0, true, false>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_FIRST_PREDICATE: return get_predicate<0, false, true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_SECOND_PREDICATE: return get_predicate<1, false, true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_THIRD_PREDICATE: return get_predicate<2, false, true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_LAST_PREDICATE: return get_right_predicate<0>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_DIRECTION: excluded_count = 0; return get_direction<true>(src.root, value); case datalog_expression_root::FEATURE_DIRECTION_ROOT: excluded_count = 0; return get_direction<false>(src.root, value); case datalog_expression_root::FEATURE_CONSTANT: return get_constant<true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_PREDICATE_ARITY: return get_predicate_arity(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_ARG1: return get_arg_constant<0, false>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_ARG2: return get_arg_constant<1, false>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_ARG3: return get_arg_constant<2, false>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_ARG1_ONLY: return get_arg_constant<0, true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_ARG2_ONLY: return get_arg_constant<1, true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_ARG3_ONLY: return get_arg_constant<2, true>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_ARG2_ARITY: return get_arg_arity<1>(src.root, value, excluded, excluded_count); case datalog_expression_root::FEATURE_NUMBER: if (src.concord == NUMBER_ANY) { value = DATALOG_LABEL_WILDCARD; excluded_count = 0; } else if (src.concord == NUMBER_NON_SINGULAR) { value = DATALOG_LABEL_WILDCARD; if (!copy_array(NUMBERS_SINGULAR, array_length(NUMBERS_SINGULAR), excluded, excluded_count)) return false; } else if (src.concord == NUMBER_NON_PLURAL) { value = DATALOG_LABEL_WILDCARD; if (!copy_array(NUMBERS_PLURAL, array_length(NUMBERS_PLURAL), excluded, excluded_count)) return false; } else { value = NUMBER_OFFSET + src.index - 1; } return true; case datalog_expression_root::FEATURE_INFLECTION: if (src.inf == INFLECTION_ANY) value = DATALOG_LABEL_WILDCARD; else value = INFLECTION_OFFSET + src.inf - 1; return true; case datalog_expression_root::FEATURE_NULL: break; } fprintf(stderr, "get_feature ERROR: Unrecognized semantic feature.\n"); return false; } template<unsigned int Predicate, typename std::enable_if< Predicate == PREDICATE_COUNT || Predicate == PREDICATE_SUM>::type* = nullptr> inline void set_function_variables(datalog_function& func) { func.vars[0] = 2; func.vars[1] = 1; } template<unsigned int Predicate, typename std::enable_if< Predicate == PREDICATE_ANSWER || Predicate == PREDICATE_HIGHEST || Predicate == PREDICATE_LOWEST || Predicate == PREDICATE_LONGEST || Predicate == PREDICATE_SHORTEST || Predicate == PREDICATE_LARGEST || Predicate == PREDICATE_SMALLEST>::type* = nullptr> inline void set_function_variables(datalog_function& func) { func.vars[0] = 1; func.vars[1] = 0; } template<unsigned int Predicate, typename std::enable_if< Predicate == PREDICATE_MOST || Predicate == PREDICATE_FEWEST>::type* = nullptr> inline void set_function_variables(datalog_function& func) { func.vars[0] = 1; func.vars[1] = 2; } template<unsigned int Predicate, typename std::enable_if< Predicate == PREDICATE_NOT || Predicate == DATALOG_LABEL_WILDCARD>::type* = nullptr> inline void set_function_variables(datalog_function& func) { func.vars[0] = 0; func.vars[1] = 0; } inline void set_function_variables(datalog_function& func, unsigned int predicate) { switch (predicate) { case PREDICATE_COUNT: case PREDICATE_SUM: func.vars[0] = 2; func.vars[1] = 1; return; case PREDICATE_ANSWER: case PREDICATE_HIGHEST: case PREDICATE_LOWEST: case PREDICATE_LONGEST: case PREDICATE_SHORTEST: case PREDICATE_LARGEST: case PREDICATE_SMALLEST: if (variable_count(*func.arg) <= 1) func.vars[0] = 1; else func.vars[0] = 2; func.vars[1] = 0; return; case PREDICATE_MOST: case PREDICATE_FEWEST: func.vars[0] = 1; func.vars[1] = 2; return; case PREDICATE_NOT: func.vars[0] = 0; func.vars[1] = 0; return; default: fprintf(stderr, "set_function_variables ERROR: Unrecognized datalog_function predicate.\n"); exit(EXIT_FAILURE); } } template<bool HigherOrderOnly> bool set_function(datalog_expression& exp, unsigned int value) { if (value == DATALOG_LABEL_EMPTY) { return (exp.type != DATALOG_FUNCTION); } else { if (exp.type == DATALOG_FUNCTION) { if (exp.func.function == DATALOG_LABEL_WILDCARD) { if (!HigherOrderOnly) return false; if (index_of(value, exp.func.excluded, exp.func.excluded_count) < exp.func.excluded_count) return false; if (exp.func.excluded_count > 0) free(exp.func.excluded); exp.func.excluded_count = 0; exp.func.function = value; set_function_variables(exp.func, value); } else if (exp.func.function != value) return false; } else { return false; /* prune parts of the search space where the function isn't known by this point */ } } return true; } bool set_has_function(datalog_expression& exp, unsigned int value) { if (value == DATALOG_LABEL_EMPTY) { return (exp.type != DATALOG_FUNCTION); } else if (value == DATALOG_TRUE) { if (exp.type == DATALOG_ANY) { exp.func.function = DATALOG_LABEL_WILDCARD; exp.func.excluded_count = 0; exp.func.arg = &DATALOG_ANY_TREE; set_function_variables<DATALOG_LABEL_WILDCARD>(exp.func); DATALOG_ANY_TREE.reference_count++; exp.type = DATALOG_FUNCTION; } else return (exp.type == DATALOG_FUNCTION); } else { return false; } return true; } template<size_t N> bool set_has_function( datalog_expression& exp, unsigned int value, const unsigned int (&named_functions)[N]) { if (value == DATALOG_LABEL_EMPTY) return (exp.type != DATALOG_FUNCTION); else if (exp.type != DATALOG_FUNCTION) return false; if (value == DATALOG_TRUE) { /* the expression is a function, but not among the list of named functions */ if (exp.func.function != DATALOG_LABEL_WILDCARD) { return index_of(exp.func.function, named_functions, N) == N; } else if (exp.func.function == DATALOG_LABEL_WILDCARD && !exp.func.exclude(named_functions, N)) { exit(EXIT_FAILURE); } return true; } for (unsigned int i = 0; i < N; i++) if (value == named_functions[i]) return exp.func.function == value; for (unsigned int i = 0; i < N; i++) if (exp.func.function == named_functions[i]) return false; return true; } bool set_predicate(datalog_expression& exp, unsigned int predicate) { if (predicate <= NUM_PREDICATES) { exp.func.function = predicate; exp.func.arg = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; exp.func.excluded_count = 0; set_function_variables<DATALOG_LABEL_WILDCARD>(exp.func); /* we don't know the head of the function variables */ exp.type = DATALOG_FUNCTION; } else if (predicate == DATALOG_STRING) { if (!init(exp.str, 1)) return false; exp.str[0] = DATALOG_STRING_LABEL_WILDCARD; exp.type = DATALOG_STRING; } else { exp.pred.function = predicate; for (unsigned int i = 0; i < array_length(exp.pred.args); i++) exp.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += array_length(exp.pred.args); exp.pred.excluded_count = 0; exp.type = DATALOG_PREDICATE; } return true; } template<unsigned int Index, bool Preterminal, bool AllowFunction> bool set_predicate(datalog_expression& exp, unsigned int predicate) { static_assert(Index == 0 || !Preterminal, "If Preterminal is true, Index must be zero"); if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { if (predicate == DATALOG_LABEL_EMPTY) { if (Index == 0 && exp.type == DATALOG_NON_EMPTY) return false; if (Index == 0) exp.type = DATALOG_EMPTY; return true; } if (Index > 0 || !Preterminal) { if (!array_init(exp.tuple.elements, Index + 1)) exit(EXIT_FAILURE); exp.tuple.position = POSITION_LEFT; exp.type = DATALOG_TUPLE; for (unsigned int i = 0; i < Index; i++) exp.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += Index; if (!new_expression(exp.tuple.elements[Index])) exit(EXIT_FAILURE); exp.tuple.elements[Index]->reference_count = 1; exp.tuple.elements[Index]->type = DATALOG_ANY; exp.tuple.elements.length = Index + 1; return set_predicate(*exp.tuple.elements[Index], predicate); } else { return set_predicate(exp, predicate); } } else if (exp.type == DATALOG_PREDICATE) { if (Index != 0) { if (predicate == DATALOG_LABEL_EMPTY) return true; if (predicate <= NUM_PREDICATES) return false; } else if (predicate == DATALOG_LABEL_EMPTY) { if (exp.pred.is_excluded(DATALOG_LABEL_EMPTY)) return false; free(exp); exp.type = DATALOG_EMPTY; exp.reference_count = 1; return true; } if (exp.pred.function == DATALOG_LABEL_WILDCARD) { if (exp.pred.is_excluded(predicate)) return false; if (exp.pred.excluded_count > 0) free(exp.pred.excluded); exp.pred.excluded_count = 0; exp.pred.function = predicate; } else if (exp.pred.function != predicate) return false; } else if (exp.type == DATALOG_FUNCTION) { if (!AllowFunction) return false; datalog_expression* arg; if (exp.func.arg->reference_count == 1) { arg = exp.func.arg; } else { if (!init(arg, *exp.func.arg)) exit(EXIT_FAILURE); free(*exp.func.arg); exp.func.arg = arg; } return set_predicate<Index, Preterminal, true>(*arg, predicate); } else if (exp.type == DATALOG_TUPLE) { if (Preterminal && exp.tuple.elements.length > 1) return false; if (exp.tuple.position == POSITION_RIGHT) return false; else if (Index >= exp.tuple.elements.length) { if (exp.tuple.position == POSITION_LEFT) { if (predicate == DATALOG_LABEL_EMPTY) { if (!exp.tuple.elements.ensure_capacity(Index)) exit(EXIT_FAILURE); for (unsigned int i = exp.tuple.elements.length; i < Index; i++) exp.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += Index - exp.tuple.elements.length; exp.tuple.elements.length = Index; exp.tuple.position = POSITION_EXACT; return true; } else { if (!exp.tuple.elements.ensure_capacity(Index + 1)) exit(EXIT_FAILURE); for (unsigned int i = exp.tuple.elements.length; i < Index + 1; i++) exp.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += Index + 1 - exp.tuple.elements.length; exp.tuple.elements.length = Index + 1; if (Preterminal) exp.tuple.position = POSITION_EXACT; } } else return predicate == DATALOG_LABEL_EMPTY; } else if (predicate == DATALOG_LABEL_EMPTY) return false; if (Preterminal) exp.tuple.position = POSITION_EXACT; datalog_expression* element; if (exp.tuple.elements[Index]->reference_count == 1) { element = exp.tuple.elements[Index]; } else { if (!init(element, *exp.tuple.elements[Index])) exit(EXIT_FAILURE); free(*exp.tuple.elements[Index]); exp.tuple.elements[Index] = element; } if (element->type == DATALOG_ANY || element->type == DATALOG_NON_EMPTY) { return set_predicate(*element, predicate); } else if (element->type == DATALOG_PREDICATE) { if (predicate <= NUM_PREDICATES) return false; if (element->pred.function == DATALOG_LABEL_WILDCARD) { if (element->pred.is_excluded(predicate)) return false; if (element->pred.excluded_count > 0) free(element->pred.excluded); element->pred.excluded_count = 0; element->pred.function = predicate; } else if (element->pred.function != predicate) return false; } else if (element->type == DATALOG_FUNCTION) { if (predicate > NUM_PREDICATES) return false; if (element->func.function == DATALOG_LABEL_WILDCARD) { if (element->func.is_excluded(predicate)) return false; if (element->func.excluded_count > 0) free(element->func.excluded); element->func.excluded_count = 0; element->func.function = predicate; set_function_variables(element->func, predicate); } else if (element->func.function != predicate) return false; } else { return false; } } else if (exp.type == DATALOG_STRING) { return predicate == DATALOG_STRING; } else if (exp.type == DATALOG_EMPTY) { return predicate == DATALOG_LABEL_EMPTY; } else { return false; } return true; } template<unsigned int Index> bool set_right_predicate(datalog_expression& exp, unsigned int predicate) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { return false; /* preterminals don't use this feature, so we can prune away this part of the search */ } else if (exp.type == DATALOG_PREDICATE) { if (Index != 0) { if (predicate == DATALOG_LABEL_EMPTY) return true; if (predicate <= NUM_PREDICATES) return false; } if (exp.pred.function == DATALOG_LABEL_WILDCARD) { if (exp.pred.is_excluded(predicate)) return false; if (exp.pred.excluded_count > 0) free(exp.pred.excluded); exp.pred.excluded_count = 0; exp.pred.function = predicate; } else if (exp.pred.function != predicate) return false; } else if (exp.type == DATALOG_FUNCTION) { return set_right_predicate<Index>(*exp.func.arg, predicate); } else if (exp.type == DATALOG_TUPLE) { if (exp.tuple.position == POSITION_LEFT) return false; else if (Index >= exp.tuple.elements.length) { if (exp.tuple.position == POSITION_RIGHT) { if (predicate == DATALOG_LABEL_EMPTY) { if (!exp.tuple.elements.ensure_capacity(Index)) exit(EXIT_FAILURE); for (unsigned int i = 0; i < exp.tuple.elements.length; i++) exp.tuple.elements[Index - i - 1] = exp.tuple.elements[exp.tuple.elements.length - i - 1]; for (unsigned int i = 0; i < Index - exp.tuple.elements.length; i++) exp.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += Index - exp.tuple.elements.length; exp.tuple.elements.length = Index; exp.tuple.position = POSITION_EXACT; } else { if (!exp.tuple.elements.ensure_capacity(Index + 1)) exit(EXIT_FAILURE); for (unsigned int i = 0; i < exp.tuple.elements.length; i++) exp.tuple.elements[Index - i] = exp.tuple.elements[exp.tuple.elements.length - i - 1]; for (unsigned int i = 0; i < Index + 1 - exp.tuple.elements.length; i++) exp.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += Index + 1 - exp.tuple.elements.length; exp.tuple.elements.length = Index + 1; } } else return predicate == DATALOG_LABEL_EMPTY; } else if (predicate == DATALOG_LABEL_EMPTY) return false; datalog_expression* element; if (exp.tuple.elements[exp.tuple.elements.length - Index - 1]->reference_count == 1) { element = exp.tuple.elements[exp.tuple.elements.length - Index - 1]; } else { if (!init(element, *exp.tuple.elements[exp.tuple.elements.length - Index - 1])) exit(EXIT_FAILURE); free(*exp.tuple.elements[exp.tuple.elements.length - Index - 1]); exp.tuple.elements[exp.tuple.elements.length - Index - 1] = element; } if (element->type == DATALOG_ANY || element->type == DATALOG_NON_EMPTY) { return set_predicate(*element, predicate); } else if (element->type == DATALOG_PREDICATE) { if (predicate <= NUM_PREDICATES) return false; if (element->pred.function == DATALOG_LABEL_WILDCARD) { if (element->pred.is_excluded(predicate)) return false; if (element->pred.excluded_count > 0) free(element->pred.excluded); element->pred.excluded_count = 0; element->pred.function = predicate; } else if (element->pred.function != predicate) return false; } else if (element->type == DATALOG_FUNCTION) { if (predicate > NUM_PREDICATES) return false; if (element->func.function == DATALOG_LABEL_WILDCARD) { if (!element->func.is_excluded(predicate)) return false; if (element->func.excluded_count > 0) free(element->func.excluded); element->func.excluded_count = 0; element->func.function = predicate; set_function_variables(element->func, predicate); } else if (element->func.function != predicate) return false; } else { return false; } } else if (exp.type == DATALOG_EMPTY) { return predicate == DATALOG_LABEL_EMPTY; } else { return false; } return true; } template<bool Preterminal> inline bool set_direction(datalog_expression& exp, unsigned int direction) { if (Preterminal && (direction == DIRECTION_PREDICATE || direction == DIRECTION_CONSTANT)) return false; if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { if (direction == DATALOG_LABEL_EMPTY) { /* this is an empty expression or empty tuple */ return true; } exp.pred.function = DATALOG_LABEL_WILDCARD; exp.pred.excluded_count = 0; exp.type = DATALOG_PREDICATE; exp.reference_count = 1; switch (direction) { case DIRECTION_NONE: for (unsigned int i = 0; i < array_length(exp.pred.args); i++) exp.pred.args[i] = NULL; break; case DIRECTION_SELF: if (!new_expression(exp.pred.args[0])) exit(EXIT_FAILURE); exp.pred.args[0]->variable = 1; exp.pred.args[0]->type = DATALOG_VARIABLE; exp.pred.args[0]->reference_count = 1; for (unsigned int i = 1; i < array_length(exp.pred.args); i++) exp.pred.args[i] = NULL; break; case DIRECTION_FORWARD: if (!new_expression(exp.pred.args[0]) || !new_expression(exp.pred.args[1])) exit(EXIT_FAILURE); exp.pred.args[0]->variable = 1; exp.pred.args[0]->type = DATALOG_VARIABLE; exp.pred.args[0]->reference_count = 1; exp.pred.args[1]->variable = 2; exp.pred.args[1]->type = DATALOG_VARIABLE; exp.pred.args[1]->reference_count = 1; for (unsigned int i = 2; i < array_length(exp.pred.args); i++) exp.pred.args[i] = NULL; break; case DIRECTION_BACKWARD: if (!new_expression(exp.pred.args[0]) || !new_expression(exp.pred.args[1])) exit(EXIT_FAILURE); exp.pred.args[0]->variable = 2; exp.pred.args[0]->type = DATALOG_VARIABLE; exp.pred.args[0]->reference_count = 1; exp.pred.args[1]->variable = 1; exp.pred.args[1]->type = DATALOG_VARIABLE; exp.pred.args[1]->reference_count = 1; for (unsigned int i = 2; i < array_length(exp.pred.args); i++) exp.pred.args[i] = NULL; break; case DIRECTION_BOTH: if (!new_expression(exp.pred.args[0]) || !new_expression(exp.pred.args[1])) exit(EXIT_FAILURE); exp.pred.args[0]->variable = 1; exp.pred.args[0]->type = DATALOG_VARIABLE; exp.pred.args[0]->reference_count = 1; exp.pred.args[1]->variable = 1; exp.pred.args[1]->type = DATALOG_VARIABLE; exp.pred.args[1]->reference_count = 1; for (unsigned int i = 2; i < array_length(exp.pred.args); i++) exp.pred.args[i] = NULL; break; case DIRECTION_PREDICATE: case DIRECTION_CONSTANT: /* we prune this part of the search since this direction should already be determined in the logical form by this point */ return false; default: fprintf(stderr, "set_direction ERROR: Unrecognized edge direction.\n"); exit(EXIT_FAILURE); } } else if (exp.type == DATALOG_PREDICATE) { if (direction == DATALOG_LABEL_EMPTY) return false; unsigned int boundary; if (direction == DIRECTION_NONE) { boundary = 0; } else if (exp.pred.args[0] == NULL) { return false; } else if (exp.pred.args[0]->type == DATALOG_ANY || exp.pred.args[0]->type == DATALOG_NON_EMPTY) { if (exp.pred.args[0]->reference_count > 1) { free(*exp.pred.args[0]); if (!new_expression(exp.pred.args[0])) exit(EXIT_FAILURE); } exp.pred.args[0]->type = DATALOG_VARIABLE; exp.pred.args[0]->reference_count = 1; exp.pred.args[0]->variable = 1; if (exp.pred.args[1] == NULL) { if (direction != DIRECTION_SELF) return false; boundary = 1; } else if (exp.pred.args[1]->type == DATALOG_ANY || exp.pred.args[1]->type == DATALOG_NON_EMPTY) { if (exp.pred.args[1]->reference_count > 1) { free(*exp.pred.args[1]); if (!new_expression(exp.pred.args[1])) exit(EXIT_FAILURE); } if (direction == DIRECTION_PREDICATE) { exp.pred.args[1]->type = DATALOG_PREDICATE; exp.pred.args[1]->reference_count = 1; exp.pred.args[1]->pred.function = DATALOG_LABEL_WILDCARD; exp.pred.args[1]->pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(exp.pred.args[1]->pred.args); i++) exp.pred.args[1]->pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += array_length(exp.pred.args[1]->pred.args); boundary = 2; } else if (direction == DIRECTION_CONSTANT) { exp.pred.args[1]->type = DATALOG_CONSTANT; exp.pred.args[1]->reference_count = 1; exp.pred.args[1]->constant.label = DATALOG_LABEL_WILDCARD; exp.pred.args[1]->constant.excluded_count = 0; boundary = 2; } else { exp.pred.args[1]->type = DATALOG_VARIABLE; exp.pred.args[1]->reference_count = 1; boundary = 2; switch (direction) { case DIRECTION_SELF: exp.pred.args[0]->variable = 1; free(*exp.pred.args[1]); if (exp.pred.args[1]->reference_count == 0) free(exp.pred.args[1]); exp.pred.args[1] = NULL; break; case DIRECTION_FORWARD: exp.pred.args[0]->variable = 1; exp.pred.args[1]->variable = 2; break; case DIRECTION_BACKWARD: exp.pred.args[0]->variable = 2; exp.pred.args[1]->variable = 1; break; case DIRECTION_BOTH: exp.pred.args[0]->variable = 1; exp.pred.args[1]->variable = 1; break; case DIRECTION_PREDICATE: case DIRECTION_CONSTANT: /* we prune this part of the search since this direction should already be determined in the logical form by this point */ return false; default: fprintf(stderr, "set_direction ERROR: Unrecognized edge direction.\n"); exit(EXIT_FAILURE); } } } else if (exp.pred.args[1]->type == DATALOG_VARIABLE) { if (exp.pred.args[1]->reference_count > 1) { free(*exp.pred.args[1]); if (!init(exp.pred.args[1], *exp.pred.args[1])) exit(EXIT_FAILURE); } boundary = 2; switch (direction) { case DIRECTION_SELF: return false; case DIRECTION_FORWARD: if (Preterminal && exp.pred.args[1]->variable != 2) return false; exp.pred.args[0]->variable = 1; break; case DIRECTION_BACKWARD: if (Preterminal && exp.pred.args[1]->variable != 1) return false; exp.pred.args[0]->variable = 2; break; case DIRECTION_BOTH: if (Preterminal && exp.pred.args[1]->variable != 1) return false; exp.pred.args[0]->variable = 1; break; case DIRECTION_PREDICATE: case DIRECTION_CONSTANT: /* we prune this part of the search since this direction should already be determined in the logical form by this point */ return false; default: fprintf(stderr, "set_direction ERROR: Unrecognized edge direction.\n"); exit(EXIT_FAILURE); } } else { return false; } } else if (exp.pred.args[0]->type == DATALOG_VARIABLE) { if (exp.pred.args[0]->reference_count > 1) { free(*exp.pred.args[0]); if (!init(exp.pred.args[0], *exp.pred.args[0])) exit(EXIT_FAILURE); } boundary = 2; if (exp.pred.args[1] != NULL && exp.pred.args[1]->type != DATALOG_VARIABLE) { if ((direction != DIRECTION_PREDICATE || exp.pred.args[1]->type != DATALOG_PREDICATE) && (direction != DIRECTION_CONSTANT || exp.pred.args[1]->type != DATALOG_CONSTANT)) return false; } else { switch (direction) { case DIRECTION_SELF: return (!Preterminal || exp.pred.args[0]->variable != 2); case DIRECTION_FORWARD: if (Preterminal && (exp.pred.args[0]->variable != 1 || exp.pred.args[1]->variable != 2)) return false; break; case DIRECTION_BACKWARD: if (Preterminal && (exp.pred.args[0]->variable != 2 || exp.pred.args[1]->variable != 1)) return false; break; case DIRECTION_BOTH: if (Preterminal && (exp.pred.args[0]->variable != 1 || exp.pred.args[1]->variable != 1)) return false; break; default: fprintf(stderr, "set_direction ERROR: Unrecognized edge direction.\n"); exit(EXIT_FAILURE); } } } else { return false; } for (unsigned int i = boundary; i < array_length(exp.pred.args); i++) { if (exp.pred.args[i] == NULL) continue; if (!can_be_empty(*exp.pred.args[i])) return false; free(*exp.pred.args[i]); if (exp.pred.args[i]->reference_count == 0) free(exp.pred.args[i]); exp.pred.args[i] = NULL; } } else if (exp.type == DATALOG_TUPLE) { if (exp.tuple.position == POSITION_RIGHT) { return false; } else { if (exp.tuple.elements.length == 0) { if (direction == DATALOG_LABEL_EMPTY) { exp.tuple.position = POSITION_EXACT; } else { if (!new_expression(exp.tuple.elements[0])) exit(EXIT_FAILURE); exp.tuple.elements[0]->type = DATALOG_ANY; exp.tuple.elements[0]->reference_count = 1; exp.tuple.elements.length = 1; return set_direction<Preterminal>(*exp.tuple.elements[0], direction); } } else { datalog_expression* arg; if (exp.tuple.elements[0]->reference_count == 1) { arg = exp.tuple.elements[0]; } else { if (!init(arg, *exp.tuple.elements[0])) exit(EXIT_FAILURE); free(*exp.tuple.elements[0]); exp.tuple.elements[0] = arg; } return set_direction<Preterminal>(*arg, direction); } } } else if (exp.type == DATALOG_FUNCTION) { datalog_expression* arg; if (exp.func.arg->reference_count == 1) { arg = exp.func.arg; } else { if (!init(arg, *exp.func.arg)) exit(EXIT_FAILURE); free(*exp.func.arg); exp.func.arg = arg; } return set_direction<Preterminal>(*arg, direction); } else if (exp.type == DATALOG_EMPTY) { return (direction == DATALOG_LABEL_EMPTY); } else { return false; } return true; } template<bool ConstantOnly> inline bool set_constant(datalog_expression& exp, unsigned int value) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { exp.type = DATALOG_CONSTANT; exp.constant.label = value; exp.constant.excluded_count = 0; } else if (exp.type == DATALOG_CONSTANT) { if (exp.constant.label == DATALOG_LABEL_WILDCARD) { if (exp.constant.is_excluded(value)) return false; if (exp.constant.excluded_count > 0) free(exp.constant.excluded); exp.constant.excluded_count = 0; exp.constant.label = value; } else return exp.constant.label == value; } else if (exp.type == DATALOG_PREDICATE) { if (ConstantOnly) return false; if (exp.pred.function == DATALOG_LABEL_WILDCARD) { if (exp.pred.is_excluded(value)) return false; if (exp.pred.excluded_count > 0) free(exp.pred.excluded_count); exp.pred.excluded_count = 0; exp.pred.function = value; } else return exp.pred.function == value; } else if (exp.type == DATALOG_STRING && exp.str.length > 0) { if (ConstantOnly) return false; return value == DATALOG_STRING; } else { if (ConstantOnly) return false; return value == DATALOG_LABEL_EMPTY; } return true; } inline bool predicate_arg_not_empty(datalog_expression*& arg) { if (arg->type == DATALOG_CONSTANT) { datalog_expression* new_arg; if (arg->reference_count == 1) { new_arg = arg; } else { if (!init(new_arg, *arg)) exit(EXIT_FAILURE); free(*arg); arg = new_arg; } if (new_arg->constant.label == DATALOG_LABEL_WILDCARD && !new_arg->constant.exclude(&DATALOG_LABEL_EMPTY, 1)) exit(EXIT_FAILURE); } else if (arg->type == DATALOG_PREDICATE) { datalog_expression* new_arg; if (arg->reference_count == 1) { new_arg = arg; } else { if (!init(new_arg, *arg)) exit(EXIT_FAILURE); free(*arg); arg = new_arg; } if (new_arg->pred.function == DATALOG_LABEL_WILDCARD && !new_arg->pred.exclude(&DATALOG_LABEL_EMPTY, 1)) exit(EXIT_FAILURE); } else if (arg->type == DATALOG_ANY || arg->type == DATALOG_NON_EMPTY) { free(*arg); if (arg->reference_count == 0) free(arg); arg = &DATALOG_NON_EMPTY_TREE; DATALOG_NON_EMPTY_TREE.reference_count++; } else if (arg->type != DATALOG_VARIABLE && arg->type != DATALOG_STRING) { return false; } return true; } inline bool set_predicate_arity_any(datalog_predicate& pred, unsigned int value) { pred.function = DATALOG_LABEL_WILDCARD; pred.excluded_count = 0; pred.args[0] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; unsigned int boundary; if (value == ARITY_ZERO) boundary = 0; else if (value == ARITY_ONE) boundary = 1; else if (value == ARITY_TWO) boundary = 2; else if (value == ARITY_THREE) boundary = 3; else { fprintf(stderr, "set_predicate_arity ERROR: Unrecognized arity.\n"); return false; } for (unsigned int i = 0; i < boundary; i++) pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += boundary; for (unsigned int i = boundary; i < array_length(pred.args); i++) pred.args[i] = NULL; return true; } inline bool set_predicate_arity(datalog_predicate& pred, unsigned int value) { unsigned int boundary; if (value == ARITY_ZERO) boundary = 0; else if (value == ARITY_ONE) boundary = 1; else if (value == ARITY_TWO) boundary = 2; else if (value == ARITY_THREE) boundary = 3; else { fprintf(stderr, "set_predicate_arity ERROR: Unrecognized arity.\n"); return false; } if (boundary > 0 && (pred.args[boundary - 1] == NULL || !predicate_arg_not_empty(pred.args[boundary - 1]))) return false; for (unsigned int i = boundary; i < array_length(pred.args); i++) { if (pred.args[i] == NULL) continue; if (!can_be_empty(*pred.args[i])) return false; free(*pred.args[i]); if (pred.args[i]->reference_count == 0) free(pred.args[i]); pred.args[i] = NULL; } return true; } inline bool set_predicate_arity(datalog_expression& exp, unsigned int value) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { if (value == ARITY_NULL) { if (!init(exp.tuple, POSITION_LEFT, 1)) exit(EXIT_FAILURE); exp.type = DATALOG_TUPLE; } else if (value == DATALOG_LABEL_EMPTY) { exp.type = DATALOG_EMPTY; } else { exp.type = DATALOG_PREDICATE; if (!set_predicate_arity_any(exp.pred, value)) return false; } } else if (exp.type == DATALOG_TUPLE) { if (value == DATALOG_LABEL_EMPTY) { if (exp.tuple.elements.length > 0) return false; exp.tuple.position = POSITION_EXACT; } else if (value != ARITY_NULL) { if (exp.tuple.elements.length > 1) return false; else if (exp.tuple.elements.length == 0) { if (exp.tuple.position == POSITION_EXACT) return false; free(exp.tuple); exp.type = DATALOG_PREDICATE; if (!set_predicate_arity_any(exp.pred, value)) return false; } else { datalog_expression element = *exp.tuple.elements[0]; swap(exp, element); if (!set_predicate_arity(exp, value)) return false; } } } else if (exp.type == DATALOG_PREDICATE) { if (value == ARITY_NULL || value == DATALOG_LABEL_EMPTY || !set_predicate_arity(exp.pred, value)) return false; } else if (exp.type == DATALOG_EMPTY) { return (value == DATALOG_LABEL_EMPTY); } else { return false; } return true; } template<unsigned int Index, bool ConstantOnly> inline bool set_arg_constant(datalog_expression& exp, unsigned int value) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { if (value == ARG_OTHER) return true; else if (!new_expression(exp.pred.args[Index])) exit(EXIT_FAILURE); exp.pred.args[Index]->type = DATALOG_ANY; exp.pred.args[Index]->reference_count = 1; for (unsigned int i = 0; i < array_length(exp.pred.args); i++) if (i != Index) exp.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += (array_length(exp.pred.args) - 1); exp.pred.function = DATALOG_LABEL_WILDCARD; exp.pred.excluded_count = 0; exp.type = DATALOG_PREDICATE; if (value == DATALOG_LABEL_EMPTY) { exp.pred.args[Index] = NULL; } else { //return set_constant<ConstantOnly>(*exp.pred.args[Index], value); return set_predicate<0, true, false>(*exp.pred.args[Index], value); } } else if (exp.type == DATALOG_PREDICATE) { if (exp.pred.args[Index] == NULL) return value == DATALOG_LABEL_EMPTY; if (value == DATALOG_LABEL_EMPTY) { if (exp.pred.args[Index]->type != DATALOG_ANY && exp.pred.args[Index]->type != DATALOG_EMPTY) return false; free(*exp.pred.args[Index]); if (exp.pred.args[Index]->reference_count == 0) free(exp.pred.args[Index]); exp.pred.args[Index] = NULL; } else { datalog_expression* arg; if (exp.pred.args[Index]->reference_count == 1) { arg = exp.pred.args[Index]; } else { if (!init(arg, *exp.pred.args[Index])) exit(EXIT_FAILURE); free(*exp.pred.args[Index]); exp.pred.args[Index] = arg; } //return set_constant<ConstantOnly>(*arg, value); return set_predicate<0, true, false>(*arg, value); } } else if (!ConstantOnly && exp.type == DATALOG_TUPLE) { if (exp.tuple.position == POSITION_RIGHT) { return false; /* prune this region of the search */ } else if (exp.tuple.elements.length == 0) { if (exp.tuple.position == POSITION_EXACT) return value == ARG_OTHER; else return value == DATALOG_LABEL_WILDCARD; } else { datalog_expression* element; if (exp.tuple.elements[0]->reference_count == 1) { element = exp.tuple.elements[0]; } else { if (!init(element, *exp.tuple.elements[0])) exit(EXIT_FAILURE); free(*exp.tuple.elements[0]); exp.tuple.elements[0] = element; } return set_arg_constant<Index, ConstantOnly>(*element, value); } } else { return value == ARG_OTHER; } return true; } template<unsigned int Index> inline bool set_arg_arity(datalog_expression& exp, unsigned int value) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { if (value == ARG_OTHER) return true; else if (!new_expression(exp.pred.args[Index])) exit(EXIT_FAILURE); exp.pred.args[Index]->type = DATALOG_ANY; exp.pred.args[Index]->reference_count = 1; for (unsigned int i = 0; i < array_length(exp.pred.args); i++) if (i != Index) exp.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += (array_length(exp.pred.args) - 1); exp.pred.function = DATALOG_LABEL_WILDCARD; exp.pred.excluded_count = 0; exp.type = DATALOG_PREDICATE; if (value == DATALOG_LABEL_EMPTY) { exp.pred.args[Index] = NULL; } else { return set_predicate_arity(*exp.pred.args[Index], value); } } else if (exp.type == DATALOG_PREDICATE) { if (exp.pred.args[Index] == NULL) return value == DATALOG_LABEL_EMPTY; if (value == DATALOG_LABEL_EMPTY) { if (exp.pred.args[Index]->type != DATALOG_ANY && exp.pred.args[Index]->type != DATALOG_EMPTY) return false; free(*exp.pred.args[Index]); if (exp.pred.args[Index]->reference_count == 0) free(exp.pred.args[Index]); exp.pred.args[Index] = NULL; } else { datalog_expression* arg; if (exp.pred.args[Index]->reference_count == 1) { arg = exp.pred.args[Index]; } else { if (!init(arg, *exp.pred.args[Index])) exit(EXIT_FAILURE); free(*exp.pred.args[Index]); exp.pred.args[Index] = arg; } return set_predicate_arity(*arg, value); } } else if (exp.type == DATALOG_TUPLE) { if (exp.tuple.position == POSITION_RIGHT) { return false; /* prune this region of the search */ } else if (exp.tuple.elements.length == 0) { if (exp.tuple.position == POSITION_EXACT) return value == ARG_OTHER; else return value == DATALOG_LABEL_WILDCARD; } else { datalog_expression* element; if (exp.tuple.elements[0]->reference_count == 1) { element = exp.tuple.elements[0]; } else { if (!init(element, *exp.tuple.elements[0])) exit(EXIT_FAILURE); free(*exp.tuple.elements[0]); exp.tuple.elements[0] = element; } return set_arg_arity<Index>(*element, value); } } else { return value == ARG_OTHER; } return true; } bool set_feature( datalog_expression_root::feature feature, datalog_expression_root& exp, unsigned int value) { static constexpr unsigned int PREDICATES_NOT[] = {PREDICATE_NOT}; static constexpr unsigned int PREDICATES_COUNT_NOT[] = {PREDICATE_COUNT, PREDICATE_NOT}; datalog_expression* arg; switch (feature) { case datalog_expression_root::FEATURE_FUNCTION: return set_function<false>(exp.root, value); case datalog_expression_root::FEATURE_FUNCTION_ONLY: return set_function<true>(exp.root, value); case datalog_expression_root::FEATURE_FUNCTION_ANSWER: if (exp.root.type == DATALOG_ANY || exp.root.type == DATALOG_NON_EMPTY) { exp.root.func.function = PREDICATE_ANSWER; set_function_variables<PREDICATE_ANSWER>(exp.root.func); exp.root.type = DATALOG_FUNCTION; if (!new_expression(exp.root.func.arg)) exit(EXIT_FAILURE); exp.root.func.arg->type = DATALOG_ANY; exp.root.func.arg->reference_count = 1; return set_function<false>(*exp.root.func.arg, value); } else if (exp.root.type == DATALOG_FUNCTION) { if (exp.root.func.function == DATALOG_LABEL_WILDCARD) { if (exp.root.func.is_excluded(PREDICATE_ANSWER)) return false; exp.root.func.function = PREDICATE_ANSWER; if (exp.root.func.excluded_count > 0) { free(exp.root.func.excluded); exp.root.func.excluded_count = 0; } set_function_variables<PREDICATE_ANSWER>(exp.root.func); } else if (exp.root.func.function != PREDICATE_ANSWER) return false; if (exp.root.func.arg->reference_count == 1) { arg = exp.root.func.arg; } else { if (!init(arg, *exp.root.func.arg)) exit(EXIT_FAILURE); free(*exp.root.func.arg); exp.root.func.arg = arg; } return set_function<false>(*exp.root.func.arg, value); } else return false; case datalog_expression_root::FEATURE_HAS_FUNCTION: return set_has_function(exp.root, value); case datalog_expression_root::FEATURE_HAS_FUNCTION_NOT: return set_has_function(exp.root, value, PREDICATES_NOT); case datalog_expression_root::FEATURE_HAS_FUNCTION_COUNT_NOT: return set_has_function(exp.root, value, PREDICATES_COUNT_NOT); case datalog_expression_root::FEATURE_HAS_FUNCTION_ANSWER: if (exp.root.type == DATALOG_ANY || exp.root.type == DATALOG_NON_EMPTY) { exp.root.func.function = PREDICATE_ANSWER; exp.root.func.excluded_count = 0; set_function_variables<PREDICATE_ANSWER>(exp.root.func); exp.root.type = DATALOG_FUNCTION; if (!new_expression(exp.root.func.arg)) exit(EXIT_FAILURE); exp.root.func.arg->type = DATALOG_ANY; exp.root.func.arg->reference_count = 1; return set_has_function(*exp.root.func.arg, value); } else if (exp.root.type == DATALOG_FUNCTION) { if (exp.root.func.function == DATALOG_LABEL_WILDCARD) { if (exp.root.func.is_excluded(PREDICATE_ANSWER)) return false; exp.root.func.function = PREDICATE_ANSWER; if (exp.root.func.excluded_count > 0) { free(exp.root.func.excluded); exp.root.func.excluded_count = 0; } set_function_variables<PREDICATE_ANSWER>(exp.root.func); } else if (exp.root.func.function != PREDICATE_ANSWER) return false; if (exp.root.func.arg->reference_count == 1) { arg = exp.root.func.arg; } else { if (!init(arg, *exp.root.func.arg)) exit(EXIT_FAILURE); free(*exp.root.func.arg); exp.root.func.arg = arg; } return set_has_function(*exp.root.func.arg, value); } else return false; case datalog_expression_root::FEATURE_PREDICATE: return set_predicate<0, true, true>(exp.root, value); case datalog_expression_root::FEATURE_PREDICATE_ONLY: return set_predicate<0, true, false>(exp.root, value); case datalog_expression_root::FEATURE_FIRST_PREDICATE: return set_predicate<0, false, true>(exp.root, value); case datalog_expression_root::FEATURE_SECOND_PREDICATE: return set_predicate<1, false, true>(exp.root, value); case datalog_expression_root::FEATURE_THIRD_PREDICATE: return set_predicate<2, false, true>(exp.root, value); case datalog_expression_root::FEATURE_LAST_PREDICATE: return set_right_predicate<0>(exp.root, value); case datalog_expression_root::FEATURE_DIRECTION: return set_direction<true>(exp.root, value); case datalog_expression_root::FEATURE_DIRECTION_ROOT: return set_direction<false>(exp.root, value); case datalog_expression_root::FEATURE_CONSTANT: return set_constant<true>(exp.root, value); case datalog_expression_root::FEATURE_PREDICATE_ARITY: return set_predicate_arity(exp.root, value); case datalog_expression_root::FEATURE_ARG1: return set_arg_constant<0, false>(exp.root, value); case datalog_expression_root::FEATURE_ARG2: return set_arg_constant<1, false>(exp.root, value); case datalog_expression_root::FEATURE_ARG3: return set_arg_constant<2, false>(exp.root, value); case datalog_expression_root::FEATURE_ARG1_ONLY: return set_arg_constant<0, true>(exp.root, value); case datalog_expression_root::FEATURE_ARG2_ONLY: return set_arg_constant<1, true>(exp.root, value); case datalog_expression_root::FEATURE_ARG3_ONLY: return set_arg_constant<2, true>(exp.root, value); case datalog_expression_root::FEATURE_ARG2_ARITY: return set_arg_arity<1>(exp.root, value); case datalog_expression_root::FEATURE_NUMBER: return intersect(exp.concord, exp.concord, static_cast<grammatical_number>(value + 1 - NUMBER_OFFSET)); case datalog_expression_root::FEATURE_INFLECTION: return intersect(exp.inf, exp.inf, static_cast<inflection>(value + 1 - INFLECTION_OFFSET)); case datalog_expression_root::FEATURE_NULL: break; } fprintf(stderr, "set_feature ERROR: Unrecognized semantic feature.\n"); exit(EXIT_FAILURE); } bool exclude_function(datalog_expression& exp, const unsigned int* values, unsigned int count) { if (exp.type != DATALOG_FUNCTION) return false; if (exp.func.function == DATALOG_LABEL_WILDCARD) { if (!exp.func.exclude(values, count)) exit(EXIT_FAILURE); return (exp.func.excluded_count < NUM_PREDICATES); } else { return (index_of(exp.func.function, values, count) == count); } } template<unsigned int Index> bool exclude_predicates(datalog_expression& exp, const unsigned int* values, unsigned int count) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { return false; } else if (exp.type == DATALOG_PREDICATE) { if (Index != 0) return last_index_of(DATALOG_LABEL_EMPTY, values, count) == static_cast<unsigned int>(-1); if (exp.pred.function == DATALOG_LABEL_WILDCARD) { if (!exp.pred.exclude(values, count)) exit(EXIT_FAILURE); } else return index_of(exp.pred.function, values, count) == count; } else if (exp.type == DATALOG_FUNCTION) { datalog_expression* arg; if (exp.func.arg->reference_count == 1) { arg = exp.func.arg; } else { if (!init(arg, *exp.func.arg)) exit(EXIT_FAILURE); free(*exp.func.arg); exp.func.arg = arg; } return exclude_predicates<Index>(*arg, values, count); } else if (exp.type == DATALOG_TUPLE) { if (exp.tuple.position != POSITION_EXACT) return false; else if (Index >= exp.tuple.elements.length) return last_index_of(DATALOG_LABEL_EMPTY, values, count) == static_cast<unsigned int>(-1); datalog_expression* element; if (exp.tuple.elements[Index]->reference_count == 1) { element = exp.tuple.elements[Index]; } else { if (!init(element, *exp.tuple.elements[Index])) exit(EXIT_FAILURE); free(*exp.tuple.elements[Index]); exp.tuple.elements[Index] = element; } if (element->type == DATALOG_ANY || element->type == DATALOG_NON_EMPTY) { return false; } else if (element->type == DATALOG_PREDICATE) { if (element->pred.function == DATALOG_LABEL_WILDCARD) { if (!element->pred.exclude(values, count)) exit(EXIT_FAILURE); } else return index_of(exp.pred.function, values, count) == count; } else if (element->type == DATALOG_FUNCTION) { if (element->func.function == DATALOG_LABEL_WILDCARD) { if (!element->func.exclude(values, count)) exit(EXIT_FAILURE); } else return index_of(exp.func.function, values, count) == count; } else { return false; } } else if (exp.type == DATALOG_EMPTY) { return last_index_of(DATALOG_LABEL_EMPTY, values, count) == static_cast<unsigned int>(-1); } else { return false; } return true; } template<unsigned int Index> bool exclude_right_predicates(datalog_expression& exp, const unsigned int* values, unsigned int count) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { return false; } else if (exp.type == DATALOG_PREDICATE) { if (Index != 0) return last_index_of(DATALOG_LABEL_EMPTY, values, count) == static_cast<unsigned int>(-1); if (exp.pred.function == DATALOG_LABEL_WILDCARD) { if (!exp.pred.exclude(values, count)) exit(EXIT_FAILURE); } else return index_of(exp.pred.function, values, count) == count; } else if (exp.type == DATALOG_FUNCTION) { datalog_expression* arg; if (exp.func.arg->reference_count == 1) { arg = exp.func.arg; } else { if (!init(arg, *exp.func.arg)) exit(EXIT_FAILURE); free(*exp.func.arg); exp.func.arg = arg; } return exclude_right_predicates<Index>(*arg, values, count); } else if (exp.type == DATALOG_TUPLE) { if (exp.tuple.position != POSITION_EXACT) return false; else if (Index >= exp.tuple.elements.length) return last_index_of(DATALOG_LABEL_EMPTY, values, count) == static_cast<unsigned int>(-1); datalog_expression* element; if (exp.tuple.elements[exp.tuple.elements.length - Index - 1]->reference_count == 1) { element = exp.tuple.elements[exp.tuple.elements.length - Index - 1]; } else { if (!init(element, *exp.tuple.elements[exp.tuple.elements.length - Index - 1])) exit(EXIT_FAILURE); free(*exp.tuple.elements[exp.tuple.elements.length - Index - 1]); exp.tuple.elements[exp.tuple.elements.length - Index - 1] = element; } if (element->type == DATALOG_ANY || element->type == DATALOG_NON_EMPTY) { return false; } else if (element->type == DATALOG_PREDICATE) { if (element->pred.function == DATALOG_LABEL_WILDCARD) { if (!element->pred.exclude(values, count)) exit(EXIT_FAILURE); } else return index_of(exp.pred.function, values, count) == count; } else if (element->type == DATALOG_FUNCTION) { if (element->func.function == DATALOG_LABEL_WILDCARD) { if (!element->func.exclude(values, count)) exit(EXIT_FAILURE); } else return index_of(exp.func.function, values, count) == count; } else { return false; } } else if (exp.type == DATALOG_EMPTY) { return last_index_of(DATALOG_LABEL_EMPTY, values, count) == static_cast<unsigned int>(-1); } else { return false; } return true; } inline bool exclude_constant(datalog_expression& exp, const unsigned int* values, unsigned int count) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { exp.type = DATALOG_CONSTANT; exp.constant.label = DATALOG_LABEL_WILDCARD; if (count > 0 && !init_excluded(exp.constant.excluded, values, count)) return false; exp.constant.excluded_count = count; } else if (exp.type == DATALOG_CONSTANT) { if (exp.constant.label == DATALOG_LABEL_WILDCARD) { if (!exp.constant.exclude(values, count)) exit(EXIT_FAILURE); } else if (index_of(exp.constant.label, values, count) < count) return false; } else if (exp.type == DATALOG_PREDICATE) { if (exp.pred.function == DATALOG_LABEL_WILDCARD) { if (!exp.pred.exclude(values, count)) exit(EXIT_FAILURE); } else if (index_of(exp.pred.function, values, count) < count) return false; } else if (exp.type == DATALOG_STRING && exp.str.length > 0) { return false; /* disallow ambiguity in strings, so prune this part of the search */ } else { return false; } return true; } template<unsigned int Index> inline bool exclude_arg_constant(datalog_expression& exp, const unsigned int* values, unsigned int count) { if (exp.type == DATALOG_ANY || exp.type == DATALOG_NON_EMPTY) { return false; /* this feature is only used in one nonterminal, so we can prune some unnecessary searching */ } else if (exp.type == DATALOG_PREDICATE) { if (exp.pred.args[Index] == NULL) return (index_of(DATALOG_LABEL_EMPTY, values, count) == count); datalog_expression* arg; if (exp.pred.args[Index]->reference_count == 1) { arg = exp.pred.args[Index]; } else { if (!init(arg, *exp.pred.args[Index])) exit(EXIT_FAILURE); free(*exp.pred.args[Index]); exp.pred.args[Index] = arg; } return exclude_constant(*arg, values, count); } else if (exp.type == DATALOG_EMPTY) { return (index_of(ARG_OTHER, values, count) == count); } return true; } bool exclude_features(datalog_expression_root::feature feature, datalog_expression_root& exp, const unsigned int* values, unsigned int count) { switch (feature) { case datalog_expression_root::FEATURE_FUNCTION: case datalog_expression_root::FEATURE_FUNCTION_ONLY: return exclude_function(exp.root, values, count); case datalog_expression_root::FEATURE_FUNCTION_ANSWER: case datalog_expression_root::FEATURE_HAS_FUNCTION_ANSWER: return false; /* this feature is only used in the root nonterminal, so we can prune some unnecessary searching */ case datalog_expression_root::FEATURE_HAS_FUNCTION: case datalog_expression_root::FEATURE_HAS_FUNCTION_NOT: case datalog_expression_root::FEATURE_HAS_FUNCTION_COUNT_NOT: return false; case datalog_expression_root::FEATURE_PREDICATE: case datalog_expression_root::FEATURE_PREDICATE_ONLY: return false; /* this feature is only used in preterminals, so we can prune some unnecessary searching */ case datalog_expression_root::FEATURE_FIRST_PREDICATE: return exclude_predicates<0>(exp.root, values, count); case datalog_expression_root::FEATURE_SECOND_PREDICATE: return exclude_predicates<1>(exp.root, values, count); case datalog_expression_root::FEATURE_THIRD_PREDICATE: return exclude_predicates<2>(exp.root, values, count); case datalog_expression_root::FEATURE_LAST_PREDICATE: return exclude_right_predicates<0>(exp.root, values, count); case datalog_expression_root::FEATURE_DIRECTION: case datalog_expression_root::FEATURE_DIRECTION_ROOT: return false; /* this feature is only used in preterminals, so we can prune some unnecessary searching */ case datalog_expression_root::FEATURE_CONSTANT: return exclude_constant(exp.root, values, count); case datalog_expression_root::FEATURE_PREDICATE_ARITY: return false; case datalog_expression_root::FEATURE_ARG1: case datalog_expression_root::FEATURE_ARG1_ONLY: return exclude_arg_constant<0>(exp.root, values, count); case datalog_expression_root::FEATURE_ARG2: case datalog_expression_root::FEATURE_ARG2_ONLY: return exclude_arg_constant<1>(exp.root, values, count); case datalog_expression_root::FEATURE_ARG3: case datalog_expression_root::FEATURE_ARG3_ONLY: return exclude_arg_constant<2>(exp.root, values, count); case datalog_expression_root::FEATURE_ARG2_ARITY: return false; case datalog_expression_root::FEATURE_NUMBER: case datalog_expression_root::FEATURE_INFLECTION: return false; case datalog_expression_root::FEATURE_NULL: break; } fprintf(stderr, "exclude_features ERROR: Unrecognized semantic feature.\n"); exit(EXIT_FAILURE); } bool intersect_labels( unsigned int& dst, unsigned int*& dst_excluded, unsigned int& dst_excluded_count, unsigned int first, unsigned int* first_excluded, unsigned int first_excluded_count, unsigned int second, unsigned int* second_excluded, unsigned int second_excluded_count) { if (first == DATALOG_LABEL_WILDCARD) { if (second == DATALOG_LABEL_WILDCARD) { unsigned int total = first_excluded_count + second_excluded_count; dst = DATALOG_LABEL_WILDCARD; dst_excluded_count = 0; if (total > 0) { dst_excluded = (unsigned int*) malloc(sizeof(unsigned int) * total); if (dst_excluded == NULL) { fprintf(stderr, "intersect_label ERROR: Out of memory.\n"); return false; } set_union(dst_excluded, dst_excluded_count, first_excluded, first_excluded_count, second_excluded, second_excluded_count); } } else { if (index_of(second, first_excluded, first_excluded_count) < first_excluded_count) return false; dst = second; dst_excluded_count = 0; } } else if (second == DATALOG_LABEL_WILDCARD) { if (index_of(first, second_excluded, second_excluded_count) < second_excluded_count) return false; dst = first; dst_excluded_count = 0; } else if (first == second) { dst = first; dst_excluded_count = 0; } else { return false; } return true; } unsigned int intersect_variable(unsigned int first, unsigned int second, array<unsigned int>& first_variables, array<unsigned int>& second_variables, array<unsigned int>& dst_variables) { if (!ensure_variable_map_capacity(first_variables, first) || !ensure_variable_map_capacity(second_variables, second)) exit(EXIT_FAILURE); unsigned int i, j; for (i = first; i > 0; i--) if (first_variables[i] != 0) break; for (j = second; j > 0; j--) if (second_variables[j] != 0) break; unsigned int first_variable = first_variables[i] + first - i; unsigned int second_variable = second_variables[j] + second - j; unsigned int new_variable; if (first_variables[first] == 0) { /* first variable is unmapped */ if (second_variables[second] == 0) { new_variable = max(first_variable, second_variable); first_variables[first] = new_variable; second_variables[second] = new_variable; } else { if (index_of(second_variable, first_variables.data, first_variables.capacity) < first_variables.capacity) return 0; first_variables[first] = second_variable; new_variable = second_variable; } } else if (second_variables[second] == 0) { if (index_of(first_variable, second_variables.data, second_variables.capacity) < second_variables.capacity) return 0; second_variables[second] = first_variable; new_variable = first_variable; } else if (first_variable == second_variable) { new_variable = first_variable; } else { return 0; } if (!ensure_variable_map_capacity(dst_variables, new_variable)) exit(EXIT_FAILURE); if (dst_variables[new_variable] == 0) dst_variables[new_variable] = 1; return new_variable; } inline bool intersect(datalog_expression*& intersection, const datalog_expression* first, const datalog_expression* second, array<unsigned int>& first_variables, array<unsigned int>& second_variables, array<unsigned int>& dst_variables) { if (!new_expression(intersection)) return false; if (!intersect(*intersection, first, second, first_variables, second_variables, dst_variables)) { free(intersection); return false; } return true; } bool intersect(datalog_expression& intersection, const datalog_expression* first, const datalog_expression* second, array<unsigned int>& first_variables, array<unsigned int>& second_variables, array<unsigned int>& dst_variables) { if (first->type == DATALOG_EMPTY) { if (!can_be_empty(*second)) return false; return init(intersection, *first, first_variables, dst_variables); } else if (second->type == DATALOG_EMPTY) { if (!can_be_empty(*first)) return false; intersection.type = DATALOG_EMPTY; intersection.reference_count = 1; } else if (first->type == DATALOG_ANY) { return init(intersection, *second, second_variables, dst_variables); } else if (second->type == DATALOG_ANY) { return init(intersection, *first, first_variables, dst_variables); } else if (first->type == DATALOG_NON_EMPTY) { if (!init(intersection, *second, second_variables, dst_variables)) return false; if (intersection.type == DATALOG_ANY) intersection.type = DATALOG_NON_EMPTY; } else if (second->type == DATALOG_NON_EMPTY) { if (!init(intersection, *first, first_variables, dst_variables)) return false; if (intersection.type == DATALOG_ANY) intersection.type = DATALOG_NON_EMPTY; } else if (first->type == DATALOG_TUPLE) { if (second->type == DATALOG_TUPLE) { tuple_position position; unsigned int tuple_length; if (first->tuple.position == POSITION_LEFT) { if (second->tuple.position == POSITION_LEFT) { tuple_length = max(first->tuple.elements.length, second->tuple.elements.length); position = POSITION_LEFT; } else if (second->tuple.position == POSITION_EXACT) { if (first->tuple.elements.length > second->tuple.elements.length) return false; tuple_length = second->tuple.elements.length; position = POSITION_EXACT; } else return false; } else if (first->tuple.position == POSITION_RIGHT) { if (second->tuple.position == POSITION_RIGHT) { tuple_length = max(first->tuple.elements.length, second->tuple.elements.length); position = POSITION_RIGHT; } else if (second->tuple.position == POSITION_EXACT) { if (first->tuple.elements.length > second->tuple.elements.length) return false; tuple_length = second->tuple.position; position = POSITION_EXACT; } else return false; } else { if (second->tuple.position == POSITION_EXACT) { if (first->tuple.elements.length != second->tuple.elements.length) return false; tuple_length = first->tuple.elements.length; position = POSITION_EXACT; } else { if (first->tuple.elements.length < second->tuple.elements.length) return false; tuple_length = first->tuple.elements.length; position = POSITION_EXACT; } } unsigned int intersection_length = min(first->tuple.elements.length, second->tuple.elements.length); if (!init_tuple(intersection, position, tuple_length)) return false; if (first->tuple.position == POSITION_RIGHT || second->tuple.position == POSITION_RIGHT) { if (first->tuple.elements.length < second->tuple.elements.length) { for (unsigned int i = 0; i < tuple_length - first->tuple.elements.length; i++) { if (!init(intersection.tuple.elements[i], second->tuple.elements[i], second_variables, dst_variables)) { free(intersection); return false; } intersection.tuple.elements.length++; } } else { for (unsigned int i = 0; i < tuple_length - second->tuple.elements.length; i++) { if (!init(intersection.tuple.elements[i], first->tuple.elements[i], first_variables, dst_variables)) { free(intersection); return false; } intersection.tuple.elements.length++; } } for (unsigned int i = 0; i < intersection_length; i++) { if (!intersect(intersection.tuple.elements[tuple_length - intersection_length + i], first->tuple.elements[first->tuple.elements.length - intersection_length + i], second->tuple.elements[second->tuple.elements.length - intersection_length + i], first_variables, second_variables, dst_variables)) { free(intersection); return false; } intersection.tuple.elements.length++; } } else { for (unsigned int i = 0; i < intersection_length; i++) { if (!intersect(intersection.tuple.elements[i], first->tuple.elements[i], second->tuple.elements[i], first_variables, second_variables, dst_variables)) { free(intersection); return false; } intersection.tuple.elements.length++; } if (first->tuple.elements.length < second->tuple.elements.length) { for (unsigned int i = 0; i < tuple_length - first->tuple.elements.length; i++) { if (!init(intersection.tuple.elements[intersection_length + i], second->tuple.elements[intersection_length + i], second_variables, dst_variables)) { free(intersection); return false; } intersection.tuple.elements.length++; } } else { for (unsigned int i = 0; i < tuple_length - second->tuple.elements.length; i++) { if (!init(intersection.tuple.elements[intersection_length + i], first->tuple.elements[intersection_length + i], first_variables, dst_variables)) { free(intersection); return false; } intersection.tuple.elements.length++; } } } } else if (second->type == DATALOG_PREDICATE || second->type == DATALOG_FUNCTION) { if (first->tuple.elements.length == 0) { if (first->tuple.position == POSITION_EXACT) return false; return init(intersection, *second, second_variables, dst_variables); } else if (first->tuple.elements.length > 1) { return false; } else { return intersect(intersection, first->tuple.elements[0], second, first_variables, second_variables, dst_variables); } } else { return false; } } else if (first->type == DATALOG_FUNCTION) { if (second->type == DATALOG_FUNCTION) { if (!intersect_labels( intersection.func.function, intersection.func.excluded, intersection.func.excluded_count, first->func.function, first->func.excluded, first->func.excluded_count, second->func.function, second->func.excluded, second->func.excluded_count)) { return false; } intersection.func.arg = NULL; intersection.type = DATALOG_FUNCTION; intersection.reference_count = 1; unsigned int i; for (i = 0; i < array_length(first->func.vars); i++) { if (first->func.vars[i] == 0) { if (second->func.vars[i] != 0) { if (!init(intersection.func.vars[i], second->func.vars[i], second_variables, dst_variables)) return false; } else break; } else if (second->func.vars[i] == 0) { if (!init(intersection.func.vars[i], first->func.vars[i], first_variables, dst_variables)) return false; } else { intersection.func.vars[i] = intersect_variable( first->func.vars[i], second->func.vars[i], first_variables, second_variables, dst_variables); if (intersection.func.vars[i] == 0) { free(intersection); return false; } } } for (; i < array_length(first->func.vars); i++) intersection.func.vars[i] = 0; if (!intersect(intersection.func.arg, first->func.arg, second->func.arg, first_variables, second_variables, dst_variables)) { intersection.func.arg = NULL; free(intersection); return false; } } else { return false; } } else if (first->type == DATALOG_PREDICATE) { if (second->type == DATALOG_PREDICATE) { if (!intersect_labels( intersection.pred.function, intersection.pred.excluded, intersection.pred.excluded_count, first->pred.function, first->pred.excluded, first->pred.excluded_count, second->pred.function, second->pred.excluded, second->pred.excluded_count)) { return false; } intersection.type = DATALOG_PREDICATE; intersection.reference_count = 1; for (unsigned int i = 0; i < array_length(intersection.pred.args); i++) intersection.pred.args[i] = NULL; for (unsigned int i = 0; i < array_length(intersection.pred.args); i++) { if (first->pred.args[i] == NULL) { if (second->pred.args[i] != NULL && second->pred.args[i]->type != DATALOG_ANY) { free(intersection); return false; } else continue; } else if (second->pred.args[i] == NULL) { if (first->pred.args[i]->type != DATALOG_ANY) { free(intersection); return false; } else continue; } if (!intersect(intersection.pred.args[i], first->pred.args[i], second->pred.args[i], first_variables, second_variables, dst_variables)) { intersection.pred.args[i] = NULL; free(intersection); return false; } } } else if (second->type == DATALOG_TUPLE) { if (second->tuple.elements.length == 0) { if (second->tuple.position == POSITION_EXACT) return false; return init(intersection, *first, first_variables, dst_variables); } else if (second->tuple.elements.length > 1) { return false; } else { return intersect(intersection, first, second->tuple.elements[0], first_variables, second_variables, dst_variables); } } else { return false; } } else if (first->type == DATALOG_VARIABLE) { if (second->type == DATALOG_VARIABLE) { unsigned int new_variable = intersect_variable( first->variable, second->variable, first_variables, second_variables, dst_variables); if (new_variable == 0) return false; intersection.variable = new_variable; intersection.type = DATALOG_VARIABLE; intersection.reference_count = 1; } else { return false; } } else if (first->type == DATALOG_CONSTANT) { if (second->type == DATALOG_CONSTANT) { if (!intersect_labels( intersection.constant.label, intersection.constant.excluded, intersection.constant.excluded_count, first->constant.label, first->constant.excluded, first->constant.excluded_count, second->constant.label, second->constant.excluded, second->constant.excluded_count)) { return false; } intersection.type = DATALOG_CONSTANT; intersection.reference_count = 1; } else { return false; } } else if (first->type == DATALOG_INTEGER) { if (second->type == DATALOG_INTEGER) { if (first->integer != second->integer) return false; intersection.integer = first->integer; intersection.type = DATALOG_INTEGER; intersection.reference_count = 1; } else { return false; } } else if (first->type == DATALOG_STRING) { if (second->type == DATALOG_STRING) { if (first->str.length == 1 && first->str[0] == DATALOG_STRING_LABEL_WILDCARD) { intersection.str = second->str; } else if (second->str.length == 1 && second->str[0] == DATALOG_STRING_LABEL_WILDCARD) { intersection.str = first->str; } else if (first->str == second->str) { intersection.str = first->str; } else { return false; } intersection.type = DATALOG_STRING; intersection.reference_count = 1; } else { return false; } } else { return false; } return true; } inline bool intersect(datalog_expression& intersection, const datalog_expression* first, const datalog_expression* second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return intersect(intersection, first, second, first_variable_map, second_variable_map, dst_variable_map); } inline bool intersect(datalog_expression*& intersection, const datalog_expression* first, const datalog_expression* second) { if (!new_expression(intersection)) return false; if (!intersect(*intersection, first, second)) { free(intersection); return false; } return true; } inline bool is_subset(const datalog_expression_root& first, const datalog_expression_root& second) { grammatical_number num; if (!intersect(num, first.index, second.index)) return false; if (num != first.index) return false; if (!intersect(num, first.concord, second.concord)) return false; if (num != first.concord) return false; inflection inf; if (!intersect(inf, first.inf, second.inf)) return false; if (inf != first.inf) return false; datalog_expression* intersection; if (!intersect(intersection, &first.root, &second.root)) return false; bool result = (intersection == &first.root || *intersection == first.root); free(*intersection); if (intersection->reference_count == 0) free(intersection); return result; } template<bool KeepHead, bool MergeVariables> inline bool init_variable_maps(const datalog_expression& second, array<bool>& first_variables, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { if (!first_variables.ensure_capacity(first_variable_map.capacity)) exit(EXIT_FAILURE); memset(first_variables.data, 0, sizeof(bool) * first_variables.capacity); for (unsigned int i = 1; i < first_variable_map.capacity; i++) if (first_variable_map[i] != 0) first_variables[first_variable_map[i]] = true; second_variable_map[1] = (KeepHead ? 1 : 2); dst_variable_map[KeepHead ? 1 : 2] = 1; return (!MergeVariables || build_variable_map<KeepHead ? 0 : 1>(second, second_variable_map, dst_variable_map)); } template<bool MergeVariables> inline bool check_variable_overlap(datalog_expression& inverse, array<bool>& first_variables, const array<unsigned int>& second_variable_map) { unsigned int unmapped_second_variables = 0; for (unsigned int i = 1; i < second_variable_map.capacity; i++) { if (second_variable_map[i] != 0) { if (second_variable_map[i] < first_variables.capacity && first_variables[second_variable_map[i]]) { if (!MergeVariables && second_variable_map[i] != 1) { free(inverse); return false; } first_variables[second_variable_map[i]] = false; } else if (second_variable_map[i] != 1) { unmapped_second_variables++; } } } unsigned int unmapped_first_variables = 0; for (unsigned int i = 2; MergeVariables && i < first_variables.capacity; i++) if (first_variables[i]) unmapped_first_variables++; if (MergeVariables && unmapped_first_variables != 0 && unmapped_second_variables != 0) { free(inverse); return false; } return true; } /* this implements select_left and select_right when 'first' is ANY */ template<unsigned int FieldCount, bool KeepHead, tuple_position Position> bool invert_select_any(datalog_expression& inverse, const datalog_expression& second) { if (second.type == DATALOG_PREDICATE || second.type == DATALOG_FUNCTION) { if (FieldCount != 1 || !init_tuple<FieldCount, Position>(inverse)) return false; inverse.tuple.elements[0] = (datalog_expression*) malloc(sizeof(datalog_expression)); if (inverse.tuple.elements[0] == NULL || (KeepHead && !init(*inverse.tuple.elements[0], second)) || (!KeepHead && !init(*inverse.tuple.elements[0], second, 1))) { if (inverse.tuple.elements[0] != NULL) free(inverse.tuple.elements[0]); fprintf(stderr, "invert_select_any ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length = 1; } else if (second.type == DATALOG_TUPLE) { if (second.tuple.elements.length != FieldCount || !init_tuple<FieldCount, Position>(inverse)) return false; for (unsigned int i = 0; i < FieldCount; i++) { if ((KeepHead && !init(inverse.tuple.elements[i], second.tuple.elements[i])) || (!KeepHead && !init(inverse.tuple.elements[i], second.tuple.elements[i], 1))) { fprintf(stderr, "invert_select_any ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } } else { return false; } return true; } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_select_left(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { array<bool> first_variables = array<bool>(8); memset(first_variables.data, 0, sizeof(bool) * first_variables.capacity); if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { return invert_select_any<FieldCount, KeepHead, POSITION_LEFT>(inverse, second); } else if (first.type == DATALOG_PREDICATE) { if (FieldCount != 1) return false; /* construct a variable map from the remaining elements of 'first' since we're not intersecting them */ if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } if (second.type == DATALOG_PREDICATE) { if (!intersect(inverse, &first, &second, first_variable_map, second_variable_map, dst_variable_map)) return false; } else if (second.type == DATALOG_TUPLE) { if (second.tuple.elements.length != 1) return false; if (!intersect(inverse, &first, second.tuple.elements[0], first_variable_map, second_variable_map, dst_variable_map)) return false; } else { return false; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); apply_variable_map(inverse, dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else if (first.type == DATALOG_TUPLE) { /* construct a variable map from the remaining elements of 'first' since we're not intersecting them */ for (unsigned int i = FieldCount; i < first.tuple.elements.length; i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } if (second.type == DATALOG_PREDICATE || second.type == DATALOG_FUNCTION) { if (FieldCount != 1 || first.tuple.position == POSITION_RIGHT || (first.tuple.position == POSITION_EXACT && first.tuple.elements.length < FieldCount)) return false; else if (!init_tuple(inverse, first.tuple.position, max(FieldCount, (unsigned int) first.tuple.elements.length))) return false; if (first.tuple.elements.length == 0) { if (!init(inverse.tuple.elements[0], second, second_variable_map, dst_variable_map)) { free(inverse); return false; } } else { if (!intersect(inverse.tuple.elements[0], first.tuple.elements[0], &second, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } } inverse.tuple.elements.length = 1; if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); apply_variable_map(*inverse.tuple.elements[0], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else if (second.type == DATALOG_TUPLE) { if (second.tuple.elements.length != FieldCount || first.tuple.position == POSITION_RIGHT || (first.tuple.position == POSITION_EXACT && first.tuple.elements.length < FieldCount)) return false; else if (!init_tuple(inverse, first.tuple.position, max(FieldCount, (unsigned int) first.tuple.elements.length))) return false; inverse.tuple.elements.length = 0; for (unsigned int i = 0; i < min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { if (!intersect(inverse.tuple.elements[i], first.tuple.elements[i], second.tuple.elements[i], first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = first.tuple.elements.length; i < FieldCount; i++) { if (!init(inverse.tuple.elements[i], second.tuple.elements[i], second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < FieldCount; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else { return false; } for (unsigned int i = FieldCount; i < first.tuple.elements.length; i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; } inverse.tuple.elements.length = max(FieldCount, (unsigned int) first.tuple.elements.length); } else { return false; } return check_variable_overlap<MergeVariables>(inverse, first_variables, second_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> inline bool invert_select_left(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return invert_select_left<FieldCount, KeepHead, MergeVariables>( inverse, first, second, first_variable_map, second_variable_map, dst_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_select_right(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { array<bool> first_variables = array<bool>(8); memset(first_variables.data, 0, sizeof(bool) * first_variables.capacity); if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { return invert_select_any<FieldCount, KeepHead, POSITION_RIGHT>(inverse, second); } else if (first.type == DATALOG_PREDICATE) { if (FieldCount != 1) return false; /* construct a variable map from the remaining elements of 'first' since we're not intersecting them */ if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } if (second.type == DATALOG_PREDICATE) { if (!intersect(inverse, &first, &second, first_variable_map, second_variable_map, dst_variable_map)) return false; } else if (second.type == DATALOG_TUPLE) { if (second.tuple.elements.length != 1) return false; if (!intersect(inverse, &first, second.tuple.elements[0], first_variable_map, second_variable_map, dst_variable_map)) return false; inverse.tuple.elements.length++; } else { return false; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); apply_variable_map(inverse, dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else if (first.type == DATALOG_TUPLE) { /* construct a variable map from the remaining elements of 'first' since we're not intersecting them */ for (unsigned int i = 0; i < max(FieldCount, (unsigned int) first.tuple.elements.length) - FieldCount; i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } if (second.type == DATALOG_PREDICATE || second.type == DATALOG_FUNCTION) { if (FieldCount != 1 || first.tuple.position == POSITION_LEFT || (first.tuple.position == POSITION_EXACT && first.tuple.elements.length < FieldCount)) return false; else if (!init_tuple(inverse, first.tuple.position, max(FieldCount, (unsigned int) first.tuple.elements.length))) return false; if (first.tuple.elements.length == 0) { if (!init(inverse.tuple.elements[0], second, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length = FieldCount; } else { for (unsigned int i = 0; i < first.tuple.elements.length - FieldCount; i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; } inverse.tuple.elements.length = first.tuple.elements.length - FieldCount; if (!intersect(inverse.tuple.elements[inverse.tuple.elements.length], first.tuple.elements.last(), &second, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length = first.tuple.elements.length; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); apply_variable_map(*inverse.tuple.elements.last(), dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else if (second.type == DATALOG_TUPLE) { if (second.tuple.elements.length != FieldCount || first.tuple.position == POSITION_LEFT || (first.tuple.position == POSITION_EXACT && first.tuple.elements.length < FieldCount)) return false; else if (!init_tuple(inverse, first.tuple.position, max(FieldCount, (unsigned int) first.tuple.elements.length))) return false; if (first.tuple.elements.length < FieldCount) { for (unsigned int i = 0; i < FieldCount - first.tuple.elements.length; i++) { inverse.tuple.elements[i] = second.tuple.elements[i]; second.tuple.elements[i]->reference_count++; } inverse.tuple.elements.length = FieldCount - first.tuple.elements.length; for (unsigned int i = FieldCount - first.tuple.elements.length; i < FieldCount; i++) { if (!intersect(inverse.tuple.elements[i], first.tuple.elements[i - FieldCount + first.tuple.elements.length], second.tuple.elements[i], first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } } else { for (unsigned int i = 0; i < first.tuple.elements.length - FieldCount; i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; } inverse.tuple.elements.length = first.tuple.elements.length - FieldCount; for (unsigned int i = first.tuple.elements.length - FieldCount; i < first.tuple.elements.length; i++) { if (!intersect(inverse.tuple.elements[i], first.tuple.elements[i], second.tuple.elements[i - first.tuple.elements.length + FieldCount], first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = first.tuple.elements.length - FieldCount; i < first.tuple.elements.length; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else { return false; } } else { return false; } return check_variable_overlap<MergeVariables>(inverse, first_variables, second_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_select_right(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return invert_select_right<FieldCount, KeepHead, MergeVariables>(inverse, first, second, first_variable_map, second_variable_map, dst_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_delete_left(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { array<bool> first_variables = array<bool>(8); memset(first_variables.data, 0, sizeof(bool) * first_variables.capacity); if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (second.type == DATALOG_PREDICATE || second.type == DATALOG_FUNCTION) { if (!init_tuple<FieldCount + 1, POSITION_EXACT>(inverse)) return false; for (unsigned int i = 0; i < FieldCount; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } inverse.tuple.elements.length = FieldCount; inverse.tuple.elements[FieldCount] = (datalog_expression*) malloc(sizeof(datalog_expression)); if (inverse.tuple.elements[FieldCount] == NULL || (KeepHead && !init(*inverse.tuple.elements[FieldCount], second)) || (!KeepHead && !init(*inverse.tuple.elements[FieldCount], second, 1))) { fprintf(stderr, "invert_delete_left ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length = FieldCount + 1; } else if (second.type == DATALOG_TUPLE) { if (second.tuple.position == POSITION_RIGHT) return false; else if (!init_tuple(inverse, second.tuple.position, FieldCount + second.tuple.elements.length)) return false; for (unsigned int i = 0; i < FieldCount; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } inverse.tuple.elements.length = FieldCount; for (unsigned int i = 0; i < second.tuple.elements.length; i++) { if ((KeepHead && !init(inverse.tuple.elements[FieldCount + i], second.tuple.elements[i])) || (!KeepHead && !init(inverse.tuple.elements[FieldCount + i], second.tuple.elements[i], 1))) { fprintf(stderr, "invert_delete_left ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } } else { return false; } } else if (first.type == DATALOG_PREDICATE) { if (FieldCount != 1) return false; if (second.type == DATALOG_EMPTY || (second.type == DATALOG_TUPLE && second.tuple.elements.length == 0)) return init(inverse, first); else return false; } else if (first.type == DATALOG_TUPLE) { if (second.type == DATALOG_PREDICATE || second.type == DATALOG_FUNCTION) { if (first.tuple.position == POSITION_LEFT) { if (first.tuple.elements.length > 1 + FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, max((unsigned int) first.tuple.elements.length, FieldCount + 1))) return false; for (unsigned int i = 0; i < min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } for (unsigned int i = 0; i < min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; } for (unsigned int i = min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount; i++) inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); inverse.tuple.elements.length = FieldCount; if (FieldCount < first.tuple.elements.length) { if (!intersect(inverse.tuple.elements[FieldCount], first.tuple.elements[FieldCount], &second, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); apply_variable_map(*inverse.tuple.elements[FieldCount], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else { if (!init(inverse.tuple.elements[FieldCount], second, second_variable_map, dst_variable_map)) { free(inverse); return false; } } inverse.tuple.elements.length = FieldCount + 1; } else { if (first.tuple.elements.length > 1 + FieldCount) { return false; } else if (first.tuple.position != POSITION_RIGHT && first.tuple.elements.length < 1 + FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, max((unsigned int) first.tuple.elements.length, FieldCount + 1))) return false; for (unsigned int i = 0; i < max(1u, (unsigned int) first.tuple.elements.length) - 1; i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } unsigned int offset = min((unsigned int) (1 + FieldCount - first.tuple.elements.length), FieldCount); for (unsigned int i = 0; i < offset; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } for (unsigned int i = offset; i < FieldCount; i++) { inverse.tuple.elements[i] = first.tuple.elements[i - offset]; first.tuple.elements[i - offset]->reference_count++; } inverse.tuple.elements.length = FieldCount; if (first.tuple.elements.length == 0) { if (!init(inverse.tuple.elements[FieldCount], second, second_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_left ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } } else { if (!intersect(inverse.tuple.elements[FieldCount], first.tuple.elements[first.tuple.elements.length - 1], &second, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); apply_variable_map(*inverse.tuple.elements[FieldCount], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } inverse.tuple.elements.length = FieldCount + 1; } } else if (second.type == DATALOG_EMPTY) { if (first.tuple.position == POSITION_LEFT) { if (first.tuple.elements.length > FieldCount) { return false; } else if (first.tuple.position != POSITION_LEFT && first.tuple.elements.length < FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, FieldCount)) return false; for (unsigned int i = 0; i < min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; } for (unsigned int i = min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount; i++) inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); inverse.tuple.elements.length = FieldCount; for (unsigned int i = FieldCount; i < first.tuple.elements.length; i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; inverse.tuple.elements.length++; } } else { if (first.tuple.elements.length > FieldCount) { return false; } else if (first.tuple.position != POSITION_RIGHT && first.tuple.elements.length < FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, FieldCount)) return false; unsigned int offset = FieldCount - first.tuple.elements.length; for (unsigned int i = 0; i < offset; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } for (unsigned int i = offset; i < FieldCount; i++) { inverse.tuple.elements[i] = first.tuple.elements[i - offset]; first.tuple.elements[i - offset]->reference_count++; } inverse.tuple.elements.length = FieldCount; } } else if (second.type == DATALOG_TUPLE) { if (second.tuple.position == POSITION_LEFT || first.tuple.position == POSITION_LEFT) { if ((first.tuple.position == POSITION_RIGHT && second.tuple.position == POSITION_LEFT) || (first.tuple.position == POSITION_LEFT && second.tuple.position == POSITION_RIGHT)) { return false; } else if (second.tuple.position != POSITION_LEFT && first.tuple.elements.length > second.tuple.elements.length + FieldCount) { return false; } else if (first.tuple.position != POSITION_LEFT && first.tuple.elements.length < second.tuple.elements.length + FieldCount) { return false; } else if (!init_tuple(inverse, (first.tuple.position == POSITION_LEFT && second.tuple.position == POSITION_LEFT) ? POSITION_LEFT : POSITION_EXACT, max(first.tuple.elements.length, FieldCount + second.tuple.elements.length))) return false; for (unsigned int i = 0; i < min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } for (unsigned int i = 0; i < min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; } for (unsigned int i = min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount; i++) inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); inverse.tuple.elements.length = FieldCount; for (unsigned int i = FieldCount; i < min(first.tuple.elements.length, FieldCount + second.tuple.elements.length); i++) { if (!intersect(inverse.tuple.elements[i], first.tuple.elements[i], second.tuple.elements[i - FieldCount], first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = inverse.tuple.elements.length; i < FieldCount + second.tuple.elements.length; i++) { if (!init(inverse.tuple.elements[i], second.tuple.elements[i - FieldCount], second_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_left ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = FieldCount + second.tuple.elements.length; i < first.tuple.elements.length; i++) { if (!init(inverse.tuple.elements[i], first.tuple.elements[i], first_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_left ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount + second.tuple.elements.length; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else { if (second.tuple.position != POSITION_RIGHT && first.tuple.elements.length > second.tuple.elements.length + FieldCount) { return false; } else if (first.tuple.position != POSITION_RIGHT && first.tuple.elements.length < second.tuple.elements.length + FieldCount) { return false; } else if (!init_tuple(inverse, (first.tuple.position == POSITION_RIGHT && second.tuple.position == POSITION_RIGHT) ? POSITION_RIGHT : POSITION_EXACT, max(first.tuple.elements.length, FieldCount + second.tuple.elements.length))) return false; unsigned int offset = min((unsigned int) (max(second.tuple.elements.length + FieldCount, first.tuple.elements.length) - first.tuple.elements.length), FieldCount); for (unsigned int i = 0; i < max(offset, FieldCount) - offset; i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } for (unsigned int i = 0; i < offset; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } for (unsigned int i = offset; i < FieldCount; i++) { inverse.tuple.elements[i] = first.tuple.elements[i - offset]; first.tuple.elements[i - offset]->reference_count++; } inverse.tuple.elements.length = FieldCount; for (unsigned int i = FieldCount; i < max(second.tuple.elements.length + FieldCount, first.tuple.elements.length) - first.tuple.elements.length; i++) { if (!init(inverse.tuple.elements[i], second.tuple.elements[i - FieldCount], second_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_left ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } offset = max((unsigned int) (max(second.tuple.elements.length + FieldCount, first.tuple.elements.length) - first.tuple.elements.length), FieldCount); unsigned int end = min(first.tuple.elements.length, second.tuple.elements.length); for (unsigned int i = 0; i < min(first.tuple.elements.length, second.tuple.elements.length); i++) { if (!intersect(inverse.tuple.elements[offset + i], first.tuple.elements[first.tuple.elements.length - end + i], second.tuple.elements[second.tuple.elements.length - end + i], first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = FieldCount; i < inverse.tuple.elements.length; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } } else { return false; } } else { return false; } return check_variable_overlap<MergeVariables>(inverse, first_variables, second_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> inline bool invert_delete_left(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return invert_delete_left<FieldCount, KeepHead, MergeVariables>( inverse, first, second, first_variable_map, second_variable_map, dst_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_delete_right(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { array<bool> first_variables = array<bool>(8); memset(first_variables.data, 0, sizeof(bool) * first_variables.capacity); if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (second.type == DATALOG_PREDICATE || second.type == DATALOG_FUNCTION) { if (!init_tuple<FieldCount + 1, POSITION_EXACT>(inverse)) return false; inverse.tuple.elements[0] = (datalog_expression*) malloc(sizeof(datalog_expression)); if (inverse.tuple.elements[0] == NULL || (KeepHead && !init(*inverse.tuple.elements[0], second)) || (!KeepHead && !init(*inverse.tuple.elements[0], second, 1))) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length = FieldCount; for (unsigned int i = 1; i < FieldCount + 1; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } inverse.tuple.elements.length = FieldCount + 1; } else if (second.type == DATALOG_TUPLE) { if (second.tuple.position == POSITION_LEFT) return false; else if (!init_tuple(inverse, second.tuple.position, FieldCount + second.tuple.elements.length)) return false; for (unsigned int i = 0; i < second.tuple.elements.length; i++) { if ((KeepHead && !init(inverse.tuple.elements[i], second.tuple.elements[i])) || (!KeepHead && !init(inverse.tuple.elements[i], second.tuple.elements[i], 1))) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = second.tuple.elements.length; i < second.tuple.elements.length + FieldCount; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } inverse.tuple.elements.length = second.tuple.elements.length + FieldCount; } else if (second.type == DATALOG_EMPTY) { if (!init_tuple(inverse, POSITION_EXACT, FieldCount)) return false; for (unsigned int i = 0; i < FieldCount; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } inverse.tuple.elements.length = FieldCount; } else { return false; } } else if (first.type == DATALOG_PREDICATE) { if (FieldCount != 1) return false; if (second.type == DATALOG_EMPTY || (second.type == DATALOG_TUPLE && second.tuple.elements.length == 0)) return init(inverse, first); else return false; } else if (first.type == DATALOG_TUPLE) { if (second.type == DATALOG_PREDICATE || second.type == DATALOG_FUNCTION) { if (first.tuple.position == POSITION_RIGHT) { if (first.tuple.elements.length > 1 + FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, FieldCount + 1)) return false; for (unsigned int i = FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount; i++) { if (!build_variable_map( *first.tuple.elements[i - (FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length))], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } if (first.tuple.elements.length == FieldCount + 1) { if (!intersect(inverse.tuple.elements[0], first.tuple.elements[0], &second, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } } else { if (!init(inverse.tuple.elements[0], second, second_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } } inverse.tuple.elements.length = 1; for (unsigned int i = 0; i < FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { inverse.tuple.elements[1 + i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; inverse.tuple.elements.length++; } for (unsigned int i = FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount; i++) { if (!init(inverse.tuple.elements[1 + i], first.tuple.elements[i - (FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length))], first_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < FieldCount + 1; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else { if (first.tuple.elements.length > 1 + FieldCount) { return false; } else if (first.tuple.position != POSITION_LEFT && first.tuple.elements.length < 1 + FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, FieldCount + 1)) return false; for (unsigned int i = 1; i < first.tuple.elements.length; i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length = 0; if (first.tuple.elements.length > 0) { if (!intersect(inverse.tuple.elements[0], first.tuple.elements[0], &second, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } } else { if (!init(inverse.tuple.elements[0], second.tuple.elements[0], second_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } } inverse.tuple.elements.length = 1; for (unsigned int i = 1; i < first.tuple.elements.length; i++) { if (!init(inverse.tuple.elements[i], first.tuple.elements[i], first_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = max((unsigned int) first.tuple.elements.length, 1u); i < max((unsigned int) first.tuple.elements.length, 1 + FieldCount); i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; inverse.tuple.elements.length++; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < first.tuple.elements.length; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } } else if (second.type == DATALOG_EMPTY) { if (first.tuple.position == POSITION_RIGHT) { if (first.tuple.elements.length > FieldCount) { return false; } else if (first.tuple.position != POSITION_RIGHT && first.tuple.elements.length < FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, FieldCount)) return false; for (unsigned int i = 0; i < FieldCount - first.tuple.elements.length; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; inverse.tuple.elements.length++; } for (unsigned int i = FieldCount - first.tuple.elements.length; i < FieldCount; i++) { inverse.tuple.elements[i] = first.tuple.elements[i - (FieldCount - first.tuple.elements.length)]; inverse.tuple.elements[i]->reference_count++; inverse.tuple.elements.length++; } } else { if (first.tuple.elements.length > FieldCount) { return false; } else if (first.tuple.position != POSITION_LEFT && first.tuple.elements.length < FieldCount) { return false; } else if (!init_tuple(inverse, POSITION_EXACT, FieldCount)) return false; for (unsigned int i = 0; i < first.tuple.elements.length; i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; inverse.tuple.elements.length++; } for (unsigned int i = first.tuple.elements.length; i < FieldCount; i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; inverse.tuple.elements.length++; } } } else if (second.type == DATALOG_TUPLE) { if (second.tuple.position == POSITION_RIGHT || first.tuple.position == POSITION_RIGHT) { if ((first.tuple.position == POSITION_RIGHT && second.tuple.position == POSITION_LEFT) || (first.tuple.position == POSITION_LEFT && second.tuple.position == POSITION_RIGHT)) { return false; } else if (second.tuple.position != POSITION_RIGHT && first.tuple.elements.length > second.tuple.elements.length + FieldCount) { return false; } else if (first.tuple.position != POSITION_RIGHT && first.tuple.elements.length < second.tuple.elements.length + FieldCount) { return false; } else if (!init_tuple(inverse, (first.tuple.position == POSITION_RIGHT && second.tuple.position == POSITION_RIGHT) ? POSITION_RIGHT : POSITION_EXACT, max(first.tuple.elements.length, FieldCount + second.tuple.elements.length))) return false; unsigned int offset = first.tuple.elements.length - min(first.tuple.elements.length, second.tuple.elements.length + FieldCount); for (unsigned int i = 0; i < offset; i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } for (unsigned int i = FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount; i++) { if (!build_variable_map(*first.tuple.elements[i - (FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length))], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } for (unsigned int i = 0; i < offset; i++) { inverse.tuple.elements[i] = first.tuple.elements[i]; first.tuple.elements[i]->reference_count++; } inverse.tuple.elements.length = offset; unsigned int next; if (first.tuple.elements.length < FieldCount) next = second.tuple.elements.length; else if (first.tuple.elements.length < FieldCount + second.tuple.elements.length) next = FieldCount + second.tuple.elements.length - first.tuple.elements.length; else next = offset; for (unsigned int i = offset; i < next; i++) { if (!init(inverse.tuple.elements[i], second.tuple.elements[i - offset], second_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } unsigned int end, first_offset, second_offset; if (first.tuple.elements.length < FieldCount) { end = next; } else if (first.tuple.elements.length < FieldCount + second.tuple.elements.length) { end = second.tuple.elements.length; first_offset = next; second_offset = 0; } else { end = first.tuple.elements.length - FieldCount; first_offset = 0; second_offset = next; } for (unsigned int i = next; i < end; i++) { if (!intersect(inverse.tuple.elements[i], first.tuple.elements[i - first_offset], second.tuple.elements[i - second_offset], first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = 0; i < FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); i++) { inverse.tuple.elements[end + i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; inverse.tuple.elements.length++; } for (unsigned int i = FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length); i < FieldCount; i++) { if (!init(inverse.tuple.elements[end + i], first.tuple.elements[i - (FieldCount - min(FieldCount, (unsigned int) first.tuple.elements.length))], first_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = offset; i < end; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } else { if (second.tuple.position != POSITION_LEFT && first.tuple.elements.length > second.tuple.elements.length + FieldCount) { return false; } else if (first.tuple.position != POSITION_LEFT && first.tuple.elements.length < second.tuple.elements.length + FieldCount) { return false; } else if (!init_tuple(inverse, (first.tuple.position == POSITION_LEFT && second.tuple.position == POSITION_LEFT) ? POSITION_RIGHT : POSITION_EXACT, max(first.tuple.elements.length, FieldCount + second.tuple.elements.length))) return false; for (unsigned int i = second.tuple.elements.length; i < first.tuple.elements.length; i++) { if (!build_variable_map(*first.tuple.elements[i], first_variable_map, dst_variable_map)) { free(inverse); return false; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length = 0; for (unsigned int i = 0; i < min(first.tuple.elements.length, second.tuple.elements.length); i++) { if (!intersect(inverse.tuple.elements[i], first.tuple.elements[i], second.tuple.elements[i], first_variable_map, second_variable_map, dst_variable_map)) { free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = min(first.tuple.elements.length, second.tuple.elements.length); i < second.tuple.elements.length; i++) { if (!init(inverse.tuple.elements[i], second.tuple.elements[i], second_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = second.tuple.elements.length; i < first.tuple.elements.length; i++) { if (!init(inverse.tuple.elements[i], first.tuple.elements[i], first_variable_map, dst_variable_map)) { fprintf(stderr, "invert_delete_right ERROR: Unable to initialize tuple element.\n"); free(inverse); return false; } inverse.tuple.elements.length++; } for (unsigned int i = max(first.tuple.elements.length, second.tuple.elements.length); i < max(first.tuple.elements.length, second.tuple.elements.length + FieldCount); i++) { inverse.tuple.elements[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; inverse.tuple.elements.length++; } if (!KeepHead) dst_variable_map[1] = 1; compress_variable_map(dst_variable_map); for (unsigned int i = 0; i < second.tuple.elements.length; i++) apply_variable_map(*inverse.tuple.elements[i], dst_variable_map); apply_variable_map(first_variable_map, dst_variable_map); apply_variable_map(second_variable_map, dst_variable_map); } } else { return false; } } else { return false; } return check_variable_overlap<MergeVariables>(inverse, first_variables, second_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> inline bool invert_delete_right(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return invert_delete_right<FieldCount, KeepHead, MergeVariables>(inverse, first, second, first_variable_map, second_variable_map, dst_variable_map); } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_select_left_delete_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (!init(inverse.func)) { fprintf(stderr, "invert_select_left_delete_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_select_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, first, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { if ((first.func.function != DATALOG_LABEL_WILDCARD && first.func.function != PREDICATE_ANSWER) || (first.func.function == DATALOG_LABEL_WILDCARD && index_of(PREDICATE_ANSWER, first.func.excluded, first.func.excluded_count) < first.func.excluded_count)) return false; if (!init(inverse.func)) { fprintf(stderr, "invert_select_left_delete_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_select_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_select_right_delete_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (!init(inverse.func)) { fprintf(stderr, "invert_select_left_delete_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_select_right<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, first, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { if ((first.func.function != DATALOG_LABEL_WILDCARD && first.func.function != PREDICATE_ANSWER) || (first.func.function == DATALOG_LABEL_WILDCARD && index_of(PREDICATE_ANSWER, first.func.excluded, first.func.excluded_count) < first.func.excluded_count)) return false; if (!init(inverse.func)) { fprintf(stderr, "invert_select_left_delete_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_select_right<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_delete_left_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (!init(inverse.func)) { fprintf(stderr, "invert_delete_left_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_delete_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, DATALOG_ANY_TREE, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { if ((first.func.function != DATALOG_LABEL_WILDCARD && first.func.function != PREDICATE_ANSWER) || (first.func.function == DATALOG_LABEL_WILDCARD && index_of(PREDICATE_ANSWER, first.func.excluded, first.func.excluded_count) < first.func.excluded_count)) return false; if (!init(inverse.func)) { fprintf(stderr, "invert_delete_left_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_delete_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } template<unsigned int FieldCount, bool KeepHead, bool MergeVariables = true> bool invert_delete_right_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (!init(inverse.func)) { fprintf(stderr, "invert_delete_left_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_delete_right<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, DATALOG_ANY_TREE, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { if ((first.func.function != DATALOG_LABEL_WILDCARD && first.func.function != PREDICATE_ANSWER) || (first.func.function == DATALOG_LABEL_WILDCARD && index_of(PREDICATE_ANSWER, first.func.excluded, first.func.excluded_count) < first.func.excluded_count)) return false; if (!init(inverse.func)) { fprintf(stderr, "invert_delete_left_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!new_expression(inverse.func.arg) || !invert_delete_right<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } bool invert_delete_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (!init(inverse.func)) { fprintf(stderr, "invert_delete_left_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!init(inverse.func.arg, second)) { free(inverse); return false; } } else if (first.type == DATALOG_FUNCTION) { if ((first.func.function != DATALOG_LABEL_WILDCARD && first.func.function != PREDICATE_ANSWER) || (first.func.function == DATALOG_LABEL_WILDCARD && index_of(PREDICATE_ANSWER, first.func.excluded, first.func.excluded_count) < first.func.excluded_count)) return false; if (!init(inverse.func)) { fprintf(stderr, "invert_delete_left_answer ERROR: Out of memory.\n"); return false; } inverse.reference_count = 1; inverse.type = DATALOG_FUNCTION; inverse.func.function = PREDICATE_ANSWER; inverse.func.vars[0] = 1; for (unsigned int i = 1; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; if (!intersect(inverse.func.arg, first.func.arg, &second)) { inverse.func.arg = NULL; free(inverse); return false; } } else { return false; } return true; } template<unsigned int FieldIndex, bool OtherArgsEmpty> bool invert_select_arg(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.type = DATALOG_PREDICATE; inverse.pred.function = DATALOG_LABEL_WILDCARD; if (!init_excluded(inverse.pred.excluded, &DATALOG_LABEL_EMPTY, 1)) return false; inverse.pred.excluded_count = 1; inverse.reference_count = 1; if (OtherArgsEmpty) { for (unsigned int i = 0; i < FieldIndex; i++) inverse.pred.args[i] = NULL; } else { for (unsigned int i = 0; i < FieldIndex; i++) inverse.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += FieldIndex; } if (second.type == DATALOG_EMPTY) { for (unsigned int i = FieldIndex; i < array_length(inverse.pred.args); i++) inverse.pred.args[i] = NULL; } else { if (!init(inverse.pred.args[FieldIndex], second)) { inverse.pred.args[FieldIndex] = NULL; free(inverse); return false; } if (OtherArgsEmpty) { for (unsigned int i = FieldIndex + 1; i < array_length(inverse.pred.args); i++) inverse.pred.args[i] = NULL; } else { for (unsigned int i = FieldIndex + 1; i < array_length(inverse.pred.args); i++) inverse.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += array_length(inverse.pred.args) - FieldIndex - 1; } } } else if (first.type == DATALOG_PREDICATE) { inverse.type = DATALOG_PREDICATE; inverse.pred.function = first.pred.function; inverse.reference_count = 1; if (first.pred.excluded_count > 0 && !init_excluded(inverse.pred.excluded, first.pred.excluded, first.pred.excluded_count)) { free(inverse); return false; } inverse.pred.excluded_count = first.pred.excluded_count; if (inverse.pred.function == DATALOG_LABEL_WILDCARD && !inverse.pred.exclude(&DATALOG_LABEL_EMPTY, 1)) { free(inverse); return false; } for (unsigned int i = 0; i < array_length(inverse.pred.args); i++) inverse.pred.args[i] = NULL; for (unsigned int i = 0; i < FieldIndex; i++) { if (OtherArgsEmpty) { if (first.pred.args[i] != NULL && !can_be_empty(*first.pred.args[i])) { free(inverse); return false; } inverse.pred.args[i] = NULL; } else { inverse.pred.args[i] = first.pred.args[i]; if (first.pred.args[i] != NULL) first.pred.args[i]->reference_count++; } } const datalog_expression* arg = first.pred.args[FieldIndex]; if (arg == NULL) { if (second.type != DATALOG_EMPTY && second.type != DATALOG_ANY) { free(inverse); return false; } } else if (!intersect(inverse.pred.args[FieldIndex], arg, &second)) { inverse.pred.args[FieldIndex] = NULL; free(inverse); return false; } if (inverse.pred.args[FieldIndex] != NULL && inverse.pred.args[FieldIndex]->type == DATALOG_EMPTY) { free(*inverse.pred.args[FieldIndex]); if (inverse.pred.args[FieldIndex]->reference_count == 0) free(inverse.pred.args[FieldIndex]); inverse.pred.args[FieldIndex] = NULL; for (unsigned int i = FieldIndex + 1; i < array_length(inverse.pred.args); i++) { if (first.pred.args[i] != NULL && !can_be_empty(*first.pred.args[i])) { free(inverse); return false; } inverse.pred.args[i] = NULL; } } else { for (unsigned int i = FieldIndex + 1; i < array_length(inverse.pred.args); i++) { if (OtherArgsEmpty) { if (first.pred.args[i] != NULL && !can_be_empty(*first.pred.args[i])) { free(inverse); return false; } inverse.pred.args[i] = NULL; } else { inverse.pred.args[i] = first.pred.args[i]; if (first.pred.args[i] != NULL) first.pred.args[i]->reference_count++; } } } } else { return false; } return true; } template<unsigned int FieldIndex> bool invert_delete_arg(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY || (first.type == DATALOG_TUPLE && first.tuple.elements.length == 0 && first.tuple.position != POSITION_EXACT)) { if (second.type != DATALOG_PREDICATE || (second.pred.args[FieldIndex] != NULL && second.pred.args[FieldIndex]->type != DATALOG_EMPTY)) return false; inverse.type = DATALOG_PREDICATE; inverse.pred.function = second.pred.function; if (second.pred.excluded_count > 0 && !init_excluded(inverse.pred.excluded, second.pred.excluded, second.pred.excluded_count)) return false; inverse.pred.excluded_count = second.pred.excluded_count; inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(second.pred.args); i++) { if (i == FieldIndex) continue; inverse.pred.args[i] = second.pred.args[i]; if (second.pred.args[i] != NULL) second.pred.args[i]->reference_count++; } inverse.pred.args[FieldIndex] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; } else if (first.type == DATALOG_PREDICATE) { if (second.type != DATALOG_PREDICATE || (second.pred.args[FieldIndex] != NULL && second.pred.args[FieldIndex]->type != DATALOG_EMPTY)) return false; inverse.type = DATALOG_PREDICATE; if (!intersect_labels( inverse.pred.function, inverse.pred.excluded, inverse.pred.excluded_count, first.pred.function, first.pred.excluded, first.pred.excluded_count, second.pred.function, second.pred.excluded, second.pred.excluded_count)) { free(inverse); return false; } inverse.reference_count = 1; array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); for (unsigned int i = 0; i < array_length(inverse.pred.args); i++) inverse.pred.args[i] = NULL; for (unsigned int i = 0; i < array_length(inverse.pred.args); i++) { if (i == FieldIndex) continue; if (first.pred.args[i] == NULL) { if (second.pred.args[i] != NULL && second.pred.args[i]->type != DATALOG_ANY && second.pred.args[i]->type != DATALOG_EMPTY) { free(inverse); return false; } } else if (second.pred.args[i] == NULL) { if (first.pred.args[i]->type != DATALOG_ANY && first.pred.args[i]->type != DATALOG_EMPTY) { free(inverse); return false; } } else if (!intersect( inverse.pred.args[i], first.pred.args[i], second.pred.args[i], first_variable_map, second_variable_map, dst_variable_map)) { inverse.pred.args[i] = NULL; free(inverse); return false; } } inverse.pred.args[FieldIndex] = first.pred.args[FieldIndex]; if (first.pred.args[FieldIndex] != NULL) first.pred.args[FieldIndex]->reference_count++; } else { return false; } return true; } bool invert_delete_args(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (second.type != DATALOG_PREDICATE) return false; for (unsigned int i = 0; i < array_length(second.pred.args); i++) if (second.pred.args[i] != NULL && !can_be_empty(*second.pred.args[i])) return false; inverse.type = DATALOG_PREDICATE; inverse.pred.function = second.pred.function; if (second.pred.excluded_count > 0 && !init_excluded(inverse.pred.excluded, second.pred.excluded, second.pred.excluded_count)) return false; inverse.pred.excluded_count = second.pred.excluded_count; inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(second.pred.args); i++) inverse.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += array_length(second.pred.args); } else if (first.type == DATALOG_PREDICATE) { if (second.type != DATALOG_PREDICATE) return false; for (unsigned int i = 0; i < array_length(second.pred.args); i++) if (second.pred.args[i] != NULL && !can_be_empty(*second.pred.args[i])) return false; inverse.type = DATALOG_PREDICATE; if (!intersect_labels( inverse.pred.function, inverse.pred.excluded, inverse.pred.excluded_count, first.pred.function, first.pred.excluded, first.pred.excluded_count, second.pred.function, second.pred.excluded, second.pred.excluded_count)) { return false; } inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(inverse.pred.args); i++) { inverse.pred.args[i] = first.pred.args[i]; if (first.pred.args[i] != NULL) first.pred.args[i]->reference_count++; } } else { return false; } return true; } template<unsigned int HeadIndex, unsigned int SelectIndex, bool OtherArgsEmpty> bool invert_head_arg_select_arg(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_TUPLE) { if (first.tuple.elements.length == 0) { if (first.tuple.position == POSITION_EXACT) return false; if (!invert_select_arg<SelectIndex, false>(inverse, DATALOG_NON_EMPTY_TREE, second)) return false; } else if (first.tuple.elements.length > 1) { return false; } else { if (!invert_select_arg<SelectIndex, false>(inverse, *first.tuple.elements[0], second)) return false; } } else { if (first.type == DATALOG_EMPTY) return false; if (!invert_select_arg<SelectIndex, false>(inverse, first, second)) return false; } if (inverse.pred.args[HeadIndex]->type == DATALOG_ANY || inverse.pred.args[HeadIndex]->type == DATALOG_NON_EMPTY) { if (inverse.pred.args[HeadIndex]->reference_count > 1) { free(*inverse.pred.args[HeadIndex]); if (!new_expression(inverse.pred.args[HeadIndex])) return false; inverse.pred.args[HeadIndex]->reference_count = 1; } inverse.pred.args[HeadIndex]->variable = 1; inverse.pred.args[HeadIndex]->type = DATALOG_VARIABLE; } else if (inverse.pred.args[HeadIndex]->type == DATALOG_VARIABLE) { if (inverse.pred.args[HeadIndex]->variable == 0) { if (inverse.pred.args[HeadIndex]->reference_count > 1) { free(*inverse.pred.args[HeadIndex]); if (!new_expression(inverse.pred.args[HeadIndex])) return false; inverse.pred.args[HeadIndex]->reference_count = 1; } inverse.pred.args[HeadIndex]->variable = 1; } else if (inverse.pred.args[HeadIndex]->variable != 1) return false; } else { return false; } for (unsigned int i = 0; OtherArgsEmpty && i < array_length(inverse.pred.args); i++) { if (i == HeadIndex || i == SelectIndex || inverse.pred.args[i] == NULL) continue; else if (!can_be_empty(*inverse.pred.args[i])) return false; free(*inverse.pred.args[i]); if (inverse.pred.args[i]->reference_count == 0) free(inverse.pred.args[i]); inverse.pred.args[i] = NULL; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool MergeVariables = true> bool invert_select_left_keep_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { /* we're not implementing the any-any case */ if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (second.func.excluded_count > 0) /* prune cases where the variables are unknown */ return false; inverse.func.function = Predicate; } else { inverse.func.function = second.func.function; if (second.func.excluded_count > 0 && !inverse.func.exclude(second.func.excluded, second.func.excluded_count)) return false; } for (unsigned int i = 0; i < array_length(second.func.vars); i++) inverse.func.vars[i] = second.func.vars[i]; if (!new_expression(inverse.func.arg) || !invert_select_any<FieldCount, true, POSITION_LEFT>(*inverse.func.arg, *second.func.arg)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; } else if (first.type == DATALOG_FUNCTION) { if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(Predicate)) { return false; } else if (second.func.function == DATALOG_LABEL_WILDCARD) { /* prune cases where the variables are unknown */ return false; } else if (second.func.function != Predicate) { return false; } } else if (first.func.function != Predicate) { return false; } inverse.func.function = Predicate; } else if (!intersect_labels( inverse.func.function, inverse.func.excluded, inverse.func.excluded_count, first.func.function, first.func.excluded, first.func.excluded_count, second.func.function, second.func.excluded, second.func.excluded_count)) { return false; } array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); for (unsigned int i = 0; MergeVariables && i < array_length(inverse.func.vars); i++) { unsigned int var = second.func.vars[i]; if (var != 0) { second_variable_map[var] = var; dst_variable_map[var] = 1; } } if (!new_expression(inverse.func.arg) || !invert_select_left<FieldCount, true, MergeVariables>(*inverse.func.arg, *first.func.arg, *second.func.arg, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(inverse.func.vars); i++) { unsigned int first_var = first.func.vars[i]; unsigned int second_var = second.func.vars[i]; if (first_var == 0) { if (second_var == 0) { inverse.func.vars[i] = 0; } else { if (second_variable_map[second_var] != 0) { inverse.func.vars[i] = second_variable_map[second_var]; } else { inverse.func.vars[i] = second_var; second_variable_map[second_var] = second_var; dst_variable_map[second_var] = 1; } } } else if (second_var == 0) { if (first_variable_map[first_var] != 0) { inverse.func.vars[i] = first_variable_map[first_var]; } else { inverse.func.vars[i] = first_var; second_variable_map[first_var] = first_var; dst_variable_map[first_var] = 1; } } else { unsigned int intersection = intersect_variable(first_var, second_var, first_variable_map, second_variable_map, dst_variable_map); if (intersection == 0) { /* the intersection is empty */ free(inverse); return false; } inverse.func.vars[i] = intersection; } } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead, bool MergeVariables = true> bool invert_delete_left_keep_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { /* we're not implementing the any-any case */ if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (second.func.excluded_count > 0) /* prune cases where the variables are unknown */ return false; inverse.func.function = Predicate; } else { inverse.func.function = second.func.function; if (second.func.excluded_count > 0 && !inverse.func.exclude(second.func.excluded, second.func.excluded_count)) { return false; } } for (unsigned int i = 0; i < array_length(second.func.vars); i++) { if (second.func.vars[i] == 0) inverse.func.vars[i] = 0; else inverse.func.vars[i] = second.func.vars[i] + (KeepHead ? 0 : 1); } if (!new_expression(inverse.func.arg) || !invert_delete_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, DATALOG_ANY_TREE, *second.func.arg)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; } else if (first.type == DATALOG_FUNCTION) { if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(Predicate)) { return false; } else if (second.func.function == DATALOG_LABEL_WILDCARD) { /* prune cases where the variables are unknown */ return false; } else if (second.func.function != Predicate) { return false; } } else if (first.func.function != Predicate) { return false; } inverse.func.function = Predicate; } else if (!intersect_labels( inverse.func.function, inverse.func.excluded, inverse.func.excluded_count, first.func.function, first.func.excluded, first.func.excluded_count, second.func.function, second.func.excluded, second.func.excluded_count)) { return false; } if (!new_expression(inverse.func.arg) || !invert_delete_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, *second.func.arg, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(inverse.func.vars); i++) { unsigned int first_var = first.func.vars[i]; unsigned int second_var = second.func.vars[i]; if (first_var == 0) { if (second_var == 0) { inverse.func.vars[i] = 0; } else { if (second_variable_map[second_var] != 0) { inverse.func.vars[i] = second_variable_map[second_var]; } else { inverse.func.vars[i] = second_var + (KeepHead ? 0 : 1); second_variable_map[second_var] = second_var + (KeepHead ? 0 : 1); dst_variable_map[second_var + (KeepHead ? 0 : 1)] = 1; } } } else if (second_var == 0) { if (first_variable_map[first_var] != 0) { inverse.func.vars[i] = first_variable_map[first_var]; } else { inverse.func.vars[i] = first_var; second_variable_map[first_var] = first_var; dst_variable_map[first_var] = 1; } } else { unsigned int intersection = intersect_variable(first_var, second_var, first_variable_map, second_variable_map, dst_variable_map); if (intersection == 0) { /* the intersection is empty */ free(inverse); return false; } inverse.func.vars[i] = intersection; } } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool invert_delete_left_keep_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return invert_delete_left_keep_function<FieldCount, Predicate, KeepHead>( inverse, first, second, first_variable_map, second_variable_map, dst_variable_map); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> bool invert_delete_right_keep_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { /* we're not implementing the any-any case */ if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (second.func.excluded_count > 0) /* prune cases where the variables are unknown */ return false; inverse.func.function = Predicate; } else { inverse.func.function = second.func.function; if (second.func.excluded_count > 0 && !inverse.func.exclude(second.func.excluded, second.func.excluded_count)) { return false; } } for (unsigned int i = 0; i < array_length(second.func.vars); i++) { if (second.func.vars[i] == 0) inverse.func.vars[i] = 0; else inverse.func.vars[i] = second.func.vars[i] + (KeepHead ? 0 : 1); } if (!new_expression(inverse.func.arg) || !invert_delete_right<FieldCount, KeepHead>(*inverse.func.arg, DATALOG_ANY_TREE, *second.func.arg)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; } else if (first.type == DATALOG_FUNCTION) { if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(Predicate)) { return false; } else if (second.func.function == DATALOG_LABEL_WILDCARD) { /* prune cases where the variables are unknown */ return false; } else if (second.func.function != Predicate) { return false; } } else if (first.func.function != Predicate) { return false; } inverse.func.function = Predicate; } else if (!intersect_labels( inverse.func.function, inverse.func.excluded, inverse.func.excluded_count, first.func.function, first.func.excluded, first.func.excluded_count, second.func.function, second.func.excluded, second.func.excluded_count)) { return false; } array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); if (!new_expression(inverse.func.arg) || !invert_delete_right<FieldCount, KeepHead>(*inverse.func.arg, *first.func.arg, *second.func.arg, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(inverse.func.vars); i++) { unsigned int first_var = first.func.vars[i]; unsigned int second_var = second.func.vars[i]; if (first_var == 0) { if (second_var == 0) { inverse.func.vars[i] = 0; } else { if (second_variable_map[second_var] != 0) { inverse.func.vars[i] = second_variable_map[second_var]; } else { inverse.func.vars[i] = second_var + (KeepHead ? 0 : 1); second_variable_map[second_var] = second_var + (KeepHead ? 0 : 1); dst_variable_map[second_var + (KeepHead ? 0 : 1)] = 1; } } } else if (second_var == 0) { if (first_variable_map[first_var] != 0) { inverse.func.vars[i] = first_variable_map[first_var]; } else { inverse.func.vars[i] = first_var; second_variable_map[first_var] = first_var; dst_variable_map[first_var] = 1; } } else { unsigned int intersection = intersect_variable(first_var, second_var, first_variable_map, second_variable_map, dst_variable_map); if (intersection == 0) { /* the intersection is empty */ free(inverse); return false; } inverse.func.vars[i] = intersection; } } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead, bool MergeVariables = true> bool invert_select_left_delete_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY || (first.type == DATALOG_TUPLE && first.tuple.elements.length == 0 && first.tuple.position != POSITION_EXACT)) { inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; inverse.func.excluded_count = 0; inverse.func.function = Predicate; set_function_variables<Predicate>(inverse.func); if (!new_expression(inverse.func.arg) || !invert_select_any<FieldCount, KeepHead, POSITION_LEFT>(*inverse.func.arg, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(Predicate)) return false; } else if (first.func.function != Predicate) { return false; } inverse.func.function = Predicate; } else { inverse.func.function = first.func.function; if (first.func.excluded_count > 0 && !inverse.func.exclude(first.func.excluded, first.func.excluded_count)) { free(inverse); return false; } } for (unsigned int i = 0; MergeVariables && i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } if (!new_expression(inverse.func.arg) || !invert_select_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; if (var != 0) { if (first_variable_map[var] == 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } else { var = first_variable_map[var]; } } inverse.func.vars[i] = var; } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> inline bool invert_select_left_delete_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return invert_select_left_delete_function<FieldCount, Predicate, KeepHead>( inverse, first, second, first_variable_map, second_variable_map, dst_variable_map); } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> bool invert_select_right_delete_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; inverse.func.excluded_count = 0; inverse.func.function = Predicate; set_function_variables<Predicate>(inverse.func); if (!new_expression(inverse.func.arg) || !invert_select_any<FieldCount, KeepHead, POSITION_RIGHT>(*inverse.func.arg, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(Predicate)) return false; } else if (first.func.function != Predicate) { return false; } inverse.func.function = Predicate; } else { inverse.func.function = first.func.function; if (first.func.excluded_count > 0 && !inverse.func.exclude(first.func.excluded, first.func.excluded_count)) { return false; } } array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); if (!new_expression(inverse.func.arg) || !invert_select_right<FieldCount, KeepHead>(*inverse.func.arg, *first.func.arg, second, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; inverse.func.vars[i] = var; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead, bool MergeVariables = true> bool invert_delete_left_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second, array<unsigned int>& first_variable_map, array<unsigned int>& second_variable_map, array<unsigned int>& dst_variable_map) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; inverse.func.excluded_count = 0; inverse.func.function = Predicate; set_function_variables<Predicate>(inverse.func); if (!new_expression(inverse.func.arg) || !invert_delete_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, DATALOG_ANY_TREE, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(Predicate)) return false; } else if (first.func.function != Predicate) { return false; } inverse.func.function = Predicate; } else { inverse.func.function = first.func.function; if (first.func.excluded_count > 0 && !inverse.func.exclude(first.func.excluded, first.func.excluded_count)) { return false; } } for (unsigned int i = 0; MergeVariables && i < array_length(inverse.func.vars); i++) { unsigned int var = first.func.vars[i]; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } if (!new_expression(inverse.func.arg) || !invert_delete_left<FieldCount, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; inverse.func.vars[i] = var; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead, bool MergeVariables = true> inline bool invert_delete_left_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); return invert_delete_left_function<FieldCount, Predicate, KeepHead, MergeVariables>( inverse, first, second, first_variable_map, second_variable_map, dst_variable_map); } template<unsigned int Predicate, bool KeepHead> bool invert_select_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (second.func.excluded_count > 0 && second.func.is_excluded(Predicate)) { return false; } inverse.func.function = Predicate; } else { inverse.func.function = second.func.function; if (second.func.excluded_count > 0 && !inverse.func.exclude(second.func.excluded, second.func.excluded_count)) { return false; } } inverse.reference_count = 1; inverse.func.arg = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count++; for (unsigned int i = 0; i < array_length(second.func.vars); i++) { if (second.func.vars[i] == 0) inverse.func.vars[i] = 0; else inverse.func.vars[i] = second.func.vars[i] + (KeepHead ? 0 : 1); } } else if (first.type == DATALOG_FUNCTION) { if (second.type != DATALOG_FUNCTION) return false; inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if ((first.func.excluded_count > 0 && first.func.is_excluded(Predicate)) || (second.func.excluded_count > 0 && second.func.is_excluded(Predicate))) { return false; } inverse.func.function = Predicate; } else { if (!intersect_labels( inverse.func.function, inverse.func.excluded, inverse.func.excluded_count, first.func.function, first.func.excluded, first.func.excluded_count, second.func.function, second.func.excluded, second.func.excluded_count)) { return false; } } inverse.reference_count = 1; inverse.func.arg = first.func.arg; first.func.arg->reference_count++; for (unsigned int i = 0; i < array_length(inverse.func.vars); i++) { unsigned int first_var = first.func.vars[i]; unsigned int second_var = second.func.vars[i]; if (second_var != 0 && !KeepHead) second_var++; if (first_var == 0) { if (second_var == 0) inverse.func.vars[i] = 0; else inverse.func.vars[i] = second_var; } else { if (second_var == 0) { inverse.func.vars[i] = first_var; } else if (first_var != second_var) { free(inverse); return false; } else { inverse.func.vars[i] = second_var; } } } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead, bool MergeVariables = true> bool invert_delete_left_answer_keep_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; set_function_variables<PREDICATE_ANSWER>(inverse.func); inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_delete_left_keep_function<FieldCount, Predicate, KeepHead>(*inverse.func.arg, DATALOG_ANY_TREE, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(PREDICATE_ANSWER)) return false; set_function_variables<PREDICATE_ANSWER>(inverse.func); } else if (first.func.function == PREDICATE_ANSWER) { for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; inverse.func.vars[i] = var; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } } else return false; inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_delete_left_keep_function<FieldCount, Predicate, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead, bool MergeVariables = true> bool invert_select_left_delete_function_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; set_function_variables<PREDICATE_ANSWER>(inverse.func); inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_select_left_delete_function<FieldCount, Predicate, KeepHead>(*inverse.func.arg, DATALOG_ANY_TREE, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(PREDICATE_ANSWER)) return false; set_function_variables<PREDICATE_ANSWER>(inverse.func); } else if (first.func.function == PREDICATE_ANSWER) { for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; inverse.func.vars[i] = var; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } } else return false; inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_select_left_delete_function<FieldCount, Predicate, KeepHead, MergeVariables>(*inverse.func.arg, *first.func.arg, second, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } template<unsigned int FieldCount, unsigned int Predicate, bool KeepHead> bool invert_delete_left_function_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; set_function_variables<PREDICATE_ANSWER>(inverse.func); inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_delete_left_function<FieldCount, Predicate, KeepHead>(*inverse.func.arg, DATALOG_ANY_TREE, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(PREDICATE_ANSWER)) return false; set_function_variables<PREDICATE_ANSWER>(inverse.func); } else if (first.func.function == PREDICATE_ANSWER) { for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; inverse.func.vars[i] = var; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } } else return false; inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_delete_left_function<FieldCount, Predicate, KeepHead>(*inverse.func.arg, *first.func.arg, second, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } template<unsigned int Predicate, bool KeepHead, bool MergeVariables = true> bool invert_delete_function(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY || (first.type == DATALOG_TUPLE && first.tuple.elements.length == 0 && first.tuple.position != POSITION_EXACT)) { inverse.type = DATALOG_FUNCTION; inverse.func.function = Predicate; inverse.func.excluded_count = 0; inverse.reference_count = 1; if (!init(inverse.func.arg, second, KeepHead ? 0 : 1)) return false; if (Predicate != DATALOG_LABEL_WILDCARD) { set_function_variables<Predicate>(inverse.func); } else { for (unsigned int i = 0; i < array_length(inverse.func.vars); i++) inverse.func.vars[i] = 0; } } else if (first.type == DATALOG_FUNCTION) { inverse.type = DATALOG_FUNCTION; inverse.func.excluded_count = 0; if (Predicate != DATALOG_LABEL_WILDCARD) { if (first.func.excluded_count > 0 && first.func.is_excluded(Predicate)) return false; inverse.func.function = Predicate; } else { inverse.func.function = first.func.function; if (first.func.excluded_count > 0 && !inverse.func.exclude(first.func.excluded, first.func.excluded_count)) return false; } array<bool> first_variables = array<bool>(8); memset(first_variables.data, 0, sizeof(bool) * first_variables.capacity); array<unsigned int> first_variable_map = array<unsigned int>(8); array<unsigned int> second_variable_map = array<unsigned int>(8); array<unsigned int> dst_variable_map = array<unsigned int>(8); memset(first_variable_map.data, 0, sizeof(unsigned int) * first_variable_map.capacity); memset(second_variable_map.data, 0, sizeof(unsigned int) * second_variable_map.capacity); memset(dst_variable_map.data, 0, sizeof(unsigned int) * dst_variable_map.capacity); for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; if (var != 0) { first_variable_map[var] = var; dst_variable_map[var] = 1; } } if (!init_variable_maps<KeepHead, MergeVariables>(second, first_variables, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } inverse.reference_count = 1; if (!intersect(inverse.func.arg, first.func.arg, &second, first_variable_map, second_variable_map, dst_variable_map)) { if (inverse.func.excluded_count > 0) free(inverse.func.excluded); return false; } for (unsigned int i = 0; i < array_length(first.func.vars); i++) { if (first.func.vars[i] == 0) { inverse.func.vars[i] = 0; continue; } unsigned int var = first.func.vars[i]; if (first_variable_map[var] != 0) { inverse.func.vars[i] = first_variable_map[var]; continue; } while (dst_variable_map[var] != 0) { var++; if (!ensure_variable_map_capacity(dst_variable_map, var)) { free(inverse); return false; } } inverse.func.vars[i] = var; } } else { return false; } return true; } template<unsigned int Predicate, bool KeepHead> bool invert_delete_function_answer(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; set_function_variables<PREDICATE_ANSWER>(inverse.func); inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_delete_function<Predicate, KeepHead>(*inverse.func.arg, DATALOG_ANY_TREE, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else if (first.type == DATALOG_FUNCTION) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(PREDICATE_ANSWER)) return false; set_function_variables<PREDICATE_ANSWER>(inverse.func); } else if (first.func.function == PREDICATE_ANSWER) { for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; inverse.func.vars[i] = var; } } else return false; inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg) || !invert_delete_function<Predicate, KeepHead>(*inverse.func.arg, *first.func.arg, second)) { if (inverse.func.arg != NULL) free(inverse.func.arg); return false; } } else { return false; } return true; } template<unsigned int Predicate, unsigned int Direction> inline bool set_predicate_answer(datalog_expression& inverse, const datalog_expression& first) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; set_function_variables<PREDICATE_ANSWER>(inverse.func); inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!new_expression(inverse.func.arg)) free(inverse); inverse.func.arg->type = DATALOG_ANY; inverse.func.arg->reference_count = 1; } else if (first.type == DATALOG_FUNCTION) { if (first.func.function == DATALOG_LABEL_WILDCARD) { if (first.func.is_excluded(PREDICATE_ANSWER)) return false; set_function_variables<PREDICATE_ANSWER>(inverse.func); } else if (first.func.function == PREDICATE_ANSWER) { for (unsigned int i = 0; i < array_length(first.func.vars); i++) { unsigned int var = first.func.vars[i]; inverse.func.vars[i] = var; } } else { return false; } inverse.func.function = PREDICATE_ANSWER; inverse.func.excluded_count = 0; inverse.type = DATALOG_FUNCTION; inverse.reference_count = 1; if (!init(inverse.func.arg, first.func.arg)) return false; } else { return false; } if (!set_predicate<0, false, true>(*inverse.func.arg, Predicate) || !set_direction<false>(*inverse.func.arg, Direction)) { free(inverse); return false; } return true; } template<unsigned int Length> inline bool invert_tuple_length(datalog_expression& inverse, const datalog_expression& first, const datalog_expression& second) { if (first.type == DATALOG_ANY || first.type == DATALOG_NON_EMPTY) { if (!tuple_length<Length>(second, inverse)) return false; } else if (first.type == DATALOG_TUPLE) { datalog_expression* intermediate; if (!new_expression(intermediate)) return false; if (!tuple_length<Length>(first, *intermediate)) { free(intermediate); return false; } if (!intersect(inverse, intermediate, &second)) { free(*intermediate); free(intermediate); return false; } free(*intermediate); free(intermediate); } else { return false; } return true; } bool invert( datalog_expression_root& inverse, datalog_expression_root::function function, const datalog_expression_root& first, const datalog_expression_root& second) { /* first invert the syntactic features */ if (function.type == datalog_expression_root::FUNCTION_NULL || function.type == datalog_expression_root::FUNCTION_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_FUNCTION_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG2_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG3_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_ARG1_FEATURES || function.type == datalog_expression_root::FUNCTION_DELETE_ARG2_FEATURES) { inverse.inf = first.inf; inverse.index = first.index; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_RIGHT2_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_SINGULAR || function.type == datalog_expression_root::FUNCTION_DELETE_ARG1_SINGULAR) { if ((second.index != NUMBER_ANY && second.index != NUMBER_SINGULAR) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.index = first.index; } else if (function.type == datalog_expression_root::FUNCTION_PLURAL || function.type == datalog_expression_root::FUNCTION_SELECT_ARG1_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_ARG1_PLURAL) { if ((second.index != NUMBER_ANY && second.index != NUMBER_PLURAL) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.index = first.index; } else if (function.type == datalog_expression_root::FUNCTION_UNCOUNTABLE) { if ((second.index != NUMBER_ANY && second.index != NUMBER_UNCOUNTABLE) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.index = first.index; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_DELETE_ARGS_CONCORD_SINGULAR) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_SINGULAR) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_PLURAL) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_UNCOUNTABLE) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_UNCOUNTABLE) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_NON_SINGULAR) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_NON_SINGULAR) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_NON_PLURAL) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_NON_PLURAL) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; if (inverse.index != NUMBER_SINGULAR) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_CONCORD_ALL) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_ALL) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; if (inverse.index == NUMBER_SINGULAR) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_CONCORD_SINGULAR || function.type == datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_ALL && second.concord != NUMBER_NON_PLURAL && second.concord != NUMBER_SINGULAR) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_CONCORD_PLURAL) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_ALL && second.concord != NUMBER_NON_SINGULAR && second.concord != NUMBER_PLURAL) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_CONCORD_UNCOUNTABLE) { if ((second.concord != NUMBER_ANY && second.concord != NUMBER_ALL && second.concord != NUMBER_NON_PLURAL && second.concord != NUMBER_NON_SINGULAR && second.concord != NUMBER_UNCOUNTABLE) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.index, first.index, second.index)) return false; inverse.concord = first.concord; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_SINGULAR) { if ((second.index != NUMBER_ANY && second.index != NUMBER_SINGULAR) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.index = first.index; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_PLURAL || function.type == datalog_expression_root::FUNCTION_DELETE_ARGS_KEEP_PLURAL) { if ((second.index != NUMBER_ANY && second.index != NUMBER_PLURAL) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.index = first.index; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_UNCOUNTABLE) { if ((second.index != NUMBER_ANY && second.index != NUMBER_UNCOUNTABLE) || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.index = first.index; } else if (function.type == datalog_expression_root::FUNCTION_PRESENT_PARTICIPLE) { if ((second.inf != INFLECTION_PRESENT_PARTICIPLE && second.inf != INFLECTION_ANY) || !intersect(inverse.index, first.index, second.index) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.inf = first.inf; } else if (function.type == datalog_expression_root::FUNCTION_PAST_PARTICIPLE || function.type == datalog_expression_root::FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE) { if ((second.inf != INFLECTION_PAST_PARTICIPLE && second.inf != INFLECTION_ANY) || !intersect(inverse.index, first.index, second.index) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.inf = first.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_PRESENT_PARTICIPLE) { if ((first.inf != INFLECTION_PRESENT_PARTICIPLE && first.inf != INFLECTION_ANY && first.inf != INFLECTION_NONE) || (second.inf != INFLECTION_PRESENT_PARTICIPLE && second.inf != INFLECTION_ANY) || !intersect(inverse.index, first.index, second.index) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.inf = first.inf; } else if (function.type == datalog_expression_root::FUNCTION_KEEP_PAST_PARTICIPLE || function.type == datalog_expression_root::FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE) { if ((first.inf != INFLECTION_PAST_PARTICIPLE && first.inf != INFLECTION_ANY && first.inf != INFLECTION_NONE) || (second.inf != INFLECTION_PAST_PARTICIPLE && second.inf != INFLECTION_ANY) || !intersect(inverse.index, first.index, second.index) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.inf = first.inf; } else if (function.type == datalog_expression_root::FUNCTION_INFINITIVE || function.type == datalog_expression_root::FUNCTION_DELETE_NOT_INFINITIVE) { if ((second.inf != INFLECTION_INFINITIVE && second.inf != INFLECTION_ANY) || !intersect(inverse.index, first.index, second.index) || !intersect(inverse.concord, first.concord, second.concord)) return false; inverse.inf = first.inf; } else if (function.type == datalog_expression_root::FUNCTION_IDENTITY_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_COORD || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT_COORD || function.type == datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_COORD) { if ((first.index == NUMBER_SINGULAR && second.concord == NUMBER_PLURAL) || first.concord == NUMBER_NONE || !intersect(inverse.inf, first.inf, second.inf) || !intersect(inverse.concord, first.concord, second.concord) || !has_intersection(inverse.concord, second.index)) return false; inverse.index = first.index; } else { if (!intersect(inverse.index, first.index, second.index) || !intersect(inverse.concord, first.concord, second.concord) || !intersect(inverse.inf, first.inf, second.inf)) return false; } /* next, invert the semantic component */ datalog_expression exp; switch (function.type) { case datalog_expression_root::FUNCTION_IDENTITY: case datalog_expression_root::FUNCTION_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SINGULAR: case datalog_expression_root::FUNCTION_PLURAL: case datalog_expression_root::FUNCTION_UNCOUNTABLE: case datalog_expression_root::FUNCTION_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_CONCORD_UNCOUNTABLE: case datalog_expression_root::FUNCTION_CONCORD_NON_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL: case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_ALL: case datalog_expression_root::FUNCTION_KEEP_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_KEEP_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_KEEP_CONCORD_UNCOUNTABLE: case datalog_expression_root::FUNCTION_KEEP_SINGULAR: case datalog_expression_root::FUNCTION_KEEP_PLURAL: case datalog_expression_root::FUNCTION_KEEP_UNCOUNTABLE: case datalog_expression_root::FUNCTION_PRESENT_PARTICIPLE: case datalog_expression_root::FUNCTION_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_KEEP_PRESENT_PARTICIPLE: case datalog_expression_root::FUNCTION_KEEP_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_INFINITIVE: case datalog_expression_root::FUNCTION_IDENTITY_COORD: return intersect(inverse.root, &first.root, &second.root); case datalog_expression_root::FUNCTION_NULL: case datalog_expression_root::FUNCTION_KEEP_FEATURES: if (second.root.type != DATALOG_ANY && second.root.type != DATALOG_EMPTY) return false; return init(inverse.root, first.root); case datalog_expression_root::FUNCTION_SELECT_LEFT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SELECT_LEFT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_LEFT_COORD: return invert_select_left<1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT_COORD: return invert_select_left<1, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FEATURES: return invert_select_left<2, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_COORD: return invert_select_left<2, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DISJOINT: return invert_select_left<3, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT4_DISJOINT: return invert_select_left<4, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT5_DISJOINT: return invert_select_left<5, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT6_DISJOINT: return invert_select_left<6, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT7_DISJOINT: return invert_select_left<7, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR: return invert_select_left<1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD: return invert_select_left<1, false, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION: return invert_select_left_keep_function<1, DATALOG_LABEL_WILDCARD>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION_DISJOINT: return invert_select_left_keep_function<1, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION: return invert_select_left_keep_function<2, DATALOG_LABEL_WILDCARD>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION_DISJOINT: return invert_select_left_keep_function<2, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_KEEP_FUNCTION: return invert_select_left_keep_function<3, DATALOG_LABEL_WILDCARD>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES: return invert_select_left_delete_function<1, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER: return invert_select_left_delete_answer<1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_ANSWER: return invert_select_left_delete_answer<2, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER: return invert_select_left_delete_answer<3, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER_DISJOINT: return invert_select_left_delete_answer<3, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT5_DELETE_ANSWER_DISJOINT: return invert_select_left_delete_answer<5, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER_HEAD: return invert_select_left_delete_answer<1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_COUNT_ANSWER: return invert_select_left_delete_function_answer<1, PREDICATE_COUNT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_COUNT_ANSWER: return invert_select_left_delete_function_answer<2, PREDICATE_COUNT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_COUNT_ANSWER: return invert_select_left_delete_function_answer<3, PREDICATE_COUNT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_ANSWER: return invert_select_left_delete_function_answer<1, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FUNCTION_ANSWER: return invert_select_left_delete_function_answer<2, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_FUNCTION_ANSWER: return invert_select_left_delete_function_answer<3, DATALOG_LABEL_WILDCARD, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES: return invert_select_left_delete_function<1, PREDICATE_NOT, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT: return invert_select_right<1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT2: case datalog_expression_root::FUNCTION_SELECT_RIGHT2_SINGULAR: return invert_select_right<2, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DISJOINT: return invert_select_right<2, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT3_DISJOINT: return invert_select_right<3, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT4_DISJOINT: return invert_select_right<4, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT5_DISJOINT: return invert_select_right<5, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT6_DISJOINT: return invert_select_right<6, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT7_DISJOINT: return invert_select_right<7, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_HEAD: return invert_select_right<1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_FUNCTION: return invert_select_right_delete_function<1, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DELETE_ANSWER: return invert_select_right_delete_answer<2, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_FEATURES: return invert_select_function<DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD: case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES: return invert_select_function<DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT: case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES: case datalog_expression_root::FUNCTION_DELETE_LEFT_COORD: return invert_delete_left<1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT_COORD: return invert_delete_left<1, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2: return invert_delete_left<2, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_COORD: case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES: return invert_delete_left<2, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES: return invert_delete_left<3, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT4_DISJOINT: return invert_delete_left<4, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT5_DISJOINT: return invert_delete_left<5, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT6_DISJOINT: return invert_delete_left<6, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT7_DISJOINT: return invert_delete_left<7, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES: return invert_delete_left<1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD_FEATURES: return invert_delete_left<2, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION: return invert_delete_left_function<1, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_DISJOINT: return invert_delete_left_function<1, DATALOG_LABEL_WILDCARD, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION: return invert_delete_left_function<2, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_DISJOINT: return invert_delete_left_function<2, DATALOG_LABEL_WILDCARD, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_HEAD: return invert_delete_left_function<1, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_HEAD: return invert_delete_left_function<3, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_ANSWER: return invert_delete_left_keep_function<1, PREDICATE_ANSWER, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION: return invert_delete_left_keep_function<1, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION: return invert_delete_left_keep_function<1, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER: return invert_delete_left_answer<1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER: return invert_delete_left_answer<2, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER: return invert_delete_left_answer<3, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_DISJOINT: return invert_delete_left_answer<3, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT5_ANSWER_DISJOINT: return invert_delete_left_answer<5, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD: return invert_delete_left_answer<1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_COUNT_ANSWER: return invert_delete_left_function_answer<1, PREDICATE_COUNT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_COUNT_ANSWER: return invert_delete_left_function_answer<2, PREDICATE_COUNT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_COUNT_ANSWER: return invert_delete_left_function_answer<3, PREDICATE_COUNT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_ANSWER: return invert_delete_left_function_answer<1, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_ANSWER: return invert_delete_left_function_answer<2, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_ANSWER: return invert_delete_left_function_answer<3, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_KEEP_FUNCTION: return invert_delete_left_answer_keep_function<1, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD_KEEP_FUNCTION: return invert_delete_left_answer_keep_function<1, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_KEEP_FUNCTION: return invert_delete_left_answer_keep_function<2, DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_HEAD_KEEP_FUNCTION: return invert_delete_left_answer_keep_function<2, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_KEEP_FUNCTION: return invert_delete_left_answer_keep_function<3, DATALOG_LABEL_WILDCARD, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_HEAD_KEEP_FUNCTION: return invert_delete_left_answer_keep_function<3, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT: return invert_delete_right<1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT2: return invert_delete_right<2, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT2_DISJOINT: return invert_delete_right<2, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT3_DISJOINT: return invert_delete_right<3, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT4_DISJOINT: return invert_delete_right<4, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT5_DISJOINT: return invert_delete_right<5, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT6_DISJOINT: return invert_delete_right<6, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT7_DISJOINT: return invert_delete_right<7, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD: return invert_delete_right<1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD_KEEP_FUNCTION: return invert_delete_right_keep_function<1, DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_RIGHT2_ANSWER: return invert_delete_right_answer<2, true, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_COUNT: return invert_delete_function<PREDICATE_COUNT, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD: case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL: return invert_delete_function<PREDICATE_COUNT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_COUNT_ANSWER: return invert_delete_function_answer<PREDICATE_COUNT, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_NOT: case datalog_expression_root::FUNCTION_DELETE_NOT_FEATURES: case datalog_expression_root::FUNCTION_DELETE_NOT_INFINITIVE: case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_PLURAL: return invert_delete_function<PREDICATE_NOT, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES: return invert_delete_left_function<1, PREDICATE_NOT, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_NOT: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT: return invert_delete_left_keep_function<1, PREDICATE_NOT, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_FUNCTION_FEATURES: return invert_delete_function<DATALOG_LABEL_WILDCARD, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_FUNCTION_HEAD: return invert_delete_function<DATALOG_LABEL_WILDCARD, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_ANSWER: return invert_delete_answer(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_ANSWER_HAS_LOC: if (!invert_delete_answer(inverse.root, first.root, second.root)) return false; if (!has_predicate<PREDICATE_LOC>(inverse.root)) { free(inverse.root); return false; } return true; case datalog_expression_root::FUNCTION_SELECT_ARG1: case datalog_expression_root::FUNCTION_SELECT_ARG1_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_ARG1_PLURAL: case datalog_expression_root::FUNCTION_SELECT_ARG1_DELETE_FEATURES: return invert_select_arg<0, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES: return invert_select_arg<0, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_ARG2: case datalog_expression_root::FUNCTION_SELECT_ARG2_DELETE_FEATURES: return invert_select_arg<1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES: return invert_select_arg<1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_ARG3: case datalog_expression_root::FUNCTION_SELECT_ARG3_DELETE_FEATURES: return invert_select_arg<2, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES: return invert_select_arg<2, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_ARG1: case datalog_expression_root::FUNCTION_DELETE_ARG1_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_ARG1_PLURAL: case datalog_expression_root::FUNCTION_DELETE_ARG1_FEATURES: return invert_delete_arg<0>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_ARG2: case datalog_expression_root::FUNCTION_DELETE_ARG2_FEATURES: return invert_delete_arg<1>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_ARG3: return invert_delete_arg<2>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_DELETE_ARGS: case datalog_expression_root::FUNCTION_DELETE_ARGS_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_ARGS_KEEP_PLURAL: return invert_delete_args(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2: return invert_head_arg_select_arg<0, 1, false>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2_ONLY: return invert_head_arg_select_arg<0, 1, true>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_EMPTY_TUPLE: if (second.root.type == DATALOG_TUPLE) { if (second.root.tuple.elements.length > 0) return false; } else if (second.root.type != DATALOG_ANY && second.root.type != DATALOG_NON_EMPTY) return false; if (first.root.type == DATALOG_ANY || first.root.type == DATALOG_NON_EMPTY) { return init_tuple(inverse.root, POSITION_LEFT, 1); } else if (first.root.type != DATALOG_TUPLE && first.root.type != DATALOG_PREDICATE && first.root.type != DATALOG_FUNCTION) { return false; } else { return init(inverse.root, first.root); } case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY: case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR: if (second.root.type == DATALOG_TUPLE) { if (second.root.tuple.elements.length > 0) return false; } else if (second.root.type != DATALOG_ANY && second.root.type != DATALOG_NON_EMPTY) return false; if (first.root.type == DATALOG_ANY || first.root.type == DATALOG_NON_EMPTY) { return init_tuple(inverse.root, POSITION_EXACT, 1); } else if (first.root.type == DATALOG_EMPTY) { inverse.root.type = DATALOG_EMPTY; inverse.root.reference_count = 1; return true; } else if (first.root.type != DATALOG_TUPLE || first.root.tuple.elements.length > 0) { return false; } else { return init_tuple(inverse.root, POSITION_EXACT, 1); } case datalog_expression_root::FUNCTION_KEEP_NULL: if (second.root.type != DATALOG_ANY && second.root.type != DATALOG_EMPTY) return false; inverse.root.type = DATALOG_EMPTY; inverse.root.reference_count = 1; return true; case datalog_expression_root::FUNCTION_EMPTY_ARG2: if (!intersect(inverse.root, &first.root, &second.root)) return false; if (inverse.root.type != DATALOG_PREDICATE || (inverse.root.pred.args[1] != NULL && !can_be_empty(*inverse.root.pred.args[1]))) { free(inverse.root); return false; } if (inverse.root.pred.args[1] != NULL) { free(*inverse.root.pred.args[1]); if (inverse.root.pred.args[1]->reference_count == 0) free(inverse.root.pred.args[1]); inverse.root.pred.args[1] = NULL; } return true; case datalog_expression_root::FUNCTION_EMPTY_ARGS: if (!intersect(inverse.root, &first.root, &second.root)) return false; if (inverse.root.type != DATALOG_PREDICATE) return false; for (unsigned int i = 0; i < array_length(inverse.root.pred.args); i++) { if (inverse.root.pred.args[i] != NULL && !can_be_empty(*inverse.root.pred.args[i])) { free(inverse.root); return false; } if (inverse.root.pred.args[i] != NULL) { free(*inverse.root.pred.args[i]); if (inverse.root.pred.args[i]->reference_count == 0) free(inverse.root.pred.args[i]); inverse.root.pred.args[i] = NULL; } } return inverse.root.pred.function != DATALOG_LABEL_WILDCARD || inverse.root.pred.exclude(&DATALOG_LABEL_EMPTY, 1); case datalog_expression_root::FUNCTION_ARG2_ZERO_ARITY: if (!intersect(inverse.root, &first.root, &second.root)) return false; if (inverse.root.type == DATALOG_ANY || inverse.root.type == DATALOG_NON_EMPTY) { if (!new_expression(inverse.root.pred.args[1])) return false; datalog_expression& arg = *inverse.root.pred.args[1]; arg.type = DATALOG_PREDICATE; arg.reference_count = 1; arg.pred.function = DATALOG_LABEL_WILDCARD; arg.pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(arg.pred.args); i++) arg.pred.args[i] = NULL; for (unsigned int i = 0; i < array_length(inverse.root.pred.args); i++) if (i != 1) inverse.root.pred.args[i] = &DATALOG_ANY_TREE; DATALOG_ANY_TREE.reference_count += array_length(inverse.root.pred.args) - 1; inverse.root.pred.function = DATALOG_LABEL_WILDCARD; if (!init_excluded(inverse.root.pred.excluded, &DATALOG_LABEL_EMPTY, 1)) return false; inverse.root.pred.excluded_count = 1; inverse.root.type = DATALOG_PREDICATE; inverse.root.reference_count = 1; } else if (inverse.root.type == DATALOG_PREDICATE) { if (inverse.root.pred.function == DATALOG_LABEL_WILDCARD && !inverse.root.pred.exclude(&DATALOG_LABEL_EMPTY, 1)) return false; else if (inverse.root.pred.args[1] == NULL) return true; datalog_expression* arg; if (inverse.root.pred.args[1]->reference_count == 1) { arg = inverse.root.pred.args[1]; } else { if (!init(arg, *inverse.root.pred.args[1])) exit(EXIT_FAILURE); free(*inverse.root.pred.args[1]); inverse.root.pred.args[1] = arg; } if (arg->type == DATALOG_ANY) { arg->type = DATALOG_PREDICATE; arg->pred.function = DATALOG_LABEL_WILDCARD; arg->pred.excluded_count = 0; for (unsigned int i = 0; i < array_length(arg->pred.args); i++) arg->pred.args[i] = NULL; } else if (arg->type == DATALOG_NON_EMPTY) { arg->type = DATALOG_PREDICATE; arg->pred.function = DATALOG_LABEL_WILDCARD; if (!init_excluded(arg->pred.excluded, &DATALOG_LABEL_EMPTY, 1)) exit(EXIT_FAILURE); arg->pred.excluded_count = 1; for (unsigned int i = 0; i < array_length(arg->pred.args); i++) arg->pred.args[i] = NULL; } else if (arg->type == DATALOG_PREDICATE) { for (unsigned int i = 0; i < array_length(arg->pred.args); i++) { if (arg->pred.args[i] != NULL) { if (!can_be_empty(*arg->pred.args[i])) { free(inverse.root); return false; } free(*arg->pred.args[i]); if (arg->pred.args[i]->reference_count == 0) free(arg->pred.args[i]); arg->pred.args[i] = NULL; } } } else { return false; } } else { return false; } return true; case datalog_expression_root::FUNCTION_LOC: if (second.root.type != DATALOG_ANY && second.root.type != DATALOG_EMPTY) return false; return set_predicate_answer<PREDICATE_LOC, DIRECTION_BACKWARD>(inverse.root, first.root); case datalog_expression_root::FUNCTION_TWO_PREDICATES: return invert_tuple_length<2>(inverse.root, first.root, second.root); case datalog_expression_root::FUNCTION_FLIP_PREDICATE: case datalog_expression_root::FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE: exp = second.root; if (!flip_predicate(exp) || !intersect(inverse.root, &first.root, &exp)) { free(exp); return false; } free(exp); return true; case datalog_expression_root::FUNCTION_EMPTY: break; } fprintf(stderr, "invert ERROR: Unrecognized transformation function.\n"); return false; } bool invert( datalog_expression_root*& inverse, unsigned int& inverse_count, datalog_expression_root::function function, const datalog_expression_root& first, const datalog_expression_root& second) { inverse = (datalog_expression_root*) malloc(sizeof(datalog_expression_root)); if (inverse == NULL) { fprintf(stderr, "invert ERROR: Out of memory.\n"); return false; } else if (!invert(*inverse, function, first, second)) { free(inverse); return false; } inverse_count = 1; unsigned int head = get_head(inverse->root); if (head != 1 && head != DATALOG_LABEL_EMPTY && head != DATALOG_LABEL_WILDCARD) { free(*inverse); free(inverse); return false; } return true; } inline bool any_number(const datalog_expression_root& src) { return src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY; } /* NOTE: this function assumes src is not DATALOG_ANY or DATALOG_NON_EMPTY */ inline bool get_number(const datalog_expression_root& src, int64_t& integer, uint64_t& decimal) { if (src.root.type != DATALOG_INTEGER) return false; integer = src.root.integer; decimal = 0; return true; } inline bool set_number(datalog_expression_root& exp, const datalog_expression_root& set, int64_t integer, uint64_t decimal) { if (set.root.type != DATALOG_ANY && set.root.type != DATALOG_NON_EMPTY && (set.root.type != DATALOG_INTEGER || set.root.integer != integer)) return false; exp.root.type = DATALOG_INTEGER; exp.root.integer = integer; exp.root.reference_count = 1; exp.concord = set.concord; exp.index = set.index; exp.inf = set.inf; return true; } inline bool any_string(const datalog_expression_root& src) { return src.root.type == DATALOG_ANY || src.root.type == DATALOG_NON_EMPTY || (src.root.type == DATALOG_STRING && src.root.str.length == 1 && src.root.str[0] == DATALOG_STRING_LABEL_WILDCARD); } /* NOTE: this function assumes src is not DATALOG_ANY or DATALOG_NON_EMPTY or a wildcard string */ inline bool get_string(const datalog_expression_root& src, string& value) { if (src.root.type != DATALOG_STRING) return false; return init(value, src.root.str); } inline bool set_string(datalog_expression_root& exp, const datalog_expression_root& set, const string& value) { if (set.root.type == DATALOG_STRING) { bool is_wildcard = (set.root.str.length == 1 && set.root.str[0] == DATALOG_STRING_LABEL_WILDCARD); if (!is_wildcard && set.root.str != value) return false; } else if (set.root.type != DATALOG_ANY && set.root.type != DATALOG_NON_EMPTY) { return false; } exp.root.type = DATALOG_STRING; exp.root.reference_count = 1; exp.concord = set.concord; exp.index = set.index; exp.inf = set.inf; return init(exp.root.str, value); } inline void get_selected( const datalog_expression_root::function& f, int& num_conjuncts, bool* args, tuple_position& position, bool& function) { function = false; switch (f.type) { case datalog_expression_root::FUNCTION_IDENTITY: case datalog_expression_root::FUNCTION_IDENTITY_COORD: case datalog_expression_root::FUNCTION_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SINGULAR: case datalog_expression_root::FUNCTION_PLURAL: case datalog_expression_root::FUNCTION_UNCOUNTABLE: case datalog_expression_root::FUNCTION_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_CONCORD_UNCOUNTABLE: case datalog_expression_root::FUNCTION_CONCORD_NON_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL: case datalog_expression_root::FUNCTION_CONCORD_NON_PLURAL_KEEP_SINGULAR: case datalog_expression_root::FUNCTION_CONCORD_ALL: case datalog_expression_root::FUNCTION_KEEP_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_KEEP_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_KEEP_CONCORD_UNCOUNTABLE: case datalog_expression_root::FUNCTION_KEEP_SINGULAR: case datalog_expression_root::FUNCTION_KEEP_PLURAL: case datalog_expression_root::FUNCTION_KEEP_UNCOUNTABLE: case datalog_expression_root::FUNCTION_INFINITIVE: case datalog_expression_root::FUNCTION_PRESENT_PARTICIPLE: case datalog_expression_root::FUNCTION_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_KEEP_PRESENT_PARTICIPLE: case datalog_expression_root::FUNCTION_KEEP_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_FLIP_PREDICATE: case datalog_expression_root::FUNCTION_FLIP_PREDICATE_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_FLIP_PREDICATE_KEEP_PAST_PARTICIPLE: case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2: case datalog_expression_root::FUNCTION_HEAD_ARG1_SELECT_ARG2_ONLY: case datalog_expression_root::FUNCTION_EMPTY_ARG2: case datalog_expression_root::FUNCTION_EMPTY_ARGS: case datalog_expression_root::FUNCTION_ARG2_ZERO_ARITY: case datalog_expression_root::FUNCTION_LOC: case datalog_expression_root::FUNCTION_TWO_PREDICATES: num_conjuncts = INT_MAX; break; case datalog_expression_root::FUNCTION_SELECT_ARG1: case datalog_expression_root::FUNCTION_SELECT_ARG1_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_ARG1_PLURAL: case datalog_expression_root::FUNCTION_SELECT_ARG1_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG1_ONLY_DELETE_FEATURES: num_conjuncts = 0; args[0] = true; break; case datalog_expression_root::FUNCTION_DELETE_ARG1: case datalog_expression_root::FUNCTION_DELETE_ARG1_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_ARG1_PLURAL: case datalog_expression_root::FUNCTION_DELETE_ARG1_FEATURES: num_conjuncts = 1; position = POSITION_LEFT; for (unsigned int i = 1; i < datalog_predicate::ARG_COUNT; i++) args[i] = true; break; case datalog_expression_root::FUNCTION_SELECT_ARG2: case datalog_expression_root::FUNCTION_SELECT_ARG2_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG2_ONLY_DELETE_FEATURES: num_conjuncts = 0; args[1] = true; break; case datalog_expression_root::FUNCTION_DELETE_ARG2: case datalog_expression_root::FUNCTION_DELETE_ARG2_FEATURES: num_conjuncts = 1; position = POSITION_LEFT; for (unsigned int i = 0; i < datalog_predicate::ARG_COUNT; i++) if (i != 1) args[i] = true; break; case datalog_expression_root::FUNCTION_SELECT_ARG3: case datalog_expression_root::FUNCTION_SELECT_ARG3_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY: case datalog_expression_root::FUNCTION_SELECT_ARG3_ONLY_DELETE_FEATURES: num_conjuncts = 0; args[2] = true; break; case datalog_expression_root::FUNCTION_DELETE_ARG3: num_conjuncts = 1; position = POSITION_LEFT; for (unsigned int i = 0; i < datalog_predicate::ARG_COUNT; i++) if (i != 2) args[i] = true; break; case datalog_expression_root::FUNCTION_DELETE_ARGS: case datalog_expression_root::FUNCTION_DELETE_ARGS_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_ARGS_KEEP_PLURAL: num_conjuncts = 1; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_NULL: case datalog_expression_root::FUNCTION_KEEP_FEATURES: case datalog_expression_root::FUNCTION_EMPTY_TUPLE: case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY: case datalog_expression_root::FUNCTION_EMPTY_TUPLE_ONLY_KEEP_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_KEEP_NULL: num_conjuncts = 0; break; case datalog_expression_root::FUNCTION_SELECT_LEFT: case datalog_expression_root::FUNCTION_SELECT_LEFT_COORD: case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DISJOINT_COORD: case datalog_expression_root::FUNCTION_SELECT_LEFT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_DISJOINT_COORD: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_HEAD_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_FEATURES: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_ANSWER_HEAD: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_COUNT_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FUNCTION_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_NOT_FEATURES: case datalog_expression_root::FUNCTION_SELECT_LEFT_DELETE_FEATURES: num_conjuncts = 1; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_LEFT_KEEP_FUNCTION_DISJOINT: num_conjuncts = 1; position = POSITION_LEFT; function = true; break; case datalog_expression_root::FUNCTION_SELECT_LEFT2: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_COORD: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DISJOINT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_COUNT_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FUNCTION_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT2_DELETE_FEATURES: num_conjuncts = 2; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_LEFT2_KEEP_FUNCTION_DISJOINT: num_conjuncts = 2; position = POSITION_LEFT; function = true; break; case datalog_expression_root::FUNCTION_SELECT_LEFT3_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_ANSWER_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_COUNT_ANSWER: case datalog_expression_root::FUNCTION_SELECT_LEFT3_DELETE_FUNCTION_ANSWER: num_conjuncts = 3; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_SELECT_LEFT3_KEEP_FUNCTION: num_conjuncts = 3; position = POSITION_LEFT; function = true; break; case datalog_expression_root::FUNCTION_SELECT_LEFT4_DISJOINT: num_conjuncts = 4; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_SELECT_LEFT5_DISJOINT: case datalog_expression_root::FUNCTION_SELECT_LEFT5_DELETE_ANSWER_DISJOINT: num_conjuncts = 5; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_SELECT_LEFT6_DISJOINT: num_conjuncts = 6; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_SELECT_LEFT7_DISJOINT: num_conjuncts = 7; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_SELECT_RIGHT: case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_HEAD: case datalog_expression_root::FUNCTION_SELECT_RIGHT_DELETE_FUNCTION: num_conjuncts = 1; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_SELECT_RIGHT2: case datalog_expression_root::FUNCTION_SELECT_RIGHT2_SINGULAR: case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DELETE_ANSWER: case datalog_expression_root::FUNCTION_SELECT_RIGHT2_DISJOINT: num_conjuncts = 2; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_SELECT_RIGHT3_DISJOINT: num_conjuncts = 3; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_SELECT_RIGHT4_DISJOINT: num_conjuncts = 4; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_SELECT_RIGHT5_DISJOINT: num_conjuncts = 5; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_SELECT_RIGHT6_DISJOINT: num_conjuncts = 6; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_SELECT_RIGHT7_DISJOINT: num_conjuncts = 7; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_SELECT_FUNCTION: case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_FEATURES: case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD: case datalog_expression_root::FUNCTION_SELECT_FUNCTION_DELETE_HEAD_FEATURES: num_conjuncts = 0; function = true; break; case datalog_expression_root::FUNCTION_DELETE_LEFT: case datalog_expression_root::FUNCTION_DELETE_LEFT_COORD: case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT_DISJOINT_COORD: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES: case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_COUNT_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT_FUNCTION_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT_NOT_HEAD_FEATURES: case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES: num_conjuncts = -1; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_DELETE_LEFT_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_FEATURES_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_ANSWER_HEAD_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_KEEP_NOT: case datalog_expression_root::FUNCTION_DELETE_LEFT_HEAD_FEATURES_KEEP_NOT: num_conjuncts = -1; position = POSITION_LEFT; function = true; break; case datalog_expression_root::FUNCTION_DELETE_LEFT2: case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_COORD: case datalog_expression_root::FUNCTION_DELETE_LEFT2_DISJOINT_FEATURES: case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT2_HEAD_FEATURES: case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT2_COUNT_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT2_FUNCTION_ANSWER: num_conjuncts = -2; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT2_ANSWER_HEAD_KEEP_FUNCTION: num_conjuncts = -2; position = POSITION_LEFT; function = true; break; case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT3_DISJOINT_FEATURES: case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_HEAD: case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT3_COUNT_ANSWER: case datalog_expression_root::FUNCTION_DELETE_LEFT3_FUNCTION_ANSWER: num_conjuncts = -3; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_KEEP_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_LEFT3_ANSWER_HEAD_KEEP_FUNCTION: num_conjuncts = -3; position = POSITION_LEFT; function = true; break; case datalog_expression_root::FUNCTION_DELETE_LEFT4_DISJOINT: num_conjuncts = -4; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_DELETE_LEFT5_DISJOINT: case datalog_expression_root::FUNCTION_DELETE_LEFT5_ANSWER_DISJOINT: num_conjuncts = -5; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_DELETE_LEFT6_DISJOINT: num_conjuncts = -6; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_DELETE_LEFT7_DISJOINT: num_conjuncts = -7; position = POSITION_LEFT; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT: case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD: num_conjuncts = -1; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT_HEAD_KEEP_FUNCTION: num_conjuncts = -1; position = POSITION_RIGHT; function = true; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT2: case datalog_expression_root::FUNCTION_DELETE_RIGHT2_ANSWER: case datalog_expression_root::FUNCTION_DELETE_RIGHT2_DISJOINT: num_conjuncts = -2; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT3_DISJOINT: num_conjuncts = -3; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT4_DISJOINT: num_conjuncts = -4; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT5_DISJOINT: num_conjuncts = -5; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT6_DISJOINT: num_conjuncts = -6; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_DELETE_RIGHT7_DISJOINT: num_conjuncts = -7; position = POSITION_RIGHT; break; case datalog_expression_root::FUNCTION_DELETE_COUNT: case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD: case datalog_expression_root::FUNCTION_DELETE_COUNT_HEAD_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_DELETE_COUNT_ANSWER: case datalog_expression_root::FUNCTION_DELETE_NOT: case datalog_expression_root::FUNCTION_DELETE_NOT_FEATURES: case datalog_expression_root::FUNCTION_DELETE_NOT_INFINITIVE: case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_SINGULAR: case datalog_expression_root::FUNCTION_DELETE_NOT_CONCORD_PLURAL: case datalog_expression_root::FUNCTION_DELETE_FUNCTION: case datalog_expression_root::FUNCTION_DELETE_FUNCTION_FEATURES: case datalog_expression_root::FUNCTION_DELETE_FUNCTION_HEAD: case datalog_expression_root::FUNCTION_DELETE_ANSWER: case datalog_expression_root::FUNCTION_DELETE_ANSWER_HAS_LOC: num_conjuncts = 0; break; case datalog_expression_root::FUNCTION_EMPTY: fprintf(stderr, "get_selected ERROR: Invalid semantic transformation function types.\n"); exit(EXIT_FAILURE); } } enum class separability { SEPARABLE, UNSEPARABLE, ALL_UNSEPARABLE }; inline separability is_separable( const transformation<datalog_expression_root>& transformation, int& num_conjuncts, tuple_position& position, bool (&args)[datalog_predicate::ARG_COUNT], bool& function) { if (transformation.function_count != 1) return separability::ALL_UNSEPARABLE; int new_num_conjuncts = 0; tuple_position new_position = POSITION_EXACT; bool new_function = false; bool new_args[datalog_predicate::ARG_COUNT]; for (unsigned int k = 0; k < array_length(new_args); k++) new_args[k] = false; get_selected(transformation.functions[0], new_num_conjuncts, new_args, new_position, new_function); bool separable_i = true; if (function && new_function) { separable_i = false; } else if (num_conjuncts + new_num_conjuncts > 0) { separable_i = false; } function |= new_function; if (position == POSITION_EXACT) { position = new_position; } else if (new_position != POSITION_EXACT && position != new_position) { return separability::ALL_UNSEPARABLE; } if (new_num_conjuncts == INT_MAX) { return separability::ALL_UNSEPARABLE; } else if (num_conjuncts == 0) { num_conjuncts = new_num_conjuncts; } else if (num_conjuncts > 0) { if (new_num_conjuncts >= 0) { num_conjuncts = max(num_conjuncts, new_num_conjuncts); } else { return separability::ALL_UNSEPARABLE; } } else { if (new_num_conjuncts <= 0) { num_conjuncts = min(num_conjuncts, new_num_conjuncts); } else { return separability::ALL_UNSEPARABLE; } } for (unsigned int k = 0; k < array_length(args); k++) { if (args[k] && new_args[k]) return separability::ALL_UNSEPARABLE; args[k] |= new_args[k]; } return separable_i ? separability::SEPARABLE : separability::UNSEPARABLE; } void is_separable( const transformation<datalog_expression_root>* functions, unsigned int rule_length, bool* separable) { int num_conjuncts = 0; bool function = false; tuple_position position = POSITION_EXACT; bool args[datalog_predicate::ARG_COUNT]; for (unsigned int k = 0; k < array_length(args); k++) args[k] = false; for (unsigned int i = 0; i < rule_length; i++) { separability result = is_separable(functions[i], num_conjuncts, position, args, function); switch (result) { case separability::SEPARABLE: separable[i] = true; break; case separability::UNSEPARABLE: separable[i] = false; break; case separability::ALL_UNSEPARABLE: for (unsigned int j = i; j < rule_length; j++) separable[j] = false; return; } } } /** * Functions for type-checking Datalog expressions. */ constexpr unsigned int DATALOG_TYPE_ENTITY = 1; constexpr unsigned int DATALOG_TYPE_BOOLEAN = 2; constexpr unsigned int DATALOG_TYPE_INTEGER = 3; constexpr unsigned int DATALOG_TYPE_STRING = 4; constexpr unsigned int DATALOG_TYPE_COUNTABLE = 5; constexpr unsigned int DATALOG_TYPE_ANY = UINT_MAX; inline bool parse_datalog_type(unsigned int& type, const string& name) { if (name == "e") { type = DATALOG_TYPE_ENTITY; return true; } else if (name == "t") { type = DATALOG_TYPE_BOOLEAN; return true; } else if (name == "i") { type = DATALOG_TYPE_INTEGER; return true; } else if (name == "str") { type = DATALOG_TYPE_STRING; return true; } else if (name == "countable") { type = DATALOG_TYPE_COUNTABLE; return true; } else { fprintf(stderr, "parse_datalog_type ERROR: Unrecognized typename.\n"); return false; } } template<typename Stream> inline bool print_datalog_type(unsigned int type, Stream& stream) { switch (type) { case DATALOG_TYPE_ENTITY: return print('e', stream); case DATALOG_TYPE_BOOLEAN: return print('t', stream); case DATALOG_TYPE_INTEGER: return print('i', stream); case DATALOG_TYPE_STRING: return print("str", stream); case DATALOG_TYPE_COUNTABLE: return print("countable", stream); case DATALOG_TYPE_ANY: return print('*', stream); } fprintf(stderr, "print_datalog_type ERROR: Unrecognized datalog type.\n"); return false; } struct predicate_signature { unsigned int return_type; unsigned int arg_types[datalog_predicate::ARG_COUNT]; }; struct datalog_ontology { array<array<predicate_signature>> types; array<array<unsigned int>> supertypes; hash_map<string, unsigned int> type_names; datalog_ontology() : types(256), supertypes(256), type_names(32) { if (!type_names.put("e", DATALOG_TYPE_ENTITY) || !type_names.put("t", DATALOG_TYPE_BOOLEAN) || !type_names.put("i", DATALOG_TYPE_INTEGER) || !type_names.put("str", DATALOG_TYPE_STRING) || !type_names.put("countable", DATALOG_TYPE_COUNTABLE)) exit(EXIT_FAILURE); } ~datalog_ontology() { free(); } bool add_supertype(unsigned int type, unsigned int supertype) { if (type <= supertype) { fprintf(stderr, "datalog_ontology.add_supertype ERROR:" " Supertypes must appear before each subtype.\n"); return false; } else if (!ensure_capacity(type)) return false; return supertypes[type].add(supertype); } inline bool add_signature(unsigned int predicate, const predicate_signature& signature) { return ensure_capacity(predicate) && types[predicate].add(signature); } inline bool add_signature_if_empty(unsigned int predicate, const predicate_signature& signature) { return types[predicate].length != 0 || types[predicate].add(signature); } bool initialize() { if (!add_supertype(DATALOG_TYPE_INTEGER, DATALOG_TYPE_ENTITY) || !add_supertype(DATALOG_TYPE_STRING, DATALOG_TYPE_ENTITY) || !add_supertype(DATALOG_TYPE_COUNTABLE, DATALOG_TYPE_ENTITY)) return false; /* if needed, add default types for the higher-order functions */ if (!ensure_capacity(NUM_PREDICATES) || !add_signature_if_empty(PREDICATE_ANSWER, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, 0, 0}}) || !add_signature_if_empty(PREDICATE_NOT, {DATALOG_TYPE_BOOLEAN, {0, 0, 0}}) || !add_signature_if_empty(PREDICATE_COUNT, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_COUNTABLE, DATALOG_TYPE_INTEGER, 0}}) || !add_signature_if_empty(PREDICATE_SUM, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_INTEGER, DATALOG_TYPE_INTEGER, 0}}) || !add_signature_if_empty(PREDICATE_HIGHEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, 0, 0}}) || !add_signature_if_empty(PREDICATE_LOWEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, 0, 0}}) || !add_signature_if_empty(PREDICATE_LONGEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, 0, 0}}) || !add_signature_if_empty(PREDICATE_SHORTEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, 0, 0}}) || !add_signature_if_empty(PREDICATE_LARGEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, 0, 0}}) || !add_signature_if_empty(PREDICATE_SMALLEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, 0, 0}}) || !add_signature( PREDICATE_LARGEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_INTEGER, 0, 0}}) || !add_signature( PREDICATE_SMALLEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_INTEGER, 0, 0}}) || !add_signature_if_empty(PREDICATE_MOST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, DATALOG_TYPE_COUNTABLE, 0}}) || !add_signature_if_empty(PREDICATE_FEWEST, {DATALOG_TYPE_BOOLEAN, {DATALOG_TYPE_ENTITY, DATALOG_TYPE_COUNTABLE, 0}})) return false; /* compute list of supertypes for every type */ for (unsigned int i = 0; i < supertypes.length; i++) { unsigned int old_length = supertypes[i].length; for (unsigned int j = 0; j < old_length; j++) { unsigned int parent = supertypes[i][j]; if (!supertypes[i].append(supertypes[parent].data, supertypes[parent].length)) return false; } if (!supertypes[i].add(i)) return false; if (supertypes[i].length > 1) { insertion_sort(supertypes[i]); unique(supertypes[i]); } } return true; } private: bool ensure_capacity(unsigned int new_type) { if (!supertypes.ensure_capacity(new_type + 1) || !types.ensure_capacity(new_type + 1)) return false; for (unsigned int i = supertypes.length; i < supertypes.capacity; i++) { if (!array_init(supertypes[i], 4)) return false; supertypes.length++; } for (unsigned int i = types.length; i < types.capacity; i++) { if (!array_init(types[i], 2)) return false; types.length++; } return true; } void free() { for (array<unsigned int>& a : supertypes) core::free(a); for (array<predicate_signature>& a : types) core::free(a); for (auto entry : type_names) core::free(entry.key); } }; /* forward declarations */ template<bool Complete> bool build_context( const datalog_tuple& tuple, const datalog_ontology& T, array<unsigned int>& context); template<bool Complete> bool type_check( const datalog_tuple& tuple, const datalog_ontology& T, const array<unsigned int>& context); /* returns true if 'second_type' is a supertype of 'first_type' */ inline bool is_supertype(const datalog_ontology& T, unsigned int first_type, unsigned int second_type) { if (second_type == DATALOG_TYPE_ANY) return true; if (first_type == DATALOG_TYPE_ANY) return second_type == DATALOG_TYPE_ANY; unsigned int index = linear_search(T.supertypes[first_type].data, second_type, 0, T.supertypes[first_type].length); return (index < T.supertypes[first_type].length && T.supertypes[first_type][index] == second_type); } bool type_check( const datalog_literal& constant, const datalog_ontology& T, unsigned int expected_type) { if (constant.label == DATALOG_LABEL_WILDCARD || constant.label >= T.types.length || T.types[constant.label].length == 0) return true; bool match = false; for (unsigned int j = 0; j < T.types[constant.label].length; j++) { const predicate_signature& signature = T.types[constant.label][j]; bool is_constant_type = true; for (unsigned int k = 0; k < array_length(signature.arg_types); k++) { if (signature.arg_types[k] != 0) { is_constant_type = false; break; } } if (!is_constant_type) continue; if (is_supertype(T, signature.return_type, expected_type) || is_supertype(T, expected_type, signature.return_type)) { match = true; break; } } return match; } inline void build_context_any( unsigned int variable, const datalog_ontology& T, array<unsigned int>& context) { if (!ensure_variable_map_capacity(context, variable)) { exit(EXIT_FAILURE); } else if (context[variable] == 0) context[variable] = DATALOG_TYPE_ANY; } inline bool build_context( unsigned int variable, unsigned int type, const datalog_ontology& T, array<unsigned int>& context) { if (!ensure_variable_map_capacity(context, variable)) { exit(EXIT_FAILURE); } else if (context[variable] == 0) { context[variable] = type; } else if (is_supertype(T, type, context[variable])) { context[variable] = type; } else if (!is_supertype(T, context[variable], type)) { return false; } return true; } template<bool Complete, bool Flippable> bool build_context( const datalog_predicate& pred, const datalog_ontology& T, array<unsigned int>& context) { if (pred.function == PREDICATE_CONST) { if (pred.args[0] == NULL) return true; /* 'delete_args' allows this to be empty during parsing */ else if (pred.args[1] == NULL) return false; else if (!Complete && pred.args[0]->type == DATALOG_ANY) return true; else if (pred.args[0]->type != DATALOG_VARIABLE) return false; unsigned int arg_type; unsigned int variable = pred.args[0]->variable; if (pred.args[1]->type == DATALOG_PREDICATE) { unsigned int predicate = pred.args[1]->pred.function; if (predicate == DATALOG_LABEL_WILDCARD || predicate >= T.types.length || T.types[predicate].length != 1) { build_context_any(variable, T, context); return true; /* defer to type checking */ } arg_type = T.types[predicate][0].return_type; } else if (pred.args[1]->type == DATALOG_CONSTANT) { unsigned int predicate = pred.args[1]->constant.label; if (predicate == DATALOG_LABEL_WILDCARD || predicate >= T.types.length || T.types[predicate].length != 1) { build_context_any(variable, T, context); return true; /* defer to type checking */ } arg_type = T.types[predicate][0].return_type; } else if (pred.args[1]->type == DATALOG_INTEGER) { arg_type = DATALOG_TYPE_INTEGER; } else if (pred.args[1]->type == DATALOG_STRING) { arg_type = DATALOG_TYPE_STRING; } else { return false; } return build_context(variable, arg_type, T, context); } else if (pred.function == DATALOG_LABEL_WILDCARD || pred.function >= T.types.length || T.types[pred.function].length != 1) { for (unsigned int i = 0; i < array_length(pred.args); i++) { if (pred.args[i] == NULL || pred.args[i]->type != DATALOG_VARIABLE) continue; build_context_any(pred.args[i]->variable, T, context); } return true; } const predicate_signature& signature = T.types[pred.function][0]; if (Complete && signature.return_type != DATALOG_TYPE_BOOLEAN) return false; for (unsigned int i = 0; i < array_length(pred.args); i++) { if (pred.args[i] == NULL || pred.args[i]->type == DATALOG_ANY || pred.args[i]->type == DATALOG_NON_EMPTY) { /* predicate arguments can be empty during parsing */ continue; } else if (pred.args[i]->type == DATALOG_VARIABLE) { if (Flippable && i < 2) build_context_any(pred.args[i]->variable, T, context); else if (!build_context(pred.args[i]->variable, signature.arg_types[i], T, context)) return false; } else if (pred.args[i]->type == DATALOG_INTEGER) { if (!is_supertype(T, DATALOG_TYPE_INTEGER, signature.arg_types[i]) && !is_supertype(T, signature.arg_types[i], DATALOG_TYPE_INTEGER)) { return false; } } else if (pred.args[i]->type == DATALOG_STRING) { if (!is_supertype(T, DATALOG_TYPE_STRING, signature.arg_types[i]) && !is_supertype(T, signature.arg_types[i], DATALOG_TYPE_STRING)) { return false; } } else if (pred.args[i]->type == DATALOG_CONSTANT) { if (!type_check(pred.args[i]->constant, T, signature.arg_types[i])) return false; } else { return false; } } return true; } template<bool Complete> bool build_context( const datalog_function& func, const datalog_ontology& T, array<unsigned int>& context) { if (func.function != DATALOG_LABEL_WILDCARD) { /* the ontology has information about this higher-order function */ if (T.types[func.function].length > 1) { for (unsigned int i = 0; i < array_length(func.vars); i++) { if (func.vars[i] == 0) continue; build_context_any(func.vars[i], T, context); } } else { const predicate_signature& signature = T.types[func.function][0]; for (unsigned int i = 0; i < array_length(func.vars); i++) { if (func.vars[i] != 0 && !build_context(func.vars[i], signature.arg_types[i], T, context)) return false; } } } if (func.arg->type == DATALOG_PREDICATE) { return build_context<Complete, false>(func.arg->pred, T, context); } else if (func.arg->type == DATALOG_TUPLE) { return build_context<Complete, false>(func.arg->tuple, T, context); } else if (func.arg->type == DATALOG_FUNCTION) { return build_context<Complete>(func.arg->func, T, context); } else if (func.arg->type == DATALOG_ANY || func.arg->type == DATALOG_NON_EMPTY || func.arg->type == DATALOG_EMPTY) { return true; } else { fprintf(stderr, "build_context ERROR: Found a higher-order function with an " "argument that is not a predicate, tuple, or another higher-order function.\n"); return false; } } template<bool Complete, bool Flippable> bool build_context( const datalog_tuple& tuple, const datalog_ontology& T, array<unsigned int>& context) { for (unsigned int i = 0; i < tuple.elements.length; i++) { const datalog_expression* element = tuple.elements[i]; switch (element->type) { case DATALOG_PREDICATE: if ((i == 0 && !build_context<Complete, Flippable>(element->pred, T, context)) || (i == 1 && !build_context<Complete, false>(element->pred, T, context))) return false; break; case DATALOG_FUNCTION: if (!build_context<Complete>(element->func, T, context)) return false; break; case DATALOG_ANY: case DATALOG_NON_EMPTY: continue; default: fprintf(stderr, "build_context ERROR: Unrecognized tuple element type.\n"); return false; } } return true; } template<bool Complete, bool Flippable> bool type_check( const datalog_predicate& pred, const datalog_ontology& T, const array<unsigned int>& context, unsigned int expected_type) { if (pred.function == PREDICATE_CONST) { /* 'select_args' allows this to be empty during parsing */ if (pred.args[0] == NULL) return Complete ? false : true; if (!is_supertype(T, expected_type, DATALOG_TYPE_BOOLEAN) && !is_supertype(T, DATALOG_TYPE_BOOLEAN, expected_type)) return false; unsigned int variable = pred.args[0]->variable; if (pred.args[1] == NULL) { return true; } else if (pred.args[1]->type == DATALOG_PREDICATE) { unsigned int predicate = pred.args[1]->pred.function; if (predicate == DATALOG_LABEL_WILDCARD || predicate >= T.types.length || T.types[predicate].length <= 1) return true; return type_check<Complete, false>(pred.args[1]->pred, T, context, context[variable]); } else if (pred.args[1]->type == DATALOG_CONSTANT) { unsigned int predicate = pred.args[1]->constant.label; if (predicate == DATALOG_LABEL_WILDCARD || predicate >= T.types.length || T.types[predicate].length <= 1) return true; return type_check(pred.args[1]->constant, T, context[variable]); } else { return true; } } else if (pred.function == DATALOG_LABEL_WILDCARD || pred.function >= T.types.length || T.types[pred.function].length == 0) { return true; } for (unsigned int i = 0; i < T.types[pred.function].length; i++) { const predicate_signature& signature = T.types[pred.function][i]; if (!is_supertype(T, expected_type, signature.return_type) && !is_supertype(T, signature.return_type, expected_type)) continue; bool match = true; for (unsigned int i = 0; i < array_length(pred.args); i++) { unsigned int arg_type; if (pred.args[i] == NULL) { if (!Complete) { continue; } else if (signature.arg_types[i] == 0) { continue; } else { match = false; break; } } else if (pred.args[i]->type == DATALOG_ANY || pred.args[i]->type == DATALOG_NON_EMPTY) { if (Complete) { match = false; break; } else continue; } else if (pred.args[i]->type == DATALOG_CONSTANT) { if (type_check(pred.args[i]->constant, T, signature.arg_types[i])) { continue; } else { match = false; break; } } else if (pred.args[i]->type == DATALOG_INTEGER) { arg_type = DATALOG_TYPE_INTEGER; } else if (pred.args[i]->type == DATALOG_STRING) { arg_type = DATALOG_TYPE_STRING; } else if (pred.args[i]->type == DATALOG_VARIABLE) { if (pred.args[i]->variable >= context.capacity || context[pred.args[i]->variable] == 0) { /* this variable is not in the context */ return false; } arg_type = context[pred.args[i]->variable]; } else { return false; } if (!is_supertype(T, arg_type, signature.arg_types[i]) && !is_supertype(T, signature.arg_types[i], arg_type)) { if (!Flippable || i >= 2 || pred.args[i]->type != DATALOG_VARIABLE) { match = false; break; } else if (!is_supertype(T, arg_type, signature.arg_types[1 - i]) && !is_supertype(T, signature.arg_types[1 - i], arg_type)) { match = false; break; } } } if (match) return true; } /* none of the type signatures for this predicate match */ return false; } template<bool Complete> bool type_check( const datalog_function& func, const datalog_ontology& T, const array<unsigned int>& context) { if (func.function != DATALOG_LABEL_WILDCARD && T.types[func.function].length > 1) { /* we didn't type check during context construction, so we do it now */ bool type_correct = false; for (unsigned int i = 0; i < T.types[func.function].length; i++) { const predicate_signature& signature = T.types[func.function][i]; if (signature.return_type != DATALOG_TYPE_BOOLEAN) continue; bool match = true; for (unsigned int i = 0; i < array_length(func.vars); i++) { if (func.vars[i] == 0) { if (signature.arg_types[i] == 0) { continue; } else { match = false; break; } } if (func.vars[i] >= context.capacity || context[func.vars[i]] == 0) { /* this variable is not in the context */ return false; } else if (!is_supertype(T, context[func.vars[i]], signature.arg_types[i]) && !is_supertype(T, signature.arg_types[i], context[func.vars[i]])) { match = false; break; } } if (match) { type_correct = true; break; } } if (!type_correct) return false; } if (func.arg->type == DATALOG_PREDICATE) { return type_check<Complete, false>(func.arg->pred, T, context, DATALOG_TYPE_BOOLEAN); } else if (func.arg->type == DATALOG_TUPLE) { return type_check<Complete, false>(func.arg->tuple, T, context); } else if (func.arg->type == DATALOG_FUNCTION) { return type_check<Complete>(func.arg->func, T, context); } else if (func.arg->type == DATALOG_ANY || func.arg->type == DATALOG_NON_EMPTY || func.arg->type == DATALOG_EMPTY) { return true; } else { fprintf(stderr, "type_check ERROR: Found a higher-order function with an " "argument that is not a predicate, tuple, or another higher-order function.\n"); return false; } } template<bool Complete, bool Flippable> bool type_check( const datalog_tuple& tuple, const datalog_ontology& T, const array<unsigned int>& context) { for (unsigned int i = 0; i < tuple.elements.length; i++) { const datalog_expression* element = tuple.elements[i]; switch (element->type) { case DATALOG_PREDICATE: if ((i == 0 && !type_check<Complete, Flippable>(element->pred, T, context, DATALOG_TYPE_BOOLEAN)) || (i == 1 && !type_check<Complete, false>(element->pred, T, context, DATALOG_TYPE_BOOLEAN))) return false; break; case DATALOG_FUNCTION: if (!type_check<Complete>(element->func, T, context)) return false; break; case DATALOG_ANY: case DATALOG_NON_EMPTY: continue; default: fprintf(stderr, "type_check ERROR: Unrecognized tuple element type.\n"); return false; } } return true; } template<bool Complete> bool type_check(const datalog_ontology& T, const datalog_expression_root& e) { array<unsigned int> context = array<unsigned int>(8); memset(context.data, 0, sizeof(unsigned int) * context.capacity); if (e.root.type == DATALOG_ANY || e.root.type == DATALOG_NON_EMPTY || e.root.type == DATALOG_EMPTY || e.root.type == DATALOG_CONSTANT || e.root.type == DATALOG_INTEGER || e.root.type == DATALOG_STRING) { return true; } else if (e.root.type == DATALOG_TUPLE) { return build_context<Complete, !Complete>(e.root.tuple, T, context) && type_check<Complete, !Complete>(e.root.tuple, T, context); } else if (e.root.type == DATALOG_FUNCTION) { return build_context<Complete>(e.root.func, T, context) && type_check<Complete>(e.root.func, T, context); } else if (e.root.type == DATALOG_PREDICATE) { return build_context<Complete, !Complete>(e.root.pred, T, context) && type_check<Complete, !Complete>(e.root.pred, T, context, Complete ? DATALOG_TYPE_BOOLEAN : DATALOG_TYPE_ANY); } else { return false; } } /** * Functionality for reading an ontology from a stream. */ enum ontology_token_type { ONTOLOGY_TOKEN_IDENTIFIER, ONTOLOGY_TOKEN_COLON, ONTOLOGY_TOKEN_SUBTYPE, ONTOLOGY_TOKEN_ARROW }; typedef lexical_token<ontology_token_type> ontology_token; template<typename Stream> inline bool print(ontology_token_type type, Stream& stream) { switch (type) { case ONTOLOGY_TOKEN_IDENTIFIER: return print("IDENTIFIER", stream); case ONTOLOGY_TOKEN_COLON: return print(':', stream); case ONTOLOGY_TOKEN_SUBTYPE: return print("<:", stream); case ONTOLOGY_TOKEN_ARROW: return print("->", stream); } fprintf(stderr, "print ERROR: Unknown ontology_token_type.\n"); return false; } enum ontology_lexer_state { ONTOLOGY_LEXER_START, ONTOLOGY_LEXER_IDENTIFIER, ONTOLOGY_LEXER_QUOTE }; bool ontology_lex(array<ontology_token>& tokens, FILE* input) { position start = position(1, 1); position current = position(1, 1); ontology_lexer_state state = ONTOLOGY_LEXER_START; array<char> token = array<char>(1024); int next = fgetc(input); bool new_line = false; while (next != -1) { switch (state) { case ONTOLOGY_LEXER_QUOTE: if (next == '\'') { if (!emit_token(tokens, token, start, current, ONTOLOGY_TOKEN_IDENTIFIER)) return false; state = ONTOLOGY_LEXER_START; token.clear(); } else { if (!token.add(next)) return false; } break; case ONTOLOGY_LEXER_IDENTIFIER: if (next == ':') { if (!emit_token(tokens, token, start, current, ONTOLOGY_TOKEN_IDENTIFIER) || !emit_token(tokens, start, start + 1, ONTOLOGY_TOKEN_COLON)) return false; state = ONTOLOGY_LEXER_START; token.clear(); } else if (next == '-') { next = fgetc(input); if (next != '>') { read_error("Expected '>'", current); return false; } else if (!emit_token(tokens, token, start, current, ONTOLOGY_TOKEN_IDENTIFIER) || !emit_token(tokens, current, current + 2, ONTOLOGY_TOKEN_ARROW)) return false; current.column++; state = ONTOLOGY_LEXER_START; token.clear(); } else if (next == '<') { next = fgetc(input); if (next != ':') { read_error("Expected ':'", current); return false; } else if (!emit_token(tokens, token, start, current, ONTOLOGY_TOKEN_IDENTIFIER) || !emit_token(tokens, current, current + 2, ONTOLOGY_TOKEN_SUBTYPE)) return false; current.column++; state = ONTOLOGY_LEXER_START; token.clear(); } else if (next == ' ' || next == '\t' || next == '\n' || next == '\r') { if (!emit_token(tokens, token, start, current, ONTOLOGY_TOKEN_IDENTIFIER)) return false; state = ONTOLOGY_LEXER_START; token.clear(); new_line = (next == '\n'); } else if (next == '\'') { read_error("Unexpected quote after identifier", current); return false; } else { if (!token.add(next)) return false; } break; case ONTOLOGY_LEXER_START: if (next == '\'') { state = ONTOLOGY_LEXER_QUOTE; start = current; } else if (next == ':') { if (!emit_token(tokens, current, current + 1, ONTOLOGY_TOKEN_COLON)) return false; } else if (next == '-') { next = fgetc(input); if (next != '>') { read_error("Expected '>'", current); return false; } if (!emit_token(tokens, current, current + 2, ONTOLOGY_TOKEN_ARROW)) return false; current.column++; } else if (next == '<') { next = fgetc(input); if (next != ':') { read_error("Expected ':'", current); return false; } if (!emit_token(tokens, current, current + 2, ONTOLOGY_TOKEN_SUBTYPE)) return false; current.column++; } else if (next == ' ' || next == '\t' || next == '\n' || next == '\r') { new_line = (next == '\n'); } else { if (!token.add(next)) return false; state = ONTOLOGY_LEXER_IDENTIFIER; start = current; } break; } if (new_line) { current.line++; current.column = 1; new_line = false; } else current.column++; next = fgetc(input); } if (state == ONTOLOGY_LEXER_QUOTE) { read_error("Expected closing quote", current); return false; } else if (state == ONTOLOGY_LEXER_IDENTIFIER) { return emit_token(tokens, token, start, current, ONTOLOGY_TOKEN_IDENTIFIER); } return true; } bool ontology_interpret_statement( const array<ontology_token>& tokens, unsigned int& index, datalog_ontology& T, hash_map<string, unsigned int>& predicate_names) { if (!expect_token(tokens, index, ONTOLOGY_TOKEN_IDENTIFIER, "identifier at beginning of type declaration")) return false; const string& identifier = tokens[index].text; index++; if (index == tokens.length) { fprintf(stderr, "ERROR: Unexpected end of input. Expected a colon or subtype operator.\n"); return false; } else if (tokens[index].type == ONTOLOGY_TOKEN_SUBTYPE) { index++; /* this is a subtype declaration */ unsigned int subtype; if (!expect_token(tokens, index, ONTOLOGY_TOKEN_IDENTIFIER, "supertype") || !get_token(identifier, subtype, T.type_names)) return false; bool contains; unsigned int supertype = T.type_names.get(tokens[index].text, contains); if (!contains) { read_error("Undefined type", tokens[index].start); return false; } else if (!T.add_supertype(subtype, supertype)) return false; index++; } else if (tokens[index].type == ONTOLOGY_TOKEN_COLON) { index++; array<unsigned int> types = array<unsigned int>(8); while (true) { if (!expect_token(tokens, index, ONTOLOGY_TOKEN_IDENTIFIER, "type in type specification")) return false; bool contains; unsigned int type_id = T.type_names.get(tokens[index].text, contains); if (!contains) { read_error("Undefined type", tokens[index].start); return false; } else if (!types.add(type_id)) return false; index++; if (index == tokens.length || tokens[index].type != ONTOLOGY_TOKEN_ARROW) break; index++; } if (types.length > datalog_predicate::ARG_COUNT + 1) { read_error("Too many arguments in type declaration", tokens[index - 1].end); return false; } else { predicate_signature signature; signature.return_type = types.last(); for (unsigned int i = 0; i < types.length - 1; i++) signature.arg_types[i] = types[i]; for (unsigned int i = types.length - 1; i < array_length(signature.arg_types); i++) signature.arg_types[i] = 0; unsigned int predicate; if (!get_token(identifier, predicate, predicate_names) || !T.add_signature(predicate, signature)) return false; } } return true; } bool ontology_interpret( const array<ontology_token>& tokens, datalog_ontology& T, hash_map<string, unsigned int>& predicate_names) { unsigned int index = 0; while (index < tokens.length) { if (!ontology_interpret_statement(tokens, index, T, predicate_names)) return false; } return true; } /** * Code to perform morphological parsing and generation. */ inline bool intersect_concord_index(grammatical_number& intersection, grammatical_number concord, grammatical_number index) { if (concord == NUMBER_SINGULAR) { if (index != NUMBER_SINGULAR && index != NUMBER_NON_PLURAL && index != NUMBER_ALL && index != NUMBER_ANY) return false; intersection = NUMBER_SINGULAR; } else if (concord == NUMBER_PLURAL) { if (index != NUMBER_PLURAL && index != NUMBER_NON_SINGULAR && index != NUMBER_ALL && index != NUMBER_ANY) return false; intersection = NUMBER_PLURAL; } else if (concord == NUMBER_UNCOUNTABLE) { if (index != NUMBER_UNCOUNTABLE && index != NUMBER_SINGULAR && index != NUMBER_NON_SINGULAR && index != NUMBER_NON_PLURAL && index != NUMBER_ALL && index != NUMBER_ANY) return false; intersection = NUMBER_UNCOUNTABLE; } else if (concord == NUMBER_NON_SINGULAR) { if (index == NUMBER_PLURAL) { intersection = NUMBER_PLURAL; } else if (index == NUMBER_UNCOUNTABLE || index == NUMBER_NON_PLURAL || index == NUMBER_SINGULAR) { intersection = NUMBER_UNCOUNTABLE; } else if (index == NUMBER_NON_SINGULAR || index == NUMBER_ALL || index == NUMBER_ANY) { intersection = NUMBER_NON_SINGULAR; } else { return false; } } else if (concord == NUMBER_NON_PLURAL) { if (index == NUMBER_SINGULAR) { intersection = NUMBER_SINGULAR; } else if (index == NUMBER_UNCOUNTABLE || index == NUMBER_NON_SINGULAR) { intersection = NUMBER_UNCOUNTABLE; } else if (index == NUMBER_NON_PLURAL || index == NUMBER_ALL || index == NUMBER_ANY) { intersection = NUMBER_NON_PLURAL; } else { return false; } } else if (concord == NUMBER_ALL || concord == NUMBER_ANY) { if (index == NUMBER_NONE) return false; intersection = index; } else { /* concord is NUMBER_NONE */ return false; } return true; } template<typename Morphology, typename PartOfSpeechType> bool morphology_is_valid( const Morphology& morphology_parser, const sequence& terminal, PartOfSpeechType pos, const datalog_expression_root& logical_form) { if (pos == POS_OTHER) { return true; } else if (pos == POS_ADJECTIVE || pos == POS_ADVERB) { if (logical_form.concord == NUMBER_SINGULAR || logical_form.concord == NUMBER_PLURAL) return false; /* we don't model adjective morphology, for now */ /* adjective compounds are head-final (TODO: need a database of exceptions) */ unsigned int head_index = terminal.length - 1; const fixed_array<token>& result = morphology_parser.parse(terminal[head_index]); for (unsigned int i = 0; i < result.length; i++) { if (result[i].get_part_of_speech() == pos) return true; } return false; } unsigned int head_index; if (pos == POS_NOUN) { /* noun compounds are head-final (TODO: need a database of exceptions) */ head_index = terminal.length - 1; } else if (pos == POS_VERB) { /* verb compounds (phrasal verbs) are head-final (TODO: need a database of exceptions) */ head_index = 0; } else { fprintf(stderr, "morphology_is_valid ERROR: Unrecognized part of speech.\n"); return false; } /* check if concord and index have a non-empty intersection (treating the numbers as set-valued) */ grammatical_number intersection = NUMBER_NONE; if (pos == POS_NOUN) { if (!intersect_concord_index(intersection, logical_form.concord, logical_form.index)) return false; } else if (pos == POS_VERB) { /* if the verb has multiple words, ensure none are auxiliary */ if (terminal.length > 1) { for (unsigned int i = 0; i + 1 < terminal.length; i++) if (morphology_parser.is_auxiliary_root(terminal[i])) return false; } } if (pos == POS_VERB) { inflection inf = logical_form.inf; if (inf == INFLECTION_NONE) inf = INFLECTION_OTHER_VERB; if (morphology_parser.inflect({terminal[head_index], NUMBER_ANY, inf}).length > 0) return true; if (has_intersection(logical_form.index, NUMBER_SINGULAR)) { if (morphology_parser.inflect({terminal[head_index], NUMBER_SINGULAR, inf}).length > 0) return true; } if (has_intersection(logical_form.index, NUMBER_PLURAL)) { if (morphology_parser.inflect({terminal[head_index], NUMBER_PLURAL, inf}).length > 0) return true; } } else if (pos == POS_NOUN) { if (has_intersection(intersection, NUMBER_SINGULAR)) { if (morphology_parser.inflect({terminal[head_index], NUMBER_SINGULAR, INFLECTION_NOUN}).length > 0) return true; } if (has_intersection(intersection, NUMBER_PLURAL)) { if (morphology_parser.inflect({terminal[head_index], NUMBER_PLURAL, INFLECTION_NOUN}).length > 0) return true; } if (has_intersection(intersection, NUMBER_UNCOUNTABLE)) { /* simply return true, since this could be a proper noun */ return true; } } return false; } template<bool First, typename Morphology, typename PartOfSpeechType, typename EmitRootFunction> bool morphology_parse( const Morphology& morphology_parser, const sequence& words, PartOfSpeechType pos, const datalog_expression_root& logical_form, EmitRootFunction emit_root) { if (pos == POS_OTHER) { return emit_root(words, logical_form); } else if (pos == POS_ADJECTIVE || pos == POS_ADVERB) { if (logical_form.concord == NUMBER_SINGULAR || logical_form.concord == NUMBER_PLURAL) return false; /* we don't model adjective morphology, for now */ /* adjective compounds are head-final (TODO: need a database of exceptions) */ unsigned int head_index = words.length - 1; const fixed_array<token>& result = morphology_parser.parse(words[head_index]); for (unsigned int i = 0; i < result.length; i++) { if (result[i].get_part_of_speech() == pos) return emit_root(words, logical_form); } return true; } unsigned int head_index; if (pos == POS_NOUN) { /* noun compounds are head-final (TODO: need a database of exceptions) */ head_index = words.length - 1; } else if (pos == POS_VERB) { /* verb compounds (phrasal verbs) are head-initial (TODO: need a database of exceptions) */ head_index = 0; } else { fprintf(stderr, "morphology_parse ERROR: Unrecognized part of speech.\n"); return false; } /* check if concord and index have a non-empty intersection (treating the numbers as set-valued) */ grammatical_number intersection = NUMBER_NONE; if (pos == POS_NOUN) { if (!intersect_concord_index(intersection, logical_form.concord, logical_form.index)) return true; } else if (pos == POS_VERB) { /* if the verb has multiple words, ensure none are auxiliary */ if (words.length > 1) { for (unsigned int i = 0; i + 1 < words.length; i++) if (morphology_parser.is_auxiliary_verb(words[i])) return true; } } sequence root(NULL, 0); root = words; bool emitted_proper_noun = false; datalog_expression_root marked_logical_form = logical_form; const fixed_array<token>& result = morphology_parser.parse(words[head_index]); for (unsigned int i = 0; i < result.length; i++) { if (result[i].get_part_of_speech() != pos) continue; if (pos == POS_VERB) { if (!intersect(marked_logical_form.inf, logical_form.inf, result[i].inf) || !has_intersection(logical_form.index, result[i].number)) continue; if (marked_logical_form.inf == INFLECTION_OTHER_VERB) marked_logical_form.inf = INFLECTION_NONE; } else if (pos == POS_NOUN) { if (result[i].number == NUMBER_SINGULAR) { if (intersection != NUMBER_SINGULAR && intersection != NUMBER_NON_PLURAL && intersection != NUMBER_ALL && intersection != NUMBER_ANY) continue; } else if (result[i].number == NUMBER_PLURAL) { if (intersection != NUMBER_PLURAL && intersection != NUMBER_NON_SINGULAR && intersection != NUMBER_ALL && intersection != NUMBER_ANY) continue; } else { /* the noun must be uncountable */ if (intersection != NUMBER_UNCOUNTABLE && intersection != NUMBER_NON_SINGULAR && intersection != NUMBER_NON_PLURAL && intersection != NUMBER_ALL && intersection != NUMBER_ANY) continue; } marked_logical_form.inf = INFLECTION_NONE; if (logical_form.concord == NUMBER_ANY) { marked_logical_form.concord = result[i].number; } else { marked_logical_form.concord = logical_form.concord; } } root[head_index] = result[i].id; emitted_proper_noun = emitted_proper_noun || (root[head_index] == words[head_index] && (logical_form.concord != NUMBER_ANY || marked_logical_form.concord == NUMBER_UNCOUNTABLE)); if (!emit_root(root, marked_logical_form)) { free(marked_logical_form); free(root); return false; } } free(root); /* the noun might be proper */ if (!emitted_proper_noun && pos == POS_NOUN && (intersection == NUMBER_UNCOUNTABLE || intersection == NUMBER_NON_SINGULAR || intersection == NUMBER_NON_PLURAL || intersection == NUMBER_ALL || intersection == NUMBER_ANY)) { marked_logical_form.inf = INFLECTION_NONE; if (logical_form.concord == NUMBER_ANY) { marked_logical_form.concord = NUMBER_UNCOUNTABLE; } else { marked_logical_form.concord = logical_form.concord; } if (!emit_root(words, marked_logical_form)) { free(marked_logical_form); return false; } } free(marked_logical_form); return true; } template<typename PartOfSpeechType> inline bool morphology_get_inflections( const sequence& tokens, PartOfSpeechType pos, hash_set<unsigned int>& inflections) { unsigned int head_index; if (pos == POS_NOUN) { /* noun compounds are head-final (TODO: need a database of exceptions) */ head_index = tokens.length - 1; } else if (pos == POS_VERB) { /* verb compounds (phrasal verbs) are head-initial (TODO: need a database of exceptions) */ head_index = 0; } else if (pos == POS_OTHER || pos == POS_ADJECTIVE || pos == POS_ADVERB) { head_index = tokens.length; /* there is no head (we don't use the root for adjectives or adverbs in morphology_parse just yet) */ } else { fprintf(stderr, "morphology_get_inflections ERROR: Unrecognized part of speech.\n"); return false; } /* first add all uninflected tokens */ if (!inflections.check_size(inflections.size + tokens.length)) return false; for (unsigned int i = 0; i < tokens.length; i++) if (i != head_index) inflections.add(tokens[i]); /* this could be a proper noun */ if (pos == POS_NOUN && !inflections.add(tokens[head_index])) return false; /* add the inflected forms of the head token */ return head_index >= tokens.length || morphology_inflect(tokens[head_index], pos, inflections); } //inline bool morphology_inflect(sequence& terminal, part_of_speech pos, // const datalog_expression_root& logical_form) //{ // if (pos == POS_OTHER) { // return true; // } else if (pos == POS_ADJECTIVE) { // /* we don't model adjective morphology, for now */ // /* adjective compounds are head-final (TODO: need a database of exceptions) */ // unsigned int head_index = terminal.length - 1; // const fixed_array<unsigned int>& result = morphology_inflect( // {terminal[head_index], NUMBER_ANY, INFLECTION_ADJECTIVE}); // if (result.length == 0) // return false; // terminal[head_index] = result.elements[0]; // return true; // } else if (pos == POS_ADVERB) { // /* we don't model adjective morphology, for now */ // /* adjective compounds are head-final (TODO: need a database of exceptions) */ // unsigned int head_index = terminal.length - 1; // const fixed_array<unsigned int>& result = morphology_inflect( // {terminal[head_index], NUMBER_ANY, INFLECTION_ADVERB}); // if (result.length == 0) // return false; // terminal[head_index] = result.elements[0]; // return true; // } // // unsigned int head_index; // if (pos == POS_NOUN) { // /* noun compounds are head-final (TODO: need a database of exceptions) */ // head_index = terminal.length - 1; // } else if (pos == POS_VERB) { // /* verb compounds (phrasal verbs) are head-final (TODO: need a database of exceptions) */ // head_index = 0; // } else { // fprintf(stderr, "morphology_inflect ERROR: Unrecognized part of speech.\n"); // return false; // } // // /* check if concord and index have a non-empty intersection (treating the numbers as set-valued) */ // grammatical_number intersection = NUMBER_NONE; // if (pos == POS_NOUN) { // if (!intersect_concord_index(intersection, logical_form.concord, logical_form.index)) // return false; // } else if (pos == POS_VERB) { // /* if the verb has multiple words, ensure none are auxiliary */ // if (terminal.length > 1) { // for (unsigned int i = 0; i + 1 < terminal.length; i++) // if (morphology_is_auxiliary_root(terminal[i])) return false; // } // } // // array<unsigned int> inflected = array<unsigned int>(16); // if (pos == POS_VERB) { // inflection inf = logical_form.inf; // if (inf == INFLECTION_NONE) // inf = INFLECTION_OTHER_VERB; // const fixed_array<unsigned int>& result = morphology_inflect({terminal[head_index], NUMBER_ANY, inf}); // if (!inflected.append(result.elements, min(1u, result.length))) return false; // if (has_intersection(logical_form.index, NUMBER_SINGULAR)) { // const fixed_array<unsigned int>& result = morphology_inflect({terminal[head_index], NUMBER_SINGULAR, inf}); // if (!inflected.append(result.elements, min(1u, result.length))) return false; // } if (has_intersection(logical_form.index, NUMBER_PLURAL)) { // const fixed_array<unsigned int>& result = morphology_inflect({terminal[head_index], NUMBER_PLURAL, inf}); // if (!inflected.append(result.elements, min(1u, result.length))) return false; // } // } else if (pos == POS_NOUN) { // if (has_intersection(intersection, NUMBER_SINGULAR)) { // const fixed_array<unsigned int>& result = morphology_inflect({terminal[head_index], NUMBER_SINGULAR, INFLECTION_NOUN}); // if (!inflected.append(result.elements, min(1u, result.length))) return false; // } if (has_intersection(intersection, NUMBER_PLURAL)) { // const fixed_array<unsigned int>& result = morphology_inflect({terminal[head_index], NUMBER_PLURAL, INFLECTION_NOUN}); // if (!inflected.append(result.elements, min(1u, result.length))) return false; // } if (has_intersection(intersection, NUMBER_UNCOUNTABLE)) { // const fixed_array<unsigned int>& result = morphology_inflect({terminal[head_index], NUMBER_UNCOUNTABLE, INFLECTION_NOUN}); // if (!inflected.append(result.elements, min(1u, result.length))) return false; // } // } // // if (inflected.length == 0) // return false; // insertion_sort(inflected); // unique(inflected); // terminal[head_index] = sample_uniform(inflected); // return true; //} template<typename Distribution> inline bool yield(const rule<datalog_expression_root>& terminal, const Distribution& rule_distribution, const datalog_expression_root& logical_form, token*& sentence, unsigned int& length, unsigned int& capacity) { part_of_speech pos = rule_distribution.get_part_of_speech(); if (!ensure_capacity(sentence, capacity, length + terminal.t.length)) return false; for (unsigned int i = 0; i < terminal.t.length; i++) { sentence[length + i].id = terminal.t.terminals[i]; sentence[length + i].number = NUMBER_NONE; sentence[length + i].inf = INFLECTION_NONE; } if (pos == POS_NOUN) { unsigned int head_index = terminal.t.length - 1; if (!intersect_concord_index( sentence[length + head_index].number, logical_form.concord, logical_form.index)) { fprintf(stderr, "yield ERROR: Invalid grammatical number for noun.\n"); return false; } sentence[length + head_index].inf = INFLECTION_NOUN; } else if (pos == POS_VERB) { unsigned int head_index = 0; if (logical_form.inf == INFLECTION_NONE) sentence[length + head_index].inf = INFLECTION_OTHER_VERB; else sentence[length + head_index].inf = logical_form.inf; sentence[length + head_index].number = logical_form.index; } else if (pos == POS_ADJECTIVE) { unsigned int head_index = terminal.t.length - 1; sentence[length + head_index].inf = INFLECTION_ADJECTIVE; } else if (pos == POS_ADVERB) { unsigned int head_index = terminal.t.length - 1; sentence[length + head_index].inf = INFLECTION_ADVERB; } else if (pos != POS_OTHER) { fprintf(stderr, "yield ERROR: Unrecognized part of speech.\n"); return false; } length += terminal.t.length; return true; } #endif /* DATALOG_H_ */
[ "abulhair.saparov@gmail.com" ]
abulhair.saparov@gmail.com
5364ff3476a381cfc65873021e4ffde4994ca1fa
3f21c24ff10cba14ca4ab16ee62e8c1213b60bd0
/src/skills/ParallelSkill.cpp
b7f6b933e687843c74c8fceaa00e8d88db3ae702
[]
no_license
watson-intu/self
273833269f5bf1027d823896e085ac675d1eb733
150dc55e193a1df01e7acfbc47610c29b279c2e7
refs/heads/develop
2021-01-20T03:15:02.118963
2018-04-16T08:19:31
2018-04-16T08:19:31
89,515,657
34
31
null
2018-04-16T08:15:51
2017-04-26T18:50:00
C++
UTF-8
C++
false
false
3,639
cpp
/** * Copyright 2017 IBM Corp. 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 "ParallelSkill.h" #include "SkillManager.h" #include "utils/Log.h" REG_SERIALIZABLE(ParallelSkill); RTTI_IMPL( ParallelSkill, ISkill); ParallelSkill::ParallelSkill() : m_ActiveSkills(0) {} ParallelSkill::ParallelSkill(const ParallelSkill & a_Copy) : ISkill(a_Copy) { for (SkillList::const_iterator iSkill = a_Copy.m_Skills.begin(); iSkill != a_Copy.m_Skills.end(); ++iSkill) m_Skills.push_back( ISkill::SP( (*iSkill)->Clone() ) ); } ParallelSkill::~ParallelSkill() { ClearSkillList(); } void ParallelSkill::Serialize(Json::Value & json) { ISkill::Serialize(json); int index = 0; for (SkillList::iterator iSkill = m_Skills.begin(); iSkill != m_Skills.end(); ++iSkill) json["m_Skills"][index++] = ISerializable::SerializeObject( (*iSkill).get() ); } void ParallelSkill::Deserialize(const Json::Value & json) { ISkill::Deserialize(json); ClearSkillList(); const Json::Value & skills = json["m_Skills"]; for (Json::ValueConstIterator iChild = skills.begin(); iChild != skills.end(); ++iChild) m_Skills.push_back( ISkill::SP( ISerializable::DeserializeObject<ISkill>(*iChild)) ); } bool ParallelSkill::CanUseSkill() { if ( m_ActiveSkills > 0 ) return false; // still pending skills. for (SkillList::iterator iSkill = m_Skills.begin(); iSkill != m_Skills.end(); ++iSkill) if (!(*iSkill)->CanUseSkill()) return false; return true; } void ParallelSkill::UseSkill(Delegate<ISkill *> a_Callback, const ParamsMap & a_Params) { if ( m_eState == ACTIVE || m_eState == BLOCKED ) AbortSkill(); m_eState = ACTIVE; m_Callback = a_Callback; m_ActiveSkills = 0; if ( m_Skills.size() > 0 ) { for(size_t i=0;i<m_Skills.size();++i) { Log::Debug( "ParallelSkill", "Using skill %s", m_Skills[i]->GetSkillName().c_str() ); m_Skills[i]->UseSkill( DELEGATE( ParallelSkill, OnSkillDone, ISkill *, this ), a_Params ); m_ActiveSkills += 1; } } else { m_eState = COMPLETED; if ( m_Callback.IsValid() ) { m_Callback( this ); m_Callback.Reset(); } } } bool ParallelSkill::AbortSkill() { Log::Debug( "ParallelSkill", "AbortSkill() invoked." ); for(size_t i=0;i<m_Skills.size();++i) if (! m_Skills[i]->AbortSkill() ) return false; m_ActiveSkills = 0; m_eState = INACTIVE; return true; } ISkill * ParallelSkill::Clone() { return new ParallelSkill(*this); } void ParallelSkill::ClearSkillList() { m_Skills.clear(); } void ParallelSkill::OnSkillDone(ISkill * a_pSkill) { if (a_pSkill != NULL && a_pSkill->GetState() != ISkill::COMPLETED) { Log::Error("ParallelSkill", "Skill %s failed to complete, aborting parallel skill %s.", a_pSkill->GetSkillName().c_str(), GetSkillName().c_str()); AbortSkill(); m_eState = FAILED; if ( m_Callback.IsValid() ) { m_Callback( this ); m_Callback.Reset(); } } else if ( --m_ActiveSkills <= 0 ) { m_eState = COMPLETED; if ( m_Callback.IsValid() ) { m_Callback( this ); m_Callback.Reset(); } } } void ParallelSkill::AddSkill(const ISkill::SP & a_pSkill) { m_Skills.push_back(a_pSkill); }
[ "rolyle@us.ibm.com" ]
rolyle@us.ibm.com
546f8541779c10c6aa73f8065f99d8de54a27a9c
773a9bc83fcbd3941bbe38aa05d0d0c98e65d5ea
/SimpleFactoryPattern/toffee.cpp
2c912670523e25ff514676f830c26df37047ad31
[]
no_license
cf-zhang/design_patterns
45d5e42901e6a9d9d0d4dcff80999ec33d065662
eb0b3224fdaa714f4eef4f6f872ff05301358608
refs/heads/master
2021-07-05T12:37:19.284216
2019-04-28T11:25:14
2019-04-28T11:25:14
148,980,613
2
1
null
null
null
null
UTF-8
C++
false
false
229
cpp
#include "toffee.h" #include <iostream> Toffee::Toffee(float wight, float shape, float price) { this->w = wight; this->s = shape; this->p = price; this->n = "toffee"; std::cout<<"i am a toffee."<<std::endl; }
[ "cfzhang@forwardx.com" ]
cfzhang@forwardx.com
3109f461b468726f5d5ff6f1f2569b3cf1906d87
fed9f14edb87cd975ac946e01e063df492a9929a
/src/chokudaispeedrun2/J.cpp
e160ff3e06fa317b941e08c3783051cd4011a277
[]
no_license
n-inja/kyoupro
ba91dd582488b2a8c7222242801cf3115ed7fd10
44c5a888984764b98e105780ca57d522a47d832d
refs/heads/master
2021-01-01T06:52:59.655419
2020-10-17T13:28:35
2020-10-17T13:28:35
97,537,227
0
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vll = vector<ll>; using vvi = vector<vector<int>>; using vvl = vector<vector<ll>>; ll dp[505050][2] = {0}; ll ab[505050][2]; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; for (int i = 0; i < n; i++) cin >> ab[i][0] >> ab[i][1]; dp[0][0] = ab[0][0]; dp[0][1] = ab[0][1]; for (int i = 1; i < n; i++) { dp[i][0] = max(__gcd(dp[i - 1][0], ab[i][0]), __gcd(dp[i - 1][1], ab[i][0])); dp[i][1] = max(__gcd(dp[i - 1][0], ab[i][1]), __gcd(dp[i - 1][1], ab[i][1])); } cout << max(dp[n - 1][0], dp[n - 1][1]) << endl; return 0; }
[ "mccreepertakumi@gmail.com" ]
mccreepertakumi@gmail.com
4ba20ab07b880af0ef489799f2af4bad5cb86ee1
8cba77d7a0b27a22338e656d638f6b59d5d5dde8
/Lab1/Prob1.cpp
d46bda5c6d0a01a686bdaa475d9f4d66026026fc
[]
no_license
fgolubic/IRG
6bc724afe234617b00c42d139a5e13b63147cb8b
cea6fa0c6aa065622bb1da8992da1bce38fb91de
refs/heads/master
2020-03-26T02:25:11.109730
2018-08-11T18:32:06
2018-08-11T18:32:06
144,409,241
0
0
null
null
null
null
UTF-8
C++
false
false
1,527
cpp
#include<stdio.h> #include<iostream> #include<cmath> #include<glm/glm.hpp> #include<glm/gtc/type_precision.hpp> #include<glm/ext.hpp> using namespace std; using namespace glm; void matAndVec(){ dvec3 vector1 = dvec3(2.0, 3.0, -4.0); dvec3 temp = dvec3(-1.0, 4.0, -1.0); //calculate the sum of two vectors vector1 = vector1 + temp; cout <<"v1= "<< vector1.x <<"i+"<< vector1.y <<"j+"<< vector1.z <<"k\n"; //find scalar product of 2 vectors using function dot double s = dot(vector1,temp); cout <<"s= "<< s << "\n"; //find vector product of 2 vectors using cross function dvec3 vector2 = cross(vector1, dvec3(2.0, 2.0, 4.0)); cout << "v2= " << vector2.x << "i+" << vector2.y << "j+" << vector2.z << "k\n"; //find ort vector of another vector using function normalize dvec3 vector3 = normalize(vector2); cout << "v3= " << vector3.x << "i+" << vector3.y << "j+" << vector3.z << "k\n"; //calculate reverse vector dvec3 vector4 = -vector2; cout << "v4= " << vector4.x << "i+" << vector4.y << "j+" << vector4.z << "k\n\n\n"; mat3 mat1 = mat3(1, 2, 3, 2, 1, 3, 4, 5, 1); mat3 mat2 = mat3(-1, 2, -3, 5,-2, 7, -4, -1, 3); //calculate the sum of two matrix cout <<"M1= "<< to_string(mat1+mat2)<<endl<<endl; //calculate product of matrix and transposed matrix cout <<"M2= "<< to_string(matrixCompMult(mat1, transpose(mat2)))<<endl<<endl; //calculate product of matrix and inverted matrix cout <<"M3= "<< to_string(matrixCompMult(mat1, inverse(mat2))) << endl<<endl; }
[ "fgolubiczg@yahoo.com" ]
fgolubiczg@yahoo.com
85a14a34fff788f6048deb600e8050a9e57f180f
4a28104787a4ce3bf362fda9182e4f1fe6276c30
/LeetCode/Matrix/next_permutation.cpp
d5a8a2ce633bcbe7dc9239562c9081208b2bed47
[]
no_license
Ason4901/geeksforgeeks
d0538a22db00c86e97ec8b9f6c548ebd1ecef8ce
777aa4c0752bb0a9b942922e1ad99095a161cc6b
refs/heads/master
2023-02-24T07:51:15.469015
2021-01-30T15:36:20
2021-01-30T15:36:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
class Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size(), k,l; for(k = n-2; k >= 0; k--){ if(nums[k]< nums[k+1]){ break; } } if( k < 0){ reverse(nums.begin(), nums.end()); } else{ for(l = n-1; l > k; l--){ if(nums[l]> nums[k]) break; } swap(nums[k], nums[l]); reverse(nums.begin()+k+1, nums.end()); } } };
[ "51023991+abhinavprkash@users.noreply.github.com" ]
51023991+abhinavprkash@users.noreply.github.com