hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
988de1d03a83713d87e6e1d507534c855881c67f
1,927
cc
C++
chrome/browser/android/consent_auditor/consent_auditor_bridge.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/android/consent_auditor/consent_auditor_bridge.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/android/consent_auditor/consent_auditor_bridge.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <jni.h> #include <string> #include <vector> #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "chrome/browser/consent_auditor/android/jni_headers/ConsentAuditorBridge_jni.h" #include "chrome/browser/consent_auditor/consent_auditor_factory.h" #include "chrome/browser/profiles/profile_android.h" #include "components/consent_auditor/consent_auditor.h" #include "components/signin/public/identity_manager/account_info.h" using base::android::JavaParamRef; static void JNI_ConsentAuditorBridge_RecordConsent( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& j_profile, const JavaParamRef<jobject>& j_account_id, jint j_feature, const JavaParamRef<jintArray>& j_consent_description, jint j_consent_confirmation) { // TODO(markusheintz): Update the ConsentAuditorBridgeInterface. DCHECK_EQ(static_cast<consent_auditor::Feature>(j_feature), consent_auditor::Feature::CHROME_SYNC); std::vector<int> consent_description; base::android::JavaIntArrayToIntVector(env, j_consent_description, &consent_description); sync_pb::UserConsentTypes::SyncConsent sync_consent; sync_consent.set_status(sync_pb::UserConsentTypes::ConsentStatus:: UserConsentTypes_ConsentStatus_GIVEN); sync_consent.set_confirmation_grd_id(j_consent_confirmation); for (int id : consent_description) { sync_consent.add_description_grd_ids(id); } ConsentAuditorFactory::GetForProfile( ProfileAndroid::FromProfileAndroid(j_profile)) ->RecordSyncConsent(ConvertFromJavaCoreAccountId(env, j_account_id), sync_consent); }
39.326531
88
0.756098
zealoussnow
9890540529b4ee14f8da7d352c5aea6ed2d48a28
341
cpp
C++
examples/tx-modifiers.cpp
commtech/cppfscc
719e90f2207ccb819637b6ee3248f1a637ece0b5
[ "MIT" ]
2
2021-04-09T10:51:02.000Z
2021-11-12T08:37:23.000Z
examples/tx-modifiers.cpp
commtech/cppfscc
719e90f2207ccb819637b6ee3248f1a637ece0b5
[ "MIT" ]
null
null
null
examples/tx-modifiers.cpp
commtech/cppfscc
719e90f2207ccb819637b6ee3248f1a637ece0b5
[ "MIT" ]
1
2017-11-15T13:10:57.000Z
2017-11-15T13:10:57.000Z
#include <fscc.hpp> // Fscc::Port int main(void) { Fscc::Port p(0); unsigned modifiers = p.GetTxModifiers(); // Enable transmit repeat & transmit on timer p.SetTxModifiers(Fscc::TxModifiers::TXT | Fscc::TxModifiers::XREP); // Revert to normal transmission p.SetTxModifiers(Fscc::TxModifiers::XF); return 0; }
21.3125
71
0.665689
commtech
9890e6910f061b2071b0adf2388febf109eb823d
1,707
hpp
C++
redemption/src/utils/redemption_info_version.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/utils/redemption_info_version.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/utils/redemption_info_version.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Product name: redemption, a FLOSS RDP proxy Copyright (C) Wallix 2010-2013 Author(s): Christophe Grosjean, Javier Caverni, Xavier Dunat, Olivier Hervieu, Martin Potier, Jonathan Poelen, Raphaël Zhou Meng Tan version number */ #pragma once #include "main/version.hpp" #include "utils/pp.hpp" #include "utils/sugar/zstring_view.hpp" inline zstring_view redemption_info_copyright() noexcept { return "Copyright (C) Wallix 2010-2020"_zv; } inline zstring_view redemption_info_version() noexcept { return "ReDemPtion " VERSION " (" RED_PP_STRINGIFY(REDEMPTION_COMP_NAME) " " REDEMPTION_COMP_STRING_VERSION ")" #ifndef NDEBUG " (DEBUG)" #endif #if defined(__SANITIZE_ADDRESS__) && __SANITIZE_ADDRESS__ == 1 " (-fsanitize=address)" #elif defined(__has_feature) # if __has_feature(address_sanitizer) " (-fsanitize=address)" # endif #endif ""_zv ; }
29.431034
75
0.691271
DianaAssistant
9891a8c998c736739fd38db45de3cbb2b0fd5b1e
232
cpp
C++
Day04_new/ex02/Brain.cpp
EnapsTer/StudyCPP
4bcf2a152fbefebab8ff68574e2b3bc198589f99
[ "MIT" ]
1
2021-09-08T12:16:13.000Z
2021-09-08T12:16:13.000Z
Day04_new/ex02/Brain.cpp
EnapsTer/StudyCPP
4bcf2a152fbefebab8ff68574e2b3bc198589f99
[ "MIT" ]
null
null
null
Day04_new/ex02/Brain.cpp
EnapsTer/StudyCPP
4bcf2a152fbefebab8ff68574e2b3bc198589f99
[ "MIT" ]
null
null
null
// // Created by Андре Шагиджанян on 11.07.2021. // #include "Brain.hpp" #include <iostream> Brain::Brain() { std::cout << "Brain constructor" << std::endl; } Brain::~Brain() { std::cout << "Brain destructor" << std::endl; }
15.466667
48
0.616379
EnapsTer
98924afed32118925bed26adc16a39f24d5d298f
724
cpp
C++
Plugins/ProjectAcoustics/Source/ProjectAcoustics/Private/AcousticsRuntimeVolume.cpp
microsoft/Acoustic-Perception-for-Virtual-AI-Agents
e9a299fef2f4c44f194b26e3346dbb5ef2674a47
[ "MIT" ]
2
2021-09-30T00:14:22.000Z
2021-12-02T16:44:31.000Z
Plugins/ProjectAcoustics/Source/ProjectAcoustics/Private/AcousticsRuntimeVolume.cpp
microsoft/Acoustic-Perception-for-Virtual-AI-Agents
e9a299fef2f4c44f194b26e3346dbb5ef2674a47
[ "MIT" ]
null
null
null
Plugins/ProjectAcoustics/Source/ProjectAcoustics/Private/AcousticsRuntimeVolume.cpp
microsoft/Acoustic-Perception-for-Virtual-AI-Agents
e9a299fef2f4c44f194b26e3346dbb5ef2674a47
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "AcousticsRuntimeVolume.h" #include "Runtime/Launch/Resources/Version.h" #include "Components/BrushComponent.h" AAcousticsRuntimeVolume::AAcousticsRuntimeVolume(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { OverrideDesignParams.OcclusionMultiplier = 1.0f; OverrideDesignParams.WetnessAdjustment = 0.0f; OverrideDesignParams.DecayTimeMultiplier = 1.0f; OverrideDesignParams.OutdoornessAdjustment = 0.0f; OverrideDesignParams.WetRatioDistanceWarp = 0.0f; OverrideDesignParams.TransmissionDb = -60.0f; OverrideDesignParams.ApplyDynamicOpenings = false; }
40.222222
99
0.799724
microsoft
9893d474b257fda1708621646472037365bad479
4,079
cpp
C++
Assignment1/Assignment_1.2/Assignment_1.2.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
Assignment1/Assignment_1.2/Assignment_1.2.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
Assignment1/Assignment_1.2/Assignment_1.2.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
/* * Author: Jasen Ratnam 40094237 * Date: 09/18/2018 * Assignment 1: Introduction to Programming with C++ * Due: 09/28/2018 * This program will print the square, square root, the factorial of a * user inputed integer value, it will also show if it is a prime number or not. */ #include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { // Declare variables and initialize them. // One to store user input. // One to store the square of the users input. // One to store the square root of the user input. // One to store the factorial of the user input. // One to know if input is prime. // And one line string to be used to separate different steps int userInput; int square; double square_root; int factorial = 1; string prime = "Yes"; string line = "*****************************************"; // Print line and go to the next line. cout << line << "\n"; // Ask for integer from user, (To be used for calculation) and save input: cout << "This program will give the square, square root and the factorial of any given integer value, it will also show if its is prime:\n" "Please enter a Integer number: \n"; cin >> userInput; // Check if input is not an integer. // Print error message if not an integer and get new input until an integer is inserted. // Save correct input in place of wrong input. // While loop until an integer is inserted. while(!cin) { cout << "ERROR: The input was not a integer, Please enter an integer: \n"; cin.clear(); // Clear the input. cin.ignore(); // Ignore the current input and wait for new input. cin >> userInput; // Save input. } // Doesn't work. Not going into the loop. // while(cin.fail()) // { // cout << "ERROR: Please only enter a integer.\n"; // cin.clear(); // cin.exceptions(); // Should find exceptions? // cin >> userInput; // } // // Do calculations: // Uses the pow function to find the square of the user input. // Uses the sqrt function to find the square-root. square = pow(userInput, 2); square_root = sqrt(userInput); // pow(userInput, 0.5); // Factorial calculations: // For loop that multiplies factorial variable from 1 to user input. // Multiply the previous number to the next number until the user input. for(int i=1; i <= userInput; i++) { factorial = factorial*i; } // Prime calculations: // For loop that verifies if the user input can be perfectly divided by any number from 2 to input-1: // If it can then it is not prime. (Breaks loop) // If it can't then it is prime. for(int i = 2; i < userInput; i++) { if(userInput % i == 0) { prime = "No"; break; } } // Print the results to the user: (Formated version) // setw(15): sets the width of both columns to 15. // left: aligns everything to the left side of the columns. // Starts and ends with a line. cout << "\n" << line << "\n"; cout << "The results are:\n\n"; cout << left << setw(15) << "Square:" << setw(15) << square << "\n" << setw(15) << "Square root:" << setw(15) << square_root << "\n" << setw(15) << "Factorial:" << setw(15) << factorial << "\n" << setw(15) << "Prime:" << setw(15) << prime << "\n" << line; //Ending line. // Hard coded formating: // cout << "\n" << line << "\n"; // cout << "The results are:\n\n"; // cout << "Square: " << square << "\n"; // cout << "Square root: " << square_root << "\n"; // cout << "Factorial: " << factorial << "\n"; // cout << "Prime: " << prime << "\n"; // cout << line; //Ending line. return 0; }
35.163793
143
0.545477
JasenRatnam
989aceb1a0cda59239ab2e4a6247f902a47535f3
1,975
hpp
C++
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
90
2019-05-19T03:48:23.000Z
2022-02-02T15:20:49.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
11
2019-05-22T07:45:46.000Z
2021-05-20T01:48:26.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
18
2019-05-19T03:48:32.000Z
2021-05-29T18:19:16.000Z
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_ROTATION_AVERAGING_HPP #define OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_ROTATION_AVERAGING_HPP #include <vector> namespace openMVG { namespace sfm { enum ERotationAveragingMethod { ROTATION_AVERAGING_L1 = 1, ROTATION_AVERAGING_L2 = 2 }; enum ERelativeRotationInferenceMethod { TRIPLET_ROTATION_INFERENCE_NONE = 0, TRIPLET_ROTATION_INFERENCE_COMPOSITION_ERROR = 1 }; } // namespace sfm } // namespace openMVG namespace openMVG { namespace graph { struct Triplet; } } #include "openMVG/types.hpp" #include "openMVG/multiview/rotation_averaging_common.hpp" namespace openMVG { namespace sfm { class GlobalSfM_Rotation_AveragingSolver { private: mutable Pair_Set used_pairs; // pair that are considered as valid by the rotation averaging solver public: bool Run( ERotationAveragingMethod eRotationAveragingMethod, ERelativeRotationInferenceMethod eRelativeRotationInferenceMethod, const rotation_averaging::RelativeRotations & relativeRot_In, Hash_Map<IndexT, Mat3> & map_globalR ) const; /// Reject edges of the view graph that do not produce triplets with tiny /// angular error once rotation composition have been computed. void TripletRotationRejection( const double max_angular_error, std::vector<graph::Triplet> & vec_triplets, rotation_averaging::RelativeRotations & relativeRotations) const; /// Return the pairs validated by the GlobalRotation routine (inference can remove some) Pair_Set GetUsedPairs() const; }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_ROTATION_AVERAGING_HPP
29.477612
100
0.787848
Aurelio93
989c6bf4799c7224060564ca1d073ddfbff46e0c
1,097
cpp
C++
pass/lnast_print/pass_lnast_print.cpp
realdavidpang/livehd
c0462922400d34c0327b4aabb450332bda50f174
[ "BSD-3-Clause" ]
46
2018-05-31T23:07:02.000Z
2019-09-16T20:21:03.000Z
pass/lnast_print/pass_lnast_print.cpp
realdavidpang/livehd
c0462922400d34c0327b4aabb450332bda50f174
[ "BSD-3-Clause" ]
120
2018-05-16T23:11:09.000Z
2019-09-25T18:52:49.000Z
pass/lnast_print/pass_lnast_print.cpp
realdavidpang/livehd
c0462922400d34c0327b4aabb450332bda50f174
[ "BSD-3-Clause" ]
8
2018-11-08T18:53:52.000Z
2019-09-05T20:04:20.000Z
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #include "pass_lnast_print.hpp" #include "lnast_writer.hpp" #include <fstream> #include <ostream> #include <iostream> static Pass_plugin sample("pass_lnast_print", Pass_lnast_print::setup); Pass_lnast_print::Pass_lnast_print(const Eprp_var& var) : Pass("pass.lnast_print", var) {} void Pass_lnast_print::setup() { Eprp_method m1("pass.lnast_print", "Print LNAST in textual form to the terminal or a specified file", &Pass_lnast_print::do_work); m1.add_label_optional("odir", "output directory"); register_pass(m1); } void Pass_lnast_print::do_work(const Eprp_var& var) { Pass_lnast_print pass(var); auto odir = pass.get_odir(var); bool has_file_output = (odir != "/INVALID"); for (const auto &lnast : var.lnasts) { std::fstream fs; if (has_file_output) { fs.open(absl::StrCat(odir, "/", lnast->get_top_module_name(), ".ln"), std::fstream::out); } std::ostream &os = (has_file_output) ? fs : std::cout; Lnast_writer writer(os, lnast); writer.write_all(); } }
31.342857
132
0.709207
realdavidpang
98a02710b2e1e4ba63288387c51900850193d080
70
cpp
C++
lib/Iterator/SudokuIterator.cpp
SosnovGennadiy2006/sudoku
38205a261fdaa127b5d0c43141d1276e243a3747
[ "Apache-2.0" ]
null
null
null
lib/Iterator/SudokuIterator.cpp
SosnovGennadiy2006/sudoku
38205a261fdaa127b5d0c43141d1276e243a3747
[ "Apache-2.0" ]
null
null
null
lib/Iterator/SudokuIterator.cpp
SosnovGennadiy2006/sudoku
38205a261fdaa127b5d0c43141d1276e243a3747
[ "Apache-2.0" ]
null
null
null
// // Created by genas on 24.03.2022. // #include "SudokuIterator.h"
11.666667
34
0.657143
SosnovGennadiy2006
98a02a22ec0da77d3923487ae14f1a256fa57d08
704
cpp
C++
origin_code/d.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
origin_code/d.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
origin_code/d.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
// function for Chapter 2 exercise #include <iostream> #include <algorithm> using namespace std; void d(int x[], int n) { for (int i = 0; i < n; i += 2) x[i] += 2; i = 1; while (i <= n/2) { x[i] += x[i+1]; i++; } } int main() { int a[15] = {1,2,3,4,5,6,7,8,9,10,0,0,0,0,0}; int n = 10; // output the array elements cout << "a[0:9] = "; copy(a, a+10, ostream_iterator<int>(cout, " ")); cout << endl; d(a,n); cout << "Completed function d(y,10)" << endl; // output the array elements cout << "a[0:9] = "; copy(a, a+10, ostream_iterator<int>(cout, " ")); cout << endl; return 0; }
16.761905
52
0.46733
vectordb-io
98a079007fbafd5d5ab337802862db0d94278463
7,822
cpp
C++
FreeBSD/contrib/llvm/tools/lldb/source/Core/StringList.cpp
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
FreeBSD/contrib/llvm/tools/lldb/source/Core/StringList.cpp
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
FreeBSD/contrib/llvm/tools/lldb/source/Core/StringList.cpp
TigerBSD/TigerBSD
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
null
null
null
//===-- StringList.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Core/StringList.h" #include "lldb/Core/StreamString.h" #include "lldb/Host/FileSpec.h" #include "lldb/Core/Log.h" #include <string> using namespace lldb_private; StringList::StringList () : m_strings () { } StringList::StringList (const char *str) : m_strings () { if (str) m_strings.push_back (str); } StringList::StringList (const char **strv, int strc) : m_strings () { for (int i = 0; i < strc; ++i) { if (strv[i]) m_strings.push_back (strv[i]); } } StringList::~StringList () { } void StringList::AppendString (const char *str) { if (str) m_strings.push_back (str); } void StringList::AppendString (const std::string &s) { m_strings.push_back (s); } void StringList::AppendString (std::string &&s) { m_strings.push_back (s); } void StringList::AppendString (const char *str, size_t str_len) { if (str) m_strings.push_back (std::string (str, str_len)); } void StringList::AppendString(llvm::StringRef str) { m_strings.push_back(str.str()); } void StringList::AppendList (const char **strv, int strc) { for (int i = 0; i < strc; ++i) { if (strv[i]) m_strings.push_back (strv[i]); } } void StringList::AppendList (StringList strings) { size_t len = strings.GetSize(); for (size_t i = 0; i < len; ++i) m_strings.push_back (strings.GetStringAtIndex(i)); } bool StringList::ReadFileLines (FileSpec &input_file) { return input_file.ReadFileLines (m_strings); } size_t StringList::GetSize () const { return m_strings.size(); } size_t StringList::GetMaxStringLength () const { size_t max_length = 0; for (const auto &s : m_strings) { const size_t len = s.size(); if (max_length < len) max_length = len; } return max_length; } const char * StringList::GetStringAtIndex (size_t idx) const { if (idx < m_strings.size()) return m_strings[idx].c_str(); return NULL; } void StringList::Join (const char *separator, Stream &strm) { size_t size = GetSize(); if (size == 0) return; for (uint32_t i = 0; i < size; ++i) { if (i > 0) strm.PutCString(separator); strm.PutCString(GetStringAtIndex(i)); } } void StringList::Clear () { m_strings.clear(); } void StringList::LongestCommonPrefix (std::string &common_prefix) { const size_t num_strings = m_strings.size(); if (num_strings == 0) { common_prefix.clear(); } else { common_prefix = m_strings.front(); for (size_t idx = 1; idx < num_strings; ++idx) { std::string &curr_string = m_strings[idx]; size_t new_size = curr_string.size(); // First trim common_prefix if it is longer than the current element: if (common_prefix.size() > new_size) common_prefix.erase (new_size); // Then trim it at the first disparity: for (size_t i = 0; i < common_prefix.size(); i++) { if (curr_string[i] != common_prefix[i]) { common_prefix.erase(i); break; } } // If we've emptied the common prefix, we're done. if (common_prefix.empty()) break; } } } void StringList::InsertStringAtIndex (size_t idx, const char *str) { if (str) { if (idx < m_strings.size()) m_strings.insert (m_strings.begin() + idx, str); else m_strings.push_back (str); } } void StringList::InsertStringAtIndex (size_t idx, const std::string &str) { if (idx < m_strings.size()) m_strings.insert (m_strings.begin() + idx, str); else m_strings.push_back (str); } void StringList::InsertStringAtIndex (size_t idx, std::string &&str) { if (idx < m_strings.size()) m_strings.insert (m_strings.begin() + idx, str); else m_strings.push_back (str); } void StringList::DeleteStringAtIndex (size_t idx) { if (idx < m_strings.size()) m_strings.erase (m_strings.begin() + idx); } size_t StringList::SplitIntoLines (const std::string &lines) { return SplitIntoLines (lines.c_str(), lines.size()); } size_t StringList::SplitIntoLines (const char *lines, size_t len) { const size_t orig_size = m_strings.size(); if (len == 0) return 0; const char *k_newline_chars = "\r\n"; const char *p = lines; const char *end = lines + len; while (p < end) { size_t count = strcspn (p, k_newline_chars); if (count == 0) { if (p[count] == '\r' || p[count] == '\n') m_strings.push_back(std::string()); else break; } else { if (p + count > end) count = end - p; m_strings.push_back(std::string(p, count)); } if (p[count] == '\r' && p[count+1] == '\n') count++; // Skip an extra newline char for the DOS newline count++; // Skip the newline character p += count; } return m_strings.size() - orig_size; } void StringList::RemoveBlankLines () { if (GetSize() == 0) return; size_t idx = 0; while (idx < m_strings.size()) { if (m_strings[idx].empty()) DeleteStringAtIndex(idx); else idx++; } } std::string StringList::CopyList(const char* item_preamble, const char* items_sep) const { StreamString strm; for (size_t i = 0; i < GetSize(); i++) { if (i && items_sep && items_sep[0]) strm << items_sep; if (item_preamble) strm << item_preamble; strm << GetStringAtIndex(i); } return std::string(strm.GetData()); } StringList& StringList::operator << (const char* str) { AppendString(str); return *this; } StringList& StringList::operator << (const std::string& str) { AppendString(str); return *this; } StringList& StringList::operator << (StringList strings) { AppendList(strings); return *this; } StringList& StringList::operator = (const std::vector<std::string> &rhs) { Clear(); for (const auto &s : rhs) m_strings.push_back(s); return *this; } size_t StringList::AutoComplete (const char *s, StringList &matches, size_t &exact_idx) const { matches.Clear(); exact_idx = SIZE_MAX; if (s && s[0]) { const size_t s_len = strlen (s); const size_t num_strings = m_strings.size(); for (size_t i=0; i<num_strings; ++i) { if (m_strings[i].find(s) == 0) { if (exact_idx == SIZE_MAX && m_strings[i].size() == s_len) exact_idx = matches.GetSize(); matches.AppendString (m_strings[i]); } } } else { // No string, so it matches everything matches = *this; } return matches.GetSize(); } void StringList::LogDump(Log *log, const char *name) { if (!log) return; StreamString strm; if (name) strm.Printf("Begin %s:\n", name); for (const auto &s : m_strings) { strm.Indent(); strm.Printf("%s\n", s.c_str()); } if (name) strm.Printf("End %s.\n", name); log->Debug("%s", strm.GetData()); }
20.693122
86
0.555229
TigerBSD
98a3eec9f76ef5a3a76dceacb991bac21a73c377
90
hpp
C++
c++/source/morth/simulate.hpp
Phytolizer/morth
41cc00080da5f62c742ea92699fef42a41dfe962
[ "MIT" ]
null
null
null
c++/source/morth/simulate.hpp
Phytolizer/morth
41cc00080da5f62c742ea92699fef42a41dfe962
[ "MIT" ]
null
null
null
c++/source/morth/simulate.hpp
Phytolizer/morth
41cc00080da5f62c742ea92699fef42a41dfe962
[ "MIT" ]
null
null
null
#pragma once #include "morth/program.hpp" void SimulateProgram(const Program& program);
15
45
0.777778
Phytolizer
f0f9ce7929d400f516c460bc7b3b284787cf5bf9
7,856
cc
C++
arccore/src/message_passing/arccore/message_passing/SerializeMessageList.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
16
2021-09-20T12:37:01.000Z
2022-03-18T09:19:14.000Z
arccore/src/message_passing/arccore/message_passing/SerializeMessageList.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
66
2021-09-17T13:49:39.000Z
2022-03-30T16:24:07.000Z
arccore/src/message_passing/arccore/message_passing/SerializeMessageList.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
11
2021-09-27T16:48:55.000Z
2022-03-23T19:06:56.000Z
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* SerializeMessageList.cc (C) 2000-2020 */ /* */ /* Liste de messages de sérialisation. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arccore/message_passing/SerializeMessageList.h" #include "arccore/message_passing/IRequestList.h" #include "arccore/message_passing/BasicSerializeMessage.h" #include "arccore/message_passing/Messages.h" #include "arccore/base/NotImplementedException.h" #include "arccore/base/FatalErrorException.h" #include <algorithm> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arccore::MessagePassing::internal { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ SerializeMessageList:: SerializeMessageList(IMessagePassingMng* mpm) : m_message_passing_mng(mpm) , m_request_list(mpCreateRequestListRef(mpm)) , m_message_passing_phase(timeMetricPhaseMessagePassing(mpm->timeMetricCollector())) { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: addMessage(ISerializeMessage* message) { BasicSerializeMessage* true_message = dynamic_cast<BasicSerializeMessage*>(message); if (!true_message) ARCCORE_FATAL("Can not convert 'ISerializeMessage' to 'BasicSerializeMessage'"); m_messages_to_process.add(true_message); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: processPendingMessages() { for( BasicSerializeMessage* sm : m_messages_to_process ){ PointToPointMessageInfo message_info(buildMessageInfo(sm)); if (sm->destination().isNull() && !m_allow_any_rank_receive){ // Il faudra faire un probe pour ce message m_messages_to_probe.add({sm,message_info}); } else _addMessage(sm,message_info); sm->setIsProcessed(true); } m_messages_to_process.clear(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer SerializeMessageList:: waitMessages(eWaitType wait_type) { processPendingMessages(); // NOTE: il faudrait peut-être faire aussi faire des probe() dans l'appel // à _waitMessages() car il est possible que tous les messages n'aient pas // été posté. Dans ce cas, il faudrait passer en mode non bloquant tant // qu'il y a des probe à faire while(!m_messages_to_probe.empty()) _doProbe(); return _waitMessages(wait_type); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: _doProbe() { // Il faut tester avec probe() si des messages sont disponibles for( ProbeInfo& p : m_messages_to_probe ){ //tm->info() << "CHECK PROBE msg=" << p.m_message_info << " is_done?=" << p.m_is_probe_done; // Ne devrait pas être 'vrai' mais par sécurité on fait le test. if (p.m_is_probe_done) continue; MessageId message_id = mpProbe(m_message_passing_mng,p.m_message_info); if (message_id.isValid()){ //tm->info() << "FOUND PROBE message_id=" << message_id; PointToPointMessageInfo message_info(message_id,NonBlocking); _addMessage(p.m_serialize_message,message_info); p.m_is_probe_done = true; } } // Supprime les probes qui sont terminés. auto k = std::remove_if(m_messages_to_probe.begin(),m_messages_to_probe.end(), [](const ProbeInfo& p) { return p.m_is_probe_done; }); m_messages_to_probe.resize(k-m_messages_to_probe.begin()); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer SerializeMessageList:: _waitMessages(eWaitType wait_type) { TimeMetricSentry tphase(m_message_passing_phase); if (wait_type==WaitAll){ m_request_list->wait(WaitAll); // Indique que les messages sont bien terminés for( ISerializeMessage* sm : m_messages_serialize ) sm->setFinished(true); m_request_list->clear(); m_messages_serialize.clear(); return (-1); } if (wait_type==WaitSome || wait_type==TestSome){ Integer nb_request = m_request_list->size(); m_request_list->wait(wait_type); m_remaining_serialize_messages.clear(); Integer nb_done = 0; for( Integer i=0; i<nb_request; ++i ){ BasicSerializeMessage* sm = m_messages_serialize[i]; if (m_request_list->isRequestDone(i)){ ++nb_done; sm->setFinished(true); } else{ m_remaining_serialize_messages.add(sm); } } m_request_list->removeDoneRequests(); m_messages_serialize = m_remaining_serialize_messages; if (nb_done==nb_request) return (-1); return nb_done; } ARCCORE_THROW(NotImplementedException,"waitMessage with wait_type=={0}",(int)wait_type); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: _addMessage(BasicSerializeMessage* sm,const PointToPointMessageInfo& message_info) { Request r; ISerializer* s = sm->serializer(); if (sm->isSend()) r = mpSend(m_message_passing_mng,s,message_info); else r = mpReceive(m_message_passing_mng,s,message_info); m_request_list->add(r); m_messages_serialize.add(sm); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ PointToPointMessageInfo SerializeMessageList:: buildMessageInfo(ISerializeMessage* sm) { MessageId message_id(sm->_internalMessageId()); if (message_id.isValid()){ PointToPointMessageInfo message_info(message_id,NonBlocking); message_info.setSourceRank(sm->source()); return message_info; } return { sm->source(), sm->destination(), sm->internalTag(), NonBlocking }; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Ref<ISerializeMessage> SerializeMessageList:: createAndAddMessage(MessageRank destination,ePointToPointMessageType type) { MessageRank source(m_message_passing_mng->commRank()); auto x = BasicSerializeMessage::create(source,destination,type); addMessage(x.get()); return x; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane::MessagePassing /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
37.588517
96
0.502037
cedricga91
0b0127cd0c6c2815889dde2d9e5e7755c47094d7
1,310
cc
C++
lib/ui/painting/image.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
lib/ui/painting/image.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
lib/ui/painting/image.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
1
2020-03-05T02:44:12.000Z
2020-03-05T02:44:12.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/painting/image.h" #include "flutter/common/threads.h" #include "flutter/lib/ui/painting/utils.h" #include "lib/tonic/converter/dart_converter.h" #include "lib/tonic/dart_args.h" #include "lib/tonic/dart_binding_macros.h" #include "lib/tonic/dart_library_natives.h" namespace blink { typedef CanvasImage Image; IMPLEMENT_WRAPPERTYPEINFO(ui, Image); #define FOR_EACH_BINDING(V) \ V(Image, width) \ V(Image, height) \ V(Image, dispose) FOR_EACH_BINDING(DART_NATIVE_CALLBACK) void CanvasImage::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } CanvasImage::CanvasImage() {} CanvasImage::~CanvasImage() { // Skia objects must be deleted on the IO thread so that any associated GL // objects will be cleaned up through the IO thread's GL context. SkiaUnrefOnIOThread(&image_); } void CanvasImage::dispose() { ClearDartWrapper(); } size_t CanvasImage::GetAllocationSize() { if (image_) { return image_->width() * image_->height() * 4; } else { return sizeof(CanvasImage); } } } // namespace blink
25.192308
76
0.730534
alibitek
0b0217152d03f464c1a1b6ba1aa070bb449fe6ef
835
hpp
C++
fwd_euler/fwd_euler.hpp
drreynolds/Math6321-codes
3cce53bbe70bdd00220b5d8888b00b20b4fd521b
[ "CC0-1.0" ]
null
null
null
fwd_euler/fwd_euler.hpp
drreynolds/Math6321-codes
3cce53bbe70bdd00220b5d8888b00b20b4fd521b
[ "CC0-1.0" ]
null
null
null
fwd_euler/fwd_euler.hpp
drreynolds/Math6321-codes
3cce53bbe70bdd00220b5d8888b00b20b4fd521b
[ "CC0-1.0" ]
1
2020-08-31T18:04:07.000Z
2020-08-31T18:04:07.000Z
/* Forward Euler time stepper class header file. D.R. Reynolds Math 6321 @ SMU Fall 2020 */ #ifndef FORWARD_EULER_DEFINED__ #define FORWARD_EULER_DEFINED__ // Inclusions #include <cmath> #include "rhs.hpp" // Forward Euler time stepper class class ForwardEulerStepper { private: // private reusable local data arma::vec f; // storage for ODE RHS vector RHSFunction *frhs; // pointer to ODE RHS function public: // number of steps in last call unsigned long int nsteps; // constructor (sets RHS function pointer, copies y for local data) ForwardEulerStepper(RHSFunction& frhs_, arma::vec& y) { frhs = &frhs_; f = y; nsteps = 0; }; // Evolve routine (evolves the solution via forward Euler) arma::mat Evolve(arma::vec tspan, double h, arma::vec y); }; #endif
19.880952
69
0.676647
drreynolds
0b02eda3e9dd0da3a9fe7325f7e786c98395f767
3,236
cpp
C++
NaoTHSoccer/Source/Tools/Debug/Logger.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NaoTHSoccer/Source/Tools/Debug/Logger.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NaoTHSoccer/Source/Tools/Debug/Logger.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * @author <a href="xu:mellmann@informatik.hu-berlin.de">Xu, Yuan</a> */ #include "Logger.h" Logger::Logger(const std::string& cmd) : logfileManager(true),command(cmd) { description = command + " on | off | close |activate=<name> | deactivate=<name>"; activated = false; activatedOnce = false; } Logger::~Logger() { // cleanup all serializer wrappers for (RepresentationsMap::iterator iter = representations.begin(); iter != representations.end(); ++iter) { delete iter->second; } } void Logger::executeDebugCommand(const std::string& command, const ArgumentMap& arguments, std::ostream &outstream) { ASSERT(command == this->command); for(std::map<std::string, std::string>::const_iterator iter=arguments.begin(); iter!=arguments.end(); ++iter) { handleCommand(iter->first, iter->second, outstream); } }//end executeDebugCommand void Logger::handleCommand(const std::string& argName, const std::string& argValue, std::ostream& outstream) { if ("open" == argName) { logfileManager.openFile(argValue.c_str()); activeRepresentations.clear(); activated = false; // list all logable representations for(RepresentationsMap::const_iterator iter=representations.begin(); iter!=representations.end(); ++iter){ outstream << iter->first <<" "; } } else if ("activate" == argName) { for(RepresentationsMap::const_iterator iter=representations.begin(); iter!=representations.end(); ++iter) { if ( argValue == iter->first) { activeRepresentations.insert(argValue); outstream << "activated logging for " << argValue; break; } }//end for } else if ("deactivate" == argName) { for(std::set<std::string>::iterator iter=activeRepresentations.begin(); iter!=activeRepresentations.end(); ++iter) { if ( argValue == *iter ) { activeRepresentations.erase(argValue); outstream << "deactivated logging for " << argValue; break; } }//end for } else if( "status" == argName) { outstream << logfileManager.getWrittentBytesCount(); } else if ("on" == argName) { activated = true; outstream << "logging on"; } else if ("off" == argName) { activated = false; logfileManager.flush(); outstream << "logging off"; } else if ("once" == argName) { activatedOnce = true; outstream << "log once"; } else if ("close" == argName) { logfileManager.closeFile(); activated = false; outstream << "logfile closed"; } else{ outstream << "Logger Error: unsupport argument: "<<argName; } }//end handleCommand void Logger::log(unsigned int frameNum) { if (!activated && !activatedOnce) { return; } if(!logfileManager.is_ready()) { return; } for (std::set<std::string>::const_iterator iter = activeRepresentations.begin(); iter != activeRepresentations.end(); ++iter) { RepresentationsMap::iterator representation = representations.find(*iter); if(representation != representations.end()) { std::stringstream& stream = logfileManager.log(frameNum, representation->first); representation->second->serialize(stream); } } activatedOnce = false; }//end log
27.65812
118
0.647404
tarsoly
0b035cdafea27f5861f8050bec3addbba883aa00
1,724
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/socket/tcp_acceptor.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/socket/tcp_acceptor.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/socket/tcp_acceptor.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <msw/noncopyable.hpp> #include <msw/asio/tcp_acceptor.hpp> #include <msw/lexical_cast/network/endpoint/to_string.hpp> #include <msw/lexical_cast/network/endpoint/from_string.hpp> namespace rubetek { struct tcp_acceptor : msw::noncopyable { typedef msw::tcp_acceptor::io_service io_service ; typedef msw::tcp_acceptor::endpoint endpoint ; typedef msw::tcp_acceptor::on_accept on_accept ; tcp_acceptor (boost::asio::io_service&, msw::wbyte port, on_accept) ; tcp_acceptor (boost::asio::io_service&, endpoint , on_accept) ; private: logger const logger_ ; msw::tcp_acceptor tcp_acceptor_ ; }; } namespace rubetek { inline tcp_acceptor::tcp_acceptor(boost::asio::io_service& io_service, endpoint endpoint, on_accept on_accept) : logger_ ( "tcp acceptor", msw::network_endpoint_to_string(endpoint), log::level::info) , tcp_acceptor_ ( io_service , endpoint , [this, on_accept](boost::asio::ip::tcp::socket socket) { logger_.debug("accepted new connection: ", msw::network_endpoint_to_string(socket.remote_endpoint())); on_accept(std::move(socket)); } , [this](boost::system::error_code ec) { logger_.error(ec.message()); throw boost::system::system_error(ec); } ) {} inline tcp_acceptor::tcp_acceptor(boost::asio::io_service& io_service, msw::wbyte port, on_accept on_accept) : tcp_acceptor (io_service, msw::tcp_endpoint_from_string("0.0.0.0", port), on_accept) {} }
32.528302
118
0.61949
yklishevich
0b077a221f8f1e994f8c9141b207ad6ad5078ef3
733
hh
C++
styler.hh
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
styler.hh
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
styler.hh
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
#ifndef __MAKEMORE_STYLER_HH__ #define __MAKEMORE_STYLER_HH__ 1 #include <string.h> #include <stdlib.h> #include <string> #include <map> #include "project.hh" #include "cholo.hh" namespace makemore { struct Styler : Project { double *tmp; unsigned int dim; std::map<std::string, Cholo*> tag_cholo; double *msamp, *fsamp; unsigned int msampn, fsampn; Styler(const std::string &dir); ~Styler() { delete[] tmp; } void add_cholo(const std::string &tag, const std::string &fn) { assert(tag_cholo.find(tag) == tag_cholo.end()); tag_cholo[tag] = new Cholo(fn, dim); } void encode(const double *ctr, Parson *prs); void generate(const Parson &prs, double *ctr, unsigned int m = 1); }; } #endif
17.878049
68
0.673943
jdb19937
0b079aeea16c86ab59c5e1475c4d1736513c341e
4,348
cxx
C++
Rendering/Core/vtkRenderTimerLog.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
3
2015-07-28T18:07:50.000Z
2018-02-28T20:59:58.000Z
Rendering/Core/vtkRenderTimerLog.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
4
2018-10-25T09:46:11.000Z
2019-01-17T16:49:17.000Z
Rendering/Core/vtkRenderTimerLog.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
4
2016-09-08T02:11:00.000Z
2019-08-15T02:38:39.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkRenderTimerLog.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkRenderTimerLog.h" #include "vtkObjectFactory.h" #include <iomanip> #include <utility> vtkObjectFactoryNewMacro(vtkRenderTimerLog) //------------------------------------------------------------------------------ vtkRenderTimerLog::vtkRenderTimerLog() : LoggingEnabled(false), FrameLimit(32) { } //------------------------------------------------------------------------------ vtkRenderTimerLog::~vtkRenderTimerLog() = default; //------------------------------------------------------------------------------ void vtkRenderTimerLog::PrintSelf(std::ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ bool vtkRenderTimerLog::IsSupported() { return false; } //------------------------------------------------------------------------------ void vtkRenderTimerLog::MarkFrame() { } //------------------------------------------------------------------------------ vtkRenderTimerLog::ScopedEventLogger vtkRenderTimerLog::StartScopedEvent(const std::string &name) { this->MarkStartEvent(name); return ScopedEventLogger(this); } //------------------------------------------------------------------------------ void vtkRenderTimerLog::MarkStartEvent(const std::string &) { } //------------------------------------------------------------------------------ void vtkRenderTimerLog::MarkEndEvent() { } //------------------------------------------------------------------------------ bool vtkRenderTimerLog::FrameReady() { vtkWarningMacro("vtkRenderTimerLog unsupported for the current rendering " "backend."); return false; } //------------------------------------------------------------------------------ vtkRenderTimerLog::Frame vtkRenderTimerLog::PopFirstReadyFrame() { return Frame(); } //------------------------------------------------------------------------------ void vtkRenderTimerLog::ReleaseGraphicsResources() { } //------------------------------------------------------------------------------ vtkRenderTimerLog::ScopedEventLogger::ScopedEventLogger(ScopedEventLogger &&o) : Log(nullptr) { std::swap(o.Log, this->Log); } //------------------------------------------------------------------------------ vtkRenderTimerLog::ScopedEventLogger & vtkRenderTimerLog::ScopedEventLogger::operator=(ScopedEventLogger &&o) { std::swap(o.Log, this->Log); return *this; } //------------------------------------------------------------------------------ void vtkRenderTimerLog::ScopedEventLogger::Stop() { if (this->Log) { this->Log->MarkEndEvent(); this->Log = nullptr; } } //------------------------------------------------------------------------------ void vtkRenderTimerLog::Frame::Print(std::ostream &os, float threshMs) { vtkIndent indent; for (auto event : this->Events) { event.Print(os, 0.f, threshMs, indent); } } //------------------------------------------------------------------------------ void vtkRenderTimerLog::Event::Print(std::ostream &os, float parentTime, float threshMs, vtkIndent indent) { float thisTime = this->ElapsedTimeMilliseconds(); if (thisTime < threshMs) { return; } float parentPercent = 100.f; if (parentTime > 0.f) { parentPercent = thisTime / parentTime * 100.f; } os << indent << "- " << std::fixed << std::setw(5) << std::setprecision(1) << parentPercent << std::setw(0) << "% " << std::setw(8) << std::setprecision(3) << thisTime << std::setw(0) << " ms \"" << this->Name << "\"\n"; vtkIndent nextIndent = indent.GetNextIndent(); for (auto event : this->Events) { event.Print(os, thisTime, threshMs, nextIndent); } }
28.418301
80
0.463661
forestGzh
0b0bf34cddfcaaf99c2bee8de7bb780719217fed
2,689
cpp
C++
src/modules/keyboardmanager/KeyboardManagerEditorLibrary/KeyboardManagerEditorStrings.cpp
tameemzabalawi/PowerToys
5c6f7b1aea90ecd9ebe5cb8c7ddf82f8113fcb45
[ "MIT" ]
76,518
2019-05-06T22:50:10.000Z
2022-03-31T22:20:54.000Z
src/modules/keyboardmanager/KeyboardManagerEditorLibrary/KeyboardManagerEditorStrings.cpp
Nakatai-0322/PowerToys
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
[ "MIT" ]
15,530
2019-05-07T01:10:24.000Z
2022-03-31T23:48:46.000Z
src/modules/keyboardmanager/KeyboardManagerEditorLibrary/KeyboardManagerEditorStrings.cpp
Nakatai-0322/PowerToys
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
[ "MIT" ]
5,184
2019-05-06T23:32:32.000Z
2022-03-31T15:43:25.000Z
#include "pch.h" #include "KeyboardManagerEditorStrings.h" // Function to return the error message winrt::hstring KeyboardManagerEditorStrings::GetErrorMessage(ShortcutErrorType errorType) { switch (errorType) { case ShortcutErrorType::NoError: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_REMAPSUCCESSFUL).c_str(); case ShortcutErrorType::SameKeyPreviouslyMapped: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SAMEKEYPREVIOUSLYMAPPED).c_str(); case ShortcutErrorType::MapToSameKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_MAPPEDTOSAMEKEY).c_str(); case ShortcutErrorType::ConflictingModifierKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_CONFLICTINGMODIFIERKEY).c_str(); case ShortcutErrorType::SameShortcutPreviouslyMapped: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SAMESHORTCUTPREVIOUSLYMAPPED).c_str(); case ShortcutErrorType::MapToSameShortcut: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_MAPTOSAMESHORTCUT).c_str(); case ShortcutErrorType::ConflictingModifierShortcut: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_CONFLICTINGMODIFIERSHORTCUT).c_str(); case ShortcutErrorType::WinL: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_WINL).c_str(); case ShortcutErrorType::CtrlAltDel: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_CTRLALTDEL).c_str(); case ShortcutErrorType::RemapUnsuccessful: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_REMAPUNSUCCESSFUL).c_str(); case ShortcutErrorType::SaveFailed: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SAVEFAILED).c_str(); case ShortcutErrorType::ShortcutStartWithModifier: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTSTARTWITHMODIFIER).c_str(); case ShortcutErrorType::ShortcutCannotHaveRepeatedModifier: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTNOREPEATEDMODIFIER).c_str(); case ShortcutErrorType::ShortcutAtleast2Keys: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTATLEAST2KEYS).c_str(); case ShortcutErrorType::ShortcutOneActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTONEACTIONKEY).c_str(); case ShortcutErrorType::ShortcutNotMoreThanOneActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTMAXONEACTIONKEY).c_str(); case ShortcutErrorType::ShortcutMaxShortcutSizeOneActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_MAXSHORTCUTSIZE).c_str(); case ShortcutErrorType::ShortcutDisableAsActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_DISABLEASACTIONKEY).c_str(); default: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_DEFAULT).c_str(); } }
54.877551
90
0.804016
tameemzabalawi
0b1885911f242e60c4263bfaf22d2f8c47cff746
12,088
cpp
C++
examples/DynamicControlDemo/MotorDemo.cpp
frk2/bullet3
225d823e4dc3f952c6c39920c3f87390383e0602
[ "Zlib" ]
26
2019-10-11T11:54:48.000Z
2022-03-04T19:49:18.000Z
examples/DynamicControlDemo/MotorDemo.cpp
frk2/bullet3
225d823e4dc3f952c6c39920c3f87390383e0602
[ "Zlib" ]
1
2018-11-19T19:07:47.000Z
2018-11-19T19:07:47.000Z
examples/DynamicControlDemo/MotorDemo.cpp
frk2/bullet3
225d823e4dc3f952c6c39920c3f87390383e0602
[ "Zlib" ]
4
2021-06-03T10:09:40.000Z
2022-01-12T09:54:10.000Z
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2007 Erwin Coumans Motor Demo This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btBulletDynamicsCommon.h" #include "LinearMath/btIDebugDraw.h" #include "MotorDemo.h" #include "LinearMath/btAlignedObjectArray.h" class btBroadphaseInterface; class btCollisionShape; class btOverlappingPairCache; class btCollisionDispatcher; class btConstraintSolver; struct btCollisionAlgorithmCreateFunc; class btDefaultCollisionConfiguration; #include "../CommonInterfaces/CommonRigidBodyBase.h" class MotorDemo : public CommonRigidBodyBase { float m_Time; float m_fCyclePeriod; // in milliseconds float m_fMuscleStrength; btAlignedObjectArray<class TestRig*> m_rigs; public: MotorDemo(struct GUIHelperInterface* helper) : CommonRigidBodyBase(helper) { } void initPhysics(); void exitPhysics(); virtual ~MotorDemo() { } void spawnTestRig(const btVector3& startOffset, bool bFixed); // virtual void keyboardCallback(unsigned char key, int x, int y); void setMotorTargets(btScalar deltaTime); void resetCamera() { float dist = 11; float pitch = -35; float yaw = 52; float targetPos[3] = {0, 0.46, 0}; m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]); } }; #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 #endif #ifndef M_PI_4 #define M_PI_4 0.785398163397448309616 #endif #ifndef M_PI_8 #define M_PI_8 0.5 * M_PI_4 #endif // /LOCAL FUNCTIONS #define NUM_LEGS 6 #define BODYPART_COUNT 2 * NUM_LEGS + 1 #define JOINT_COUNT BODYPART_COUNT - 1 class TestRig { btDynamicsWorld* m_ownerWorld; btCollisionShape* m_shapes[BODYPART_COUNT]; btRigidBody* m_bodies[BODYPART_COUNT]; btTypedConstraint* m_joints[JOINT_COUNT]; btRigidBody* localCreateRigidBody(btScalar mass, const btTransform& startTransform, btCollisionShape* shape) { bool isDynamic = (mass != 0.f); btVector3 localInertia(0, 0, 0); if (isDynamic) shape->calculateLocalInertia(mass, localInertia); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, shape, localInertia); btRigidBody* body = new btRigidBody(rbInfo); m_ownerWorld->addRigidBody(body); return body; } public: TestRig(btDynamicsWorld* ownerWorld, const btVector3& positionOffset, bool bFixed) : m_ownerWorld(ownerWorld) { btVector3 vUp(0, 1, 0); // // Setup geometry // float fBodySize = 0.25f; float fLegLength = 0.45f; float fForeLegLength = 0.75f; m_shapes[0] = new btCapsuleShape(btScalar(fBodySize), btScalar(0.10)); int i; for (i = 0; i < NUM_LEGS; i++) { m_shapes[1 + 2 * i] = new btCapsuleShape(btScalar(0.10), btScalar(fLegLength)); m_shapes[2 + 2 * i] = new btCapsuleShape(btScalar(0.08), btScalar(fForeLegLength)); } // // Setup rigid bodies // float fHeight = 0.5; btTransform offset; offset.setIdentity(); offset.setOrigin(positionOffset); // root btVector3 vRoot = btVector3(btScalar(0.), btScalar(fHeight), btScalar(0.)); btTransform transform; transform.setIdentity(); transform.setOrigin(vRoot); if (bFixed) { m_bodies[0] = localCreateRigidBody(btScalar(0.), offset * transform, m_shapes[0]); } else { m_bodies[0] = localCreateRigidBody(btScalar(1.), offset * transform, m_shapes[0]); } // legs for (i = 0; i < NUM_LEGS; i++) { float fAngle = 2 * M_PI * i / NUM_LEGS; float fSin = sin(fAngle); float fCos = cos(fAngle); transform.setIdentity(); btVector3 vBoneOrigin = btVector3(btScalar(fCos * (fBodySize + 0.5 * fLegLength)), btScalar(fHeight), btScalar(fSin * (fBodySize + 0.5 * fLegLength))); transform.setOrigin(vBoneOrigin); // thigh btVector3 vToBone = (vBoneOrigin - vRoot).normalize(); btVector3 vAxis = vToBone.cross(vUp); transform.setRotation(btQuaternion(vAxis, M_PI_2)); m_bodies[1 + 2 * i] = localCreateRigidBody(btScalar(1.), offset * transform, m_shapes[1 + 2 * i]); // shin transform.setIdentity(); transform.setOrigin(btVector3(btScalar(fCos * (fBodySize + fLegLength)), btScalar(fHeight - 0.5 * fForeLegLength), btScalar(fSin * (fBodySize + fLegLength)))); m_bodies[2 + 2 * i] = localCreateRigidBody(btScalar(1.), offset * transform, m_shapes[2 + 2 * i]); } // Setup some damping on the m_bodies for (i = 0; i < BODYPART_COUNT; ++i) { m_bodies[i]->setDamping(0.05, 0.85); m_bodies[i]->setDeactivationTime(0.8); //m_bodies[i]->setSleepingThresholds(1.6, 2.5); m_bodies[i]->setSleepingThresholds(0.5f, 0.5f); } // // Setup the constraints // btHingeConstraint* hingeC; //btConeTwistConstraint* coneC; btTransform localA, localB, localC; for (i = 0; i < NUM_LEGS; i++) { float fAngle = 2 * M_PI * i / NUM_LEGS; float fSin = sin(fAngle); float fCos = cos(fAngle); // hip joints localA.setIdentity(); localB.setIdentity(); localA.getBasis().setEulerZYX(0, -fAngle, 0); localA.setOrigin(btVector3(btScalar(fCos * fBodySize), btScalar(0.), btScalar(fSin * fBodySize))); localB = m_bodies[1 + 2 * i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA; hingeC = new btHingeConstraint(*m_bodies[0], *m_bodies[1 + 2 * i], localA, localB); hingeC->setLimit(btScalar(-0.75 * M_PI_4), btScalar(M_PI_8)); //hingeC->setLimit(btScalar(-0.1), btScalar(0.1)); m_joints[2 * i] = hingeC; m_ownerWorld->addConstraint(m_joints[2 * i], true); // knee joints localA.setIdentity(); localB.setIdentity(); localC.setIdentity(); localA.getBasis().setEulerZYX(0, -fAngle, 0); localA.setOrigin(btVector3(btScalar(fCos * (fBodySize + fLegLength)), btScalar(0.), btScalar(fSin * (fBodySize + fLegLength)))); localB = m_bodies[1 + 2 * i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA; localC = m_bodies[2 + 2 * i]->getWorldTransform().inverse() * m_bodies[0]->getWorldTransform() * localA; hingeC = new btHingeConstraint(*m_bodies[1 + 2 * i], *m_bodies[2 + 2 * i], localB, localC); //hingeC->setLimit(btScalar(-0.01), btScalar(0.01)); hingeC->setLimit(btScalar(-M_PI_8), btScalar(0.2)); m_joints[1 + 2 * i] = hingeC; m_ownerWorld->addConstraint(m_joints[1 + 2 * i], true); } } virtual ~TestRig() { int i; // Remove all constraints for (i = 0; i < JOINT_COUNT; ++i) { m_ownerWorld->removeConstraint(m_joints[i]); delete m_joints[i]; m_joints[i] = 0; } // Remove all bodies and shapes for (i = 0; i < BODYPART_COUNT; ++i) { m_ownerWorld->removeRigidBody(m_bodies[i]); delete m_bodies[i]->getMotionState(); delete m_bodies[i]; m_bodies[i] = 0; delete m_shapes[i]; m_shapes[i] = 0; } } btTypedConstraint** GetJoints() { return &m_joints[0]; } }; void motorPreTickCallback(btDynamicsWorld* world, btScalar timeStep) { MotorDemo* motorDemo = (MotorDemo*)world->getWorldUserInfo(); motorDemo->setMotorTargets(timeStep); } void MotorDemo::initPhysics() { m_guiHelper->setUpAxis(1); // Setup the basic world m_Time = 0; m_fCyclePeriod = 2000.f; // in milliseconds // m_fMuscleStrength = 0.05f; // new SIMD solver for joints clips accumulated impulse, so the new limits for the motor // should be (numberOfsolverIterations * oldLimits) // currently solver uses 10 iterations, so: m_fMuscleStrength = 0.5f; m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); btVector3 worldAabbMin(-10000, -10000, -10000); btVector3 worldAabbMax(10000, 10000, 10000); m_broadphase = new btAxisSweep3(worldAabbMin, worldAabbMax); m_solver = new btSequentialImpulseConstraintSolver; m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration); m_dynamicsWorld->setInternalTickCallback(motorPreTickCallback, this, true); m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld); // Setup a big ground box { btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(200.), btScalar(10.), btScalar(200.))); m_collisionShapes.push_back(groundShape); btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(0, -10, 0)); createRigidBody(btScalar(0.), groundTransform, groundShape); } // Spawn one ragdoll btVector3 startOffset(1, 0.5, 0); spawnTestRig(startOffset, false); startOffset.setValue(-2, 0.5, 0); spawnTestRig(startOffset, true); m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); } void MotorDemo::spawnTestRig(const btVector3& startOffset, bool bFixed) { TestRig* rig = new TestRig(m_dynamicsWorld, startOffset, bFixed); m_rigs.push_back(rig); } void PreStep() { } void MotorDemo::setMotorTargets(btScalar deltaTime) { float ms = deltaTime * 1000000.; float minFPS = 1000000.f / 60.f; if (ms > minFPS) ms = minFPS; m_Time += ms; // // set per-frame sinusoidal position targets using angular motor (hacky?) // for (int r = 0; r < m_rigs.size(); r++) { for (int i = 0; i < 2 * NUM_LEGS; i++) { btHingeConstraint* hingeC = static_cast<btHingeConstraint*>(m_rigs[r]->GetJoints()[i]); btScalar fCurAngle = hingeC->getHingeAngle(); btScalar fTargetPercent = (int(m_Time / 1000) % int(m_fCyclePeriod)) / m_fCyclePeriod; btScalar fTargetAngle = 0.5 * (1 + sin(2 * M_PI * fTargetPercent)); btScalar fTargetLimitAngle = hingeC->getLowerLimit() + fTargetAngle * (hingeC->getUpperLimit() - hingeC->getLowerLimit()); btScalar fAngleError = fTargetLimitAngle - fCurAngle; btScalar fDesiredAngularVel = 1000000.f * fAngleError / ms; hingeC->enableAngularMotor(true, fDesiredAngularVel, m_fMuscleStrength); } } } #if 0 void MotorDemo::keyboardCallback(unsigned char key, int x, int y) { switch (key) { case '+': case '=': m_fCyclePeriod /= 1.1f; if (m_fCyclePeriod < 1.f) m_fCyclePeriod = 1.f; break; case '-': case '_': m_fCyclePeriod *= 1.1f; break; case '[': m_fMuscleStrength /= 1.1f; break; case ']': m_fMuscleStrength *= 1.1f; break; default: DemoApplication::keyboardCallback(key, x, y); } } #endif void MotorDemo::exitPhysics() { int i; for (i = 0; i < m_rigs.size(); i++) { TestRig* rig = m_rigs[i]; delete rig; } //cleanup in the reverse order of creation/initialization //remove the rigidbodies from the dynamics world and delete them for (i = m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--) { btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } m_dynamicsWorld->removeCollisionObject(obj); delete obj; } //delete collision shapes for (int j = 0; j < m_collisionShapes.size(); j++) { btCollisionShape* shape = m_collisionShapes[j]; delete shape; } //delete dynamics world delete m_dynamicsWorld; //delete solver delete m_solver; //delete broadphase delete m_broadphase; //delete dispatcher delete m_dispatcher; delete m_collisionConfiguration; } class CommonExampleInterface* MotorControlCreateFunc(struct CommonExampleOptions& options) { return new MotorDemo(options.m_guiHelper); }
27.981481
243
0.717158
frk2
0b1a22c034a428f434ddd4bf173b5f6915edd535
530
cpp
C++
Array/02. ReverseTheArray.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
2
2021-05-21T17:10:02.000Z
2021-05-29T05:13:06.000Z
Array/02. ReverseTheArray.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
Array/02. ReverseTheArray.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
// ? Reverse the Array #include <iostream> using namespace std; void reverse(int arr[], int n) { int low = 0, high = n - 1; while (low < high) swap(arr[low++], arr[high--]); } int main() { int arr[] = {10, 5, 7, 30}, n = 4; cout << "Before Reverse" << endl; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; reverse(arr, n); cout << "After Reverse" << endl; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
16.060606
38
0.445283
sohamnandi77
0b1deba262300c5eafdfdb5ba756458872f13ce3
15,232
cpp
C++
IvmpDotNet.Proxy/SDK/Shared/CSettings.cpp
purm/IvmpDotNet
8ec3b7819aba9d806f9a95b2b87e4375fdfdefe2
[ "MIT" ]
1
2021-01-26T05:52:04.000Z
2021-01-26T05:52:04.000Z
IvmpDotNet.Proxy/SDK/Shared/CSettings.cpp
purm/IvmpDotNet
8ec3b7819aba9d806f9a95b2b87e4375fdfdefe2
[ "MIT" ]
null
null
null
IvmpDotNet.Proxy/SDK/Shared/CSettings.cpp
purm/IvmpDotNet
8ec3b7819aba9d806f9a95b2b87e4375fdfdefe2
[ "MIT" ]
null
null
null
//============== IV: Multiplayer - http://code.iv-multiplayer.com ============== // // File: CSettings.cpp // Project: Shared // Author(s): jenksta // mabako // License: See LICENSE in root directory // //============================================================================== #include "CSettings.h" #include "SharedUtility.h" #include "CLogFile.h" std::map<String, SettingsValue *> CSettings::m_values; bool CSettings::m_bOpen = false; bool CSettings::m_bSave = false; TiXmlDocument CSettings::m_XMLDocument; void CSettings::LoadDefaults() { // jenksta: HACKY, find another way #ifdef _SERVER AddString("logfile", "ivmp-svr.log"); AddInteger("port", 9999, 1024, 65535); AddInteger("httpport", 9998, 80, 65535); AddString("httpserver", ""); AddInteger("maxplayers", MAX_PLAYERS, 1, MAX_PLAYERS); AddInteger("maxvehicles", MAX_VEHICLES, 0, MAX_VEHICLES); AddString("password", ""); AddBool("query", true); AddBool("listed", false); AddBool("guinametags",false); AddBool("vehicledamage", false); AddBool("vehiclewaterdeath", true); AddBool("headmovement",true); AddString("hostname", VERSION_IDENTIFIER_2 " Server"); AddString("hostaddress", ""); AddBool("frequentevents", false); AddBool("kickoldplayers", true); AddBool("paynspray", true); AddBool("autoaim", true); AddInteger("weather", 1, 1, 10); AddFloat("wind",0.0,0.0,50.0); AddBool("silent", false); AddBool("timestamp", true); AddList("script"); AddList("clientscript"); AddList("clientresource"); AddList("module"); AddList("config"); #else AddString("ip", "127.0.0.1"); AddInteger("port", 9999, 1024, 65535); //AddString("nick", "kyefag"); //AddString("nick", "jenksta"); AddString("nick", "player"); AddString("pass", ""); AddBool("windowed", false); AddBool("fps", false); AddString("chatfont", "tahoma-bold"); AddInteger("chatsize", 10, 1, 100); AddInteger("chatbga", 0, 0, 255); AddInteger("chatbgr", 0, 0, 255); AddInteger("chatbgg", 0, 0, 255); AddInteger("chatbgb", 0, 0, 255); #endif } SettingsValue * CSettings::GetSetting(String strSetting) { for(std::map<String, SettingsValue *>::iterator iter = m_values.begin(); iter != m_values.end(); iter++) { if(iter->first == strSetting) return iter->second; } return NULL; } bool CSettings::Open(String strPath, bool bCreate, bool bSave) { // Flag we are not allowed to save the file by default m_bSave = false; // Load the default settings LoadDefaults(); // Does the settings file not exist? bool bExists = true; if(!SharedUtility::Exists(strPath.Get())) { if(!bCreate) { CLogFile::Printf("ERROR: Settings file %s does not exist.", strPath.Get()); return false; } else { CLogFile::Printf("WARNING: Settings file %s does not exist, it will now be created.", strPath.Get()); // Attempt to open the file for write FILE * fFile = fopen(strPath.Get(), "w"); // Ensure the file was opened if(!fFile) { CLogFile::Printf("WARNING: Failed to create settings file %s, no settings will be loaded or saved.", strPath.Get()); // Flag the settings file as does not exist bExists = false; } else { // Write the default contents to the file fprintf(fFile, "<settings />"); // Close the file fclose(fFile); } } } // Load the settings file if(bExists) { // Attempt to load the XML file if(m_XMLDocument.LoadFile(strPath.Get())) { // Flag ourselves as open m_bOpen = true; // Loop through all XML nodes for(TiXmlNode * pNode = m_XMLDocument.RootElement()->FirstChildElement(); pNode; pNode = pNode->NextSibling()) { // Is this not an element node? if(pNode->Type() != TiXmlNode::ELEMENT) continue; // Get the setting and value String strSetting = pNode->Value(); String strValue = pNode->ToElement()->GetText(); // Does the setting not exist? if(!Exists(strSetting)) CLogFile::Printf("WARNING: Log file setting %s does not exist.", strSetting.Get()); else SetEx(strSetting, strValue); } // Flag if we are allowed to save the file m_bSave = bSave; // Save the XML file Save(); } else { if(bCreate) { CLogFile::Printf("ERROR: Failed to open settings file %s.", strPath.Get()); return false; } else CLogFile::Printf("WARNING: Failed to open settings file %s, no settings will be loaded or saved.", strPath.Get()); } } return true; } bool CSettings::Close() { // Are we flagged as open? if(m_bOpen) return true; return false; } bool CSettings::Save() { // Are we not flagged as open? if(!m_bOpen) return false; // Are we not flagged as allowed to save the file? if(!m_bSave) return false; // Loop through all values for(std::map<String, SettingsValue *>::iterator iter = m_values.begin(); iter != m_values.end(); iter++) { // Get the setting pointer SettingsValue * setting = iter->second; // Find all nodes for this value bool bFoundNode = false; for(TiXmlNode * pNode = m_XMLDocument.RootElement()->FirstChildElement(iter->first.Get()); pNode; pNode = pNode->NextSibling()) { // Is this not an element node? if(pNode->Type() != TiXmlNode::ELEMENT) continue; // Is this not the node we are looking for? if(iter->first.Compare(pNode->Value())) continue; // Is this a list node? if(setting->IsList()) { // Remove the node m_XMLDocument.RootElement()->RemoveChild(pNode); } else { // Clear the node pNode->Clear(); // Get the node value String strValue = GetEx(iter->first); // Create a new node value TiXmlText * pNewNodeValue = new TiXmlText(strValue.Get()); // Add the new node value to the new node pNode->LinkEndChild(pNewNodeValue); } // Flag as found a node bFoundNode = true; break; } // Is this a list value? if(setting->IsList()) { // Loop through each list item for(std::list<String>::iterator iter2 = setting->listValue.begin(); iter2 != setting->listValue.end(); iter2++) { // Create a new node TiXmlElement * pNewNode = new TiXmlElement(iter->first.Get()); // Create a new node value TiXmlText * pNewNodeValue = new TiXmlText((*iter2).Get()); // Add the new node value to the new node pNewNode->LinkEndChild(pNewNodeValue); // Add the new node to the XML document m_XMLDocument.RootElement()->LinkEndChild(pNewNode); } } else { // Do we need to create a new node? if(!bFoundNode) { // Create a new node TiXmlElement * pNewNode = new TiXmlElement(iter->first.Get()); // Get the node value String strValue = GetEx(iter->first); // Create a new node value TiXmlText * pNewNodeValue = new TiXmlText(strValue.Get()); // Add the new node value to the new node pNewNode->LinkEndChild(pNewNodeValue); // Add the new node to the XML document m_XMLDocument.RootElement()->LinkEndChild(pNewNode); } } } // Save the XML document return m_XMLDocument.SaveFile(); } bool CSettings::AddBool(String strSetting, bool bDefaultValue) { if(Exists(strSetting)) return false; SettingsValue * setting = new SettingsValue; setting->cFlags = 0; SET_BIT(setting->cFlags, SETTINGS_FLAG_BOOL); setting->bValue = bDefaultValue; m_values[strSetting] = setting; // Save the XML file Save(); return true; } bool CSettings::AddInteger(String strSetting, int iDefaultValue, int iMinimumValue, int iMaximumValue) { if(Exists(strSetting)) return false; SettingsValue * setting = new SettingsValue; setting->cFlags = 0; SET_BIT(setting->cFlags, SETTINGS_FLAG_INTEGER); setting->iValue = iDefaultValue; setting->iMinimumValue = iMinimumValue; setting->iMaximimValue = iMaximumValue; m_values[strSetting] = setting; // Save the XML file Save(); return true; } bool CSettings::AddFloat(String strSetting, float fDefaultValue, float fMinimumValue, float fMaximumValue) { if(Exists(strSetting)) return false; SettingsValue * setting = new SettingsValue; setting->cFlags = 0; SET_BIT(setting->cFlags, SETTINGS_FLAG_FLOAT); setting->fValue = fDefaultValue; setting->fMinimumValue = fMinimumValue; setting->fMaximimValue = fMaximumValue; m_values[strSetting] = setting; // Save the XML file Save(); return true; } bool CSettings::AddString(String strSetting, String strDefaultValue) { if(Exists(strSetting)) return false; SettingsValue * setting = new SettingsValue; setting->cFlags = 0; SET_BIT(setting->cFlags, SETTINGS_FLAG_STRING); setting->strValue = strDefaultValue; m_values[strSetting] = setting; // Save the XML file Save(); return true; } bool CSettings::AddList(String strSetting) { if(Exists(strSetting)) return false; SettingsValue * setting = new SettingsValue; setting->cFlags = 0; SET_BIT(setting->cFlags, SETTINGS_FLAG_LIST); m_values[strSetting] = setting; return true; } bool CSettings::SetBool(String strSetting, bool bValue) { if(IsBool(strSetting)) { GetSetting(strSetting)->bValue = bValue; // Save the XML file Save(); return true; } return false; } bool CSettings::SetInteger(String strSetting, int iValue) { if(IsInteger(strSetting)) { SettingsValue * setting = GetSetting(strSetting); if(iValue < setting->iMinimumValue || iValue > setting->iMaximimValue) return false; setting->iValue = iValue; // Save the XML file Save(); return true; } return false; } bool CSettings::SetFloat(String strSetting, float fValue) { if(IsFloat(strSetting)) { SettingsValue * setting = GetSetting(strSetting); if(fValue < setting->fMinimumValue || fValue > setting->fMaximimValue) return false; setting->fValue = fValue; // Save the XML file Save(); return true; } return false; } bool CSettings::SetString(String strSetting, String strValue) { if(IsString(strSetting)) { GetSetting(strSetting)->strValue = strValue; // Save the XML file Save(); return true; } return false; } bool CSettings::AddToList(String strSetting, String strValue) { if(IsList(strSetting)) { GetSetting(strSetting)->listValue.push_back(strValue); // Save the XML file Save(); return true; } return false; } bool CSettings::SetEx(String strSetting, String strValue) { if(IsBool(strSetting)) SetBool(strSetting, strValue.ToBoolean()); else if(IsInteger(strSetting)) SetInteger(strSetting, strValue.ToInteger()); else if(IsFloat(strSetting)) SetFloat(strSetting, strValue.ToFloat()); else if(IsString(strSetting)) SetString(strSetting, strValue); else if(IsList(strSetting)) AddToList(strSetting, strValue); else return false; return true; } bool CSettings::GetBool(String strSetting) { if(IsBool(strSetting)) return GetSetting(strSetting)->bValue; return false; } int CSettings::GetInteger(String strSetting) { if(IsInteger(strSetting)) return GetSetting(strSetting)->iValue; return 0; } float CSettings::GetFloat(String strSetting) { if(IsFloat(strSetting)) return GetSetting(strSetting)->fValue; return 0.0f; } String CSettings::GetString(String strSetting) { if(IsString(strSetting)) return GetSetting(strSetting)->strValue; return ""; } std::list<String> CSettings::GetList(String strSetting) { if(IsList(strSetting)) return GetSetting(strSetting)->listValue; return std::list<String>(); } String CSettings::GetEx(String strSetting) { String strValue; // Get the setting SettingsValue * setting = GetSetting(strSetting); // Does the setting exist? if(setting) { if(setting->IsBool()) strValue.FromBoolean(setting->bValue); else if(setting->IsInteger()) strValue.FromInteger(setting->iValue); else if(setting->IsFloat()) strValue.FromFloat(setting->fValue); else if(setting->IsString()) strValue = setting->strValue; } return strValue; } bool CSettings::Exists(String strSetting) { return (GetSetting(strSetting) != NULL); } bool CSettings::IsBool(String strSetting) { SettingsValue * setting = GetSetting(strSetting); if(setting && setting->IsBool()) return true; return false; } bool CSettings::IsInteger(String strSetting) { SettingsValue * setting = GetSetting(strSetting); if(setting && setting->IsInteger()) return true; return false; } bool CSettings::IsFloat(String strSetting) { SettingsValue * setting = GetSetting(strSetting); if(setting && setting->IsFloat()) return true; return false; } bool CSettings::IsString(String strSetting) { SettingsValue * setting = GetSetting(strSetting); if(setting && setting->IsString()) return true; return false; } bool CSettings::IsList(String strSetting) { SettingsValue * setting = GetSetting(strSetting); if(setting && setting->IsList()) return true; return false; } bool CSettings::Remove(String strSetting) { if(!Exists(strSetting)) return false; for(std::map<String, SettingsValue *>::iterator iter = m_values.begin(); iter != m_values.end(); iter++) { if(iter->first == strSetting) { delete iter->second; m_values.erase(iter); break; } } // Save the XML file Save(); return true; } void CSettings::ParseCommandLine(int argc, char ** argv) { for(int i = 0; i < argc; i++) { // Is the current char a '-'? if(argv[i][0] == '-') { // Is there a value? if((i + 1) < argc) { // Get the setting and value pointers String strSetting = (argv[i] + 1); String strValue = argv[i + 1]; // Set the setting and value if(!SetEx(strSetting, strValue)) CLogFile::Printf("WARNING: Command line setting %s does not exist.", strSetting.Get()); CLogFile::Printf("argv/argc command line: setting %s value %s", strSetting.Get(), strValue.Get()); } } } } void CSettings::ParseCommandLine(char * szCommandLine) { // Loop until we reach the end of the command line string while(*szCommandLine) { // Is the current char not a space? if(!isspace(*szCommandLine)) { // Is the current char a '-'? if(*szCommandLine == '-') { // Skip the '-' szCommandLine++; // Collect the setting string String strSetting; while(*szCommandLine && !isspace(*szCommandLine)) { strSetting += *szCommandLine; szCommandLine++; } // If we have run out of command line to process break out of the loop if(!(*szCommandLine)) break; // Skip the spaces between the option and the value while(*szCommandLine && isspace(*szCommandLine)) szCommandLine++; // If we have run out of command line to process break out of the loop if(!(*szCommandLine)) break; // Collect the value string String strValue; while(*szCommandLine && !isspace(*szCommandLine)) { strValue += *szCommandLine; szCommandLine++; } // Set the setting and value if(!SetEx(strSetting, strValue)) CLogFile::Printf("WARNING: Command line setting %s does not exist.", strSetting.Get()); CLogFile::Printf("argv/argc command line: setting %s value %s", strSetting.Get(), strValue.Get()); // If we have run out of command line to process break out of the loop if(!(*szCommandLine)) break; } } // Increment the command line string pointer szCommandLine++; } }
22.269006
129
0.672532
purm
0b201498c9eb0fab6c8d1ce966c3686fdcffb97b
2,606
cpp
C++
2021/Coding_Research/CodeTestSetup/CodeTestSetup/src/Drivesetup.cpp
eshsrobotics/vex
bc3b03a6694924c59139c8a761929b8c9a1b6248
[ "MIT" ]
1
2021-12-13T06:24:19.000Z
2021-12-13T06:24:19.000Z
2021/Coding_Research/CodeTestSetup/CodeTestSetup/src/Drivesetup.cpp
eshsrobotics/vex
bc3b03a6694924c59139c8a761929b8c9a1b6248
[ "MIT" ]
1
2021-06-03T00:17:19.000Z
2021-06-03T00:25:14.000Z
2021/Coding_Research/CodeTestSetup/CodeTestSetup/src/Drivesetup.cpp
eshsrobotics/vex
bc3b03a6694924c59139c8a761929b8c9a1b6248
[ "MIT" ]
2
2018-10-28T23:59:13.000Z
2019-11-17T18:29:34.000Z
/*---------------------------------------------------------------------------*/ /* */ /* User Control Task */ /* */ /* This task is used to control your robot during the user control phase of */ /* a VEX Competition. */ /* */ /* You must modify the code to add your own robot specific commands here. */ /*---------------------------------------------------------------------------*/ #include "vex.h" using namespace vex; int driveSpeed = 50, driveSpeedSlow = driveSpeed / 2; bool moveArm(int armSpeed, controller::button &upButton,controller::button &downButton) { bool buttonPressed = false; if (upButton.pressing()) { buttonPressed = true; ArmLeft.spin(forward, armSpeed, pct); ArmRight.spin(forward, armSpeed, pct); } else if (downButton.pressing()) { buttonPressed = true; if (!LeftArmBumper.pressing()) { ArmLeft.spin(reverse, armSpeed, pct); } else { ArmLeft.stop(hold); } if (!RightArmBumper.pressing()) { ArmRight.spin(reverse, armSpeed, pct); } else { ArmRight.stop(hold); } } return buttonPressed; } void usercontrol(void) { // User control code here, inside the loop while (1) { // This is the main execution loop for the user control program. // Each time through the loop your program should update motor + servo // values based on feedback from the joysticks. // ........................................................................ // Insert user code here. This is where you use the joystick values to // update your motors, etc. // ........................................................................ clearAllScreens(); temperatureDisplay(); wait(25, msec); // Controls the arms of the robot when the shoulder buttons are pressed // The right shoulder buttons move the arms up and down at 50% driveSpeed // The left shoulder buttons move the arms up and down at 25% driveSpeed if (!moveArm(driveSpeed, Controller1.ButtonR1, Controller1.ButtonR2) && !moveArm(driveSpeedSlow, Controller1.ButtonL1, Controller1.ButtonL2)) { ArmLeft.stop(hold); ArmRight.stop(hold); } wait(20, msec); // Sleep the task for a short amount of time to // prevent wasted resources. } }
38.895522
89
0.501151
eshsrobotics
0b2051112760609d5343b2c0c725d2dad8076f12
2,714
hpp
C++
event_camera_simulator/imp/imp_unrealcv_renderer/include/esim/imp_unrealcv_renderer/utils.hpp
Louis-Jin/rpg_esim
eea20b84e2bb788431f93b8aace82b0f98606982
[ "MIT" ]
371
2018-11-02T10:09:22.000Z
2022-03-31T05:09:39.000Z
event_camera_simulator/imp/imp_unrealcv_renderer/include/esim/imp_unrealcv_renderer/utils.hpp
Louis-Jin/rpg_esim
eea20b84e2bb788431f93b8aace82b0f98606982
[ "MIT" ]
97
2018-11-06T11:47:53.000Z
2022-03-10T16:25:59.000Z
event_camera_simulator/imp/imp_unrealcv_renderer/include/esim/imp_unrealcv_renderer/utils.hpp
Louis-Jin/rpg_esim
eea20b84e2bb788431f93b8aace82b0f98606982
[ "MIT" ]
101
2018-11-05T12:33:43.000Z
2022-03-24T17:40:50.000Z
#pragma once #include <esim/common/types.hpp> namespace event_camera_simulator { /** * https://github.com/EpicGames/UnrealEngine/blob/dbced2dd59f9f5dfef1d7786fd67ad2970adf95f/Engine/Source/Runtime/Core/Public/Math/Rotator.h#L580 * Helper function for eulerFromQuatSingularityTest, angles are expected to be given in degrees **/ inline FloatType clampAxis(FloatType angle) { // returns angle in the range (-360,360) angle = std::fmod(angle, 360.f); if (angle < 0.f) { // shift to [0,360) range angle += 360.f; } return angle; } /** * https://github.com/EpicGames/UnrealEngine/blob/dbced2dd59f9f5dfef1d7786fd67ad2970adf95f/Engine/Source/Runtime/Core/Public/Math/Rotator.h#L595$ * Helper function for eulerFromQuatSingularityTest, angles are expected to be given in degrees **/ inline FloatType normalizeAxis(FloatType angle) { angle = clampAxis(angle); if(angle > 180.f) { // shift to (-180,180] angle -= 360.f; } return angle; } /** * * https://github.com/EpicGames/UnrealEngine/blob/f794321ffcad597c6232bc706304c0c9b4e154b2/Engine/Source/Runtime/Core/Private/Math/UnrealMath.cpp#L540 * Quaternion given in (x,y,z,w) representation **/ void quaternionToEulerUnrealEngine(const Transformation::Rotation& q, FloatType& yaw, FloatType& pitch, FloatType& roll) { const FloatType X = q.x(); const FloatType Y = q.y(); const FloatType Z = q.z(); const FloatType W = q.w(); const FloatType SingularityTest = Z*X-W*Y; const FloatType YawY = 2.f*(W*Z+X*Y); const FloatType YawX = (1.f-2.f*(Y*Y + Z*Z)); // reference // http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/ // this value was found from experience, the above websites recommend different values // but that isn't the case for us, so I went through different testing, and finally found the case // where both of world lives happily. const FloatType SINGULARITY_THRESHOLD = 0.4999995; const FloatType RAD_TO_DEG = (180.0)/CV_PI; if (SingularityTest < -SINGULARITY_THRESHOLD) { pitch = -90.; yaw = std::atan2(YawY, YawX) * RAD_TO_DEG; roll = normalizeAxis(-yaw - (2.f * std::atan2(X, W) * RAD_TO_DEG)); } else if (SingularityTest > SINGULARITY_THRESHOLD) { pitch = 90.; yaw = std::atan2(YawY, YawX) * RAD_TO_DEG; roll = normalizeAxis(yaw - (2.f * std::atan2(X, W) * RAD_TO_DEG)); } else { pitch = std::asin(2.f*(SingularityTest)) * RAD_TO_DEG; yaw = std::atan2(YawY, YawX) * RAD_TO_DEG; roll = std::atan2(-2.f*(W*X+Y*Z), (1.f-2.f*(X*X + Y*Y))) * RAD_TO_DEG; } } } // namespace event_camera_simulator
30.494382
151
0.701548
Louis-Jin
0b21689bf454bb127eb423865300009db13c4fbf
568
cc
C++
samples/language/src/InputMethod/AbstractInputMethod.cc
gongo/Tython
a2bf95a15123606fbbd5a1cf1186ff1defe4c752
[ "MIT" ]
5
2017-05-20T12:58:49.000Z
2021-05-21T12:34:36.000Z
samples/language/src/InputMethod/AbstractInputMethod.cc
gongo/Tython
a2bf95a15123606fbbd5a1cf1186ff1defe4c752
[ "MIT" ]
null
null
null
samples/language/src/InputMethod/AbstractInputMethod.cc
gongo/Tython
a2bf95a15123606fbbd5a1cf1186ff1defe4c752
[ "MIT" ]
null
null
null
#include "AbstractInputMethod.h" AbstractInputMethod::AbstractInputMethod(void) { } AbstractInputMethod::~AbstractInputMethod(void) { IMmap::iterator ip = inputList.begin(); IMquit::iterator qu = quitList.end(); // while (ip != inputList.end()) { // delete ip->second; // ++ip; // } // while (qu != quitList.end()) { // AbstractDetector* quit = *(qu++); // delete quit; // } } IMmap AbstractInputMethod::input(void) { return inputList; } IMquit AbstractInputMethod::quit(void) { return quitList; }
17.75
47
0.610915
gongo
0b2273c658e543a5400da4c1729f347895bbdac6
9,068
hpp
C++
addons/uh60_ui/uiConfig/MELB_GUI.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
14
2021-02-11T23:23:21.000Z
2021-09-08T05:36:47.000Z
addons/uh60_ui/uiConfig/MELB_GUI.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
130
2021-09-09T21:43:16.000Z
2022-03-30T09:00:37.000Z
addons/uh60_ui/uiConfig/MELB_GUI.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
11
2021-02-18T19:55:51.000Z
2021-09-01T17:08:47.000Z
class MELB_GUI: RscControlsGroup { idc = 170; class VScrollbar: VScrollbar { width = 0; }; class HScrollbar: HScrollbar { height = 0; }; x = "0 * (0.01875 * SafezoneH) + (SafezoneX + ((SafezoneW - SafezoneH) / 2))"; y = "0 * (0.025 * SafezoneH) + (SafezoneY)"; w = "53.5 * (0.01875 * SafezoneH)"; h = "40 * (0.025 * SafezoneH)"; class controls { class TextDistance: RangeText { idc = 1010; text = "RNG"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "41.8 * (0.01875 * SafezoneH)"; y = "4.8 * (0.025 * SafezoneH)"; w = "3* (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class CA_Distance: RscText { idc = 151; sizeEx = "0.0295*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; font = "PuristaMedium"; x = "46 * (0.01875 * SafezoneH)"; y = "4.8 * (0.025 * SafezoneH)"; w = "4 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class TextSpeed: RangeText { idc = 1010; text = "SPD"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "2.5 * (0.01875 * SafezoneH)"; y = "4.8 * (0.025 * SafezoneH)"; w = "8 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class CA_Speed: RangeText { idc = 188; sizeEx = "0.0295*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; font = "PuristaMedium"; text = "120"; x = "8 * (0.01875 * SafezoneH)"; y = "4.8 * (0.025 * SafezoneH)"; w = "4 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class TextAlt: RangeText { idc = 1010; text = "ALT"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "2.5 * (0.01875 * SafezoneH)"; y = "5.6 * (0.025 * SafezoneH)"; w = "8 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class CA_Alt: RangeText { idc = 189; sizeEx = "0.0295*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; font = "PuristaMedium"; text = "3825"; x = "8 * (0.01875 * SafezoneH)"; y = "5.6 * (0.025 * SafezoneH)"; w = "4 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class CA_VisionMode: RscText { idc = 152; sizeEx = "0.022*SafezoneH"; colorText[] = {0,0,0,1}; colorBackground[] = {1,1,1,1}; shadow = 0; font = "PuristaMedium"; text = "VIS"; x = "25.75 * (0.01875 * SafezoneH)"; y = "7.25 * (0.025 * SafezoneH)"; w = "1.5 * (0.01875 * SafezoneH)"; h = "0.6 * (0.025 * SafezoneH)"; }; class CA_FlirMode: RscText { idc = 153; sizeEx = "0.022*SafezoneH"; shadow = 2; colorText[] = {1,1,1,1}; font = "PuristaMedium"; text = "BHOT"; x = "25.5* (0.01875 * SafezoneH)"; y = "7.75 * (0.025 * SafezoneH)"; w = "2* (0.01875 * SafezoneH)"; h = "0.8 * (0.025 * SafezoneH)"; }; class TextACPOS: RangeText { idc = 1010; text = "CRAFT POS"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "2.5 * (0.01875 * SafezoneH)"; y = "3 * (0.025 * SafezoneH)"; w = "8 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class ValueACPOS: RangeText { idc = 171; font = "PuristaMedium"; sizeEx = "0.0295*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "2.5 * (0.01875 * SafezoneH)"; y = "4 * (0.025 * SafezoneH)"; w = "6 * (0.01875 * SafezoneH)"; h = "1 * (0.025 * SafezoneH)"; }; class TextTPOS: RangeText { idc = 1010; text = "TARGET POS"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "41.8* (0.01875 * SafezoneH)"; y = "3 * (0.025 * SafezoneH)"; w = "8 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class ValueTPOS: RangeText { idc = 172; font = "PuristaMedium"; sizeEx = "0.0295*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "41.8* (0.01875 * SafezoneH)"; y = "4 * (0.025 * SafezoneH)"; w = "6 * (0.01875 * SafezoneH)"; h = "1 * (0.025 * SafezoneH)"; }; class ValueTime: RangeText { idc = 190; text = "20:28:35"; font = "PuristaMedium"; sizeEx = "0.0295*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "2.5* (0.01875 * SafezoneH)"; y = "9 * (0.025 * SafezoneH)"; w = "6 * (0.01875 * SafezoneH)"; h = "1 * (0.025 * SafezoneH)"; }; class TextLaser: RangeText { idc = 158; text = "LRF ARMED"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {0.9,0,0,1}; shadow = 2; x = "3* (0.01875 * SafezoneH)"; y = "14.1 * (0.025 * SafezoneH)"; w = "13 * (0.01875 * SafezoneH)"; h = "2 * (0.025 * SafezoneH)"; }; class CA_Heading: RscText { idc = 156; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; font = "PuristaMedium"; text = "023"; x = "27.25* (0.01875 * SafezoneH)"; y = "5 * (0.025 * SafezoneH)"; w = "4 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class TextHDG: RangeText { idc = 1010; text = "HDG"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "24* (0.01875 * SafezoneH)"; y = "5* (0.025 * SafezoneH)"; w = "4 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; class OpticsZoom1: RangeText { idc = 180; text = "28x"; colorText[] = {1,1,1,1}; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; shadow = 2; x = "5 * (0.01875 * SafezoneH)"; y = "25 * (0.025 * SafezoneH)"; w = "6 * (0.01875 * SafezoneH)"; h = "1 * (0.025 * SafezoneH)"; }; class TextZOOM: RangeText { idc = 1010; text = "ZOOM"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "2.5 * (0.01875 * SafezoneH)"; y = "25 * (0.025 * SafezoneH)"; w = "4 * (0.01875 * SafezoneH)"; h = "1 * (0.025 * SafezoneH)"; }; class ValueGEOLOCK: RscText { idc = 154; text = "TRK COR"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "42* (0.01875 * SafezoneH)"; y = "33 * (0.025 * SafezoneH)"; w = "8 * (0.01875 * SafezoneH)"; h = "1 * (0.025 * SafezoneH)"; }; class TextGEOLOCK: RangeText { idc = 155; text = "GEOLOCK"; font = "PuristaMedium"; sizeEx = "0.0255*SafezoneH"; colorText[] = {1,1,1,1}; shadow = 2; x = "42* (0.01875 * SafezoneH)"; y = "32 * (0.025 * SafezoneH)"; w = "8 * (0.01875 * SafezoneH)"; h = "1.2 * (0.025 * SafezoneH)"; }; }; };
32.618705
86
0.379687
ZHANGTIANYAO1
0b22d828b0bfdd834df15572e104e15fd6eb002a
17,109
cpp
C++
src/maple_ir/src/mir_module.cpp
isrc-cas/openarkcompiler
35bdd8d940af7f19c30dee32e1c26969f3e24dc8
[ "MulanPSL-1.0" ]
80
2019-09-15T04:32:05.000Z
2022-02-26T03:27:10.000Z
src/maple_ir/src/mir_module.cpp
isrc-cas/openarkcompiler
35bdd8d940af7f19c30dee32e1c26969f3e24dc8
[ "MulanPSL-1.0" ]
2
2019-09-20T14:06:40.000Z
2020-04-03T05:37:17.000Z
src/maple_ir/src/mir_module.cpp
isrc-cas/openarkcompiler
35bdd8d940af7f19c30dee32e1c26969f3e24dc8
[ "MulanPSL-1.0" ]
18
2019-09-15T10:06:42.000Z
2021-03-19T08:29:33.000Z
/* * Copyright (c) [2019] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #include "mir_module.h" #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <unordered_set> #include <cctype> #include "mir_const.h" #include "mir_preg.h" #include "mir_function.h" #include "mir_builder.h" #include "intrinsics.h" #include "bin_mplt.h" namespace maple { #if MIR_FEATURE_FULL // to avoid compilation error when MIR_FEATURE_FULL=0 MIRModule::MIRModule(const std::string &fn) : memPool(memPoolCtrler.NewMemPool("maple_ir mempool")), memPoolAllocator(memPool), functionList(memPoolAllocator.Adapter()), compilationList(memPoolAllocator.Adapter()), importedMplt(memPoolAllocator.Adapter()), typeDefOrder(memPoolAllocator.Adapter()), externStructTypeSet(std::less<TyIdx>(), memPoolAllocator.Adapter()), symbolSet(std::less<StIdx>(), memPoolAllocator.Adapter()), symbolDefOrder(memPoolAllocator.Adapter()), out(LogInfo::MapleLogger()), fileName(fn), fileInfo(memPoolAllocator.Adapter()), fileInfoIsString(memPoolAllocator.Adapter()), fileData(memPoolAllocator.Adapter()), srcFileInfo(memPoolAllocator.Adapter()), importFiles(memPoolAllocator.Adapter()), importPaths(memPoolAllocator.Adapter()), classList(memPoolAllocator.Adapter()), optimizedFuncs(memPoolAllocator.Adapter()), puIdxFieldInitializedMap(std::less<PUIdx>(), memPoolAllocator.Adapter()) { GlobalTables::GetGsymTable().SetModule(this); typeNameTab = memPool->New<MIRTypeNameTable>(memPoolAllocator); mirBuilder = memPool->New<MIRBuilder>(this); IntrinDesc::InitMIRModule(this); } MIRModule::~MIRModule() { memPoolCtrler.DeleteMemPool(memPool); if (binMplt) { delete binMplt; } } MemPool *MIRModule::CurFuncCodeMemPool(void) const { return CurFunction()->GetCodeMempool(); } MapleAllocator *MIRModule::CurFuncCodeMemPoolAllocator(void) const { return &curFunction->GetCodeMempoolAllocator(); } MapleAllocator &MIRModule::GetCurFuncCodeMPAllocator(void) const { return curFunction->GetCodeMPAllocator(); } void MIRModule::AddExternStructType(TyIdx tyIdx) { externStructTypeSet.insert(tyIdx); } void MIRModule::AddExternStructType(const MIRType *t) { ASSERT(t != nullptr, "MIRType is null"); externStructTypeSet.insert(t->GetTypeIndex()); } void MIRModule::AddSymbol(StIdx stIdx) { auto it = symbolSet.find(stIdx); if (it == symbolSet.end()) { symbolDefOrder.push_back(stIdx); } symbolSet.insert(stIdx); } void MIRModule::AddSymbol(const MIRSymbol *s) { ASSERT(s != nullptr, "s is null"); AddSymbol(s->GetStIdx()); } void MIRModule::DumpGlobals(bool emitStructureType) const { if (flavor != kFlavorUnknown) { LogInfo::MapleLogger() << "flavor " << flavor << std::endl; } if (srcLang != kSrcLangUnknown) { LogInfo::MapleLogger() << "srclang " << srcLang << std::endl; } LogInfo::MapleLogger() << "id " << id << std::endl; if (globalMemSize != 0) { LogInfo::MapleLogger() << "globalmemsize " << globalMemSize << std::endl; } if (globalBlkMap != nullptr) { LogInfo::MapleLogger() << "globalmemmap = [ "; uint32 *p = reinterpret_cast<uint32*>(globalBlkMap); LogInfo::MapleLogger() << std::hex; while (p < reinterpret_cast<uint32*>(globalBlkMap + globalMemSize)) { LogInfo::MapleLogger() << std::hex << "0x" << *p << " "; p++; } LogInfo::MapleLogger() << std::dec << "]\n"; } if (globalWordsTypeTagged != nullptr) { LogInfo::MapleLogger() << "globalwordstypetagged = [ "; uint32 *p = reinterpret_cast<uint32*>(globalWordsTypeTagged); LogInfo::MapleLogger() << std::hex; while (p < reinterpret_cast<uint32*>(globalWordsTypeTagged + BlockSize2BitVectorSize(globalMemSize))) { LogInfo::MapleLogger() << std::hex << "0x" << *p << " "; p++; } LogInfo::MapleLogger() << std::dec << "]\n"; } if (globalWordsRefCounted != nullptr) { LogInfo::MapleLogger() << "globalwordsrefcounted = [ "; uint32 *p = reinterpret_cast<uint32*>(globalWordsRefCounted); LogInfo::MapleLogger() << std::hex; while (p < reinterpret_cast<uint32*>(globalWordsRefCounted + BlockSize2BitVectorSize(globalMemSize))) { LogInfo::MapleLogger() << std::hex << "0x" << *p << " "; p++; } LogInfo::MapleLogger() << std::dec << "]\n"; } LogInfo::MapleLogger() << "numfuncs " << numFuncs << std::endl; if (!importFiles.empty()) { // Output current module's mplt on top, imported ones at below for (auto it = importFiles.rbegin(); it != importFiles.rend(); it++) { LogInfo::MapleLogger() << "import \"" << GlobalTables::GetStrTable().GetStringFromStrIdx(*it) << "\"" << std::endl; } } if (!importPaths.empty()) { size_t size = importPaths.size(); for (size_t i = 0; i < size; i++) { LogInfo::MapleLogger() << "importpath \"" << GlobalTables::GetStrTable().GetStringFromStrIdx(importPaths[i]) << "\"" << std::endl; } } if (entryFuncName.length()) { LogInfo::MapleLogger() << "entryfunc &" << entryFuncName << std::endl; } if (!fileInfo.empty()) { LogInfo::MapleLogger() << "fileinfo {\n"; size_t size = fileInfo.size(); for (size_t i = 0; i < size; i++) { LogInfo::MapleLogger() << " @" << GlobalTables::GetStrTable().GetStringFromStrIdx(fileInfo[i].first) << " "; if (!fileInfoIsString[i]) { LogInfo::MapleLogger() << "0x" << std::hex << fileInfo[i].second; } else { LogInfo::MapleLogger() << "\"" << GlobalTables::GetStrTable().GetStringFromStrIdx(GStrIdx(fileInfo[i].second)) << "\""; } if (i < size - 1) { LogInfo::MapleLogger() << ",\n"; } else { LogInfo::MapleLogger() << "}\n"; } } LogInfo::MapleLogger() << std::dec; } if (!srcFileInfo.empty()) { LogInfo::MapleLogger() << "srcfileinfo {\n"; size_t size = srcFileInfo.size(); size_t i = 0; for (auto it : srcFileInfo) { LogInfo::MapleLogger() << " " << it.second; LogInfo::MapleLogger() << " \"" << GlobalTables::GetStrTable().GetStringFromStrIdx(it.first) << "\""; if (i++ < size - 1) { LogInfo::MapleLogger() << ",\n"; } else { LogInfo::MapleLogger() << "}\n"; } } } if (!fileData.empty()) { LogInfo::MapleLogger() << "filedata {\n"; size_t size = fileData.size(); for (size_t i = 0; i < size; i++) { LogInfo::MapleLogger() << " @" << GlobalTables::GetStrTable().GetStringFromStrIdx(fileData[i].first) << " "; size_t dataSize = fileData[i].second.size(); for (size_t j = 0; j < dataSize; j++) { uint8 data = fileData[i].second[j]; LogInfo::MapleLogger() << "0x" << std::hex << static_cast<uint32>(data); if (j < dataSize - 1) { LogInfo::MapleLogger() << ' '; } } if (i < size - 1) { LogInfo::MapleLogger() << ",\n"; } else { LogInfo::MapleLogger() << "}\n"; } } LogInfo::MapleLogger() << std::dec; } if (flavor < kMmpl) { for (auto it = typeDefOrder.begin(); it != typeDefOrder.end(); it++) { TyIdx tyIdx = typeNameTab->GetTyIdxFromGStrIdx(*it); const std::string &name = GlobalTables::GetStrTable().GetStringFromStrIdx(*it); MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tyIdx); ASSERT(type != nullptr, "type should not be nullptr here"); MIRStructType *structType = dynamic_cast<MIRStructType*>(type); if (structType != nullptr && !emitStructureType) { // still emit what in extern_structtype_set_ if (externStructTypeSet.find(structType->GetTypeIndex()) == externStructTypeSet.end()) { continue; } } if (structType != nullptr && structType->IsImported()) { continue; } LogInfo::MapleLogger() << "type $" << name << " "; if (type->GetKind() == kTypeByName) { LogInfo::MapleLogger() << "void"; } else if (type->GetNameStrIdx() == *it) { type->Dump(1, true); } else { type->Dump(1); } LogInfo::MapleLogger() << std::endl; } if (someSymbolNeedForwDecl) { // an extra pass thru the global symbol table to print forward decl for (auto sit = symbolSet.begin(); sit != symbolSet.end(); sit++) { MIRSymbol *s = GlobalTables::GetGsymTable().GetSymbolFromStidx((*sit).Idx()); if (s->IsNeedForwDecl()) { s->Dump(false, 0, true); } } } // dump javaclass and javainterface first for (auto sit = symbolDefOrder.begin(); sit != symbolDefOrder.end(); sit++) { MIRSymbol *s = GlobalTables::GetGsymTable().GetSymbolFromStidx((*sit).Idx()); if (!s->IsJavaClassInterface()) { continue; } // Verify: all wpofake variables should have been deleted from globaltable if (!s->IsDeleted()) { s->Dump(false, 0); } } for (auto sit = symbolDefOrder.begin(); sit != symbolDefOrder.end(); sit++) { MIRSymbol *s = GlobalTables::GetGsymTable().GetSymbolFromStidx((*sit).Idx()); CHECK_FATAL(s != nullptr, "nullptr check"); if (s->IsJavaClassInterface()) { continue; } if (!s->IsDeleted() && !s->GetIsImported()) { s->Dump(false, 0); } } } } void MIRModule::Dump(bool emitStructureType) const { DumpGlobals(emitStructureType); DumpFunctionList(); } void MIRModule::DumpGlobalArraySymbol() const { MapleSet<StIdx>::iterator sit = symbolSet.begin(); for (; sit != symbolSet.end(); sit++) { MIRSymbol *s = GlobalTables::GetGsymTable().GetSymbolFromStidx((*sit).Idx()); MIRType *sType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(s->GetTyIdx()); if (sType == nullptr || sType->GetKind() != kTypeArray) { continue; } s->Dump(false, 0); } } void MIRModule::Emit(const std::string &outfileName) const { std::ofstream file; // Change cout's buffer to file. std::streambuf *backup = LogInfo::MapleLogger().rdbuf(); LogInfo::MapleLogger().rdbuf(file.rdbuf()); file.open(outfileName.c_str(), std::ios::trunc); DumpGlobals(); for (MIRFunction *mirFunc : functionList) { mirFunc->Dump(); } // Restore cout's buffer. LogInfo::MapleLogger().rdbuf(backup); file.close(); } void MIRModule::DumpFunctionList(bool skipBody) const { for (auto it = functionList.begin(); it != functionList.end(); it++) { (*it)->Dump(skipBody); } } void MIRModule::OutputFunctionListAsciiMpl(const std::string &phaseName) { std::string fileStem; std::string::size_type lastDot = fileName.find_last_of('.'); if (lastDot == std::string::npos) { fileStem = fileName.append(phaseName); } else { fileStem = fileName.substr(0, lastDot).append(phaseName); } std::string outfileName; if (flavor >= kMmpl) { outfileName = fileStem.append(".mmpl"); } else { outfileName = fileStem.append(".mpl"); } std::ofstream mplFile; mplFile.open(outfileName, std::ios::app); std::streambuf *backup = LogInfo::MapleLogger().rdbuf(); LogInfo::MapleLogger().rdbuf(mplFile.rdbuf()); // change cout's buffer to that of file DumpGlobalArraySymbol(); DumpFunctionList(); LogInfo::MapleLogger().rdbuf(backup); // restore cout's buffer mplFile.close(); return; } void MIRModule::DumpToFile(const std::string &fileNameStr, bool emitStructureType) const { std::ofstream file; file.open(fileNameStr.c_str(), std::ios::trunc); if (!file.is_open()) { ERR(kLncErr, "Cannot open %s", fileNameStr.c_str()); return; } // Change cout's buffer to file. std::streambuf *backup = LogInfo::MapleLogger().rdbuf(); LogInfo::MapleLogger().rdbuf(file.rdbuf()); Dump(emitStructureType); // Restore cout's buffer. LogInfo::MapleLogger().rdbuf(backup); } void MIRModule::DumpInlineCandidateToFile(const std::string &fileNameStr) const { if (optimizedFuncs.empty()) { return; } std::ofstream file; // Change cout's buffer to file. std::streambuf *backup = LogInfo::MapleLogger().rdbuf(); LogInfo::MapleLogger().rdbuf(file.rdbuf()); file.open(fileNameStr.c_str(), std::ios::trunc); for (auto it = optimizedFuncs.begin(); it != optimizedFuncs.end(); it++) { (*it)->SetWithLocInfo(false); (*it)->Dump(); } // Restore cout's buffer. LogInfo::MapleLogger().rdbuf(backup); file.close(); } // This is not efficient. Only used in debug mode for now. const std::string &MIRModule::GetFileNameFromFileNum(uint32 fileNum) const { GStrIdx nameIdx = GStrIdx(0); for (auto &info : srcFileInfo) { if (info.second == fileNum) { nameIdx = info.first; } } return GlobalTables::GetStrTable().GetStringFromStrIdx(nameIdx); } void MIRModule::DumpClassToFile(const std::string &path) const { std::string spath(path); spath.append("/"); for (auto it : typeNameTab->GetGStrIdxToTyIdxMap()) { const std::string &name = GlobalTables::GetStrTable().GetStringFromStrIdx(it.first); MIRType *type = GlobalTables::GetTypeTable().GetTypeFromTyIdx(it.second); std::string outClassFile = name.c_str(); /* replace class name / with - */ std::replace(outClassFile.begin(), outClassFile.end(), '/', '-'); outClassFile.insert(0, spath); outClassFile.append(".mpl"); std::ofstream mplFile; mplFile.open(outClassFile.c_str(), std::ios::trunc); std::streambuf *backup = LogInfo::MapleLogger().rdbuf(); LogInfo::MapleLogger().rdbuf(mplFile.rdbuf()); /* dump class type */ LogInfo::MapleLogger() << "type $" << name << " "; if (type->GetNameStrIdx() == it.first && type->GetKind() != kTypeByName) { type->Dump(1, true); } else { type->Dump(1); } LogInfo::MapleLogger() << std::endl; /* restore cout */ LogInfo::MapleLogger().rdbuf(backup); mplFile.close(); } } MIRFunction *MIRModule::FindEntryFunction() { for (size_t i = 0; i < functionList.size(); i++) { MIRFunction *currFunc = functionList[i]; if (currFunc->GetName() == entryFuncName) { entryFunc = currFunc; return currFunc; } } return nullptr; } // given the phase name (including '.' at beginning), output the program in the // module in ascii form to the file with either .mpl or .mmpl suffix, and file // stem from this->fileName appended with phasename void MIRModule::OutputAsciiMpl(const std::string &phaseName, bool emitStructureType) { std::string fileStem; std::string::size_type lastDot = fileName.find_last_of("."); if (lastDot == std::string::npos) { fileStem = fileName.append(phaseName); } else { fileStem = fileName.substr(0, lastDot).append(phaseName); } std::string outfileName; if (flavor >= kMmpl) { outfileName = fileStem.append(".mmpl"); } else { outfileName = fileStem.append(".mpl"); } std::ofstream mplFile; mplFile.open(outfileName, std::ios::trunc); std::streambuf *backup = LogInfo::MapleLogger().rdbuf(); LogInfo::MapleLogger().rdbuf(mplFile.rdbuf()); // change cout's buffer to that of file Dump(emitStructureType); LogInfo::MapleLogger().rdbuf(backup); // restore cout's buffer mplFile.close(); return; } uint32 MIRModule::GetFileinfo(GStrIdx strIdx) const { size_t size = fileInfo.size(); for (size_t i = 0; i < size; i++) { if (fileInfo[i].first == strIdx) { return fileInfo[i].second; } } ASSERT(false, "should not be here"); return 0; } std::string MIRModule::GetFileNameAsPostfix() const { std::string fileNameStr = NameMangler::kFileNameSplitterStr; if (!fileInfo.empty()) { // option 1: file name in INFO uint32 fileNameIdx = GetFileinfo(GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("INFO_filename")); fileNameStr += GlobalTables::GetStrTable().GetStringFromStrIdx(GStrIdx(fileNameIdx)); } else { // option 2: src file name removing ext name. ASSERT(fileNameStr.find_last_of(".") != fileNameStr.npos, "not found ."); fileNameStr += fileNameStr.substr(0, fileNameStr.find_last_of(".")); } for (uint32 i = 0; i < fileNameStr.length(); ++i) { char c = fileNameStr[i]; if (!isalpha(c) && !isdigit(c) && c != '_' && c != '$') { fileNameStr[i] = '_'; } } return fileNameStr; } void MIRModule::AddClass(TyIdx t) { classList.insert(t.GetIdx()); return; } void MIRModule::RemoveClass(TyIdx t) { classList.erase(t.GetIdx()); return; } #endif // MIR_FEATURE_FULL void MIRModule::SetFuncInfoPrinted() const { CurFunction()->SetInfoPrinted(); } } // namespace maple
34.77439
118
0.640365
isrc-cas
0b246cc5eb41758d7fe76ce517d688e0dde6fb25
1,998
cpp
C++
LaFullCholeskySolver.cpp
davidbrochart/daetk
66b2a69d3f3df77f766d3d3eeb5c28d31587e278
[ "MIT" ]
9
2018-06-17T13:54:24.000Z
2021-05-06T11:22:10.000Z
LaFullCholeskySolver.cpp
davidbrochart/daetk
66b2a69d3f3df77f766d3d3eeb5c28d31587e278
[ "MIT" ]
2
2019-02-13T18:50:05.000Z
2019-10-19T00:13:35.000Z
LaFullCholeskySolver.cpp
davidbrochart/daetk
66b2a69d3f3df77f766d3d3eeb5c28d31587e278
[ "MIT" ]
4
2019-06-21T07:41:34.000Z
2021-12-28T12:36:17.000Z
#include "LaFullCholeskySolver.h" namespace Daetk { using std::cerr; using std::endl; void LaFullCholeskySolver::storeLower(){uplo='L';} void LaFullCholeskySolver::storeUpper(){uplo='U';} LaFullCholeskySolver::LaFullCholeskySolver(): uplo('L'), neq(0), LEAD_DIM_STORAGE(0), errorFlag(0), x(this), arrayptr(0), M(0) {} LaFullCholeskySolver::LaFullCholeskySolver(Mat& Min): uplo('L'), neq(Min.dim(1)), LEAD_DIM_STORAGE(Min.dim(0)), errorFlag(0), x(this,Min.dim(1)), arrayptr(Min.castToArray()), M(&Min) {} LaFullCholeskySolver::~LaFullCholeskySolver(){} bool LaFullCholeskySolver::prepare() { #ifndef CRAYCC #ifndef USE_SINGLE_PRECISION F77NAME(dpotrf)(uplo,neq,arrayptr,LEAD_DIM_STORAGE,errorFlag); #else F77NAME(spotrf)(uplo,neq,arrayptr,LEAD_DIM_STORAGE,errorFlag); #endif #else #ifndef USE_SINGLE_PRECISION F77NAME(DPOTRF)(uplo,neq,arrayptr,LEAD_DIM_STORAGE,errorFlag); #else F77NAME(SPOTRF)(uplo,neq,arrayptr,LEAD_DIM_STORAGE,errorFlag); #endif #endif if (errorFlag!=0) { cerr<<"error in cholesky factorization, code "<<errorFlag<<endl; } return errorFlag; } bool LaFullCholeskySolver::solve(const Vec& bIn,Vec& xIn) { int numberOfRhs(1),ldaRhs(x.v_.dim()); #ifndef USE_BLAS xIn=bIn; #else copy(bIn,xIn); #endif x.attachToTarget(xIn); #ifndef CRAYCC #ifndef USE_SINGLE_PRECISION F77NAME(dpotrs)(uplo,neq,numberOfRhs,arrayptr,LEAD_DIM_STORAGE,x.v_.castToArray(),ldaRhs,errorFlag); #else F77NAME(spotrs)(uplo,neq,numberOfRhs,arrayptr,LEAD_DIM_STORAGE,x.castToArray(),ldaRhs,errorFlag); #endif #else #ifndef USE_SINGLE_PRECISION F77NAME(DPOTRS)(uplo,neq,numberOfRhs,arrayptr,LEAD_DIM_STORAGE,x.castToArray(),ldaRhs,errorFlag); #else F77NAME(SPOTRS)(uplo,neq,numberOfRhs,arrayptr,LEAD_DIM_STORAGE,x.castToArray(),ldaRhs,errorFlag); #endif #endif x.restoreToTarget(); if (errorFlag!=0) { cerr<<"error in cholesky back substitution, code "<<errorFlag<<endl; } return errorFlag; } }//Daetk
21.717391
102
0.735235
davidbrochart
0b29b92c94cf83ddbe654da341d90e3bf1481b97
10,016
cc
C++
chromium/media/mojo/services/mojo_cdm.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
chromium/media/mojo/services/mojo_cdm.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
2
2017-03-09T09:00:50.000Z
2017-09-21T15:48:20.000Z
chromium/media/mojo/services/mojo_cdm.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/mojo/services/mojo_cdm.h" #include <stddef.h> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "media/base/cdm_context.h" #include "media/base/cdm_key_information.h" #include "media/base/cdm_promise.h" #include "media/mojo/interfaces/decryptor.mojom.h" #include "media/mojo/services/media_type_converters.h" #include "media/mojo/services/mojo_decryptor.h" #include "mojo/shell/public/cpp/connect.h" #include "mojo/shell/public/interfaces/service_provider.mojom.h" #include "url/gurl.h" namespace media { template <typename PromiseType> static void RejectPromise(scoped_ptr<PromiseType> promise, interfaces::CdmPromiseResultPtr result) { promise->reject(static_cast<MediaKeys::Exception>(result->exception), result->system_code, result->error_message); } // static void MojoCdm::Create( const std::string& key_system, const GURL& security_origin, const media::CdmConfig& cdm_config, interfaces::ContentDecryptionModulePtr remote_cdm, const media::SessionMessageCB& session_message_cb, const media::SessionClosedCB& session_closed_cb, const media::LegacySessionErrorCB& legacy_session_error_cb, const media::SessionKeysChangeCB& session_keys_change_cb, const media::SessionExpirationUpdateCB& session_expiration_update_cb, const media::CdmCreatedCB& cdm_created_cb) { scoped_refptr<MojoCdm> mojo_cdm( new MojoCdm(std::move(remote_cdm), session_message_cb, session_closed_cb, legacy_session_error_cb, session_keys_change_cb, session_expiration_update_cb)); // |mojo_cdm| ownership is passed to the promise. scoped_ptr<CdmInitializedPromise> promise( new CdmInitializedPromise(cdm_created_cb, mojo_cdm)); mojo_cdm->InitializeCdm(key_system, security_origin, cdm_config, std::move(promise)); } MojoCdm::MojoCdm(interfaces::ContentDecryptionModulePtr remote_cdm, const SessionMessageCB& session_message_cb, const SessionClosedCB& session_closed_cb, const LegacySessionErrorCB& legacy_session_error_cb, const SessionKeysChangeCB& session_keys_change_cb, const SessionExpirationUpdateCB& session_expiration_update_cb) : remote_cdm_(std::move(remote_cdm)), binding_(this), cdm_id_(CdmContext::kInvalidCdmId), session_message_cb_(session_message_cb), session_closed_cb_(session_closed_cb), legacy_session_error_cb_(legacy_session_error_cb), session_keys_change_cb_(session_keys_change_cb), session_expiration_update_cb_(session_expiration_update_cb), weak_factory_(this) { DVLOG(1) << __FUNCTION__; DCHECK(!session_message_cb_.is_null()); DCHECK(!session_closed_cb_.is_null()); DCHECK(!legacy_session_error_cb_.is_null()); DCHECK(!session_keys_change_cb_.is_null()); DCHECK(!session_expiration_update_cb_.is_null()); interfaces::ContentDecryptionModuleClientPtr client_ptr; binding_.Bind(GetProxy(&client_ptr)); remote_cdm_->SetClient(std::move(client_ptr)); } MojoCdm::~MojoCdm() { DVLOG(1) << __FUNCTION__; } void MojoCdm::InitializeCdm(const std::string& key_system, const GURL& security_origin, const media::CdmConfig& cdm_config, scoped_ptr<CdmInitializedPromise> promise) { DVLOG(1) << __FUNCTION__ << ": " << key_system; remote_cdm_->Initialize( key_system, security_origin.spec(), interfaces::CdmConfig::From(cdm_config), base::Bind(&MojoCdm::OnCdmInitialized, weak_factory_.GetWeakPtr(), base::Passed(&promise))); } void MojoCdm::SetServerCertificate(const std::vector<uint8_t>& certificate, scoped_ptr<SimpleCdmPromise> promise) { DVLOG(2) << __FUNCTION__; remote_cdm_->SetServerCertificate( mojo::Array<uint8_t>::From(certificate), base::Bind(&MojoCdm::OnPromiseResult<>, weak_factory_.GetWeakPtr(), base::Passed(&promise))); } void MojoCdm::CreateSessionAndGenerateRequest( SessionType session_type, EmeInitDataType init_data_type, const std::vector<uint8_t>& init_data, scoped_ptr<NewSessionCdmPromise> promise) { DVLOG(2) << __FUNCTION__; remote_cdm_->CreateSessionAndGenerateRequest( static_cast<interfaces::ContentDecryptionModule::SessionType>( session_type), static_cast<interfaces::ContentDecryptionModule::InitDataType>( init_data_type), mojo::Array<uint8_t>::From(init_data), base::Bind(&MojoCdm::OnPromiseResult<std::string>, weak_factory_.GetWeakPtr(), base::Passed(&promise))); } void MojoCdm::LoadSession(SessionType session_type, const std::string& session_id, scoped_ptr<NewSessionCdmPromise> promise) { DVLOG(2) << __FUNCTION__; remote_cdm_->LoadSession( static_cast<interfaces::ContentDecryptionModule::SessionType>( session_type), session_id, base::Bind(&MojoCdm::OnPromiseResult<std::string>, weak_factory_.GetWeakPtr(), base::Passed(&promise))); } void MojoCdm::UpdateSession(const std::string& session_id, const std::vector<uint8_t>& response, scoped_ptr<SimpleCdmPromise> promise) { DVLOG(2) << __FUNCTION__; remote_cdm_->UpdateSession( session_id, mojo::Array<uint8_t>::From(response), base::Bind(&MojoCdm::OnPromiseResult<>, weak_factory_.GetWeakPtr(), base::Passed(&promise))); } void MojoCdm::CloseSession(const std::string& session_id, scoped_ptr<SimpleCdmPromise> promise) { DVLOG(2) << __FUNCTION__; remote_cdm_->CloseSession(session_id, base::Bind(&MojoCdm::OnPromiseResult<>, weak_factory_.GetWeakPtr(), base::Passed(&promise))); } void MojoCdm::RemoveSession(const std::string& session_id, scoped_ptr<SimpleCdmPromise> promise) { DVLOG(2) << __FUNCTION__; remote_cdm_->RemoveSession(session_id, base::Bind(&MojoCdm::OnPromiseResult<>, weak_factory_.GetWeakPtr(), base::Passed(&promise))); } CdmContext* MojoCdm::GetCdmContext() { DVLOG(2) << __FUNCTION__; return this; } media::Decryptor* MojoCdm::GetDecryptor() { if (decryptor_ptr_) { DCHECK(!decryptor_); decryptor_.reset(new MojoDecryptor(std::move(decryptor_ptr_))); } return decryptor_.get(); } int MojoCdm::GetCdmId() const { DCHECK_NE(CdmContext::kInvalidCdmId, cdm_id_); return cdm_id_; } void MojoCdm::OnSessionMessage(const mojo::String& session_id, interfaces::CdmMessageType message_type, mojo::Array<uint8_t> message, const mojo::String& legacy_destination_url) { DVLOG(2) << __FUNCTION__; GURL verified_gurl = GURL(legacy_destination_url); if (!verified_gurl.is_valid() && !verified_gurl.is_empty()) { DLOG(WARNING) << "SessionMessage destination_url is invalid : " << verified_gurl.possibly_invalid_spec(); verified_gurl = GURL::EmptyGURL(); // Replace invalid destination_url. } session_message_cb_.Run(session_id, static_cast<MediaKeys::MessageType>(message_type), message.storage(), verified_gurl); } void MojoCdm::OnSessionClosed(const mojo::String& session_id) { DVLOG(2) << __FUNCTION__; session_closed_cb_.Run(session_id); } void MojoCdm::OnLegacySessionError(const mojo::String& session_id, interfaces::CdmException exception, uint32_t system_code, const mojo::String& error_message) { DVLOG(2) << __FUNCTION__; legacy_session_error_cb_.Run(session_id, static_cast<MediaKeys::Exception>(exception), system_code, error_message); } void MojoCdm::OnSessionKeysChange( const mojo::String& session_id, bool has_additional_usable_key, mojo::Array<interfaces::CdmKeyInformationPtr> keys_info) { DVLOG(2) << __FUNCTION__; // TODO(jrummell): Handling resume playback should be done in the media // player, not in the Decryptors. http://crbug.com/413413. if (has_additional_usable_key && decryptor_) decryptor_->OnKeyAdded(); media::CdmKeysInfo key_data; key_data.reserve(keys_info.size()); for (size_t i = 0; i < keys_info.size(); ++i) { key_data.push_back( keys_info[i].To<scoped_ptr<media::CdmKeyInformation>>().release()); } session_keys_change_cb_.Run(session_id, has_additional_usable_key, std::move(key_data)); } void MojoCdm::OnSessionExpirationUpdate(const mojo::String& session_id, double new_expiry_time_sec) { DVLOG(2) << __FUNCTION__; session_expiration_update_cb_.Run( session_id, base::Time::FromDoubleT(new_expiry_time_sec)); } void MojoCdm::OnCdmInitialized(scoped_ptr<CdmInitializedPromise> promise, interfaces::CdmPromiseResultPtr result, int cdm_id, interfaces::DecryptorPtr decryptor) { DVLOG(2) << __FUNCTION__ << " cdm_id: " << cdm_id; if (!result->success) { RejectPromise(std::move(promise), std::move(result)); return; } DCHECK_NE(CdmContext::kInvalidCdmId, cdm_id); cdm_id_ = cdm_id; decryptor_ptr_ = std::move(decryptor); promise->resolve(); } } // namespace media
38.671815
80
0.665036
wedataintelligence
0b2bf6318d53ae09c85190fe55afd45ace1b82f4
4,946
cpp
C++
source/solution_zoo/xstream/methods/fasterrcnnmethod/example/test_model_info.cpp
HorizonRobotics-Platform/AI-EXPRESS
413206d88dae1fbd465ced4d60b2a1769d15c171
[ "BSD-2-Clause" ]
98
2020-09-11T13:52:44.000Z
2022-03-23T11:52:02.000Z
source/solution_zoo/xstream/methods/fasterrcnnmethod/example/test_model_info.cpp
HorizonRobotics-Platform/ai-express
413206d88dae1fbd465ced4d60b2a1769d15c171
[ "BSD-2-Clause" ]
8
2020-10-19T14:23:30.000Z
2022-03-16T01:00:07.000Z
source/solution_zoo/xstream/methods/fasterrcnnmethod/example/test_model_info.cpp
HorizonRobotics-Platform/AI-EXPRESS
413206d88dae1fbd465ced4d60b2a1769d15c171
[ "BSD-2-Clause" ]
28
2020-09-17T14:20:35.000Z
2022-01-10T16:26:00.000Z
/** * Copyright (c) 2019 Horizon Robotics. All rights reserved. * @author yaoyao.sun * @date 2019.04.12 */ #include <chrono> #include <iostream> #include <thread> #include <string> #include <vector> #include "bpu_predict/bpu_predict.h" #include "./hb_vio_interface.h" #include "./plat_cnn.h" static void Usage() { std::cout << "./FasterRCNNMethod_example model_info model_name ipc/panel\n"; } int TestModelInfo(int argc, char **argv) { if (argc < 3) { Usage(); return -1; } std::cout << "core num: " << cnn_core_num() << std::endl; std::string model = argv[2]; std::string model_file_path; if (model == "ipc") { model_file_path = "./models/IPCModel.hbm"; } else if (model == "panel") { model_file_path = "./models/faceMultitask.hbm"; } else { std::cout << "not support this model " << model << "\n"; } const char *bpu_config_path = "./configs/bpu_config.json"; BPUHandle bpu_handle; int ret = BPU_loadModel(model_file_path.c_str(), &bpu_handle, bpu_config_path); if (ret != 0) { std::cout << "here load bpu model failed: " << BPU_getLastError(bpu_handle) << std::endl; return 1; } std::cout << "here load bpu model OK" << std::endl; // get bpu version const char* version = BPU_getVersion(bpu_handle); if (version == nullptr) { std::cout << "here get bpu version failed: " << BPU_getLastError(bpu_handle) << std::endl; return 1; } std::cout << "here get bpu version: " << version << std::endl; // get model names const char** name_list; int name_cnt; ret = BPU_getModelNameList(bpu_handle, &name_list, &name_cnt); if (ret != 0) { std::cout << "here get name list failed: " << BPU_getLastError(bpu_handle) << std::endl; return 1; } // print all name list std::cout << "here get all name list: " << name_cnt << " list below: " << std::endl; for (int i = 0; i < name_cnt; ++i) { std::cout << name_list[i] << std::endl; } // const char* model_name = "personMultiTask"; const char* model_name = argv[1]; // get input info BPUModelInfo input_info; ret = BPU_getModelInputInfo(bpu_handle, model_name, &input_info); if (ret != 0) { std::cout << "here get model: " << model_name << " input info failed: " << BPU_getLastError(bpu_handle) << "\n"; return 1; } // print input info std::cout << "model: " << model_name << " has input: " << input_info.num << "\n"; for (int i = 0; i < input_info.num; ++i) { std::cout << "("; for (int j = input_info.ndim_array[i]; j < input_info.ndim_array[i + 1]; ++j) { std::cout << input_info.valid_shape_array[j] << ","; } std::cout << ")" << std::endl; } // get output info BPUModelInfo output_info; ret = BPU_getModelOutputInfo(bpu_handle, model_name, &output_info); if (ret != 0) { std::cout << "here get model: " << model_name << " output info failed: " << BPU_getLastError(bpu_handle) << std::endl; return 1; } // print output info std::cout << "model: " << model_name << " has output: " << output_info.num << std::endl; uint32_t output_layer_num = output_info.num; for (size_t i = 0; i < output_layer_num; ++i) { const uint8_t *shift_value = output_info.shift_value[i]; // dim of per shape = 4 int *aligned_dim = output_info.aligned_shape_array + i * 4; int *valid_dim = output_info.valid_shape_array + i * 4; int alligned_channel_num = aligned_dim[3]; int padding_channel_num = aligned_dim[3] - valid_dim[3]; std::cout << "layer num: " << i << " aligned channel num: " << alligned_channel_num << " padding channel num: " << padding_channel_num << "\n"; std::cout << " shift: ["; for (int j = 0; j < alligned_channel_num - padding_channel_num; ++j) { std::cout << static_cast<uint32_t>(shift_value[j]) << ","; } std::cout << "]\n"; const char *feature_name = output_info.name_list[i]; std::cout << "feature name: " << feature_name << std::endl; } int out_dtype_size = 0; std::vector<BPU_Buffer_Handle> out_buf; for (int i = 0; i < output_info.num; ++i) { int model_out_size = 1; std::cout << "("; for (int j = output_info.ndim_array[i]; j < output_info.ndim_array[i+1]; ++j) { std::cout << output_info.aligned_shape_array[j] << ","; model_out_size *= output_info.aligned_shape_array[j]; } std::cout << ")" << std::endl; // get dtype if (output_info.dtype_array[i] == BPU_DTYPE_FLOAT32) { out_dtype_size = sizeof(float); } else { out_dtype_size = sizeof(int8_t); } void *output_data = malloc(model_out_size * out_dtype_size); BPU_Buffer_Handle out_handle = BPU_createBPUBuffer(output_data, model_out_size * out_dtype_size); out_buf.push_back(out_handle); } return 0; }
31.106918
80
0.604327
HorizonRobotics-Platform
0b31c4a702f1518920931546d18b58e1b4cf3843
968
cpp
C++
tests/EnjoLibTest/src/CentroidTest.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
tests/EnjoLibTest/src/CentroidTest.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
tests/EnjoLibTest/src/CentroidTest.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include "CentroidTest.h" #include <Statistical/Centroid.hpp> #include <Statistical/VectorD.hpp> #include <Template/Array.hpp> #include <Math/RandomMath.hpp> #include <Ios/Osstream.hpp> #include <Util/CoutBuf.hpp> using namespace EnjoLib; using namespace std; CentroidTest::CentroidTest() { ELO Centroid<VectorD> centr; const RandomMath rmath; rmath.RandSeed(); int numVec = 5; int dims = 8; vector<VectorD> vsamples; for (int n = 0; n < numVec; ++n) { VectorD in; for (int i = 0; i < dims; ++i) { double y = rmath.Rand(0, 1); in.push_back(y); } vsamples.push_back(in); Osstream ossFile; ossFile << "var" << n; LOG << in.PrintPython(ossFile.str().c_str()); } Array<VectorD> samples(vsamples); VectorD centroid = centr.Calc(samples); LOG << centroid.PrintPython("centroid"); } CentroidTest::~CentroidTest() { //dtor }
20.595745
53
0.603306
EnjoMitch
0b358aac0ff1d2c5f7b0a4ee49ada8391c543c2c
1,295
cc
C++
blaze/blaze/operator/op/split_op.cc
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
blaze/blaze/operator/op/split_op.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
blaze/blaze/operator/op/split_op.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* * \file split_op.cc * \brief The split operation on cpu */ #include "blaze/operator/op/split_op.h" namespace blaze { template <typename DType> void RunSplit(SplitParam<DType>& params) { size_t y_offset[kMaxInputSize] = { 0 }; for (size_t i = 0; i < params.outer_size; ++i) { for (size_t k = 0; k < params.split_num; ++k) { memcpy(params.split_item[k].y + y_offset[k], params.x, params.split_item[k].split_axis_size * sizeof(DType)); params.x += params.split_item[k].split_axis_size; y_offset[k] += params.split_item[k].split_axis_size; } } } template <> bool SplitOp<CPUContext>::RunOnDevice() { if (auto_split_ && axis_ == 0) { return RunOnDevice_SplitAxis0(); } // Check the validity of Split CheckValid(); Blob* x = this->Input(0); TYPE_SWITCH(x->data_type(), DType, { SplitParam<DType> params; // Prepare params and reshape Setup<DType>(&params); // Start to execute split kernel RunSplit(params); }); return true; } REGISTER_CPU_OPERATOR(Split, SplitOp<CPUContext>); // Input: X Output: Y1, Y2, ... OPERATOR_SCHEMA(Split) .NumInputs(1) .NumOutputs(1, INT_MAX) .IdenticalTypeOfInput(0) .SetDoc(R"DOC( Split a tensor into many tensors. )DOC"); } // namespace blaze
22.719298
67
0.648649
Ru-Xiang
0b35997bbbdc79cf929bd4d1866d695b6d67e471
1,130
cc
C++
src/15.cc
o-olll/shuati
64a031a5218670afd4bdbba5d3af3c428757b3fd
[ "Apache-2.0" ]
null
null
null
src/15.cc
o-olll/shuati
64a031a5218670afd4bdbba5d3af3c428757b3fd
[ "Apache-2.0" ]
null
null
null
src/15.cc
o-olll/shuati
64a031a5218670afd4bdbba5d3af3c428757b3fd
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <unordered_map> #include <string> #include "utils.h" using namespace std; vector<vector<int>> threeSum(vector<int>& nums) { if (nums.size() < 3) return {}; vector<vector<int>> res; int l, r, s, k; sort(nums.begin(), nums.end()); for (int i=0; i<nums.size()-2; ++i) { l = i+1; r = nums.size()-1; k = -nums[i]; while (l < r) { s = nums[l] + nums[r]; if (s == k) { res.push_back({nums[i], nums[l], nums[r]}); while (r>l && nums[r]==nums[r-1]) --r; while (l<r && nums[l]==nums[l+1]) ++l; --r; ++l; } else if (s > k) { --r; } else { ++l; } } while (i<nums.size()-3 && nums[i]==nums[i+1]) ++i; } return res; } int main(int argc, char** argv) { vector<int> test_case = {-1}; auto res = threeSum(test_case); for (auto& v : res) { utils::printContainer(v.begin(), v.end()); } return 0; }
20.925926
59
0.423009
o-olll
0b36a345f95fafb1213f1e8482735e0ed4ed5a09
3,595
cpp
C++
csapex_core_plugins/src/tools/unix_signal_emitter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
2
2016-09-02T15:33:22.000Z
2019-05-06T22:09:33.000Z
csapex_core_plugins/src/tools/unix_signal_emitter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
1
2021-02-14T19:53:30.000Z
2021-02-14T19:53:30.000Z
csapex_core_plugins/src/tools/unix_signal_emitter.cpp
AdrianZw/csapex_core_plugins
1b23c90af7e552c3fc37c7dda589d751d2aae97f
[ "BSD-3-Clause" ]
6
2016-10-12T00:55:23.000Z
2021-02-10T17:49:25.000Z
/// PROJECT #include <csapex/model/node.h> #include <csapex/model/node_modifier.h> #include <csapex/msg/any_message.h> #include <csapex/msg/io.h> #include <csapex/param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> /// SYSTEM #include <map> #include <signal.h> using namespace csapex; using namespace csapex::connection_types; namespace csapex { class UnixSignalEmitter : public Node { public: UnixSignalEmitter() : signal_list({ { SIGHUP, "SIGHUP - Hangup" }, { SIGINT, "SIGINT - Interrupt" }, { SIGQUIT, "SIGQUIT - Quit" }, { SIGILL, "SIGILL - Illegal instruction" }, { SIGTRAP, "SIGTRAP - Trace trap" }, { SIGABRT, "SIGABRT - Abort" }, { SIGIOT, "SIGIOT - IOT trap" }, { SIGBUS, "SIGBUS - BUS error" }, { SIGFPE, "SIGFPE - Floating-point exception" }, { SIGKILL, "SIGKILL - Kill, unblockable" }, { SIGUSR1, "SIGUSR1 - User-defined signal 1" }, { SIGSEGV, "SIGSEGV - Segmentation violation" }, { SIGUSR2, "SIGUSR2 - User-defined signal 2" }, { SIGPIPE, "SIGPIPE - Broken pipe" }, { SIGALRM, "SIGALRM - Alarm clock" }, { SIGTERM, "SIGTERM - Termination" }, { SIGSTKFLT, "SIGSTKFLT - Stack fault" }, { SIGCHLD, "SIGCHLD - Child status has changed" }, { SIGCONT, "SIGCONT - Continue" }, { SIGSTOP, "SIGSTOP - Stop, unblockable" }, { SIGTSTP, "SIGTSTP - Keyboard stop" }, { SIGTTIN, "SIGTTIN - Background read from tty" }, { SIGTTOU, "SIGTTOU - Background write to tty" }, { SIGURG, "SIGURG - Urgent condition on socket" }, { SIGXCPU, "SIGXCPU - CPU limit exceeded" }, { SIGXFSZ, "SIGXFSZ - File size limit exceeded" }, { SIGVTALRM, "SIGVTALRM - Virtual alarm clock" }, { SIGPROF, "SIGPROF - Profiling alarm clock" }, { SIGWINCH, "SIGWINCH - Window size change (4.3 BSD, Sun)" }, { SIGPOLL, "SIGPOLL - Pollable event occurred (System V)" }, { SIGIO, "SIGIO - I/O now possible" }, { SIGPWR, "SIGPWR - Power failure restart (System V)" }, { SIGSYS, "SIGSYS - Bad system call" } }) { } void setup(csapex::NodeModifier& modifier) override { modifier.addInput<csapex::connection_types::AnyMessage>("trigger"); modifier.addSlot("trigger", [this]() { trigger(); }); } void setupParameters(csapex::Parameterizable& params) override { std::map<std::string, int> signal; for (const auto& pair : signal_list) { signal.insert({ pair.second, pair.first }); } params.addParameter(param::factory::declareParameterSet("signal", signal, SIGUSR1), signal_); } void process() override { trigger(); } void trigger() { ainfo << "raise " << signal_list.at(signal_) << std::endl; raise(signal_); } private: std::map<int, const char*> signal_list; int signal_; }; } // namespace csapex CSAPEX_REGISTER_CLASS(csapex::UnixSignalEmitter, csapex::Node)
37.842105
101
0.512935
AdrianZw
0b3f7725e00fd0afb3be84e1339d2661d670d7db
10,421
cpp
C++
logdevice/server/rebuilding/RebuildingFilter.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
1
2018-09-12T15:45:05.000Z
2018-09-12T15:45:05.000Z
logdevice/server/rebuilding/RebuildingFilter.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
null
null
null
logdevice/server/rebuilding/RebuildingFilter.cpp
majra20/LogDevice
dea0df7991120d567354d7a29d832b0e10be7477
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <folly/Optional.h> #include "logdevice/common/Timestamp.h" #include "logdevice/common/debug.h" #include "logdevice/server/LogRebuilding.h" namespace facebook { namespace logdevice { bool RebuildingReadFilter:: operator()(logid_t log, lsn_t lsn, const ShardID* copyset, copyset_size_t copyset_size, LocalLogStoreRecordFormat::csi_flags_t flags, RecordTimestamp min_ts, RecordTimestamp max_ts) { if (flags & LocalLogStoreRecordFormat::CSI_FLAG_DRAINED) { noteRecordFiltered(FilteredReason::DRAINED); return false; } bool try_filter_relocate = rebuildingSet->filter_relocate_shards; FilteredReason filtered_reason = FilteredReason::NOT_DIRTY; if (try_filter_relocate) { // Setting filter_relocate=true ensures that shards that are being rebuilt // in RELOCATE mode are added to scd's known down list for filtering. If we // do not do this, a bias is introduced that leads to that node rebuilding // around 1/3rd of the copysets it belongs to, which is undesired as we // prefer the load is distributed among all failure domains in the tier. filtered_reason = populateFilterParams( copyset, copyset_size, min_ts, max_ts, /*filter_relocate=*/true); } if (!try_filter_relocate || scd_known_down_.size() >= copyset_size) { // Looks like all nodes are in `scd_known_down_`, which can happen if there // are shards being rebuilt in RELOCATE mode and there are copysets that // contain this shard but also in which all other shards are being rebuilt // in RESTORE mode. In that case we have to resort to the node being rebuilt // in RELOCATE mode to be donor. // Retry with filter_relocate=false. filtered_reason = populateFilterParams( copyset, copyset_size, min_ts, max_ts, /*filter_relocate=*/false); } // Perform SCD copyset filtering. bool result = !required_in_copyset_.empty(); if (result) { filtered_reason = FilteredReason::SCD; result = LocalLogStoreReadFilter::operator()( log, lsn, copyset, copyset_size, flags, min_ts, max_ts); } if (!result) { noteRecordFiltered(filtered_reason); } return result; } RebuildingReadFilter::FilteredReason RebuildingReadFilter::populateFilterParams(const ShardID* copyset, const copyset_size_t copyset_size, RecordTimestamp min_ts, RecordTimestamp max_ts, bool filter_relocate) { required_in_copyset_.clear(); scd_known_down_.clear(); // Disable the ability to have a node seen as down ship its own copy as for // rebuilding, and if filter_relocate=true, this can cause two nodes to // rebuild the same copy. ship_if_i_am_down_ = false; auto filtered_reason = FilteredReason::NOT_DIRTY; // TODO(T43708398): in order to work around T43708398, we always look for // append dirty ranges. auto dc = DataClass::APPEND; for (copyset_off_t i = 0; i < copyset_size; ++i) { ShardID shard = copyset[i]; auto node_kv = rebuildingSet->shards.find(shard); if (node_kv != rebuildingSet->shards.end()) { auto& node_info = node_kv->second; if (!node_info.dc_dirty_ranges.empty()) { // Node is only partially dirty (time range data is provided). ld_check(node_info.mode == RebuildingMode::RESTORE); // Exclude if DataClass/Timestamp do not match. auto dc_tr_kv = node_info.dc_dirty_ranges.find(dc); if (dc_tr_kv == node_info.dc_dirty_ranges.end() || dc_tr_kv->second.empty()) { // DataClass isn't dirty. // We should never serialize an empty DataClass since it is // not dirty, but we tolerate it in production builds. ld_check(dc_tr_kv == node_info.dc_dirty_ranges.end()); continue; } // Check if the record's timestamp intersects some of the // time ranges of this shard in the rebuilding set. const auto& time_ranges = dc_tr_kv->second; bool intersects; if (timeRangeCache.valid(min_ts, max_ts)) { // (a) Just like (d), but we already have a cached result for this // time range. intersects = !timeRangeCache.shardsOutsideTimeRange.count( std::make_pair(shard, dc)); } else if (min_ts == max_ts) { // (b) We know the exact timestamp of the record. intersects = time_ranges.find(min_ts) != time_ranges.end(); } else if (min_ts > max_ts) { // (c) Invalid range. Be paranoid and assume that it intersects the // rebuilding range. RATELIMIT_INFO( std::chrono::seconds(10), 2, "operator() called with min_ts > max_ts: %s > %s. Log: %lu", min_ts.toString().c_str(), max_ts.toString().c_str(), logid_.val_); intersects = true; } else { // (d) We don't know the exact timestamp, but we know that it's // somewhere in [min_ts, max_ts] range. Check if this range // intersects any of the rebuilding time ranges for this shard. intersects = boost::icl::intersects( time_ranges, RecordTimeInterval(min_ts, max_ts)); // At the time of writing, this should be unreachable with all // existing LocalLogStore::ReadIterator implementations. // If you see this message, it's likely that there's a bug. RATELIMIT_INFO( std::chrono::seconds(10), 1, "Time range in operator() doesn't match time range in " "shouldProcessTimeRange(). Suspicious. Please check the code."); } if (!intersects) { // Record falls outside a dirty time range. filtered_reason = FilteredReason::TIMESTAMP; continue; } } // Records inside a dirty region may be lost, but some/all may // have been durably stored before we crashed. We only serve as a // donor for records we happen to find in a dirty region if some // other node's failure also impacts the record (i.e. if we get past // this point during a different iteration of this loop). ld_check(scd_my_shard_id_.isValid()); if (shard == scd_my_shard_id_ && node_kv->second.mode == RebuildingMode::RESTORE) { continue; } // Node's shard either needs to be fully rebuilt or is dirty in this // region and we can serve as a donor. required_in_copyset_.push_back(shard); // If the rebuilding node is rebuilding in RESTORE mode, it should not // participate as a donor. Add it to the known down list so that other // nodes will send the records for which it was the leader. // // Note: If this node is in the rebuilding set for a time-ranged // rebuild, and that range overlaps with under-replication // on another node, it is possible for our node id to be added // here. However, the SCD filtering logic ignores known_down // for the local node id and we will be considered a donor for // the record. This can lead to overreplication, but also // ensures that data that can be rebuilt isn't skipped. // Add nodes that are being rebuilt in RESTORE mode to the known down list // as we know they are down and cannot be donor. // If filter_relocate==true, also add nodes that are being rebuilt in // RELOCATE mode in order to avoid a bias where that node ends up // rebuilding 1/3rd of all the copysets that it belongs to. if (filter_relocate || node_kv->second.mode == RebuildingMode::RESTORE) { scd_known_down_.push_back(shard); } } } return filtered_reason; } bool RebuildingReadFilter::shouldProcessTimeRange(RecordTimestamp min, RecordTimestamp max) { auto& cache = timeRangeCache; cache.clear(); if (min > max) { RATELIMIT_INFO( std::chrono::seconds(10), 2, "shouldProcessTimeRange() called with min > max: %s > %s. Log: %lu", min.toString().c_str(), max.toString().c_str(), logid_.val_); // Be conservative. return true; } cache.minTs = min; cache.maxTs = max; bool have_shards_intersecting_range = false; for (const auto& node_kv : rebuildingSet->shards) { ShardID shard = node_kv.first; auto& node_info = node_kv.second; if (node_info.dc_dirty_ranges.empty()) { // Empty dc_dirty_ranges means that the node is dirty for all time points. have_shards_intersecting_range = true; continue; } // Node is only partially dirty (time range data is provided). ld_check(node_info.mode == RebuildingMode::RESTORE); for (const auto& dc_tr_kv : node_info.dc_dirty_ranges) { if (dc_tr_kv.second.empty()) { ld_check(false); continue; } auto& time_ranges = dc_tr_kv.second; if (boost::icl::intersects(time_ranges, RecordTimeInterval(min, max))) { // The shard is dirty for some of the timestamps in [min, max]. have_shards_intersecting_range = true; } else { // The shard is clean for all timestamps in [min, max]. cache.shardsOutsideTimeRange.emplace(shard, dc_tr_kv.first); } } } return have_shards_intersecting_range; } /** * Update stats regarding skipped records. */ void RebuildingReadFilter::noteRecordFiltered(FilteredReason reason) { switch (reason) { case FilteredReason::SCD: ++nRecordsSCDFiltered; break; case FilteredReason::NOT_DIRTY: ++nRecordsNotDirtyFiltered; break; case FilteredReason::DRAINED: ++nRecordsDrainedFiltered; break; case FilteredReason::TIMESTAMP: // Timestamp data is only available after retrieving the full record. ++nRecordsLateFiltered; ++nRecordsTimestampFiltered; break; } } }} // namespace facebook::logdevice
39.623574
80
0.644756
majra20
0b43c689a0074b1ba70ed2b69cb0986a5629883d
2,779
hpp
C++
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/schedule_query_spacetime__builder.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/schedule_query_spacetime__builder.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/schedule_query_spacetime__builder.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_generator_cpp/resource/idl__builder.hpp.em // with input from rmf_traffic_msgs:msg/ScheduleQuerySpacetime.idl // generated code does not contain a copyright notice #ifndef RMF_TRAFFIC_MSGS__MSG__DETAIL__SCHEDULE_QUERY_SPACETIME__BUILDER_HPP_ #define RMF_TRAFFIC_MSGS__MSG__DETAIL__SCHEDULE_QUERY_SPACETIME__BUILDER_HPP_ #include "rmf_traffic_msgs/msg/detail/schedule_query_spacetime__struct.hpp" #include <rosidl_runtime_cpp/message_initialization.hpp> #include <algorithm> #include <utility> namespace rmf_traffic_msgs { namespace msg { namespace builder { class Init_ScheduleQuerySpacetime_timespan { public: explicit Init_ScheduleQuerySpacetime_timespan(::rmf_traffic_msgs::msg::ScheduleQuerySpacetime & msg) : msg_(msg) {} ::rmf_traffic_msgs::msg::ScheduleQuerySpacetime timespan(::rmf_traffic_msgs::msg::ScheduleQuerySpacetime::_timespan_type arg) { msg_.timespan = std::move(arg); return std::move(msg_); } private: ::rmf_traffic_msgs::msg::ScheduleQuerySpacetime msg_; }; class Init_ScheduleQuerySpacetime_shape_context { public: explicit Init_ScheduleQuerySpacetime_shape_context(::rmf_traffic_msgs::msg::ScheduleQuerySpacetime & msg) : msg_(msg) {} Init_ScheduleQuerySpacetime_timespan shape_context(::rmf_traffic_msgs::msg::ScheduleQuerySpacetime::_shape_context_type arg) { msg_.shape_context = std::move(arg); return Init_ScheduleQuerySpacetime_timespan(msg_); } private: ::rmf_traffic_msgs::msg::ScheduleQuerySpacetime msg_; }; class Init_ScheduleQuerySpacetime_regions { public: explicit Init_ScheduleQuerySpacetime_regions(::rmf_traffic_msgs::msg::ScheduleQuerySpacetime & msg) : msg_(msg) {} Init_ScheduleQuerySpacetime_shape_context regions(::rmf_traffic_msgs::msg::ScheduleQuerySpacetime::_regions_type arg) { msg_.regions = std::move(arg); return Init_ScheduleQuerySpacetime_shape_context(msg_); } private: ::rmf_traffic_msgs::msg::ScheduleQuerySpacetime msg_; }; class Init_ScheduleQuerySpacetime_type { public: Init_ScheduleQuerySpacetime_type() : msg_(::rosidl_runtime_cpp::MessageInitialization::SKIP) {} Init_ScheduleQuerySpacetime_regions type(::rmf_traffic_msgs::msg::ScheduleQuerySpacetime::_type_type arg) { msg_.type = std::move(arg); return Init_ScheduleQuerySpacetime_regions(msg_); } private: ::rmf_traffic_msgs::msg::ScheduleQuerySpacetime msg_; }; } // namespace builder } // namespace msg template<typename MessageType> auto build(); template<> inline auto build<::rmf_traffic_msgs::msg::ScheduleQuerySpacetime>() { return rmf_traffic_msgs::msg::builder::Init_ScheduleQuerySpacetime_type(); } } // namespace rmf_traffic_msgs #endif // RMF_TRAFFIC_MSGS__MSG__DETAIL__SCHEDULE_QUERY_SPACETIME__BUILDER_HPP_
26.721154
127
0.801367
flitzmo-hso
0b48bd349894bdaa7e8fe767deefd7efffcdac8d
9,705
cpp
C++
src/verifier/tree_compress.cpp
jre233kei/slim
13764ed193cc49a6008e1fdb28575e66165b045d
[ "BSD-3-Clause" ]
18
2015-02-11T13:52:46.000Z
2021-07-05T10:50:22.000Z
src/verifier/tree_compress.cpp
jre233kei/slim
13764ed193cc49a6008e1fdb28575e66165b045d
[ "BSD-3-Clause" ]
58
2015-01-02T11:31:12.000Z
2022-03-23T07:16:47.000Z
src/verifier/tree_compress.cpp
jre233kei/slim
13764ed193cc49a6008e1fdb28575e66165b045d
[ "BSD-3-Clause" ]
17
2015-04-02T03:52:48.000Z
2021-02-07T02:29:38.000Z
/* * tree_compress.cpp * * Copyright (c) 2008, Ueda Laboratory LMNtal Group * <lmntal@ueda.info.waseda.ac.jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the Ueda Laboratory LMNtal Group nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id$ */ /** @author Taketo Yoshida * Parallel Recursive State Compression for Free */ #include "tree_compress.h" #include <math.h> #define atomic_fetch_and_inc(t) __sync_fetch_and_add(t, 1) #define atomic_fetch_and_dec(t) __sync_fetch_and_sub(t, 1) #define atomic_compare_and_swap(t, old, new) \ __sync_bool_compare_and_swap(t, old, new) #define TREE_UNIT_SIZE 8 #define TREE_THRESHOLD 10 #define TREE_CACHE_LINE 8 typedef struct TreeNodeStr *TreeNodeStrRef; struct TreeNodeStr { TreeNodeElement *nodes; int len; int extra; }; uint64_t murmurhash64(const void *key, int len, unsigned int seed) { const uint64_t m = 0xc6a4a7935bd1e995; const int r = 47; uint64_t h = seed ^ (len * m); const uint64_t *data = (const uint64_t *)key; const uint64_t *end = data + (len / 8); while (data != end) { uint64_t k = *data++; k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; } const unsigned char *data2 = (const unsigned char *)data; switch (len & 7) { case 7: h ^= ((uint64_t)data2[6]) << 48; case 6: h ^= ((uint64_t)data2[5]) << 40; case 5: h ^= ((uint64_t)data2[4]) << 32; case 4: h ^= ((uint64_t)data2[3]) << 24; case 3: h ^= ((uint64_t)data2[2]) << 16; case 2: h ^= ((uint64_t)data2[1]) << 8; case 1: h ^= ((uint64_t)data2[0]); h *= m; }; h ^= h >> r; h *= m; h ^= h >> r; return h; } uint64_t mix64(uint64_t key) { key = (~key) + (key << 21); // key = (key << 21) - key - 1; key = key ^ (((int64_t)key) >> 24); key = (key + (key << 3)) + (key << 8); // key * 265 key = key ^ (((int64_t)key) >> 14); key = (key + (key << 2)) + (key << 4); // key * 21 key = key ^ (((int64_t)key) >> 28); key = key + (key << 31); return key; } int tree_get_split_position(int start, int end) { int size = end - start; return (int)(size / 2.0); } TreeNodeUnit vector_unit(TreeNodeStrRef str, int start, int end) { unsigned long long ret; int copy_len = TREE_UNIT_SIZE; if (str->extra && end == str->len - 1) { copy_len = str->extra; } // printf("start :%d\n", start * TREE_UNIT_SIZE); // printf("copy_len :%d\n", copy_len); memcpy(&ret, ((BYTE *)str->nodes + (start * TREE_UNIT_SIZE)), sizeof(BYTE) * copy_len); // printf("start :0x%14llx\n", ret); return ret; } uint64_t hash_node(TreeNodeElement left, TreeNodeElement right) { struct TreeNode node = {.left = left, .right = right}; return murmurhash64(&node, 16, 0x5bd1e995); } BOOL is_compress_node(TreeNodeElement left, TreeNodeElement right) { return ((left & 0x00000000FFFFFFFF) == left && (right & 0x00000000FFFFFFFF) == right); } BOOL tree_node_equal(TreeNodeRef node1, TreeNodeElement left, TreeNodeElement right) { return node1->left == left && node1->right == right; } LmnBinStrRef binstr_make(unsigned int len) { int real_len = ((len + 1) / TAG_IN_BYTE); LmnBinStrRef bs = LMN_MALLOC(struct LmnBinStr); bs->len = len; bs->type = 0x00U; bs->v = LMN_NALLOC(BYTE, real_len); memset(bs->v, 0x0U, sizeof(BYTE) * real_len); return bs; } TreeNodeRef tree_node_make(TreeNodeElement left, TreeNodeElement right) { TreeNodeRef node=LMN_MALLOC(struct TreeNode); node->left = left; node->right = right; return node; } BOOL TreeDatabase::table_find_or_put(TreeNodeElement left, TreeNodeElement right, TreeNodeID *ref) { int count, i; uint64_t mask = this->mask; TreeNodeRef *table = this->nodes; uint64_t offset; redo: offset = (hash_node(left, right) & mask); count = 0; while (count < TREE_THRESHOLD) { // Walk Cache line for (i = 0; i < TREE_CACHE_LINE; i++) { if (table[(offset + i) & mask] == 0) { TreeNodeRef node = tree_node_make(left, right); if (atomic_compare_and_swap(&table[(offset + i) & mask], 0, node)) { atomic_fetch_and_inc(&this->node_count); *ref = (offset + i) & mask; return FALSE; } else { std::free(node); goto redo; } } else if (tree_node_equal(table[(offset + i) & mask], left, right)) { *ref = (offset + i) & mask; return TRUE; } } offset = (mix64(offset) & mask); count++; } fprintf(stderr, "error full table\n"); fprintf(stderr, "node count : %10lu\n", this->node_count); fprintf(stderr, "table size : %10lu\n", (this->mask + 1)); fprintf(stderr, "load factor : %10.3lf\n", (double)tree_db_node_count(this) / (this->mask + 1)); fprintf(stderr, "memory : %7lu MB\n", (uint64_t)this->space() / 1024 / 1024); exit(EXIT_FAILURE); } TreeDatabase::TreeDatabase(size_t size){ this->nodes = LMN_CALLOC(TreeNodeRef, size); this->mask = size - 1; this->node_count = 0; } void TreeDatabase::clear(){ int i; this->node_count = 0; for (i = 0; i < this->mask + 1; i++) { if (this->nodes[i]) { LMN_FREE(this->nodes[i]); this->nodes[i] = NULL; } } } TreeDatabase::~TreeDatabase() { this->clear(); LMN_FREE(this->nodes); return; } TreeNodeElement TreeDatabase::tree_find_or_put_rec(TreeNodeStrRef str, int start, int end, BOOL *found) { int split; TreeNodeID ref; if ((end - start + 1) <= 1) { return vector_unit(str, start, end); } split = tree_get_split_position(start, end); TreeNodeElement left = this->tree_find_or_put_rec(str, start, start + split, found); TreeNodeElement right = this->tree_find_or_put_rec(str, start + split + 1, end, found); if ((end - start + 1) == str->len) { BOOL _found = this->table_find_or_put(left, right, &ref); if (found) (*found) = _found; } else { this->table_find_or_put(left, right, &ref); } return ref; } TreeNodeID TreeDatabase::tree_find_or_put(LmnBinStrRef bs, BOOL *found) { struct TreeNodeStr str; TreeNodeID ref; int v_len_real = ((bs->len + 1) / TAG_IN_BYTE); str.len = v_len_real / TREE_UNIT_SIZE; str.extra = v_len_real % TREE_UNIT_SIZE; str.nodes = (TreeNodeElement *)bs->v; if (str.extra > 0) str.len += 1; // printf("node_count: %d, extra:%d\n", str.len, str.extra); ref = this->tree_find_or_put_rec(&str, 0, str.len - 1, found); return ref; } void TreeDatabase::get_rec(TreeNodeElement elem, int start, int end, TreeNodeStrRef dst) { int k = end - start + 1; if (k <= TREE_UNIT_SIZE) { int copy_len = TREE_UNIT_SIZE; if (end + 1 == (dst->len * TREE_UNIT_SIZE) && dst->extra != 0) { copy_len = dst->extra; } // printf("%d-%d len:%d\n", start, end, dst->len * TREE_UNIT_SIZE); // printf("elem:%llu, copy_len: %d\n", elem, copy_len); memcpy((BYTE *)dst->nodes + start, &elem, sizeof(BYTE) * copy_len); } else if (this->nodes[elem & this->mask] != NULL) { TreeNodeRef node = this->nodes[elem & this->mask]; int split = ((end - start) / TREE_UNIT_SIZE) / 2; // printf("Split: %d\n", split); this->get_rec(node->left, start, start + (split * TREE_UNIT_SIZE), dst); this->get_rec(node->right, start + ((split + 1) * TREE_UNIT_SIZE), end, dst); } } LmnBinStrRef TreeDatabase::get(TreeNodeID ref, int len) { LmnBinStrRef bs = binstr_make(len); struct TreeNodeStr str; int real_len = ((len + 1) / TAG_IN_BYTE); str.len = real_len / TREE_UNIT_SIZE; str.extra = real_len % TREE_UNIT_SIZE; str.nodes = (TreeNodeElement *)bs->v; if (str.extra > 0) str.len += 1; // printf("node_count: %d, extra:%d\n", str.len, str.extra); this->get_rec(ref, 0, str.len * TREE_UNIT_SIZE - 1, &str); return bs; } uint64_t TreeDatabase::space(void) { uint64_t memory = 0; memory += sizeof(struct TreeDatabase); memory += this->node_count * sizeof(struct TreeNode); memory += (this->mask + 1) * sizeof(TreeNodeRef); return memory; }
30.615142
80
0.625245
jre233kei
0b50fcf134a195c21be92cde7a900ef0bce6b5fc
1,758
hh
C++
examples/ScatteringExample/include/SEGasHit.hh
QTNM/Electron-Tracking
b9dff0232af5a99fd795fd504dbddde71f4dd31c
[ "MIT" ]
2
2022-03-16T22:30:19.000Z
2022-03-16T22:30:26.000Z
examples/ScatteringExample/include/SEGasHit.hh
QTNM/Electron-Tracking
b9dff0232af5a99fd795fd504dbddde71f4dd31c
[ "MIT" ]
18
2021-03-02T15:14:11.000Z
2022-02-14T08:12:20.000Z
examples/ScatteringExample/include/SEGasHit.hh
QTNM/Electron-Tracking
b9dff0232af5a99fd795fd504dbddde71f4dd31c
[ "MIT" ]
null
null
null
#ifndef SEGasHit_h #define SEGasHit_h 1 #include "G4VHit.hh" #include "G4THitsCollection.hh" #include "G4Allocator.hh" /// Gas hit class /// /// It defines data members to store the energy deposit, /// and position in a selected volume: class SEGasHit : public G4VHit { public: SEGasHit(); SEGasHit(const SEGasHit&); virtual ~SEGasHit(); // operators const SEGasHit& operator=(const SEGasHit&); G4bool operator==(const SEGasHit&) const; inline void* operator new(size_t); inline void operator delete(void*); // methods from base class virtual void Draw(); virtual void Print(); // Set methods void SetParentID (G4int id) { fPid = id; }; void SetTrackID (G4int id) { fTid = id; }; void SetEdep (G4double de) { fEdep = de; }; void SetTime (G4double ti) { fTime = ti; }; void SetKine (G4double ke) { fKine = ke; }; // Get methods G4int GetParentID() const { return fPid; }; G4int GetTrackID() const { return fTid; }; G4double GetEdep() const { return fEdep; }; G4double GetTime() const { return fTime; }; G4double GetKine() const { return fKine; }; private: G4int fTid; G4int fPid; G4double fEdep; G4double fTime; G4double fKine; }; typedef G4THitsCollection<SEGasHit> SEGasHitsCollection; extern G4ThreadLocal G4Allocator<SEGasHit>* SEGasHitAllocator; inline void* SEGasHit::operator new(size_t) { if(!SEGasHitAllocator) SEGasHitAllocator = new G4Allocator<SEGasHit>; return (void *) SEGasHitAllocator->MallocSingle(); } inline void SEGasHit::operator delete(void *hit) { SEGasHitAllocator->FreeSingle((SEGasHit*) hit); } #endif
24.416667
62
0.642207
QTNM
0b584c4bb028a5912beb4ad6cc6326136f12b665
1,238
cpp
C++
LeetCode/0022/0022_2.cpp
samsonwang/ToyCpp
a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c
[ "MIT" ]
null
null
null
LeetCode/0022/0022_2.cpp
samsonwang/ToyCpp
a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c
[ "MIT" ]
null
null
null
LeetCode/0022/0022_2.cpp
samsonwang/ToyCpp
a6a757aacf1a0e6d9ba3c943c5744fde611a2f7c
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> #include <cstdio> #include <set> using namespace std; static const auto fast = [](){ ios_base::sync_with_stdio(false); cin.tie(NULL); return 0; }(); // 使用dp vector<string> generateParenthesis(int n) { vector<vector<string>> dp; dp.reserve(n+1); dp.push_back(vector<string>()); dp.push_back(vector<string>({"()"})); for (int i=2; i<n+1; ++i) { set<string> s; for (int j=1; j<=i-j; ++j) { for (size_t m=0; m<dp[j].size(); ++m) { for (size_t n=0; n<dp[i-j].size(); ++n) { s.insert(dp[j][m] + dp[i-j][n]); s.insert(dp[i-j][n] + dp[j][m]); if (j == 1) { s.insert('(' + dp[i-j][n] + ')'); } } } } dp.push_back(vector<string>(s.begin(), s.end())); } return dp[n]; } int main(int argc, char* argv[]) { vector<string> ans = generateParenthesis(4); cout << ans.size() << endl; for (const auto& s : ans) { cout << s << endl; } return 0; }
22.509091
62
0.417609
samsonwang
0b5bfabcfc61d89cb379480f58302b0b1a278f28
12,810
cpp
C++
Server/sq_functions.cpp
LHMPTeam/lhmp-old
84dd379ab8ae59418135c940e700f3022339e136
[ "Apache-2.0" ]
8
2017-02-13T13:29:39.000Z
2022-01-12T17:12:04.000Z
Server/sq_functions.cpp
LHMPTeam/lhmp-old
84dd379ab8ae59418135c940e700f3022339e136
[ "Apache-2.0" ]
null
null
null
Server/sq_functions.cpp
LHMPTeam/lhmp-old
84dd379ab8ae59418135c940e700f3022339e136
[ "Apache-2.0" ]
10
2017-01-14T09:41:06.000Z
2021-10-10T00:02:32.000Z
// (C) LHMP Team 2013-2016; Licensed under Apache 2; See LICENSE;; #include "sq_funcdef.h" #include "sq_functions.h" int Init(SQVM* vM) { //RegisterFunction(vM, "testfunc", (SQFUNCTION)sq_dopice, 0, ""); RegisterFunction(vM, "banIP", (SQFUNCTION)sq_banIP, 4, ".sns"); RegisterFunction(vM, "banPlayer", (SQFUNCTION)sq_banPlayer, 4, ".nns"); RegisterFunction(vM, "sendPlayerMessage", (SQFUNCTION)sq_sendPlayerMessage, 3, ".is"); RegisterFunction(vM, "sendAllMessage", (SQFUNCTION)sq_sendAllMessage, 2, ".s"); // Player natives RegisterFunction(vM, "playerChangeSkin", (SQFUNCTION)sq_playerChangeSkin, 3, ".nn"); RegisterFunction(vM, "playerIsConnected", (SQFUNCTION)sq_playerIsConnected, 2, ".n"); RegisterFunction(vM, "playerGetSkinID", (SQFUNCTION)sq_playerGetSkinID,2, ".n"); RegisterFunction(vM, "playerGetHealth", (SQFUNCTION)sq_playerGetHealth, 2, ".n"); RegisterFunction(vM, "playerGetMoney", (SQFUNCTION)sq_playerGetMoney, 2, ".n"); RegisterFunction(vM, "playerGetPosition", (SQFUNCTION)sq_playerGetPosition, 2, ".n"); RegisterFunction(vM, "playerGetRotation", (SQFUNCTION)sq_playerGetRotation, 2, ".n"); RegisterFunction(vM, "playerGetRotationAsVector", (SQFUNCTION)sq_playerGetRotationAsVector, 2, ".n"); RegisterFunction(vM, "playerInVehicleID", (SQFUNCTION)sq_playerInVehicleID, 2, ".n"); RegisterFunction(vM, "playerSetPosition", (SQFUNCTION)sq_playerSetPosition, 5, ".nfff"); RegisterFunction(vM, "playerSetHealth", (SQFUNCTION)sq_playerSetHealth, 3, ".nf"); RegisterFunction(vM, "playerSetMoney", (SQFUNCTION)sq_playerSetMoney, 3, ".nn"); RegisterFunction(vM, "playerEnableMoney", (SQFUNCTION)sq_playerEnableMoney, 3, ".nn"); RegisterFunction(vM, "playerSetRotation", (SQFUNCTION)sq_playerSetRotation, 3, ".nf"); RegisterFunction(vM, "playerSetRotationVector", (SQFUNCTION)sq_playerSetRotationVector, 5, ".nfff"); RegisterFunction(vM, "playerGetIP", (SQFUNCTION)sq_playerGetIP, 2, ".n"); RegisterFunction(vM, "playerPutToVehicle", (SQFUNCTION)sq_playerPutToVehicle, 4, ".nnn"); RegisterFunction(vM, "playerKickOutVehicle", (SQFUNCTION)sq_playerKickOutVehicle, 2, ".n"); RegisterFunction(vM, "playerKick", (SQFUNCTION)sq_playerKick, 2, ".n"); RegisterFunction(vM, "playerGetPing", (SQFUNCTION)sq_playerGetPing, 2, ".n"); RegisterFunction(vM, "playerGetName", (SQFUNCTION)sq_playerGetName, 2, ".n"); RegisterFunction(vM, "playerAddWeapon", (SQFUNCTION)sq_playerAddWeapon, 5, ".nnnn"); RegisterFunction(vM, "playerDeleteWeapon", (SQFUNCTION)sq_playerDeleteWeapon, 3, ".nn"); RegisterFunction(vM, "playerPlayAnim", (SQFUNCTION)sq_playerPlayAnim, 3, ".ns"); RegisterFunction(vM, "playerPlaySound", (SQFUNCTION)sq_playerPlaySound, 3, ".ns"); RegisterFunction(vM, "allPlaySound", (SQFUNCTION)sq_allPlaySound, 2, ".s"); RegisterFunction(vM, "playerToggleCityMusic", (SQFUNCTION)sq_playerToggleCityMusic, 3, ".nn"); RegisterFunction(vM, "playerLockControls", (SQFUNCTION)sq_playerLockControls, 3, ".nb"); RegisterFunction(vM, "playerIsLocked", (SQFUNCTION)sq_playerIsLocked, 2, ".n"); RegisterFunction(vM, "playerToggleCityMusic", (SQFUNCTION)sq_playerToggleCityMusic, 3, ".nn"); RegisterFunction(vM, "playerSetNickColor", (SQFUNCTION)sq_playerSetNickColor, 3, ".nn"); RegisterFunction(vM, "guiToggleNametag", (SQFUNCTION)sq_guiToggleNametag, 3, ".nn"); RegisterFunction(vM, "playerSetCameraPos", (SQFUNCTION)sq_playerSetCameraPos, 8, ".nffffff"); RegisterFunction(vM, "playerSetCameraToDefault", (SQFUNCTION)sq_playerSetCameraToDefault, 2, ".n"); RegisterFunction(vM, "playerSetCameraSwing", (SQFUNCTION)sq_playerSetCameraSwing, 4, ".nnf"); RegisterFunction(vM, "playerSetCameraFov", (SQFUNCTION)sq_playerSetCameraFov, 3, ".nf"); RegisterFunction(vM, "playerGetCameraFov", (SQFUNCTION)sq_playerGetCameraFov, 2, ".n"); RegisterFunction(vM, "playerSetWeatherParam", (SQFUNCTION)sq_playerSetWeatherParam, 4, ".nsn"); RegisterFunction(vM, "playerSetObjective", (SQFUNCTION)sq_playerSetObjective, 3, ".ns"); RegisterFunction(vM, "playerClearObjective", (SQFUNCTION)sq_playerClearObjective, 2, ".n"); RegisterFunction(vM, "playerAddConsoleText", (SQFUNCTION)sq_playerConsoleAddText, 4, ".nss"); RegisterFunction(vM, "vehicleSpawn", (SQFUNCTION)sq_vehicleSpawn, 8, ".nffffff"); RegisterFunction(vM, "vehicleDelete", (SQFUNCTION)sq_vehicleDelete, 2, ".n"); RegisterFunction(vM, "vehicleGetDriverID", (SQFUNCTION)sq_vehicleGetDriverID, 2, ".n"); RegisterFunction(vM, "vehicleGetPlayerIDFromSeat", (SQFUNCTION)sq_vehicleGetPlayerIDFromSeat, 3, ".nn"); RegisterFunction(vM, "vehicleGetPosition", (SQFUNCTION)sq_vehicleGetPosition, 2, ".n"); RegisterFunction(vM, "vehicleGetDamage", (SQFUNCTION)sq_vehicleGetDamage, 2, ".n"); RegisterFunction(vM, "vehicleGetRotation", (SQFUNCTION)sq_vehicleGetRotation, 2, ".n"); RegisterFunction(vM, "vehicleSetPosition", (SQFUNCTION)sq_vehicleSetPosition, 5, ".nfff"); RegisterFunction(vM, "vehicleSetFuel", (SQFUNCTION)sq_vehicleSetFuel, 3, ".nf"); RegisterFunction(vM, "vehicleGetFuel", (SQFUNCTION)sq_vehicleGetFuel, 2, ".n"); RegisterFunction(vM, "vehicleSetSpeed", (SQFUNCTION)sq_vehicleSetSpeed, 3, ".nf"); RegisterFunction(vM, "vehicleSetDamage", (SQFUNCTION)sq_vehicleSetDamage, 3, ".nf"); RegisterFunction(vM, "vehicleSetRotation", (SQFUNCTION)sq_vehicleSetRotation, 5, ".nfff"); RegisterFunction(vM, "vehicleToggleRoof", (SQFUNCTION)sq_vehicleToggleRoof, 3, ".nn"); RegisterFunction(vM, "vehicleToggleSiren", (SQFUNCTION)sq_vehicleToggleSiren, 3, ".nb"); RegisterFunction(vM, "vehicleGetSirenState", (SQFUNCTION)sq_vehicleGetSirenState, 2, ".n"); RegisterFunction(vM, "vehicleGetRoofState", (SQFUNCTION)sq_vehicleGetRoofState, 2, ".n"); RegisterFunction(vM, "vehicleExplode", (SQFUNCTION)sq_vehicleExplode, 2, ".n"); RegisterFunction(vM, "vehicleExists", (SQFUNCTION)sq_vehicleExists, 2, ".n"); RegisterFunction(vM, "isAnyPlayerInVehicle", (SQFUNCTION)sq_isAnyPlayerInVehicle, 2, ".n"); RegisterFunction(vM, "getDistanceBetween3DPoints", (SQFUNCTION)sq_getDistanceBetween3DPoints, 7, ".ffffff"); RegisterFunction(vM, "getDistanceBetween2DPoints", (SQFUNCTION)sq_getDistanceBetween2DPoints, 5, ".ffff"); RegisterFunction(vM, "serverGetName", (SQFUNCTION)sq_serverGetName, 1, "."); RegisterFunction(vM, "serverGetGamemodeName", (SQFUNCTION)sq_serverGetGamemodeName, 1, "."); RegisterFunction(vM, "serverSetGamemodeName", (SQFUNCTION)sq_serverSetGamemodeName, 2, ".s"); RegisterFunction(vM, "serverGetOnlinePlayers", (SQFUNCTION)sq_serverGetOnlinePlayers, 1, "."); RegisterFunction(vM, "serverGetMaxPlayers", (SQFUNCTION)sq_serverGetMaxPlayers, 1, "."); RegisterFunction(vM, "serverSetDefaultMap", (SQFUNCTION)sq_serverSetDefaultMap, 2, ".s"); RegisterFunction(vM, "timerCreate", (SQFUNCTION)sq_timerCreate, 5, ".snnn"); RegisterFunction(vM, "timerDelete", (SQFUNCTION)sq_timerDelete, 2, ".n"); RegisterFunction(vM, "pickupCreate", (SQFUNCTION)sq_pickupCreate, 7, ".snffff"); RegisterFunction(vM, "pickupDelete", (SQFUNCTION)sq_pickupDelete, 2, ".n"); RegisterFunction(vM, "iniFileExists", (SQFUNCTION)sq_iniFileExists, 2, ".s"); RegisterFunction(vM, "iniGetParam", (SQFUNCTION)sq_iniGetParam, 4, ".sss"); RegisterFunction(vM, "iniSetParam", (SQFUNCTION)sq_iniSetParam, 4, ".sss"); RegisterFunction(vM, "iniRemoveFile", (SQFUNCTION)sq_iniRemoveFile, 2, ".s"); RegisterFunction(vM, "iniCreateFile", (SQFUNCTION)sq_iniCreateFile, 2, ".s"); RegisterFunction(vM, "sqlite3_query", (SQFUNCTION)sq_sqlite3_query, 3, ".ss"); RegisterFunction(vM, "sqlite3_finalize", (SQFUNCTION)sq_sqlite3_finalize, 2, ".n"); RegisterFunction(vM, "sqlite3_column_name", (SQFUNCTION)sq_sqlite3_column_name, 3, ".nn"); RegisterFunction(vM, "sqlite3_column_text", (SQFUNCTION)sq_sqlite3_column_text, 3, ".nn"); RegisterFunction(vM, "sqlite3_step", (SQFUNCTION)sq_sqlite3_step, 2, ".n"); RegisterFunction(vM, "sqlite3_column_count", (SQFUNCTION)sq_sqlite3_column_count, 2, ".n"); RegisterFunction(vM, "include", (SQFUNCTION)sq_include, 2, ".s"); RegisterFunction(vM, "callClientFunc", (SQFUNCTION)sq_callClientFunc, 5, ".nss."); RegisterFunction(vM, "callFunc", (SQFUNCTION)sq_callFunc, 4, ".ss."); // part of human body RegisterVariable(vM, "PLAYER_RIGHHAND", 1); RegisterVariable(vM, "PLAYER_LEFTHAND", 2); RegisterVariable(vM, "PLAYER_RIGHTLEG", 3); RegisterVariable(vM, "PLAYER_LEFTLEG", 4); RegisterVariable(vM, "PLAYER_TORSO", 5); RegisterVariable(vM, "PLAYER_HEAD", 6); // keyboard const. RegisterVariable(vM, "VK_BACK", (int)0x08); RegisterVariable(vM, "VK_TAB", (int)0x09); RegisterVariable(vM, "VK_RETURN", (int)0x0D); RegisterVariable(vM, "VK_SPACE", (int)0x20); RegisterVariable(vM, "VK_LEFT", (int)0x25); RegisterVariable(vM, "VK_RIGHT", (int)0x27); RegisterVariable(vM, "VK_UP", (int)0x26); RegisterVariable(vM, "VK_DOWN", (int)0x28); RegisterVariable(vM, "VK_NUM0", (int)0x30); RegisterVariable(vM, "VK_NUM1", (int)0x31); RegisterVariable(vM, "VK_NUM2", (int)0x32); RegisterVariable(vM, "VK_NUM3", (int)0x33); RegisterVariable(vM, "VK_NUM4", (int)0x34); RegisterVariable(vM, "VK_NUM5", (int)0x35); RegisterVariable(vM, "VK_NUM6", (int)0x36); RegisterVariable(vM, "VK_NUM7", (int)0x37); RegisterVariable(vM, "VK_NUM8", (int)0x38); RegisterVariable(vM, "VK_NUM9", (int)0x39); RegisterVariable(vM, "VK_A", (int)0x41); RegisterVariable(vM, "VK_B", (int)0x42); RegisterVariable(vM, "VK_C", (int)0x43); RegisterVariable(vM, "VK_D", (int)0x44); RegisterVariable(vM, "VK_E", (int)0x45); RegisterVariable(vM, "VK_F", (int)0x46); RegisterVariable(vM, "VK_G", (int)0x47); RegisterVariable(vM, "VK_H", (int)0x48); RegisterVariable(vM, "VK_I", (int)0x49); RegisterVariable(vM, "VK_J", (int)0x4A); RegisterVariable(vM, "VK_K", (int)0x4B); RegisterVariable(vM, "VK_L", (int)0x4C); RegisterVariable(vM, "VK_M", (int)0x4D); RegisterVariable(vM, "VK_N", (int)0x4E); RegisterVariable(vM, "VK_O", (int)0x4F); RegisterVariable(vM, "VK_P", (int)0x50); RegisterVariable(vM, "VK_Q", (int)0x51); RegisterVariable(vM, "VK_R", (int)0x52); RegisterVariable(vM, "VK_S", (int)0x53); RegisterVariable(vM, "VK_T", (int)0x54); RegisterVariable(vM, "VK_U", (int)0x55); RegisterVariable(vM, "VK_V", (int)0x56); RegisterVariable(vM, "VK_W", (int)0x57); RegisterVariable(vM, "VK_X", (int)0x58); RegisterVariable(vM, "VK_Y", (int)0x59); RegisterVariable(vM, "VK_Z", (int)0x5A); RegisterVariable(vM, "SQLITE_ERROR", 1); RegisterVariable(vM, "SQLITE_INTERNAL", 2); RegisterVariable(vM, "SQLITE_PERM", 3); RegisterVariable(vM, "SQLITE_ABORT", 4); /* Callback routine requested an abort */ RegisterVariable(vM, "SQLITE_BUSY", 5); /* The database file is locked */ RegisterVariable(vM, "SQLITE_LOCKED", 6); /* A table in the database is locked */ RegisterVariable(vM, "SQLITE_NOMEM", 7); /* A malloc() failed */ RegisterVariable(vM, "SQLITE_READONLY", 8); /* Attempt to write a readonly database */ RegisterVariable(vM, "SQLITE_INTERRUPT", 9); /* Operation terminated by sqlite3_interrupt()*/ RegisterVariable(vM, "SQLITE_IOERR", 10); /* Some kind of disk I/O error occurred */ RegisterVariable(vM, "SQLITE_CORRUPT", 11); /* The database disk image is malformed */ RegisterVariable(vM, "SQLITE_NOTFOUND", 12); /* Unknown opcode in sqlite3_file_control() */ RegisterVariable(vM, "SQLITE_FULL", 13); /* Insertion failed because database is full */ RegisterVariable(vM, "SQLITE_CANTOPEN", 14); /* Unable to open the database file */ RegisterVariable(vM, "SQLITE_PROTOCOL", 15); /* Database lock protocol error */ RegisterVariable(vM, "SQLITE_EMPTY", 16); /* Database is empty */ RegisterVariable(vM, "SQLITE_SCHEMA", 17); /* The database schema changed */ RegisterVariable(vM, "SQLITE_TOOBIG", 18); /* String or BLOB exceeds size limit */ RegisterVariable(vM, "SQLITE_CONSTRAINT", 19); /* Abort due to constraint violation */ RegisterVariable(vM, "SQLITE_MISMATCH", 20); /* Data type mismatch */ RegisterVariable(vM, "SQLITE_MISUSE", 21); /* Library used incorrectly */ RegisterVariable(vM, "SQLITE_NOLFS", 22); /* Uses OS features not supported on host */ RegisterVariable(vM, "SQLITE_AUTH", 23); /* Authorization denied */ RegisterVariable(vM, "SQLITE_FORMAT", 24); /* Auxiliary database format error */ RegisterVariable(vM, "SQLITE_RANGE", 25); /* 2nd parameter to sqlite3_bind out of range */ RegisterVariable(vM, "SQLITE_NOTADB", 26); /* File opened that is not a database file */ RegisterVariable(vM, "SQLITE_NOTICE", 27); /* Notifications from sqlite3_log() */ RegisterVariable(vM, "SQLITE_WARNING", 28); /* Warnings from sqlite3_log() */ RegisterVariable(vM, "SQLITE_ROW", 100); /* sqlite3_step() has another row ready */ RegisterVariable(vM, "SQLITE_DONE", 101); /* sqlite3_step() has finished executing */ return 1; }
62.794118
109
0.741374
LHMPTeam
0b5f9783b85e3ec6525bc0aa7206c1ae717754ff
2,084
cpp
C++
ares/msx/cartridge/cartridge.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/msx/cartridge/cartridge.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
176
2020-07-25T19:11:23.000Z
2021-10-04T17:11:32.000Z
ares/msx/cartridge/cartridge.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
#include <msx/msx.hpp> namespace ares::MSX { Cartridge& cartridge = cartridgeSlot.cartridge; Cartridge& expansion = expansionSlot.cartridge; #include "board/board.cpp" #include "slot.cpp" #include "serialization.cpp" auto Cartridge::allocate(Node::Port parent) -> Node::Peripheral { return node = parent->append<Node::Peripheral>(string{system.name(), " Cartridge"}); } auto Cartridge::connect() -> void { if(!node->setPak(pak = platform->pak(node))) return; information = {}; information.title = pak->attribute("title"); information.region = pak->attribute("region"); information.board = pak->attribute("board"); if(information.board == "ASC16") board = new Board::ASC16{*this}; if(information.board == "ASC8") board = new Board::ASC8{*this}; if(information.board == "CrossBlaim") board = new Board::CrossBlaim{*this}; if(information.board == "Konami") board = new Board::Konami{*this}; if(information.board == "KonamiSCC") board = new Board::KonamiSCC{*this}; if(information.board == "Linear") board = new Board::Linear{*this}; if(information.board == "SuperLodeRunner") board = new Board::SuperLodeRunner{*this}; if(information.board == "SuperPierrot") board = new Board::SuperPierrot{*this}; if(!board) board = new Board::Konami{*this}; board->pak = pak; board->load(); power(); } auto Cartridge::disconnect() -> void { if(!node) return; if(board) board->unload(); board.reset(); pak.reset(); node.reset(); } auto Cartridge::save() -> void { if(!node) return; board->save(); } auto Cartridge::main() -> void { if(board) return board->main(); step(system.colorburst()); } auto Cartridge::step(u32 clocks) -> void { Thread::step(clocks); Thread::synchronize(cpu); } auto Cartridge::power() -> void { Thread::create(system.colorburst(), {&Cartridge::main, this}); if(board) board->power(); } auto Cartridge::read(n16 address) -> n8 { if(board) return board->read(address, 0xff); return 0xff; } auto Cartridge::write(n16 address, n8 data) -> void { if(board) return board->write(address, data); } }
27.421053
87
0.673225
CasualPokePlayer
0b6024f0a83689e35fe3eb8c55e34ec77a56d216
2,564
cpp
C++
Capu/test/src/container/CapuDefaultHashFunctionTest.cpp
bmwcarit/capu
b04f0c2b44ed875fea6cbbaf326b73a7210272a8
[ "Apache-2.0" ]
16
2015-01-13T12:47:49.000Z
2018-05-23T05:05:18.000Z
Capu/test/src/container/CapuDefaultHashFunctionTest.cpp
bmwcarit/capu
b04f0c2b44ed875fea6cbbaf326b73a7210272a8
[ "Apache-2.0" ]
18
2015-02-04T07:13:33.000Z
2017-01-05T08:01:27.000Z
Capu/test/src/container/CapuDefaultHashFunctionTest.cpp
bmwcarit/capu
b04f0c2b44ed875fea6cbbaf326b73a7210272a8
[ "Apache-2.0" ]
12
2015-01-15T09:52:25.000Z
2019-11-27T12:52:30.000Z
/* * Copyright (C) 2012 BMW Car IT GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include "capu/container/Hash.h" namespace capu { class SomeClass {}; enum SomeEnum { SOME_ENUM_MEMBER }; TEST(CapuDefaultHashFunctionTest, useTraitsToFindCorrectHashFunction) { uint64_t sometype1 = 42; uint32_t sometype2 = 42; int32_t sometype3 = 42; uint16_t sometype4 = 42; int16_t sometype5 = 42; uint8_t sometype6 = 42; int8_t sometype7 = 42; char sometype8 = 42; float sometype10 = 42.f; double sometype11 = 42.0; bool sometype12 = true; char sometype13[] = "HashTest"; const char* sometype14 = "HashTest2"; SomeClass clazz; SomeClass clazz2; SomeClass* ptr = &clazz; SomeClass* ptr2 = &clazz2; // everything must compile... capu::CapuDefaultHashFunction<>::Digest(sometype1); capu::CapuDefaultHashFunction<>::Digest(sometype2); capu::CapuDefaultHashFunction<>::Digest(sometype3); capu::CapuDefaultHashFunction<>::Digest(sometype4); capu::CapuDefaultHashFunction<>::Digest(sometype5); capu::CapuDefaultHashFunction<>::Digest(sometype6); capu::CapuDefaultHashFunction<>::Digest(sometype7); capu::CapuDefaultHashFunction<>::Digest(sometype8); capu::CapuDefaultHashFunction<>::Digest(sometype10); capu::CapuDefaultHashFunction<>::Digest(sometype11); capu::CapuDefaultHashFunction<>::Digest(sometype12); capu::CapuDefaultHashFunction<>::Digest(sometype13); capu::CapuDefaultHashFunction<>::Digest(sometype14); capu::CapuDefaultHashFunction<>::Digest(clazz); capu::CapuDefaultHashFunction<>::Digest(ptr, 4); capu::CapuDefaultHashFunction<>::Digest(ptr2, 4); capu::CapuDefaultHashFunction<>::Digest(SOME_ENUM_MEMBER); } }
35.123288
75
0.644306
bmwcarit
0b643f365fd20266794b8fb47d56be53142bb3cf
2,108
cpp
C++
OcularCore/src/Events/AEvent.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
8
2017-01-27T01:06:06.000Z
2020-11-05T20:23:19.000Z
OcularCore/src/Events/AEvent.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
39
2016-06-03T02:00:36.000Z
2017-03-19T17:47:39.000Z
OcularCore/src/Events/AEvent.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
4
2019-05-22T09:13:36.000Z
2020-12-01T03:17:45.000Z
/** * Copyright 2014-2015 Steven T Sell (ssell@vertexfragment.com) * * 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 "Events/AEvent.hpp" #include "OcularEngine.hpp" //------------------------------------------------------------------------------------------ namespace Ocular { namespace Core { //---------------------------------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------------------------------- AEvent::AEvent(std::string name, Priority priority) : Object(name, "Core::AEvent"), m_Priority(priority) { } AEvent::~AEvent() { } //---------------------------------------------------------------------------------- // PUBLIC METHODS //---------------------------------------------------------------------------------- Priority AEvent::getPriority() const { return m_Priority; } //bool AEvent::isType(std::string const& name) const //{ // return (m_Name.compare(name) == 0); //} //---------------------------------------------------------------------------------- // PROTECTED METHODS //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- // PRIVATE METHODS //---------------------------------------------------------------------------------- } }
33.460317
92
0.376186
ssell
0b651b714eb4c774c12ba2129a3a782f51dd66cc
670
hpp
C++
Siv3D/src/Siv3D/Cursor/CursorState.hpp
yumetodo/OpenSiv3D
ea191438ecbc64185f5df3d9f79dffc6757e4192
[ "MIT" ]
7
2020-04-26T11:06:02.000Z
2021-09-05T16:42:31.000Z
Siv3D/src/Siv3D/Cursor/CursorState.hpp
yumetodo/OpenSiv3D
ea191438ecbc64185f5df3d9f79dffc6757e4192
[ "MIT" ]
10
2020-04-26T13:25:36.000Z
2022-03-01T12:34:44.000Z
Siv3D/src/Siv3D/Cursor/CursorState.hpp
yumetodo/OpenSiv3D
ea191438ecbc64185f5df3d9f79dffc6757e4192
[ "MIT" ]
2
2020-05-11T08:23:23.000Z
2020-08-08T12:33:30.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <Siv3D/Fwd.hpp> namespace s3d { template <class VectorType> struct CursorState { using value_type = typename VectorType::value_type; VectorType previous = { 0,0 }; VectorType current = { 0,0 }; VectorType delta = { 0,0 }; void update(value_type x, value_type y) { previous = current; current.set(x, y); delta = (current - previous); } }; }
18.611111
53
0.559701
yumetodo
0b657a515b38bfd09b7ad8088e605a51df6e69b3
7,857
cpp
C++
client/src/bindings/WebView.cpp
Marvisak/altv-js-module
8b7c0b600a4444596805a8872788f051a50609d2
[ "MIT" ]
null
null
null
client/src/bindings/WebView.cpp
Marvisak/altv-js-module
8b7c0b600a4444596805a8872788f051a50609d2
[ "MIT" ]
null
null
null
client/src/bindings/WebView.cpp
Marvisak/altv-js-module
8b7c0b600a4444596805a8872788f051a50609d2
[ "MIT" ]
null
null
null
#include "V8Helpers.h" #include "helpers/BindHelpers.h" #include "V8Class.h" #include "V8Entity.h" #include "V8ResourceImpl.h" #include "../CV8Resource.h" #include "cpp-sdk/script-objects/IWebView.h" using namespace alt; static void ToString(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT(); auto webview = info.This(); V8_OBJECT_GET_STRING(webview, "url", url); std::ostringstream ss; ss << "WebView{ url: " << url.CStr() << " }"; V8_RETURN_STRING(ss.str().c_str()); } static void On(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT_RESOURCE(); V8_CHECK_ARGS_LEN(2); V8_ARG_TO_STRING(1, evName); V8_ARG_TO_FUNCTION(2, fun); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); static_cast<CV8ResourceImpl*>(resource)->SubscribeWebView(view, evName.ToString(), fun, V8Helpers::SourceLocation::GetCurrent(isolate)); } static void Once(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT_RESOURCE(); V8_CHECK_ARGS_LEN(2); V8_ARG_TO_STRING(1, evName); V8_ARG_TO_FUNCTION(2, fun); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); static_cast<CV8ResourceImpl*>(resource)->SubscribeWebView(view, evName.ToString(), fun, V8Helpers::SourceLocation::GetCurrent(isolate), true); } static void Off(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT_RESOURCE(); V8_CHECK_ARGS_LEN(2); V8_ARG_TO_STRING(1, evName); V8_ARG_TO_FUNCTION(2, fun); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); static_cast<CV8ResourceImpl*>(resource)->UnsubscribeWebView(view, evName.ToString(), fun); } static void Emit(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT_RESOURCE(); V8_CHECK_ARGS_LEN_MIN(1); V8_ARG_TO_STRING(1, evName); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); alt::MValueArgs mvArgs; for(int i = 1; i < info.Length(); ++i) mvArgs.Push(V8Helpers::V8ToMValue(info[i], false)); if(!view->IsLoaded()) static_cast<CV8ResourceImpl*>(resource)->AddWebViewEventToQueue(view, evName, mvArgs); else view->Trigger(evName, mvArgs); } static void GetEventListeners(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT_RESOURCE(); V8_CHECK_ARGS_LEN(1); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); V8_ARG_TO_STRING(1, eventName); std::vector<V8Helpers::EventCallback*> handlers = static_cast<CV8ResourceImpl*>(resource)->GetWebViewHandlers(view, eventName.ToString()); auto array = v8::Array::New(isolate, handlers.size()); for(int i = 0; i < handlers.size(); i++) { array->Set(ctx, i, handlers[i]->fn.Get(isolate)); } V8_RETURN(array); } static void FocusedGetter(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE(); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); V8_RETURN_BOOLEAN(view->IsFocused()); } static void FocusedSetter(v8::Local<v8::String>, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& info) { V8_GET_ISOLATE_CONTEXT(); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); V8_TO_BOOLEAN(value, shouldBeFocused); if(shouldBeFocused) view->Focus(); else view->Unfocus(); } static void Constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT_RESOURCE(); V8_CHECK_CONSTRUCTOR(); V8_CHECK_ARGS_LEN_MIN_MAX(1, 4); V8_ARG_TO_STRING(1, url); alt::IResource* altres = V8ResourceImpl::GetResource(isolate->GetEnteredOrMicrotaskContext()); V8_CHECK(altres, "invalid resource"); alt::Ref<IWebView> view = nullptr; if(info.Length() == 4) { V8_ARG_TO_BOOLEAN(2, isOverlayBool); V8_ARG_TO_OBJECT(3, pos); V8_ARG_TO_OBJECT(4, size); V8_OBJECT_GET_INT(pos, "x", posX); V8_OBJECT_GET_INT(pos, "y", posY); V8_OBJECT_GET_INT(size, "x", sizeX); V8_OBJECT_GET_INT(size, "y", sizeY); view = alt::ICore::Instance().CreateWebView(altres, url, { posX, posY }, { sizeX, sizeY }, true, isOverlayBool); } else if(info.Length() == 3 && info[2]->IsObject()) { V8_ARG_TO_OBJECT(2, pos); V8_ARG_TO_OBJECT(3, size); V8_OBJECT_GET_INT(pos, "x", posX); V8_OBJECT_GET_INT(pos, "y", posY); V8_OBJECT_GET_INT(size, "x", sizeX); V8_OBJECT_GET_INT(size, "y", sizeY); view = alt::ICore::Instance().CreateWebView(altres, url, { posX, posY }, { sizeX, sizeY }, true, false); } else if(info.Length() == 3) { V8_ARG_TO_INT(2, drawableHash); V8_ARG_TO_STRING(3, targetTextureStr); auto texture = alt::ICore::Instance().GetTextureFromDrawable(drawableHash, targetTextureStr); V8_CHECK(texture != nullptr, "Texture not found"); view = alt::ICore::Instance().CreateWebView(altres, url, (uint32_t)drawableHash, targetTextureStr); V8_CHECK(!view.IsEmpty(), "Interactive WebView cannot be created"); } else if(info.Length() == 2 && info[1]->IsObject()) { V8_ARG_TO_OBJECT(2, pos); V8_OBJECT_GET_INT(pos, "x", posX); V8_OBJECT_GET_INT(pos, "y", posY); view = alt::ICore::Instance().CreateWebView(altres, url, { posX, posY }, { 0, 0 }, true, false); } else if(info.Length() == 2) { V8_ARG_TO_BOOLEAN(2, isOverlayBool); view = alt::ICore::Instance().CreateWebView(altres, url, { 0, 0 }, { 0, 0 }, true, isOverlayBool); } else { view = alt::ICore::Instance().CreateWebView(altres, url, { 0, 0 }, { 0, 0 }, true, false); } V8_BIND_BASE_OBJECT(view, "Failed to create WebView"); } static void SetExtraHeader(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT(); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); V8_CHECK_ARGS_LEN(2); V8_ARG_TO_STRING(1, name); V8_ARG_TO_STRING(2, value); view->SetExtraHeader(name, value); } static void SetZoomLevel(const v8::FunctionCallbackInfo<v8::Value>& info) { V8_GET_ISOLATE_CONTEXT(); V8_GET_THIS_BASE_OBJECT(view, alt::IWebView); V8_CHECK_ARGS_LEN(1); V8_ARG_TO_NUMBER(1, zoomLevel); view->SetZoomLevel(zoomLevel); } extern V8Class v8BaseObject; extern V8Class v8WebView("WebView", v8BaseObject, &Constructor, [](v8::Local<v8::FunctionTemplate> tpl) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); V8Helpers::SetMethod(isolate, tpl, "toString", ToString); V8Helpers::SetAccessor<IWebView, bool, &IWebView::IsVisible, &IWebView::SetVisible>(isolate, tpl, "isVisible"); V8Helpers::SetAccessor<IWebView, StringView, &IWebView::GetUrl, &IWebView::SetUrl>(isolate, tpl, "url"); V8Helpers::SetAccessor<IWebView, bool, &IWebView::IsOverlay>(isolate, tpl, "isOverlay"); V8Helpers::SetAccessor<IWebView, bool, &IWebView::IsReady>(isolate, tpl, "isReady"); V8Helpers::SetAccessor(isolate, tpl, "focused", &FocusedGetter, &FocusedSetter); V8Helpers::SetAccessor<IWebView, Vector2i, &IWebView::GetSize, &IWebView::SetSize>(isolate, tpl, "size"); V8Helpers::SetAccessor<IWebView, Vector2i, &IWebView::GetPosition, &IWebView::SetPosition>(isolate, tpl, "pos"); V8Helpers::SetMethod(isolate, tpl, "on", &On); V8Helpers::SetMethod(isolate, tpl, "once", &Once); V8Helpers::SetMethod(isolate, tpl, "off", &Off); V8Helpers::SetMethod(isolate, tpl, "getEventListeners", GetEventListeners); V8Helpers::SetMethod(isolate, tpl, "emit", &Emit); V8Helpers::SetMethod<IWebView, &IWebView::Focus>(isolate, tpl, "focus"); V8Helpers::SetMethod<IWebView, &IWebView::Unfocus>(isolate, tpl, "unfocus"); V8Helpers::SetMethod(isolate, tpl, "setExtraHeader", &SetExtraHeader); V8Helpers::SetMethod(isolate, tpl, "setZoomLevel", &SetZoomLevel); });
31.809717
146
0.683467
Marvisak
0b669c48dca306a837059354351359aa480ded22
35,896
cpp
C++
src/devices/cpu/tx0/tx0.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/cpu/tx0/tx0.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/cpu/tx0/tx0.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Raphael Nabet /* TX-0 emulator Two variants: * initial model 64kWord RAM * later model 8kWord RAM Raphael Nabet 2004 */ #include "emu.h" #include "tx0.h" #include "tx0dasm.h" #include "debugger.h" #define LOG_RIM (1 << 1U) //#define VERBOSE (LOG_RIM) #include "logmacro.h" #define READ_TX0_18BIT(A) ((signed)m_program->read_dword(A)) #define WRITE_TX0_18BIT(A,V) (m_program->write_dword((A),(V))) #define io_handler_rim 3 #define PC m_pc #define IR m_ir #define MBR m_mbr #define MAR m_mar #define AC m_ac #define LR m_lr #define XR m_xr #define PF m_pf #define ADDRESS_MASK_64KW 0177777 #define ADDRESS_MASK_8KW 0017777 #define INCREMENT_PC_64KW (PC = (PC+1) & ADDRESS_MASK_64KW) #define INCREMENT_PC_8KW (PC = (PC+1) & ADDRESS_MASK_8KW) DEFINE_DEVICE_TYPE(TX0_8KW, tx0_8kw_device, "tx0_8kw_cpu", "MIT Lincoln Laboratory TX-0 8KW (new)") DEFINE_DEVICE_TYPE(TX0_8KW_OLD, tx0_8kwo_device, "tx0_8kwo_cpu", "MIT Lincoln Laboratory TX-0 8KW (old)") DEFINE_DEVICE_TYPE(TX0_64KW, tx0_64kw_device, "tx0_64kw_cpu", "MIT Lincoln Laboratory TX-0 64KW") tx0_device::tx0_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock, int addr_bits, int address_mask, int ir_mask) : cpu_device(mconfig, type, tag, owner, clock) , m_program_config("program", ENDIANNESS_BIG, 32, addr_bits , -2), m_mbr(0), m_ac(0), m_mar(0), m_pc(0), m_ir(0), m_lr(0), m_xr(0), m_pf(0), m_tbr(0), m_tac(0), m_cm_sel(0) , m_lr_sel(0), m_gbl_cm_sel(0), m_stop_cyc0(0), m_stop_cyc1(0), m_run(0), m_rim(0), m_cycle(0), m_ioh(0), m_ios(0), m_rim_step(0) , m_address_mask(address_mask) , m_ir_mask(ir_mask), m_icount(0), m_program(nullptr) , m_cpy_handler(*this) , m_r1l_handler(*this) , m_dis_handler(*this) , m_r3l_handler(*this) , m_prt_handler(*this) , m_rsv_handler(*this) , m_p6h_handler(*this) , m_p7h_handler(*this) , m_sel_handler(*this) , m_io_reset_callback(*this) { m_program_config.m_is_octal = true; } tx0_8kw_device::tx0_8kw_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock) : tx0_device(mconfig, type, tag, owner, clock, 13, ADDRESS_MASK_8KW, 037) { } tx0_8kw_device::tx0_8kw_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : tx0_8kw_device(mconfig, TX0_8KW, tag, owner, clock) { } tx0_8kwo_device::tx0_8kwo_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : tx0_8kw_device(mconfig, TX0_8KW_OLD, tag, owner, clock) { } tx0_64kw_device::tx0_64kw_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : tx0_device(mconfig, TX0_64KW, tag, owner, clock, 16, ADDRESS_MASK_64KW, 03) { } device_memory_interface::space_config_vector tx0_device::memory_space_config() const { return space_config_vector { std::make_pair(AS_PROGRAM, &m_program_config) }; } int tx0_device::tx0_read(offs_t address) { if ((address >= 16) || (m_gbl_cm_sel) || ((m_cm_sel >> address) & 1)) /* core memory (CM) */ return READ_TX0_18BIT(address); else if ((m_lr_sel >> address) & 1) /* live register (LR) */ return LR; /* toggle switch storage (TSS) */ return m_tss[address]; } void tx0_device::tx0_write(offs_t address, int data) { if ((address >= 16) || (m_gbl_cm_sel) || ((m_cm_sel >> address) & 1)) /* core memory (CM) */ WRITE_TX0_18BIT(address, data); else if ((m_lr_sel >> address) & 1) /* live register (LR) */ LR = data; else /* toggle switch storage (TSS) */ /* TSS is read-only */ { /* nothing */ } } void tx0_device::device_start() { m_mbr = 0; m_ac = 0; m_mar = 0; m_lr = 0; m_xr = 0; m_pf = 0; m_tbr = 0; m_tac = 0; for (auto & elem : m_tss) { elem = 0; } m_cm_sel = 0; m_lr_sel = 0; m_gbl_cm_sel = 0; m_stop_cyc0 = 0; m_stop_cyc1 = 0; m_cycle = 0; m_pc = 0; m_ir = 0; m_run = 0; m_rim = 0; m_ioh = 0; m_ios = 0; // Resolve callbacks m_cpy_handler.resolve(); m_r1l_handler.resolve(); m_dis_handler.resolve(); m_r3l_handler.resolve(); m_prt_handler.resolve(); m_rsv_handler.resolve(); m_p6h_handler.resolve(); m_p7h_handler.resolve(); m_sel_handler.resolve(); m_io_reset_callback.resolve(); m_program = &space(AS_PROGRAM); save_item(NAME(m_mbr)); save_item(NAME(m_ac)); save_item(NAME(m_mar)); save_item(NAME(m_pc)); save_item(NAME(m_ir)); save_item(NAME(m_lr)); save_item(NAME(m_xr)); save_item(NAME(m_pf)); save_item(NAME(m_tbr)); save_item(NAME(m_tac)); save_item(NAME(m_tss)); save_item(NAME(m_cm_sel)); save_item(NAME(m_lr_sel)); save_item(NAME(m_gbl_cm_sel)); save_item(NAME(m_stop_cyc0)); save_item(NAME(m_stop_cyc1)); save_item(NAME(m_run)); save_item(NAME(m_rim)); save_item(NAME(m_cycle)); save_item(NAME(m_ioh)); save_item(NAME(m_ios)); save_item(NAME(m_rim_step)); // Register state for debugger state_add( TX0_PC, "PC", m_pc ).mask(m_address_mask).formatstr("0%06O"); state_add( TX0_IR, "IR", m_ir ).mask(m_ir_mask) .formatstr("0%02O"); state_add( TX0_MBR, "MBR", m_mbr ).mask(0777777) .formatstr("0%06O"); state_add( TX0_MAR, "MAR", m_mar ).mask(m_address_mask).formatstr("0%06O"); state_add( TX0_AC, "AC", m_ac ).mask(0777777) .formatstr("0%06O"); state_add( TX0_LR, "LR", m_lr ).mask(0777777) .formatstr("0%06O"); state_add( TX0_XR, "XR", m_xr ).mask(0037777) .formatstr("0%05O"); state_add( TX0_PF, "PF", m_pf ).mask(077) .formatstr("0%02O"); state_add( TX0_TBR, "TBR", m_tbr ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TAC, "TAC", m_tac ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS00, "TSS00", m_tss[000] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS01, "TSS01", m_tss[001] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS02, "TSS02", m_tss[002] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS03, "TSS03", m_tss[003] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS04, "TSS04", m_tss[004] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS05, "TSS05", m_tss[005] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS06, "TSS06", m_tss[006] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS07, "TSS07", m_tss[007] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS10, "TSS10", m_tss[010] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS11, "TSS11", m_tss[011] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS12, "TSS12", m_tss[012] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS13, "TSS13", m_tss[013] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS14, "TSS14", m_tss[014] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS15, "TSS15", m_tss[015] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS16, "TSS16", m_tss[016] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_TSS17, "TSS17", m_tss[017] ).mask(0777777) .formatstr("0%06O"); state_add( TX0_CM_SEL, "CMSEL", m_cm_sel ).mask(0177777) .formatstr("0%06O"); state_add( TX0_LR_SEL, "LRSEL", m_lr_sel ).mask(0177777) .formatstr("0%06O"); state_add( TX0_GBL_CM_SEL, "GBLCMSEL", m_gbl_cm_sel ).mask(1) .formatstr("%1X"); state_add( TX0_STOP_CYC0, "STOPCYC0", m_stop_cyc0 ).mask(1) .formatstr("%1X"); state_add( TX0_STOP_CYC1, "STOPCYC1", m_stop_cyc1 ).mask(1) .formatstr("%1X"); state_add( TX0_RUN, "RUN", m_run ).mask(1) .formatstr("%1X"); state_add( TX0_RIM, "RIM", m_rim ).mask(1) .formatstr("%1X"); state_add( TX0_CYCLE, "CYCLE", m_cycle ) .formatstr("%1X"); state_add( TX0_IOH, "IOH", m_ioh ) .formatstr("%1X"); state_add( TX0_IOS, "IOS", m_ios ).mask(1) .formatstr("%1X"); state_add(STATE_GENPC, "GENPC", m_pc).formatstr("0%06O").noshow(); state_add(STATE_GENPCBASE, "CURPC", m_pc).formatstr("0%06O").noshow(); state_add(STATE_GENFLAGS, "GENFLAGS", m_ir).noshow(); set_icountptr(m_icount); } void tx0_device::device_reset() { /* reset CPU flip-flops */ pulse_reset(); m_gbl_cm_sel = 1; /* HACK */ } void tx0_device::call_io_handler(int io_handler) { /* data will be transferred to AC */ switch (io_handler) { case 0: m_cpy_handler(ASSERT_LINE); break; case 1: m_r1l_handler(ASSERT_LINE); break; case 2: m_dis_handler(ASSERT_LINE); break; case 3: m_r3l_handler(ASSERT_LINE); break; case 4: m_prt_handler(ASSERT_LINE); break; case 5: m_rsv_handler(ASSERT_LINE); break; case 6: m_p6h_handler(ASSERT_LINE); break; case 7: m_p7h_handler(ASSERT_LINE); break; } } /* execute instructions on this CPU until icount expires */ void tx0_64kw_device::execute_run() { do { if (m_ioh && m_ios) { m_ioh = 0; } if ((! m_run) && (! m_rim)) { debugger_instruction_hook(PC); m_icount = 0; /* if processor is stopped, just burn cycles */ } else if (m_rim) { switch (m_rim_step) { case 0: /* read first word as instruction */ AC = 0; call_io_handler(io_handler_rim); m_rim_step = 1; m_ios = 0; break; case 1: if (! m_ios) { /* transfer incomplete: wait some more */ m_icount = 0; } else { /* data transfer complete */ m_ios = 0; MBR = AC; IR = MBR >> 16; /* basic opcode */ if ((IR == 2) || (IR == 1)) /* trn or add instruction? */ { PC = MBR & ADDRESS_MASK_64KW; m_rim = 0; /* exit read-in mode */ m_run = (IR == 2) ? 1 : 0; /* stop if add instruction */ m_rim_step = 0; LOGMASKED(LOG_RIM, "RIM %s: PC <- %06o\n", (IR == 2) ? "start" : "stop", PC); } else if ((IR == 0) || (IR == 3)) /* sto or opr instruction? */ { MAR = MBR & ADDRESS_MASK_64KW; m_rim_step = 2; } } break; case 2: /* read second word as data */ AC = 0; call_io_handler(io_handler_rim); m_rim_step = 3; m_ios = 0; break; case 3: if (! m_ios) { /* transfer incomplete: wait some more */ m_icount = 0; } else { /* data transfer complete */ m_ios = 0; LOGMASKED(LOG_RIM, "RIM transfer: %06o <- %06o\n", MAR, AC); tx0_write(MAR, MBR = AC); m_rim_step = 0; } break; } } else { if (m_cycle == 0) { /* fetch new instruction */ debugger_instruction_hook(PC); MBR = tx0_read(MAR = PC); INCREMENT_PC_64KW; IR = MBR >> 16; /* basic opcode */ MAR = MBR & ADDRESS_MASK_64KW; } if (! m_ioh) { if ((m_stop_cyc0 && (m_cycle == 0)) || (m_stop_cyc1 && (m_cycle == 1))) m_run = 0; execute_instruction_64kw(); } m_icount --; } } while (m_icount > 0); } /* execute instructions on this CPU until icount expires */ void tx0_8kw_device::execute_run() { do { if (m_ioh && m_ios) { m_ioh = 0; } if ((! m_run) && (! m_rim)) { debugger_instruction_hook(PC); m_icount = 0; /* if processor is stopped, just burn cycles */ } else if (m_rim) { switch (m_rim_step) { case 0: /* read first word as instruction */ AC = 0; call_io_handler(io_handler_rim); m_rim_step = 1; m_ios = 0; break; case 1: if (! m_ios) { /* transfer incomplete: wait some more */ m_icount = 0; } else { /* data transfer complete */ m_ios = 0; MBR = AC; IR = MBR >> 13; /* basic opcode */ if ((IR == 16) || (IR == 8)) /* trn or add instruction? */ { PC = MBR & ADDRESS_MASK_8KW; m_rim = 0; /* exit read-in mode */ m_run = (IR == 16) ? 1 : 0; /* stop if add instruction */ m_rim_step = 0; LOGMASKED(LOG_RIM, "RIM %s: PC <- %05o\n", (IR == 16) ? "start" : "stop", PC); } else if ((IR == 0) || (IR == 24)) /* sto or opr instruction? */ { MAR = MBR & ADDRESS_MASK_8KW; m_rim_step = 2; } } break; case 2: /* read second word as data */ AC = 0; call_io_handler(io_handler_rim); m_rim_step = 3; m_ios = 0; break; case 3: if (! m_ios) { /* transfer incomplete: wait some more */ m_icount = 0; } else { /* data transfer complete */ m_ios = 0; LOGMASKED(LOG_RIM, "RIM transfer: %05o <- %06o\n", MAR, AC); tx0_write(MAR, MBR = AC); m_rim_step = 0; } break; } } else { if (m_cycle == 0) { /* fetch new instruction */ debugger_instruction_hook(PC); MBR = tx0_read(MAR = PC); INCREMENT_PC_8KW; IR = MBR >> 13; /* basic opcode */ MAR = MBR & ADDRESS_MASK_8KW; } if (! m_ioh) { if ((m_stop_cyc0 && (m_cycle == 0)) || (m_stop_cyc1 && (m_cycle == 1))) m_run = 0; execute_instruction_8kw(); } m_icount -= 1; } } while (m_icount > 0); } /* execute one instruction */ void tx0_64kw_device::execute_instruction_64kw() { if (! m_cycle) { m_cycle = 1; /* most frequent case */ switch (IR) { case 0: /* STOre */ case 1: /* ADD */ break; case 2: /* TRansfer on Negative */ if (AC & 0400000) { PC = MAR & ADDRESS_MASK_64KW; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ } break; case 3: /* OPeRate */ if (MAR & 0100000) /* (0.8) CLL = Clear the left nine digital positions of the AC */ AC &= 0000777; if (MAR & 0040000) /* (0.8) CLR = Clear the right nine digital positions of the AC */ AC &= 0777000; if (((MAR & 0030000) >> 12) == 2) /* (0.8) IOS In-Out Stop = Stop machine so that an In-Out command (specified by digits 6 7 8 of MAR) may be executed */ m_ios = 0; if (((MAR & 0007000) >> 9) != 0) { /* ((MAR & 0007000) >> 9) is device ID */ /* 7: */ /* (0.8) P7H = Punch holes 1-6 in flexo tape specified by AC digital positions 2, 5, 8, 11, 14, and 17. Also punches a 7th hole on tape. */ /* 6: */ /* (0.8) P6H = Same as P7H but no seventh hole */ /* 4: */ /* (0.8) PNT = Print one flexowriter character specified by AC digits 2, 5, 8, 11, 14, and 17. */ /* 1: */ /* (0.8) R1C = Read one line of flexo tape so that tape positions 1, 2, 3, 4, 5, and 6 will be put in the AC digital positions 0, 3, 6, 9, 12 and 15. */ /* 3: */ /* (0.8) R3C = Read one line of flexo tape into AC digits 0, 3, 6, 9, 12 and 15. Then cycle the AC one digital position; read the next line on tape into AC digits 0, 3, 6, 9, 12 and 15, cycle the AC right one digital position and read the third and last line into AC digits 0, 3, 6, 9, 12 and 15. (This command is equal to a triple CYR-R1C.) */ /* 2: */ /* (0.8) DIS = Intensify a point on the scope with x and y coordinates where x is specified by AC digits 0-8 with digit 0 being used as the sign and y is specified by AC digits 9-17 with digit 9 being used as the sign for y. The complement system is in effect when the signs are negative. */ /* (5 is undefined) */ int index = (MAR & 0007000) >> 9; call_io_handler(index); m_ioh = 1; } break; } } else { m_cycle = 0; /* always true */ switch (IR) { case 0: /* STOre */ tx0_write(MAR, (MBR = AC)); break; case 1: /* ADD */ MBR = tx0_read(MAR); AC = AC + MBR; AC = (AC + (AC >> 18)) & 0777777; /* propagate carry around */ break; case 2: /* TRansfer on Negative */ break; case 3: /* OPeRate */ MBR = 0; if ((MAR & 0000104) == 0000100) /* (1.1) PEN = Read the light pen flip-flops 1 and 2 into AC(0) and AC(1). */ /*...*/{ } if ((MAR & 0000104) == 0000004) /* (1.1) TAC = Insert a one in each digital position of the AC wherever there is a one in the corresponding digital position of the TAC. */ AC |= m_tac; if ((MAR & 0000003) == 1) /* (1.2) AMB = Store the contents of the AC in the MBR. */ MBR = AC; if (MAR & 0000040) /* (1.2) COM = Complement every digit in the accumulator */ AC ^= 0777777; if ((MAR & 0000003) == 3) /* (1.2) TBR = Store the contents of the TBR in the MBR. */ MBR |= m_tbr; if ((MAR & 0000003) == 2 && ((MAR & 0000600) >> 7) == 1) /* LMB and MBL used simultaneously interchange LR and MBR */ std::swap(LR, MBR); else if ((MAR & 0000003) == 2) /* (1.3) LMB = Store the contents of the LR in the MBR. */ MBR = LR; else if (((MAR & 0000600) >> 7) == 1) /* (1.3) MLR = Store the contents of the MBR (memory buffer register) in the live reg. */ LR = MBR; if (((MAR & 0000600) >> 7) == 2) /* (1.4) SHR = Shift the AC right one place, i.e. multiply the AC by 2^-1 */ AC >>= 1; if (((MAR & 0000600) >> 7) == 3) /* (1.4) CYR = Cycle the AC right one digital position (AC(17) will become AC(0)) */ AC = (AC >> 1) | ((AC & 1) << 17); if (MAR & 0000020) /* (1.4) PAD = Partial add AC to MBR, that is, for every digital position of the MBR that contains a one, complement the digit in the corresponding digital position of the AC. This is also called a half add. */ AC ^= MBR; if (MAR & 0000010) { /* (1.7) CRY = Partial add the 18 digits of the AC to the corresponding 18 digits of the carry. To determine what the 18 digits of the carry are, use the following rule: "Grouping the AC and MBR digits into pairs and proceeding from right to left, assign the carry digit of the next pair to a one if in the present pair MBR = 1 and AC = 0 or if in the present pair AC = 1 and carry 1. (Note: the 0th digit pair determines the 17th pair's carry digit)" */ AC ^= MBR; AC = AC + MBR; AC = (AC + (AC >> 18)) & 0777777; /* propagate carry around */ } if (((MAR & 0030000) >> 12) == 3) /* (1.8) Hlt = Halt the computer */ m_run = 0; break; } } } /* execute one instruction */ void tx0_8kwo_device::execute_instruction_8kw() { if (! m_cycle) { m_cycle = 1; /* most frequent case */ switch (IR) { case 0: /* STOre */ case 4: /* Store LR */ case 8: /* ADD */ case 12: /* Load LR */ break; case 16: /* TRansfer on Negative */ if (AC & 0400000) { PC = MAR & 0017777; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ } break; case 20: /* TRAnsfer */ PC = MAR & 0017777; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ break; case 24: /* OPeRate */ case 25: case 26: case 27: case 28: case 29: case 30: case 31: if (IR & 004) /* (0.8) CLL = Clear the left nine digital positions of the AC */ AC &= 0000777; if (IR & 002) /* (0.8) CLR = Clear the right nine digital positions of the AC */ AC &= 0777000; if (((IR & 001) == 01) && ((MAR & 010000) == 000000)) { /* (0.8) IOS In-Out Stop = Stop machine so that an In-Out command (specified by digits 6 7 8 of MAR) may be executed */ /* ((MAR & 0007000) >> 9) is device ID */ /* 7: */ /* (0.8) P7H = Punch holes 1-6 in flexo tape specified by AC digital positions 2, 5, 8, 11, 14, and 17. Also punches a 7th hole on tape. */ /* 6: */ /* (0.8) P6H = Same as P7H but no seventh hole */ /* 4: */ /* (0.8) PNT = Print one flexowriter character specified by AC digits 2, 5, 8, 11, 14, and 17. */ /* 1: */ /* (0.8) R1C = Read one line of flexo tape so that tape positions 1, 2, 3, 4, 5, and 6 will be put in the AC digital positions 0, 3, 6, 9, 12 and 15. */ /* 3: */ /* (0.8) R3C = Read one line of flexo tape into AC digits 0, 3, 6, 9, 12 and 15. Then cycle the AC one digital position; read the next line on tape into AC digits 0, 3, 6, 9, 12 and 15, cycle the AC right one digital position and read the third and last line into AC digits 0, 3, 6, 9, 12 and 15. (This command is equal to a triple CYR-R1C.) */ /* 2: */ /* (0.8) DIS = Intensify a point on the scope with x and y coordinates where x is specified by AC digits 0-8 with digit 0 being used as the sign and y is specified by AC digits 9-17 with digit 9 being used as the sign for y. The complement system is in effect when the signs are negative. */ /* (5 is undefined) */ int index = (MAR & 0007000) >> 9; m_ios = 0; call_io_handler(index); m_ioh = 1; } if (((IR & 001) == 00) && ((MAR & 010000) == 010000)) { /* (IOS) EX0 through EX7 = operate user's EXternal equipment. */ switch ((MAR & 0007000) >> 9) { /* ... */ } } break; } } else { m_cycle = 0; /* always true */ switch (IR) { case 0: /* STOre */ tx0_write(MAR, (MBR = AC)); break; case 4: /* Store LR */ tx0_write(MAR, (MBR = LR)); break; case 8: /* ADD */ MBR = tx0_read(MAR); AC = AC + MBR; AC = (AC + (AC >> 18)) & 0777777; /* propagate carry around */ break; case 12: /* Load LR */ LR = MBR = tx0_read(MAR); break; case 16: /* TRansfer on Negative */ case 20: /* TRAnsfer */ break; case 24: /* OPeRate */ case 25: case 26: case 27: case 28: case 29: case 30: case 31: MBR = 0; if ((MAR & 0000104) == 0000100) /* (1.1) PEN = Read the light pen flip-flops 1 and 2 into AC(0) and AC(1). */ /*...*/{ } if ((MAR & 0000104) == 0000004) /* (1.1) TAC = Insert a one in each digital position of the AC wherever there is a one in the corresponding digital position of the TAC. */ AC |= m_tac; if ((MAR & 0000003) == 1) /* (1.2) AMB = Store the contents of the AC in the MBR. */ MBR = AC; if (MAR & 0000040) /* (1.2) COM = Complement every digit in the accumulator */ AC ^= 0777777; if ((MAR & 0000003) == 3) /* (1.2) TBR = Store the contents of the TBR in the MBR. */ MBR |= m_tbr; uint32_t tmp = MBR; if ((MAR & 0000003) == 2) /* (1.3) LMB = Store the contents of the LR in the MBR. */ MBR = LR; if (((MAR & 0000600) >> 7) == 1) /* (1.3) MLR = Store the contents of the MBR (memory buffer register) in the live reg. */ LR = tmp; if ((MAR & 0000704) == 0000104) /* (1.3) ORL = Inclusive or MBR into LR. */ LR |= tmp; if ((MAR & 0000704) == 0000304) /* (1.3) ANL = And MBR into LR. */ LR &= tmp; if (((MAR & 0000600) >> 7) == 2) /* (1.4) SHR = Shift the AC right one place, i.e. multiply the AC by 2^-1 */ AC >>= 1; if (((MAR & 0000600) >> 7) == 3) /* (1.4) CYR = Cycle the AC right one digital position (AC(17) will become AC(0)) */ AC = (AC >> 1) | ((AC & 1) << 17); if (MAR & 0000020) /* (1.4) PAD = Partial add AC to MBR, that is, for every digital position of the MBR that contains a one, complement the digit in the corresponding digital position of the AC. This is also called a half add. */ AC ^= MBR; if (MAR & 0000010) { /* (1.7) CRY = Partial add the 18 digits of the AC to the corresponding 18 digits of the carry. To determine what the 18 digits of the carry are, use the following rule: "Grouping the AC and MBR digits into pairs and proceeding from right to left, assign the carry digit of the next pair to a one if in the present pair MBR = 1 and AC = 0 or if in the present pair AC = 1 and carry 1. (Note: the 0th digit pair determines the 17th pair's carry digit)" */ AC ^= MBR; AC = AC + MBR; AC = (AC + (AC >> 18)) & 0777777; /* propagate carry around */ } if (((IR & 001) == 01) && ((MAR & 017000) == 010000)) /* (1.8) Hlt = Halt the computer */ m_run = 0; break; } } } void tx0_device::indexed_address_eval() { MAR = MAR + XR; MAR = (MAR + (MAR >> 14)) & 0037777; /* propagate carry around */ } /* execute one instruction */ void tx0_8kw_device::execute_instruction_8kw() { if (! m_cycle) { m_cycle = 1; /* most frequent case */ switch (IR) { case 0: /* STOre */ case 1: /* STore indeXed */ case 2: /* Store indeX in Address */ case 3: /* ADd One */ case 4: /* Store LR */ case 5: /* Store Lr indeXed */ case 6: /* STore Zero */ case 8: /* ADD */ case 9: /* ADd indeXed */ case 10: /* LoaD indeX */ case 11: /* AUgment indeX */ case 12: /* Load LR */ case 13: /* Load Lr indeXed */ case 14: /* LoaD Ac */ case 15: /* Load Ac indeXed */ break; case 16: /* TRansfer on Negative */ if (AC & 0400000) { PC = MAR & 0017777; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ } break; case 17: /* Transfer on ZEro */ if ((AC == 0000000) || (AC == 0777777)) { PC = MAR & 0017777; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ } break; case 18: /* Transfer and Set indeX */ XR = PC; PC = MAR & 0017777; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ break; case 19: /* Transfer and IndeX */ if ((XR != 0000000) && (XR != 0037777)) { if (XR & 0020000) XR ++; else XR--; PC = MAR & 0017777; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ } break; case 21: /* TRansfer indeXed */ indexed_address_eval(); [[fallthrough]]; case 20: /* TRAnsfer */ PC = MAR & 0017777; m_cycle = 0; /* instruction only takes one cycle if branch is taken */ break; case 22: /* Transfer on external LeVel */ /*if (...) { PC = MAR & 0017777; m_cycle = 0;*/ /* instruction only takes one cycle if branch is taken */ /*}*/ break; case 24: /* OPeRate */ case 25: case 26: case 27: case 28: case 29: case 30: case 31: if (((IR & 001) == 00) && ((MAR & 017000) == 004000)) { /* Select class instruction */ if (IR & 004) /* (0.8???) CLA = CLear Ac */ AC = 0; /* (IOS???) SEL = SELect */ m_sel_handler(ASSERT_LINE); } else { /* Normal operate class instruction */ if (((IR & 001) == 01) && ((MAR & 017000) == 011000)) /* (0.6) CLL = CLear Left 9 bits of ac */ AC &= 0000777; if (((IR & 001) == 01) && ((MAR & 017000) == 012000)) /* (0.6) CLR = CLear Right 9 bits of ac */ AC &= 0777000; if (IR & 002) /* (0.7) AMB = transfer Ac to MBr */ MBR = AC; if (IR & 004) /* (0.8) CLA = CLear Ac */ AC = 0; if (((IR & 001) == 01) && ((MAR & 010000) == 000000)) { /* (IOS) In-Out group commands */ /* ((MAR & 0007000) >> 9) is device ID */ /* 0: */ /* (***) CPY = CoPY synchronizes transmission of information between in-out equipment and computer. */ /* 1: */ /* (IOS) R1L = Read 1 Line of tape from PETR into AC bits 0, 3, 6, 9, 12, 15, with CYR before read (inclusive or) */ /* 3: */ /* (IOS) R3L = Read 3 Lines of tape from PETR into AC bits 0, 3, 6, 9, 12, 15, with CYR before each read (inclusive or) */ /* 2: */ /* (IOS) DIS = DISplay a point on scope (AC bits 0-8 specify x coordinate, AC bits 9-17 specify y coordinate). The coordinate (0, 0) is usually at the lower left hand corner of the scope. A console switch is available to relocate (0,0) to the center. */ /* 6: */ /* (IOS) P6H = Punch one 6-bit line of flexo tape (without 7th hole) from ac bits 2, 5, 8, 11, 14, 17. Note: lines without 7th hole are ignored by PETR. */ /* 7: */ /* (IOS) P7H = same as P6H, but with 7th hole */ /* 4: */ /* (IOS) PRT = Print one six bit flexo character from AC bits 2, 5, 8, 11, 14, 17. */ /* (5 is undefined) */ int index = (MAR & 0007000) >> 9; m_ios = 0; call_io_handler(index); m_ioh = 1; } if (((IR & 001) == 00) && ((MAR & 010000) == 010000)) { /* (IOS) EX0 through EX7 = operate user's EXternal equipment. */ switch ((MAR & 0007000) >> 9) { /* ... */ } } } break; } } else { if (((IR != 2) && (IR != 3)) || (m_cycle == 2)) m_cycle = 0; else m_cycle = 2; /* SXA and ADO have an extra cycle 2 */ switch (IR) { case 1: /* STore indeXed */ indexed_address_eval(); [[fallthrough]]; case 0: /* STOre */ tx0_write(MAR, (MBR = AC)); break; case 2: /* Store indeX in Address */ if (m_cycle) { /* cycle 1 */ MBR = tx0_read(MAR); MBR = (MBR & 0760000) | (XR & 0017777); } else { /* cycle 2 */ tx0_write(MAR, MBR); } break; case 3: /* ADd One */ if (m_cycle) { /* cycle 1 */ AC = tx0_read(MAR) + 1; AC = (AC + (AC >> 18)) & 0777777; /* propagate carry around */ } else { /* cycle 2 */ tx0_write(MAR, (MBR = AC)); } break; case 5: /* Store Lr indeXed */ indexed_address_eval(); [[fallthrough]]; case 4: /* Store LR */ tx0_write(MAR, (MBR = LR)); break; case 6: /* STore Zero */ tx0_write(MAR, (MBR = 0)); break; case 9: /* ADd indeXed */ indexed_address_eval(); [[fallthrough]]; case 8: /* ADD */ MBR = tx0_read(MAR); AC = AC + MBR; AC = (AC + (AC >> 18)) & 0777777; /* propagate carry around */ break; case 10: /* LoaD indeX */ MBR = tx0_read(MAR); XR = (MBR & 0017777) | ((MBR >> 4) & 0020000); break; case 11: /* AUgment indeX */ MBR = tx0_read(MAR); XR = XR + ((MBR & 0017777) | ((MBR >> 4) & 0020000)); XR = (XR + (XR >> 14)) & 0037777; /* propagate carry around */ break; case 13: /* Load Lr indeXed */ indexed_address_eval(); [[fallthrough]]; case 12: /* Load LR */ LR = MBR = tx0_read(MAR); break; case 15: /* Load Ac indeXed */ indexed_address_eval(); [[fallthrough]]; case 14: /* LoaD Ac */ AC = MBR = tx0_read(MAR); break; case 16: /* TRansfer on Negative */ case 17: /* Transfer on ZEro */ case 18: /* Transfer and Set indeX */ case 19: /* Transfer and IndeX */ case 20: /* TRAnsfer */ case 21: /* TRansfer indeXed */ case 22: /* Transfer on external LeVel */ break; case 24: /* OPeRate */ case 25: case 26: case 27: case 28: case 29: case 30: case 31: if (((IR & 001) == 00) && ((MAR & 017000) == 004000)) { /* Select class instruction */ } else { /* Normal operate class instruction */ if (((IR & 001) == 00) && ((MAR & 017000) == 003000)) { /* (1.1) PEN = set ac bit 0 from light PEN ff, and ac bit 1 from light gun ff. (ffs contain one if pen or gun saw displayed point.) Then clear both light pen and light gun ffs */ /*AC = (AC & 0177777) |?...;*/ /*... = 0;*/ } if (((IR & 001) == 00) && ((MAR & 017000) == 001000)) /* (1.1) TAC = transfer TAC into ac (inclusive or) */ AC |= m_tac; if ((IR & 002) == 00) MBR = 0; // MBR cleared at 1.1 if (((IR & 001) == 00) && ((MAR & 017000) == 002000)) /* (1.2) TBR = transfer TBR into mbr (inclusive or) */ MBR |= m_tbr; if (((IR & 001) == 00) && ((MAR & 017000) == 006000)) /* (1.2) RPF = Read Program Flag register into mbr (inclusive or) */ MBR |= PF << 8; if (MAR & 0000040) /* (1.2) COM = COMplement ac */ AC ^= 0777777; if ((! (MAR & 0000400)) && (MAR & 0000100)) { /* (1.2) XMB = Transfer XR contents to MBR */ MBR = XR; if (XR & 0020000) MBR |= 0740000; } if (MAR & 0000004) { switch (MAR & 0000003) { case 0000003: /* (1.2) And LR and MBR */ MBR &= LR; break; case 0000001: /* (1.3) Or LR into MBR */ MBR |= LR; break; default: LOG("unrecognized instruction\n"); break; } } if (((! (MAR & 0000400)) && (MAR & 0000200)) && ((! (MAR & 0000004)) && (MAR & 0000002))) /* LMB and MBL used simultaneously interchange LR and MBR */ std::swap(LR, MBR); else if ((! (MAR & 0000400)) && (MAR & 0000200)) /* (1.4) MBL = Transfer MBR contents to LR */ LR = MBR; else if ((! (MAR & 0000004)) && (MAR & 0000002)) /* (1.4) LMB = Store the contents of the LR in the MBR. */ MBR = LR; if (MAR & 0000020) /* (1.5) PAD = Partial ADd mbr to ac */ AC ^= MBR; if (MAR & 0000400) { switch (MAR & 0000300) { case 0000200: /* (1.6) CYR = CYcle ac contents Right one binary position (AC(17) -> AC(0)) */ AC = (AC >> 1) | ((AC & 1) << 17); break; case 0000000: /* (1.6) SHR = SHift ac contents Right one binary position (AC(0) unchanged) */ AC = (AC >> 1) | (AC & 0400000); break; default: LOG("unrecognized instruction\n"); break; } } if (((IR & 001) == 00) && ((MAR & 017000) == 007000)) /* (1.6) SPF = Set Program Flag register from mbr */ PF = (MBR >> 8) & 077; if (MAR & 0000010) { /* (1.7?) CRY = Partial ADd the 18 digits of the AC to the corresponding 18 digits of the carry. */ AC ^= MBR; AC = AC + MBR; AC = (AC + (AC >> 18)) & 0777777; /* propagate carry around */ } if ((! (MAR & 0000004)) && (MAR & 0000001)) /* (1.8) MBX = Transfer MBR contents to XR */ XR = (MBR & 0017777) | ((MBR >> 4) & 0020000); if (((IR & 001) == 01) && ((MAR & 017000) == 010000)) /* (1.8) HLT = HaLT the computer and sound chime */ m_run = 0; } break; default: /* Illegal */ /* ... */ break; } } } /* Simulate a pulse on reset line: reset most registers and flip-flops, and initialize a few emulator state variables. */ void tx0_device::pulse_reset() { /* processor registers */ PC = 0; /* ??? */ IR = 0; /* ??? */ /*MBR = 0;*/ /* ??? */ /*MAR = 0;*/ /* ??? */ /*AC = 0;*/ /* ??? */ /*LR = 0;*/ /* ??? */ /* processor state flip-flops */ m_run = 0; /* ??? */ m_rim = 0; /* ??? */ m_ioh = 0; /* ??? */ m_ios = 0; /* ??? */ m_rim_step = 0; /* now, we kindly ask IO devices to reset, too */ m_io_reset_callback(ASSERT_LINE); } void tx0_device::io_complete() { m_ios = 1; } std::unique_ptr<util::disasm_interface> tx0_8kw_device::create_disassembler() { return std::make_unique<tx0_8kw_disassembler>(); } std::unique_ptr<util::disasm_interface> tx0_8kwo_device::create_disassembler() { return std::make_unique<tx0_8kwo_disassembler>(); } std::unique_ptr<util::disasm_interface> tx0_64kw_device::create_disassembler() { return std::make_unique<tx0_64kw_disassembler>(); }
27.276596
173
0.550507
Robbbert
0b6a4576e35499d3aafa6e478f2aa021e2a0db76
21,279
cpp
C++
Code_arduino/arduino-1.0.6/libraries/AP_Motors/AP_MotorsHeli.cpp
NeLy-EPFL/SeptaCam
7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a
[ "MIT" ]
null
null
null
Code_arduino/arduino-1.0.6/libraries/AP_Motors/AP_MotorsHeli.cpp
NeLy-EPFL/SeptaCam
7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a
[ "MIT" ]
null
null
null
Code_arduino/arduino-1.0.6/libraries/AP_Motors/AP_MotorsHeli.cpp
NeLy-EPFL/SeptaCam
7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a
[ "MIT" ]
null
null
null
/* * AP_MotorsHeli.cpp - ArduCopter motors library * Code by RandyMackay. DIYDrones.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. */ #include "AP_MotorsHeli.h" const AP_Param::GroupInfo AP_MotorsHeli::var_info[] PROGMEM = { // @Param: SV1_POS // @DisplayName: Servo 1 Position // @Description: This is the angular location of swash servo #1. // @Range: -180 180 // @Units: Degrees // @User: Standard // @Increment: 1 AP_GROUPINFO("SV1_POS", 1, AP_MotorsHeli, servo1_pos, -60), // @Param: SV2_POS // @DisplayName: Servo 2 Position // @Description: This is the angular location of swash servo #2. // @Range: -180 180 // @Units: Degrees // @User: Standard // @Increment: 1 AP_GROUPINFO("SV2_POS", 2, AP_MotorsHeli, servo2_pos, 60), // @Param: SV3_POS // @DisplayName: Servo 3 Position // @Description: This is the angular location of swash servo #3. // @Range: -180 180 // @Units: Degrees // @User: Standard // @Increment: 1 AP_GROUPINFO("SV3_POS", 3, AP_MotorsHeli, servo3_pos, 180), // @Param: ROL_MAX // @DisplayName: Maximum Roll Angle // @Description: This is the maximum allowable roll of the swash plate. // @Range: 0 18000 // @Units: Degrees // @Increment: 1 // @User: Advanced AP_GROUPINFO("ROL_MAX", 4, AP_MotorsHeli, roll_max, 4500), // @Param: PIT_MAX // @DisplayName: Maximum Pitch Angle // @Description: This is the maximum allowable pitch of the swash plate. // @Range: 0 18000 // @Units: Degrees // @Increment: 1 // @User: Advanced AP_GROUPINFO("PIT_MAX", 5, AP_MotorsHeli, pitch_max, 4500), // @Param: COL_MIN // @DisplayName: Collective Pitch Minimum // @Description: This controls the lowest possible servo position for the swashplate. // @Range: 1000 2000 // @Units: PWM // @Increment: 1 // @User: Standard AP_GROUPINFO("COL_MIN", 6, AP_MotorsHeli, collective_min, 1250), // @Param: COL_MAX // @DisplayName: Collective Pitch Maximum // @Description: This controls the highest possible servo position for the swashplate. // @Range: 1000 2000 // @Units: PWM // @Increment: 1 // @User: Standard AP_GROUPINFO("COL_MAX", 7, AP_MotorsHeli, collective_max, 1750), // @Param: COL_MID // @DisplayName: Collective Pitch Mid-Point // @Description: This is the swash servo position corresponding to zero collective pitch (or zero lift for Assymetrical blades). // @Range: 1000 2000 // @Units: PWM // @Increment: 1 // @User: Standard AP_GROUPINFO("COL_MID", 8, AP_MotorsHeli, collective_mid, 1500), // @Param: GYR_ENABLE // @DisplayName: External Gyro Enabled // @Description: Setting this to Enabled(1) will enable an external rudder gyro control which means outputting a gain on channel 7 and using a simpler heading control algorithm. Setting this to Disabled(0) will disable the external gyro gain on channel 7 and revert to a more complex yaw control algorithm. // @Values: 0:Disabled,1:Enabled // @User: Standard AP_GROUPINFO("GYR_ENABLE", 9, AP_MotorsHeli, ext_gyro_enabled, 0), // @Param: SWASH_TYPE // @DisplayName: Swash Plate Type // @Description: Setting this to 0 will configure for a 3-servo CCPM. Setting this to 1 will configure for mechanically mixed "H1". // @User: Standard AP_GROUPINFO("SWASH_TYPE", 10, AP_MotorsHeli, swash_type, AP_MOTORS_HELI_SWASH_CCPM), // @Param: GYR_GAIN // @DisplayName: External Gyro Gain // @Description: This is the PWM which is passed to the external gyro when external gyro is enabled. // @Range: 1000 2000 // @Units: PWM // @Increment: 1 // @User: Standard AP_GROUPINFO("GYR_GAIN", 11, AP_MotorsHeli, ext_gyro_gain, 1350), // @Param: SV_MAN // @DisplayName: Manual Servo Mode // @Description: Setting this to Enabled(1) will pass radio inputs directly to servos. Setting this to Disabled(0) will enable Arducopter control of servos. This is only meant to be used by the Mission Planner using swash plate set-up. // @Values: 0:Disabled,1:Enabled // @User: Standard AP_GROUPINFO("SV_MAN", 12, AP_MotorsHeli, servo_manual, 0), // @Param: PHANG // @DisplayName: Swashplate Phase Angle Compensation // @Description: This corrects for phase angle errors of the helicopter main rotor head. For example if pitching the swash forward also induces a roll, that effect can be offset with this parameter. // @Range: -90 90 // @Units: Degrees // @User: Advanced // @Increment: 1 AP_GROUPINFO("PHANG", 13, AP_MotorsHeli, phase_angle, 0), // @Param: COLYAW // @DisplayName: Collective-Yaw Mixing // @Description: This is a feed-forward compensation to automatically add rudder input when collective pitch is increased. // @Range: 0 5 AP_GROUPINFO("COLYAW", 14, AP_MotorsHeli, collective_yaw_effect, 0), // @Param: GOV_SETPOINT // @DisplayName: External Motor Governor Setpoint // @Description: This is the PWM which is passed to the external motor governor when external governor is enabled. // @Range: 1000 2000 // @Units: PWM // @Increment: 10 // @User: Standard AP_GROUPINFO("GOV_SETPOINT", 15, AP_MotorsHeli, ext_gov_setpoint, 1500), // @Param: RSC_MODE // @DisplayName: Rotor Speed Control Mode // @Description: This sets which ESC control mode is active. // @Range: 1 3 // @User: Standard AP_GROUPINFO("RSC_MODE", 16, AP_MotorsHeli, rsc_mode, 1), // @Param: RSC_RATE // @DisplayName: RSC Ramp Rate // @Description: This sets the time the RSC takes to ramp up to full speed (Soft Start). // @Range: 0 6000 // @Units: Seconds // @User: Standard AP_GROUPINFO("RSC_RATE", 17, AP_MotorsHeli, rsc_ramp_up_rate, 1000), // @Param: FLYBAR_MODE // @DisplayName: Flybar Mode Selector // @Description: This sets which acro mode is active. (0) is Flybarless (1) is Mechanical Flybar // @Range: 0 1 // @User: Standard AP_GROUPINFO("FLYBAR_MODE", 18, AP_MotorsHeli, flybar_mode, 0), AP_GROUPEND }; // init void AP_MotorsHeli::Init() { // set update rate set_update_rate(_speed_hz); } // set update rate to motors - a value in hertz or AP_MOTORS_SPEED_INSTANT_PWM for instant pwm void AP_MotorsHeli::set_update_rate( uint16_t speed_hz ) { // record requested speed _speed_hz = speed_hz; // setup fast channels if( _speed_hz != AP_MOTORS_SPEED_INSTANT_PWM ) { _rc->SetFastOutputChannels(_BV(_motor_to_channel_map[AP_MOTORS_MOT_1]) | _BV(_motor_to_channel_map[AP_MOTORS_MOT_2]) | _BV(_motor_to_channel_map[AP_MOTORS_MOT_3]) | _BV(_motor_to_channel_map[AP_MOTORS_MOT_4]), _speed_hz); } } // enable - starts allowing signals to be sent to motors void AP_MotorsHeli::enable() { // enable output channels _rc->enable_out(_motor_to_channel_map[AP_MOTORS_MOT_1]); // swash servo 1 _rc->enable_out(_motor_to_channel_map[AP_MOTORS_MOT_2]); // swash servo 2 _rc->enable_out(_motor_to_channel_map[AP_MOTORS_MOT_3]); // swash servo 3 _rc->enable_out(_motor_to_channel_map[AP_MOTORS_MOT_4]); // yaw _rc->enable_out(AP_MOTORS_HELI_EXT_GYRO); // for external gyro _rc->enable_out(AP_MOTORS_HELI_EXT_RSC); // for external RSC } // output_min - sends minimum values out to the motors void AP_MotorsHeli::output_min() { // move swash to mid move_swash(0,0,500,0); } // output_armed - sends commands to the motors void AP_MotorsHeli::output_armed() { // if manual override (i.e. when setting up swash), pass pilot commands straight through to swash if( servo_manual == 1 ) { _rc_roll->servo_out = _rc_roll->control_in; _rc_pitch->servo_out = _rc_pitch->control_in; _rc_throttle->servo_out = _rc_throttle->control_in; _rc_yaw->servo_out = _rc_yaw->control_in; } //static int counter = 0; _rc_roll->calc_pwm(); _rc_pitch->calc_pwm(); _rc_throttle->calc_pwm(); _rc_yaw->calc_pwm(); move_swash( _rc_roll->servo_out, _rc_pitch->servo_out, _rc_throttle->servo_out, _rc_yaw->servo_out ); rsc_control(); } // output_disarmed - sends commands to the motors void AP_MotorsHeli::output_disarmed() { if(_rc_throttle->control_in > 0) { // we have pushed up the throttle // remove safety _auto_armed = true; } // for helis - armed or disarmed we allow servos to move output_armed(); } // output_disarmed - sends commands to the motors void AP_MotorsHeli::output_test() { int16_t i; // Send minimum values to all motors output_min(); // servo 1 for( i=0; i<5; i++ ) { _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_1], _servo_1->radio_trim + 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_1], _servo_1->radio_trim - 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_1], _servo_1->radio_trim + 0); delay(300); } // servo 2 for( i=0; i<5; i++ ) { _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_2], _servo_2->radio_trim + 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_2], _servo_2->radio_trim - 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_2], _servo_2->radio_trim + 0); delay(300); } // servo 3 for( i=0; i<5; i++ ) { _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_3], _servo_3->radio_trim + 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_3], _servo_3->radio_trim - 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_3], _servo_3->radio_trim + 0); delay(300); } // external gyro if( ext_gyro_enabled ) { _rc->OutputCh(AP_MOTORS_HELI_EXT_GYRO, ext_gyro_gain); } // servo 4 for( i=0; i<5; i++ ) { _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_4], _servo_4->radio_trim + 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_4], _servo_4->radio_trim - 100); delay(300); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_4], _servo_4->radio_trim + 0); delay(300); } // Send minimum values to all motors output_min(); } // reset_swash - free up swash for maximum movements. Used for set-up void AP_MotorsHeli::reset_swash() { // free up servo ranges _servo_1->radio_min = 1000; _servo_1->radio_max = 2000; _servo_2->radio_min = 1000; _servo_2->radio_max = 2000; _servo_3->radio_min = 1000; _servo_3->radio_max = 2000; if( swash_type == AP_MOTORS_HELI_SWASH_CCPM ) { //CCPM Swashplate, perform servo control mixing // roll factors _rollFactor[CH_1] = cos(radians(servo1_pos + 90 - phase_angle)); _rollFactor[CH_2] = cos(radians(servo2_pos + 90 - phase_angle)); _rollFactor[CH_3] = cos(radians(servo3_pos + 90 - phase_angle)); // pitch factors _pitchFactor[CH_1] = cos(radians(servo1_pos - phase_angle)); _pitchFactor[CH_2] = cos(radians(servo2_pos - phase_angle)); _pitchFactor[CH_3] = cos(radians(servo3_pos - phase_angle)); // collective factors _collectiveFactor[CH_1] = 1; _collectiveFactor[CH_2] = 1; _collectiveFactor[CH_3] = 1; }else{ //H1 Swashplate, keep servo outputs seperated // roll factors _rollFactor[CH_1] = 1; _rollFactor[CH_2] = 0; _rollFactor[CH_3] = 0; // pitch factors _pitchFactor[CH_1] = 0; _pitchFactor[CH_2] = 1; _pitchFactor[CH_3] = 0; // collective factors _collectiveFactor[CH_1] = 0; _collectiveFactor[CH_2] = 0; _collectiveFactor[CH_3] = 1; } // set roll, pitch and throttle scaling _roll_scaler = 1.0; _pitch_scaler = 1.0; _collective_scalar = ((float)(_rc_throttle->radio_max - _rc_throttle->radio_min))/1000.0; // we must be in set-up mode so mark swash as uninitialised _swash_initialised = false; } // init_swash - initialise the swash plate void AP_MotorsHeli::init_swash() { // swash servo initialisation _servo_1->set_range(0,1000); _servo_2->set_range(0,1000); _servo_3->set_range(0,1000); _servo_4->set_angle(4500); // ensure _coll values are reasonable if( collective_min >= collective_max ) { collective_min = 1000; collective_max = 2000; } collective_mid = constrain(collective_mid, collective_min, collective_max); // calculate throttle mid point throttle_mid = ((float)(collective_mid-collective_min))/((float)(collective_max-collective_min))*1000.0; // determine roll, pitch and throttle scaling _roll_scaler = (float)roll_max/4500.0; _pitch_scaler = (float)pitch_max/4500.0; _collective_scalar = ((float)(collective_max-collective_min))/1000.0; if( swash_type == AP_MOTORS_HELI_SWASH_CCPM ) { //CCPM Swashplate, perform control mixing // roll factors _rollFactor[CH_1] = cos(radians(servo1_pos + 90 - phase_angle)); _rollFactor[CH_2] = cos(radians(servo2_pos + 90 - phase_angle)); _rollFactor[CH_3] = cos(radians(servo3_pos + 90 - phase_angle)); // pitch factors _pitchFactor[CH_1] = cos(radians(servo1_pos - phase_angle)); _pitchFactor[CH_2] = cos(radians(servo2_pos - phase_angle)); _pitchFactor[CH_3] = cos(radians(servo3_pos - phase_angle)); // collective factors _collectiveFactor[CH_1] = 1; _collectiveFactor[CH_2] = 1; _collectiveFactor[CH_3] = 1; }else{ //H1 Swashplate, keep servo outputs seperated // roll factors _rollFactor[CH_1] = 1; _rollFactor[CH_2] = 0; _rollFactor[CH_3] = 0; // pitch factors _pitchFactor[CH_1] = 0; _pitchFactor[CH_2] = 1; _pitchFactor[CH_3] = 0; // collective factors _collectiveFactor[CH_1] = 0; _collectiveFactor[CH_2] = 0; _collectiveFactor[CH_3] = 1; } // servo min/max values _servo_1->radio_min = 1000; _servo_1->radio_max = 2000; _servo_2->radio_min = 1000; _servo_2->radio_max = 2000; _servo_3->radio_min = 1000; _servo_3->radio_max = 2000; // mark swash as initialised _swash_initialised = true; } // // heli_move_swash - moves swash plate to attitude of parameters passed in // - expected ranges: // roll : -4500 ~ 4500 // pitch: -4500 ~ 4500 // collective: 0 ~ 1000 // yaw: -4500 ~ 4500 // void AP_MotorsHeli::move_swash(int16_t roll_out, int16_t pitch_out, int16_t coll_out, int16_t yaw_out) { int16_t yaw_offset = 0; int16_t coll_out_scaled; if( servo_manual == 1 ) { // are we in manual servo mode? (i.e. swash set-up mode)? // check if we need to free up the swash if( _swash_initialised ) { reset_swash(); } coll_out_scaled = coll_out * _collective_scalar + _rc_throttle->radio_min - 1000; }else{ // regular flight mode // check if we need to reinitialise the swash if( !_swash_initialised ) { init_swash(); } // rescale roll_out and pitch-out into the min and max ranges to provide linear motion // across the input range instead of stopping when the input hits the constrain value // these calculations are based on an assumption of the user specified roll_max and pitch_max // coming into this equation at 4500 or less, and based on the original assumption of the // total _servo_x.servo_out range being -4500 to 4500. roll_out = roll_out * _roll_scaler; roll_out = constrain(roll_out, (int16_t)-roll_max, (int16_t)roll_max); pitch_out = pitch_out * _pitch_scaler; pitch_out = constrain(pitch_out, (int16_t)-pitch_max, (int16_t)pitch_max); // scale collective pitch coll_out = constrain(coll_out, 0, 1000); coll_out_scaled = coll_out * _collective_scalar + collective_min - 1000; // rudder feed forward based on collective if( !ext_gyro_enabled ) { yaw_offset = collective_yaw_effect * abs(coll_out_scaled - throttle_mid); } } // swashplate servos _servo_1->servo_out = (_rollFactor[CH_1] * roll_out + _pitchFactor[CH_1] * pitch_out)/10 + _collectiveFactor[CH_1] * coll_out_scaled + (_servo_1->radio_trim-1500); _servo_2->servo_out = (_rollFactor[CH_2] * roll_out + _pitchFactor[CH_2] * pitch_out)/10 + _collectiveFactor[CH_2] * coll_out_scaled + (_servo_2->radio_trim-1500); if( swash_type == AP_MOTORS_HELI_SWASH_H1 ) { _servo_1->servo_out += 500; _servo_2->servo_out += 500; } _servo_3->servo_out = (_rollFactor[CH_3] * roll_out + _pitchFactor[CH_3] * pitch_out)/10 + _collectiveFactor[CH_3] * coll_out_scaled + (_servo_3->radio_trim-1500); _servo_4->servo_out = yaw_out + yaw_offset; // use servo_out to calculate pwm_out and radio_out _servo_1->calc_pwm(); _servo_2->calc_pwm(); _servo_3->calc_pwm(); _servo_4->calc_pwm(); // actually move the servos _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_1], _servo_1->radio_out); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_2], _servo_2->radio_out); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_3], _servo_3->radio_out); _rc->OutputCh(_motor_to_channel_map[AP_MOTORS_MOT_4], _servo_4->radio_out); // to be compatible with other frame types motor_out[AP_MOTORS_MOT_1] = _servo_1->radio_out; motor_out[AP_MOTORS_MOT_2] = _servo_2->radio_out; motor_out[AP_MOTORS_MOT_3] = _servo_3->radio_out; motor_out[AP_MOTORS_MOT_4] = _servo_4->radio_out; // output gyro value if( ext_gyro_enabled ) { _rc->OutputCh(AP_MOTORS_HELI_EXT_GYRO, ext_gyro_gain); } // InstantPWM if( _speed_hz == AP_MOTORS_SPEED_INSTANT_PWM ) { _rc->Force_Out0_Out1(); _rc->Force_Out2_Out3(); } } void AP_MotorsHeli::rsc_control() { switch ( rsc_mode ) { case AP_MOTORSHELI_RSC_MODE_CH8_PASSTHROUGH: if( armed() && _rc_8->control_in > 10 ) { if (rsc_ramp < rsc_ramp_up_rate) { rsc_ramp++; rsc_output = map(rsc_ramp, 0, rsc_ramp_up_rate, 1000, _rc_8->control_in); } else { rsc_output = _rc_8->control_in; } } else if( !armed() ) { _rc->OutputCh(AP_MOTORS_HELI_EXT_RSC, _rc_8->radio_min); rsc_ramp = 0; //Return RSC Ramp to 0 } break; case AP_MOTORSHELI_RSC_MODE_EXT_GOV: if( armed() && _rc_throttle->control_in > 10) { if (rsc_ramp < rsc_ramp_up_rate) { rsc_ramp++; rsc_output = map(rsc_ramp, 0, rsc_ramp_up_rate, 1000, ext_gov_setpoint); } else { rsc_output = ext_gov_setpoint; } } else { rsc_ramp--; //Return RSC Ramp to 0 slowly, allowing for "warm restart" if (rsc_ramp < 0) { rsc_ramp = 0; } rsc_output = 1000; //Just to be sure RSC output is 0 } _rc->OutputCh(AP_MOTORS_HELI_EXT_RSC, rsc_output); break; // case 3: // Open Loop ESC Control // // coll_scaled = _motors->coll_out_scaled + 1000; // if(coll_scaled <= _motors->collective_mid){ // esc_ol_output = map(coll_scaled, _motors->collective_min, _motors->collective_mid, esc_out_low, esc_out_mid); // Bottom half of V-curve // } else if (coll_scaled > _motors->collective_mid){ // esc_ol_output = map(coll_scaled, _motors->collective_mid, _motors->collective_max, esc_out_mid, esc_out_high); // Top half of V-curve // } else { esc_ol_output = 1000; } // Just in case. // // if(_motors->armed() && _rc_throttle->control_in > 10){ // if (ext_esc_ramp < ext_esc_ramp_up){ // ext_esc_ramp++; // ext_esc_output = map(ext_esc_ramp, 0, ext_esc_ramp_up, 1000, esc_ol_output); // } else { // ext_esc_output = esc_ol_output; // } // } else { // ext_esc_ramp = 0; //Return ESC Ramp to 0 // ext_esc_output = 1000; //Just to be sure ESC output is 0 //} // _rc->OutputCh(AP_MOTORS_HELI_EXT_ESC, ext_esc_output); // break; default: break; } };
37.006957
310
0.64035
NeLy-EPFL
0b6aed1e0fe6e31aa4d1325c0cf387e54d516ba1
1,420
cpp
C++
UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/LandscapeTextureBakingNotification.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/LandscapeTextureBakingNotification.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/LandscapeTextureBakingNotification.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "UnrealEd.h" #include "GlobalEditorNotification.h" #include "Landscape.h" #include "SNotificationList.h" /** Notification class for grassmmap rendering. */ class FLandscapeTextureBakingNotificationImpl : public FGlobalEditorNotification { protected: /** FGlobalEditorNotification interface */ virtual bool ShouldShowNotification(const bool bIsNotificationAlreadyActive) const override; virtual void SetNotificationText(const TSharedPtr<SNotificationItem>& InNotificationItem) const override; }; /** Global notification object. */ FLandscapeTextureBakingNotificationImpl GLandscapeTextureBakingNotification; bool FLandscapeTextureBakingNotificationImpl::ShouldShowNotification(const bool bIsNotificationAlreadyActive) const { return ALandscapeProxy::TotalComponentsNeedingTextureBaking > 0; } void FLandscapeTextureBakingNotificationImpl::SetNotificationText(const TSharedPtr<SNotificationItem>& InNotificationItem) const { if (ALandscapeProxy::TotalComponentsNeedingTextureBaking > 0) { FFormatNamedArguments Args; Args.Add(TEXT("OutstandingTextures"), FText::AsNumber(ALandscapeProxy::TotalComponentsNeedingTextureBaking)); const FText ProgressMessage = FText::Format(NSLOCTEXT("TextureBaking", "TextureBakingFormat", "Baking Landscape Textures ({OutstandingTextures})"), Args); InNotificationItem->SetText(ProgressMessage); } }
40.571429
156
0.83169
armroyce
0b6d3e92e8a0ab793faec23dcc650a963a747529
3,773
cpp
C++
c++/src/objtools/readers/read_util.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/objtools/readers/read_util.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/objtools/readers/read_util.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: read_util.cpp 352696 2012-02-08 19:35:14Z ludwigf $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Frank Ludwig * * File Description: Common file reader utility functions. * */ #include <ncbi_pch.hpp> #include <objects/seqloc/Seq_id.hpp> #include <objtools/readers/read_util.hpp> #include <objtools/readers/reader_base.hpp> BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: // ---------------------------------------------------------------------------- void CReadUtil::Tokenize( const string& str, const string& delim, vector< string >& parts ) // ---------------------------------------------------------------------------- { string temp; bool inQuote(false); const char joiner('#'); for (size_t i=0; i < str.size(); ++i) { switch(str[i]) { default: break; case '\"': inQuote = inQuote ^ true; break; case ' ': if (inQuote) { if (temp.empty()) temp = str; temp[i] = joiner; } break; } } if (temp.empty()) { NStr::Tokenize(str, delim, parts, NStr::eMergeDelims); return; } NStr::Tokenize(temp, delim, parts, NStr::eMergeDelims); for (size_t j=0; j < parts.size(); ++j) { for (size_t i=0; i < parts[j].size(); ++i) { if (parts[j][i] == joiner) { parts[j][i] = ' '; } } } } // ----------------------------------------------------------------- CRef<CSeq_id> CReadUtil::AsSeqId( const string& rawId, unsigned int flags) // ----------------------------------------------------------------- { CRef<CSeq_id> pId; if (flags & CReaderBase::fAllIdsAsLocal) { pId.Reset(new CSeq_id(CSeq_id::e_Local, rawId)); return pId; } try { pId.Reset(new CSeq_id(rawId)); if (!pId) { pId.Reset(new CSeq_id(CSeq_id::e_Local, rawId)); return pId; } if (pId->IsGi()) { if (flags & CReaderBase::fNumericIdsAsLocal) { pId.Reset(new CSeq_id(CSeq_id::e_Local, rawId)); return pId; } if (pId->GetGi() < 500) { pId.Reset(new CSeq_id(CSeq_id::e_Local, rawId)); return pId; } } return pId; } catch(...) { pId.Reset(new CSeq_id(CSeq_id::e_Local, rawId)); } return pId; } END_objects_SCOPE END_NCBI_SCOPE
31.181818
80
0.51471
OpenHero
0b7186333a770ddc1ef104c54ee3461e978c1d40
10,771
cpp
C++
Code/lib/AspenSIM800/src/atcmds/general.cpp
johannes51/Telefon
751ff691b184f5fc456e5b978ebe39aecb1d3961
[ "MIT" ]
null
null
null
Code/lib/AspenSIM800/src/atcmds/general.cpp
johannes51/Telefon
751ff691b184f5fc456e5b978ebe39aecb1d3961
[ "MIT" ]
null
null
null
Code/lib/AspenSIM800/src/atcmds/general.cpp
johannes51/Telefon
751ff691b184f5fc456e5b978ebe39aecb1d3961
[ "MIT" ]
null
null
null
// "Aspen SIM800" is a comprehensive SIM800 library for simplified and in-depth chip access. // Copyright (C) 2016 Mattias Aabmets (https://github.com/aspenforest) // // This API library is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This API library 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 API library. If not, see <http://www.gnu.org/licenses/>. #include <SIM800.h> // ============================================================ void SIM800::callMeter(CmdType type, const char* str) { outBuilder(type, str, P("CACM")); print(ioBuffer); } // ============================================================ void SIM800::callMeterMax(CmdType type, const char* str) { outBuilder(type, str, P("CAMM")); print(ioBuffer); } // ============================================================ void SIM800::chargeAdvice(CmdType type, const char* str) { outBuilder(type, str, P("CAOC")); print(ioBuffer); } // ============================================================ void SIM800::dataCallService(CmdType type, const char* str) { outBuilder(type, str, P("CBST")); print(ioBuffer); } // ============================================================ void SIM800::callForward(CmdType type, const char* str) { outBuilder(type, str, P("CCFC")); print(ioBuffer); } // ============================================================ void SIM800::callWait(CmdType type, const char* str) { outBuilder(type, str, P("CCWA")); print(ioBuffer); } // ============================================================ void SIM800::errorReport(CmdType type, const char* str) { outBuilder(type, str, P("CEER")); print(ioBuffer); } // ============================================================ void SIM800::reqMakerID(CmdType type) { outBuilder(type, "", P("CGMI")); print(ioBuffer); } // ============================================================ void SIM800::reqDeviceModelID(CmdType type) { outBuilder(type, "", P("CGMM")); print(ioBuffer); } // ============================================================ void SIM800::reqSoftwareID(CmdType type) { outBuilder(type, "", P("CGMR")); print(ioBuffer); } // ============================================================ void SIM800::reqIMEI(CmdType type) { outBuilder(type, "", P("CGSN")); print(ioBuffer); } // ============================================================ void SIM800::charset(CmdType type, const char* str) { outBuilder(type, str, P("CSCS")); print(ioBuffer); } // ============================================================ void SIM800::addressType(CmdType type, const char* str) { outBuilder(type, str, P("CSTA")); print(ioBuffer); } // ============================================================ void SIM800::callHold(CmdType type, const char* str) { outBuilder(type, str, P("CHLD")); print(ioBuffer); } // ============================================================ void SIM800::reqIMSI(CmdType type) { outBuilder(type, "", P("CIMI")); print(ioBuffer); } // ============================================================ void SIM800::activeCalls(CmdType type, const char* str) { outBuilder(type, str, P("CLCC")); print(ioBuffer); } // ============================================================ void SIM800::facilityLock(CmdType type, const char* str) { outBuilder(type, str, P("CLCK")); print(ioBuffer); } // ============================================================ void SIM800::showCallerID(CmdType type, const char* str) { outBuilder(type, str, P("CLIP")); print(ioBuffer); } // ============================================================ void SIM800::hideSelfID(CmdType type, const char* str) { outBuilder(type, str, P("CLIR")); print(ioBuffer); } // ============================================================ void SIM800::deviceError(CmdType type, const char* str) { outBuilder(type, str, P("CMEE")); print(ioBuffer); } // ============================================================ void SIM800::callerID(CmdType type, const char* str) { outBuilder(type, str, P("COLP")); print(ioBuffer); } // ============================================================ void SIM800::netOps(CmdType type, const char* str) { outBuilder(type, str, P("COPS")); print(ioBuffer); } // ============================================================ void SIM800::activity(CmdType type) { outBuilder(type, "", P("CPAS")); print(ioBuffer); } // ============================================================ void SIM800::pbFind(CmdType type, const char* str) { outBuilder(type, str, P("CPBF")); print(ioBuffer); } // ============================================================ void SIM800::pbRead(CmdType type, const char* str) { outBuilder(type, str, P("CPBR")); print(ioBuffer); } // ============================================================ void SIM800::pbStorage(CmdType type, const char* str) { outBuilder(type, str, P("CPBS")); print(ioBuffer); } // ============================================================ void SIM800::pbWrite(CmdType type, const char* str) { outBuilder(type, str, P("CPBW")); print(ioBuffer); } // ============================================================ void SIM800::pinCode(CmdType type, const char* str) { outBuilder(type, str, P("CPIN")); print(ioBuffer); } // ============================================================ void SIM800::changePwd(CmdType type, const char* str) { outBuilder(type, str, P("CPWD")); print(ioBuffer); } // ============================================================ void SIM800::serviceReport(CmdType type, const char* str) { outBuilder(type, str, P("CR")); print(ioBuffer); } // ============================================================ void SIM800::ringCodeMode(CmdType type, const char* str) { outBuilder(type, str, P("CRC")); print(ioBuffer); } // ============================================================ void SIM800::netReg(CmdType type, const char* str) { outBuilder(type, str, P("CREG")); print(ioBuffer); } // ============================================================ void SIM800::radioLinkParams(CmdType type, const char* str) { outBuilder(type, str, P("CRLP")); print(ioBuffer); } // ============================================================ void SIM800::simRawAccess(CmdType type, const char* str) { outBuilder(type, str, P("CRSM")); print(ioBuffer); } // ============================================================ void SIM800::signalQuality(CmdType type) { outBuilder(type, "", P("CSQ")); print(ioBuffer); } // ============================================================ void SIM800::dtmfDuration(CmdType type, const char* str) { outBuilder(type, str, P("VTD")); print(ioBuffer); } // ============================================================ void SIM800::dtmfPlay(CmdType type, const char* str) { outBuilder(type, str, P("VTS")); print(ioBuffer); } // ============================================================ void SIM800::muxControl(CmdType type, const char* str) { outBuilder(type, str, P("CMUX")); print(ioBuffer); } // ============================================================ void SIM800::getSelfAddr(CmdType type) { outBuilder(type, "", P("CNUM")); print(ioBuffer); } // ============================================================ void SIM800::prefOperators(CmdType type, const char* str) { outBuilder(type, str, P("CPOL")); print(ioBuffer); } // ============================================================ void SIM800::listAllOperators(CmdType type) { outBuilder(type, "", P("COPN")); print(ioBuffer); } // ============================================================ void SIM800::deviceMode(CmdType type, const char* str) { outBuilder(type, str, P("CFUN")); print(ioBuffer); } // ============================================================ void SIM800::clock(CmdType type, const char* str) { outBuilder(type, str, P("CCLK")); print(ioBuffer); } // ============================================================ void SIM800::simStrAccess(CmdType type, const char* str) { outBuilder(type, str, P("CSIM")); print(ioBuffer); } // ============================================================ void SIM800::alertMode(CmdType type, const char* str) { outBuilder(type, str, P("CALM")); print(ioBuffer); } // ============================================================ void SIM800::alertSound(CmdType type, const char* str) { outBuilder(type, str, P("CALS")); print(ioBuffer); } // ============================================================ void SIM800::ringerVolume(CmdType type, const char* str) { outBuilder(type, str, P("CRSL")); print(ioBuffer); } // ============================================================ void SIM800::loudSpeakerVol(CmdType type, const char* str) { outBuilder(type, str, P("CLVL")); print(ioBuffer); } // ============================================================ void SIM800::mute(CmdType type, const char* str) { outBuilder(type, str, P("CMUT")); print(ioBuffer); } // ============================================================ void SIM800::pricePerUnit(CmdType type, const char* str) { outBuilder(type, str, P("CPUC")); print(ioBuffer); } // ============================================================ void SIM800::callMeterMaxEvent(CmdType type, const char* str) { outBuilder(type, str, P("CCWE")); print(ioBuffer); } // ============================================================ void SIM800::battery(CmdType type) { outBuilder(type, "", P("CBC")); print(ioBuffer); } // ============================================================ void SIM800::usd(CmdType type, const char* str) { outBuilder(type, str, P("CUSD")); print(ioBuffer); } // ============================================================ void SIM800::ssn(CmdType type, const char* str) { outBuilder(type, str, P("CSSN")); print(ioBuffer); } // ============================================================ void SIM800::dtmfDetect(CmdType type, const char* str) { outBuilder(type, str, P("DDET")); print(ioBuffer); }
30.774286
94
0.444156
johannes51
0b71dfdcb29fb90cbe22dda32a3c935d6bbec326
25,326
cpp
C++
libraries/VAL/src/graphconstruct.cpp
teyssieuman/VAL
15320d3988bb6ed633babe6c7bd663a97c23a393
[ "BSD-3-Clause" ]
65
2015-01-08T09:58:01.000Z
2021-11-16T11:08:31.000Z
libraries/VAL/src/graphconstruct.cpp
teyssieuman/VAL
15320d3988bb6ed633babe6c7bd663a97c23a393
[ "BSD-3-Clause" ]
48
2015-01-19T01:07:16.000Z
2021-07-29T18:26:54.000Z
libraries/VAL/src/graphconstruct.cpp
teyssieuman/VAL
15320d3988bb6ed633babe6c7bd663a97c23a393
[ "BSD-3-Clause" ]
45
2016-01-08T01:57:01.000Z
2022-03-07T04:00:36.000Z
// Copyright 2019 - University of Strathclyde, King's College London and Schlumberger Ltd // This source code is licensed under the BSD license found in the LICENSE file in the root directory of this source tree. #include "graphconstruct.h" #include "Evaluator.h" #include "FuncAnalysis.h" #include "InstPropLinker.h" #include "State.h" #include "Validator.h" #include "ptree.h" #include <fstream> using namespace VAL; namespace Inst { class PlanGraph::BVEvaluator : public VAL::VisitController { private: // The BVEvaluator is going to own this bval. BoundedValue *bval; PlanGraph &pg; VAL::FastEnvironment *fenv; bool continuous; public: BVEvaluator(PlanGraph &p, VAL::FastEnvironment *fe) : bval(0), pg(p), fenv(fe), continuous(false){}; ~BVEvaluator() { delete bval; }; bool isContinuous() const { return continuous; }; BoundedValue *getBV() { BoundedValue *bv = bval; bval = 0; return bv; }; virtual void visit_plus_expression(plus_expression *pe) { pe->getRHS()->visit(this); BoundedValue *br = bval; bval = 0; pe->getLHS()->visit(this); br = (*bval += br); if (br != bval) { delete bval; bval = br; }; }; virtual void visit_minus_expression(minus_expression *me) { me->getRHS()->visit(this); BoundedValue *br = bval; bval = 0; me->getLHS()->visit(this); br = (*bval -= br); if (br != bval) { delete bval; bval = br; }; }; virtual void visit_mul_expression(mul_expression *pe) { pe->getRHS()->visit(this); BoundedValue *br = bval; bval = 0; pe->getLHS()->visit(this); if (continuous) { bval = br; } else { br = (*bval *= br); if (br != bval) { delete bval; bval = br; }; }; }; virtual void visit_div_expression(div_expression *pe) { pe->getRHS()->visit(this); BoundedValue *br = bval; bval = 0; pe->getLHS()->visit(this); br = (*bval /= br); if (br != bval) { delete bval; bval = br; }; }; virtual void visit_uminus_expression(uminus_expression *um) { um->getExpr()->visit(this); bval->negate(); }; virtual void visit_int_expression(int_expression *ie) { bval = new PointValue(ie->double_value()); }; virtual void visit_float_expression(float_expression *fe) { bval = new PointValue(fe->double_value()); }; virtual void visit_special_val_expr(special_val_expr *) { continuous = true; }; virtual void visit_func_term(func_term *ft) { PNE pne(ft, fenv); FluentEntry *fe = pg.fluents.find(instantiatedOp::getPNE(&pne)); bval = fe ? fe->getBV()->copy() : new Undefined(); }; }; class SpikeEvaluator : public VisitController { private: Spike< PropEntry > &spes; Spike< FluentEntry > &sfes; FastEnvironment *f; bool evaluation; PlanGraph &pg; pred_symbol *equality; public: SpikeEvaluator(PlanGraph &p, Spike< PropEntry > &s1, Spike< FluentEntry > &s2, FastEnvironment *fe) : spes(s1), sfes(s2), f(fe), evaluation(true), pg(p), equality(current_analysis->pred_tab.symbol_probe("=")) {} virtual void visit_simple_goal(simple_goal *s) { if (EPS(s->getProp()->head)->getParent() == this->equality) { evaluation = ((*f)[s->getProp()->args->front()] == (*f)[s->getProp()->args->back()]); if (s->getPolarity() == E_NEG) { evaluation = !evaluation; }; return; } else { Literal e(s->getProp(), f); Literal *lptr = instantiatedOp::getLiteral(&e); PropEntry *eid = spes.find(lptr); if (eid) { if (s->getPolarity() == E_NEG) { evaluation = eid->gotDeleters(); } else { evaluation = eid->gotAchievers(); } } else { if (s->getPolarity() == E_NEG) { evaluation = true; } else { evaluation = false; } }; }; }; bool getEvaluation() const { return evaluation; }; virtual void visit_qfied_goal(qfied_goal *qg) { cout << "Not currently handling quantified goals\n"; } virtual void visit_conj_goal(conj_goal *c) { for (goal_list::const_iterator i = c->getGoals()->begin(); i != c->getGoals()->end(); ++i) { (*i)->visit(this); if (!evaluation) { return; } } }; virtual void visit_disj_goal(disj_goal *c) { cout << "Not dealing with disjunctive goals\n"; }; virtual void visit_timed_goal(timed_goal *t) { cout << "Not currently handling timed goals\n"; } virtual void visit_imply_goal(imply_goal *ig) { cout << "Not dealing with implications\n"; }; virtual void visit_neg_goal(neg_goal *ng) { ng->getGoal()->visit(this); evaluation = !evaluation; } virtual void visit_comparison(comparison *c) { // Evaluate the parts and combine according to // rearrangement then do the comparison with a // bounds check. PlanGraph::BVEvaluator bve(pg, f); c->getLHS()->visit(&bve); BoundedValue *bvl = bve.getBV(); c->getRHS()->visit(&bve); BoundedValue *bvr = bve.getBV(); BoundedValue *bvres = (*bvl -= bvr); switch (c->getOp()) { case E_GREATER: evaluation = !bvres->gotUB() || bvres->getUB() > 0; break; case E_GREATEQ: evaluation = !bvres->gotUB() || bvres->getUB() >= 0; break; case E_LESS: evaluation = !bvres->gotLB() || bvres->getLB() < 0; break; case E_LESSEQ: evaluation = !bvres->gotLB() || bvres->getLB() <= 0; break; case E_EQUALS: evaluation = (!bvres->gotLB() || bvres->getLB() <= 0) && (!bvres->gotUB() || bvres->getUB() >= 0); break; default: break; }; } virtual void visit_action(action *op) { op->precondition->visit(this); }; virtual void visit_event(event *e) { e->precondition->visit(this); }; virtual void visit_process(process *p) { p->precondition->visit(this); }; virtual void visit_durative_action(durative_action *da) { cout << "Not dealing with duratives\n"; }; }; class SpikeSupporter : public VisitController { private: Spike< PropEntry > &spes; Spike< FluentEntry > &sfes; FastEnvironment *f; ActEntry *ae; GraphFactory *myFac; bool context; pred_symbol *equality; public: SpikeSupporter(Spike< PropEntry > &s1, Spike< FluentEntry > &s2, FastEnvironment *fe, ActEntry *a, GraphFactory *mf) : spes(s1), sfes(s2), f(fe), ae(a), myFac(mf), context(true), equality(current_analysis->pred_tab.symbol_probe("=")) {} virtual void visit_simple_goal(simple_goal *s) { if (EPS(s->getProp()->head)->getParent() != this->equality) { Literal e(s->getProp(), f); Literal *lptr = instantiatedOp::getLiteral(&e); PropEntry *eid = spes.findInAll(lptr); if (eid) { if ((context && s->getPolarity() == E_NEG) || (!context && s->getPolarity() == E_POS)) { ae->addSupportedByNeg(eid); cout << "Support by neg: " << *ae << " with " << *eid << "\n"; } else { ae->addSupportedBy(eid); } } else { eid = myFac->makePropEntry(lptr); // make the entry for eid ae->addSupportedByNeg(eid); spes.insertAbsentee(eid); }; }; }; virtual void visit_conj_goal(conj_goal *c) { for (goal_list::const_iterator i = c->getGoals()->begin(); i != c->getGoals()->end(); ++i) { (*i)->visit(this); } }; virtual void visit_comparison(comparison *c) { // cout << "Er....what?\n"; } virtual void visit_neg_goal(neg_goal *ng) { context = !context; ng->getGoal()->visit(this); }; virtual void visit_action(action *op) { op->precondition->visit(this); }; virtual void visit_event(event *e) { e->precondition->visit(this); }; virtual void visit_process(process *p) { p->precondition->visit(this); }; virtual void visit_durative_action(durative_action *da) { cout << "Not dealing with duratives\n"; }; }; void FluentEntry::write(ostream &o) const { thefluent->write(o); o << "["; for (vector< Constraint * >::const_iterator i = constrs.begin(); i != constrs.end(); ++i) { (*i)->write(o); o << " "; }; o << "]\nBounded Range: " << *bval << "\n"; }; BoundedValue *BoundedInterval::operator+=(const BoundedValue *bv) { if (!finitelbnd || !bv->gotLB()) { finitelbnd = false; } else { lbnd += bv->getLB(); }; if (!finiteubnd || !bv->gotUB()) { finiteubnd = false; } else { ubnd += bv->getUB(); }; return this; }; BoundedValue *BoundedInterval::operator-=(const BoundedValue *bv) { if (!finitelbnd || !bv->gotUB()) { finitelbnd = false; } else { lbnd -= bv->getUB(); }; if (!finiteubnd || !bv->gotLB()) { finiteubnd = false; } else { ubnd -= bv->getLB(); }; return this; }; BoundedValue *BoundedInterval::operator*=(const BoundedValue *bv) { if (!finitelbnd || !bv->gotLB()) { finitelbnd = false; } else { lbnd *= bv->getLB(); }; if (!finiteubnd || !bv->gotUB()) { finiteubnd = false; } else { ubnd *= bv->getUB(); }; return this; }; BoundedValue *BoundedInterval::operator/=(const BoundedValue *bv) { /* if(!finitelbnd || !bv->gotLB()) { finitelbnd = false; } else { lbnd += bv->getLB(); }; if(!finiteubnd || !bv->gotUB()) { finiteubnd = false; } else { ubnd += bv->getUB(); }; return this; */ // This case must be handled properly... cout << "WARNING: Division not managed properly, yet!\n"; finitelbnd = finiteubnd = false; return this; }; BoundedValue *PointValue::operator+=(const BoundedValue *bv) { BoundedInterval *bi = new BoundedInterval(val, val); *bi += bv; return bi; }; BoundedValue *PointValue::operator-=(const BoundedValue *bv) { BoundedInterval *bi = new BoundedInterval(val, val); *bi -= bv; return bi; }; BoundedValue *PointValue::operator*=(const BoundedValue *bv) { BoundedInterval *bi = new BoundedInterval(val, val); *bi *= bv; return bi; }; BoundedValue *PointValue::operator/=(const BoundedValue *bv) { BoundedInterval *bi = new BoundedInterval(val, val); *bi /= bv; return bi; }; BoundedValue *PlanGraph::update(BoundedValue *bv, const VAL::expression *exp, const VAL::assign_op op, VAL::FastEnvironment *fe) { BVEvaluator bve(*this, fe); exp->visit(&bve); BoundedValue *b = bve.getBV(); cout << "Evaluated to " << *b << "\n"; switch (op) { case E_ASSIGN: bv = b->copy(); break; case E_INCREASE: if (bve.isContinuous()) { if (!b->gotLB() || b->getLB() < 0) { bv = bv->infLower(); }; if (!b->gotUB() || b->getUB() > 0) { bv = bv->infUpper(); }; } else { bv = (*bv += b); }; break; case E_DECREASE: if (bve.isContinuous()) { if (!b->gotLB() || b->getLB() < 0) { bv = bv->infUpper(); }; if (!b->gotUB() || b->getUB() > 0) { bv = bv->infLower(); }; } else { bv = (*bv -= b); }; break; case E_SCALE_UP: bv = (*bv *= b); break; case E_SCALE_DOWN: bv = (*bv /= b); break; default: break; }; delete b; return bv; }; void Constraint::write(ostream &o) const { o << *bval; }; void InitialValue::write(ostream &o) const { o << "Initially " << *bval; }; void UpdateValue::write(ostream &o) const { o << "Updated by " << *(updater->getIO()) << " at " << (updater->getWhen()) //<< " with effect: " << *exp << " to " << *bval; }; void FluentEntry::addUpdatedBy(ActEntry *ae, const VAL::expression *expr, const VAL::assign_op op, PlanGraph *pg) { cout << "Performing BV calc on " << *bval << "\n"; BoundedValue *vv = bval->copy(); BoundedValue *v = pg->update(vv, expr, op, ae->getIO()->getEnv()); cout << "Got " << *v << "\n"; if (vv != v) { delete vv; }; Constraint *c = new UpdateValue(ae, expr, op, v); constrs.push_back(c); if (!tmpaccum) { tmpaccum = bval->copy(); }; cout << "tmpaccum is " << *tmpaccum << "\n"; BoundedValue *nv = tmpaccum->accum(v); if (nv != tmpaccum) { delete tmpaccum; }; tmpaccum = nv; }; BoundedValue *PointValue::accum(const BoundedValue *bv) { if (bv->contains(val)) { return bv->copy(); } else { BoundedValue *b = new BoundedInterval(val, val); b->accum(bv); return b; }; }; PlanGraph::PlanGraph(GraphFactory *f) : myFac(f), inactive(instantiatedOp::opsBegin(), instantiatedOp::opsEnd()) { // Set up the initial state in the proposition spike... for (pc_list< simple_effect * >::const_iterator i = current_analysis->the_problem->initial_state->add_effects.begin(); i != current_analysis->the_problem->initial_state->add_effects.end(); ++i) { Literal lit((*i)->prop, 0); Literal *lit1 = instantiatedOp::getLiteral(&lit); PropEntry *p = myFac->makePropEntry(lit1); props.addEntry(p); }; props.finishedLevel(); for (pc_list< assignment * >::const_iterator i = current_analysis->the_problem->initial_state->assign_effects .begin(); i != current_analysis->the_problem->initial_state->assign_effects.end(); ++i) { PNE pne((*i)->getFTerm(), 0); PNE *pne1 = instantiatedOp::getPNE(&pne); FluentEntry *fl = myFac->makeFluentEntry(pne1); fluents.addEntry(fl); fl->addInitial( (EFT(pne1->getHead())->getInitial(pne1->begin(), pne1->end())) .second); }; fluents.finishedLevel(); // copy(instantiatedOp::opsBegin(),instantiatedOp::opsEnd(),front_inserter(inactive)); }; Constraint::~Constraint() { delete bval; }; void FluentEntry::transferValue() { if (!tmpaccum) return; delete bval; bval = tmpaccum; tmpaccum = 0; }; struct IteratingActionChecker : public VisitController { bool iterating; IteratingActionChecker() : iterating(false){}; virtual void visit_forall_effect(forall_effect *fa) { cout << "Not handling for all effects yet (IteratingActionChecker)!\n"; }; virtual void visit_cond_effect(cond_effect *) { cout << "Not handling conditional effects yet (IteratingActionChecker)!\n"; }; // virtual void visit_timed_effect(timed_effect *) {}; virtual void visit_effect_lists(effect_lists *effs) { for (VAL::pc_list< assignment * >::iterator i = effs->assign_effects.begin(); i != effs->assign_effects.end(); ++i) { (*i)->visit(this); }; }; virtual void visit_assignment(assignment *a) { switch (a->getOp()) { case E_INCREASE: case E_DECREASE: case E_SCALE_UP: case E_SCALE_DOWN: iterating = true; default: break; }; }; }; void DurationHolder::readDurations(const string &nm) { std::ifstream dursFile(nm.c_str()); string a; string ax; string s; dursFile >> a; ax = a; vector< int > args; while (!dursFile.eof()) { dursFile >> s; if (s == "=") { relevantArgs[a] = args; args.clear(); double d; dursFile >> d; dursFor[ax] = new DurationConstraint(new PointValue(d)); dursFile >> a; ax = a; } else { int arg; dursFile >> arg; args.push_back(arg); ax += " "; ax += s; }; }; }; DurationHolder ActEntry::dursFor; void DurationConstraint::write(ostream &o) const { o << "Duration for "; if (start) o << *(start->getIO()) << " "; if (inv) o << *(inv->getIO()) << " "; if (end) o << *(end->getIO()) << " "; o << "is " << *bval; }; DurationConstraint *DurationHolder::lookUp(const string &nm, instantiatedOp *io) { vector< int > args = relevantArgs[nm]; string s = nm; for (vector< int >::iterator i = args.begin(); i != args.end(); ++i) { s += " "; s += io->getArg(*i)->getName(); }; return dursFor[s]; }; ActEntry::ActEntry(instantiatedOp *io) : theact(io), iterating(false), atype(ATOMIC), dur(0) { IteratingActionChecker iac; io->forOp()->effects->visit(&iac); iterating = iac.iterating; string s = io->forOp()->name->getName(); if (s.length() < 6) return; string tl = s.substr(s.length() - 4, 4); if (tl == "-inv") { cout << "Found an invariant action " << *io << "\n"; atype = INV; tl = s.substr(0, s.length() - 4); dur = dursFor.lookUp(tl, io); dur->setInv(this); } else if (tl == "-end") { cout << "Found an end action " << *io << "\n"; atype = END; tl = s.substr(0, s.length() - 4); dur = dursFor.lookUp(tl, io); dur->setEnd(this); } else if (s.length() > 6 && s.substr(s.length() - 6, 6) == "-start") { cout << "Found a start action " << *io << "\n"; atype = START; tl = s.substr(0, s.length() - 6); dur = dursFor.lookUp(tl, io); dur->setStart(this); }; }; bool PlanGraph::extendPlanGraph() { for (vector< ActEntry * >::iterator i = iteratingActs.begin(); i != iteratingActs.end(); ++i) { iterateEntry(*i); }; bool levelOut = true; for (InstOps::iterator i = inactive.begin(); i != inactive.end();) { cout << "Considering: " << **i << "\n"; if (activated((*i))) { ActEntry *io = acts.addEntry(myFac->makeActEntry((*i))); cout << "Activated: " << (*(*i)) << "\n"; activateEntry(io); InstOps::iterator j = i; ++i; inactive.erase(j); levelOut = false; } else ++i; } // Determine which actions are now activated and add them to spike. // // Then add their postconditions to the proposition spike, ensuring we only // add new ones. acts.finishedLevel(); props.finishedLevel(); fluents.finishedLevel(); for (Spike< FluentEntry >::SpikeIterator i = fluents.begin(); i != fluents.end(); ++i) { (*i)->transferValue(); }; return levelOut; }; void PlanGraph::extendToGoals() { VAL::FastEnvironment bs(0); while (true) { extendPlanGraph(); SpikeEvaluator spiv(*this, props, fluents, &bs); current_analysis->the_problem->the_goal->visit(&spiv); if (spiv.getEvaluation()) break; }; }; void PlanGraph::iterateEntry(ActEntry *io) { for (instantiatedOp::PNEEffectsIterator e = io->getIO()->PNEEffectsBegin(); e != io->getIO()->PNEEffectsEnd(); ++e) { FluentEntry *eid = fluents.find((*e)); cout << "Fluent effect updated: " << (*(*e)) << "\n"; if (!eid) { eid = fluents.addEntry(myFac->makeFluentEntry((*e))); }; eid->addUpdatedBy(io, e.getUpdate(), e.getOp(), this); io->addUpdates(eid); } }; void PlanGraph::activateEntry(ActEntry *io) { for (instantiatedOp::PropEffectsIterator e = io->getIO()->addEffectsBegin(); e != io->getIO()->addEffectsEnd(); ++e) { PropEntry *eid = props.find((*e)); if (!eid) { eid = props.addEntry(myFac->makePropEntry((*e))); cout << "Prop effect added: " << (*(*e)) << "\n"; }; eid->addAchievedBy(io); io->addAchieves(eid); } for (instantiatedOp::PropEffectsIterator e = io->getIO()->delEffectsBegin(); e != io->getIO()->delEffectsEnd(); ++e) { PropEntry *eid = props.find((*e)); if (!eid) { eid = props.addEntry(myFac->makePropEntry((*e))); cout << "Prop effect deleted: " << (*(*e)) << "\n"; } eid->addDeletedBy(io); io->addDeletes(eid); } iterateEntry(io); SpikeSupporter spipp(props, fluents, io->getIO()->getEnv(), io, myFac); io->getIO()->forOp()->visit(&spipp); if (io->isIterating()) { iteratingActs.push_back(io); }; }; // Method to check whether an action is to be activated at a given level. bool PlanGraph::activated(instantiatedOp *io) { SpikeEvaluator spiv(*this, props, fluents, io->getEnv()); io->forOp()->visit(&spiv); return spiv.getEvaluation(); } void ActEntry::write(ostream &o) const { o << *theact; if (atype != ATOMIC && dur) { o << " " << *dur; }; }; void PlanGraph::write(ostream &o) const { o << "Propositions:\n"; props.write(o); o << "Actions:\n"; acts.write(o); o << "Fluents:\n"; fluents.write(o); }; int PropEntry::counter = 0; bool ActEntry::isActivated(const vector< bool > &actives) const { for (vector< PropEntry * >::const_iterator i = supports.begin(); i != supports.end(); ++i) { cout << "Checking +" << **i << " = " << actives[(*i)->getID()] << "\n"; if (!actives[(*i)->getID()]) return false; }; for (vector< PropEntry * >::const_iterator i = negSupports.begin(); i != negSupports.end(); ++i) { cout << "Checking -" << **i << " = " << actives[(*i)->getID()] << "\n"; if (actives[(*i)->getID()]) return false; }; return true; }; bool ActEntry::isActivated(Validator *v, const State *s) const { Evaluator ev(v, s, theact); theact->forOp()->visit(&ev); return ev(); }; bool ActEntry::isRelevant(Validator *v, const State *s) const { Evaluator ev(v, s, theact, true); theact->forOp()->visit(&ev); return ev(); }; vector< ActEntry * > PlanGraph::applicableActions(Validator *v, const State *s) { int lastActiveLayer = 0; for (State::const_iterator i = s->begin(); i != s->end(); ++i) { Literal *lit = toLiteral(*i); PropEntry *pe = props.findInAll(lit); lastActiveLayer = std::max(lastActiveLayer, pe->getWhen()); }; vector< ActEntry * > actives; for (Spike< ActEntry >::SpikeIterator i = acts.begin(); i != acts.toLevel(lastActiveLayer); ++i) { cout << "Considering " << **i << "\n"; if ((*i)->isActivated(v, s)) { actives.push_back(*i); }; }; return actives; /* This version was used to translate a State into a vector of bools * that could be used for reference against preconditions. * The problem is that it doesn't handle metric expressions, so we * have switched to evaluation in the state. * vector<bool> activations(props.size(),false); int lastActiveLayer = 0; for(State::const_iterator i = s->begin();i != s->end();++i) { Literal * lit = toLiteral(*i); PropEntry * pe = props.findInAll(lit); activations[pe->getID()] = true; cout << "Set " << *pe << " active\n"; lastActiveLayer = std::max(lastActiveLayer,pe->getWhen()); }; vector<ActEntry *> actives; for(Spike<ActEntry>::SpikeIterator i = acts.begin();i != acts.toLevel(lastActiveLayer);++i) { cout << "Considering " << **i << "\n"; if((*i)->isActivated(activations)) { actives.push_back(*i); }; }; return actives; */ }; vector< ActEntry * > PlanGraph::relevantActions(Validator *v, const State *s) { int lastActiveLayer = 0; for (State::const_iterator i = s->begin(); i != s->end(); ++i) { Literal *lit = toLiteral(*i); PropEntry *pe = props.findInAll(lit); lastActiveLayer = std::max(lastActiveLayer, pe->getWhen()); }; vector< ActEntry * > actives; for (Spike< ActEntry >::SpikeIterator i = acts.begin(); i != acts.toLevel(lastActiveLayer); ++i) { // cout << "Considering " << **i << "\n"; if ((*i)->isRelevant(v, s)) { actives.push_back(*i); }; }; return actives; }; }; // namespace Inst
29.621053
122
0.535142
teyssieuman
0b7280055691a15afa962c7c470639c63a20a9c9
2,943
cpp
C++
code_blocks/checking_statistics/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
12
2020-01-20T14:22:18.000Z
2022-01-26T04:41:36.000Z
code_blocks/checking_statistics/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
1
2020-05-23T07:35:03.000Z
2020-05-23T07:35:03.000Z
code_blocks/checking_statistics/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
9
2019-11-02T19:01:55.000Z
2021-07-08T21:51:44.000Z
#include <iostream> #include "xtechnical_statistics.hpp" #include <array> #include <vector> int main() { std::cout << "Hello world!" << std::endl; std::array<double,6> test_data = {3,8,10,17,24,27}; double median_absolute_deviation_value = xtechnical_statistics::calc_median_absolute_deviation<double>(test_data); std::cout << "median absolute deviation value: " << median_absolute_deviation_value << std::endl; double median_value = xtechnical_statistics::calc_median<double>(test_data); std::cout << "median value: " << median_value << std::endl; double harmonic_mean = xtechnical_statistics::calc_harmonic_mean<double>(test_data); std::cout << "harmonic mean: " << harmonic_mean << std::endl; double mean_value = xtechnical_statistics::calc_mean_value<double>(test_data); std::cout << "mean value: " << mean_value << std::endl; double skewness = xtechnical_statistics::calc_skewness<double>(test_data); std::cout << "skewness: " << skewness << std::endl; double snr = xtechnical_statistics::calc_signal_to_noise_ratio<double>(test_data); std::cout << "snr: " << snr << std::endl; std::array<double,6> test_data2 = {1.1,1.1,1.1,1.1,1.1,1.1}; double geometric_mean = xtechnical_statistics::calc_geometric_mean<double>(test_data2); std::cout << "geometric mean: " << geometric_mean << std::endl; std::array<double,3> test_out; std::vector<double> test_data3 = {1.1,1.1,1.1,1.1,1.1,1.1}; test_out[0] = xtechnical_statistics::calc_median<double>(test_data3); std::cout << "median: " << test_out[0] << std::endl; std::vector<double> test_data4 = {1,1,2,2,3,3,4,5,6,7}; double excess = xtechnical_statistics::calc_excess<double>(test_data4); std::cout << "excess: " << excess << std::endl; std::vector<double> test_data5 = {1,1,1,0,0,1}; double standard_error = xtechnical_statistics::calc_standard_error<double>(test_data5); std::cout << "standard_error: " << standard_error << std::endl; double integral_laplace = xtechnical_statistics::calc_integral_laplace<double>(0.01, 0.00001); std::cout << "integral_laplace: " << integral_laplace << std::endl; double integral_laplace2 = xtechnical_statistics::calc_integral_laplace<double>(1.51, 0.01); std::cout << "integral_laplace2: " << integral_laplace2 << std::endl; double p_bet = xtechnical_statistics::calc_probability_winrate<double>(0.6, 31, 44); std::cout << "p_bet: " << p_bet << std::endl; // получим ответ 93.6 p_bet = xtechnical_statistics::calc_probability_winrate<double>(0.56, 5700, 10000); std::cout << "p_bet: " << p_bet << std::endl; p_bet = xtechnical_statistics::calc_probability_winrate<double>(0.54, 5700, 10000); std::cout << "p_bet: " << p_bet << std::endl; p_bet = xtechnical_statistics::calc_probability_winrate<double>(0.57, 1, 1); std::cout << "p_bet (1): " << p_bet << std::endl; return 0; }
44.590909
118
0.684336
rafald
0b7292b705f65f8ad3e92805d9232cea1c4d9624
458
cpp
C++
p/videojoiner/cv.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/videojoiner/cv.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
p/videojoiner/cv.cpp
jose-lp/docker-ie0521
e2c471bdc79fd94cb6dca4fe0cecc3ab2a649d7d
[ "MIT" ]
null
null
null
#include "cv.h" #include <opencv2/opencv.hpp> void cvWindow(const char *name, int x, int y, int w, int h) { namedWindow(name, CV_WINDOW_NORMAL | CV_GUI_NORMAL); moveWindow(name, x, y); resizeWindow(name, w, h); } void msgBox(const char *msg) { Mat win = Mat::zeros(200, 1200, CV_8UC1); putText(win, msg, Point(50,50), FONT_HERSHEY_COMPLEX, 1, 255, 2); imshow("Mensaje", win); moveWindow("Mensaje", 500, 0); waitKey(); destroyWindow("Mensaje"); }
24.105263
66
0.683406
jose-lp
0b7841561a34404b668d78abbb27f69031de463e
5,918
cpp
C++
iotsa433ReceiveForwarder.cpp
cwi-dis/iotsa433
cd634342de50881ed9105f2c3e40e26793d866cc
[ "MIT" ]
null
null
null
iotsa433ReceiveForwarder.cpp
cwi-dis/iotsa433
cd634342de50881ed9105f2c3e40e26793d866cc
[ "MIT" ]
null
null
null
iotsa433ReceiveForwarder.cpp
cwi-dis/iotsa433
cd634342de50881ed9105f2c3e40e26793d866cc
[ "MIT" ]
null
null
null
#include "iotsa.h" #include "iotsa433ReceiveForwarder.h" #include <RCSwitch.h> bool Iotsa433ReceiveForwarder::configLoad(IotsaConfigFileLoad& cf, const String& f_name) { bool ok = IotsaRequest::configLoad(cf, f_name); if (!ok) return false; cf.get(f_name + ".telegram_tristate", telegram_tristate, ""); cf.get(f_name + ".brand", brand, ""); cf.get(f_name + ".group", group, ""); cf.get(f_name + ".appliance", appliance, ""); cf.get(f_name + ".state", state, ""); cf.get(f_name + ".parameters", parameters, false); return true; } void Iotsa433ReceiveForwarder::configSave(IotsaConfigFileSave& cf, const String& f_name) { IotsaRequest::configSave(cf, f_name); cf.put(f_name + ".telegram_tristate", telegram_tristate); cf.put(f_name + ".brand", brand); cf.put(f_name + ".group", group); cf.put(f_name + ".appliance", appliance); cf.put(f_name + ".state", state); cf.put(f_name + ".parameters", (int)parameters); } void Iotsa433ReceiveForwarder::formHandler_TH(String& message, bool includeConfig) { IotsaRequest::formHandler_TH(message, includeConfig); message += "<th>telegram_tristate</th><th>brand</th><th>group</th><th>appliance</th><th>state</th><th>parameters?</th>"; } void Iotsa433ReceiveForwarder::formHandler_emptyfields(String& message) { IotsaRequest::formHandler_emptyfields(message); message += "Filter on telegram_tristate: <input name='telegram_tristate'><br>"; message += "Filter on brand: <input name='brand'><br>"; message += "Filter on group: <input name='group'><br>"; message += "Filter on appliance: <input name='appliance'><br>"; message += "Filter on state: <input name='state'><br>"; message += "Add parameters to URL on reception: <input type='checkbox' name='parameters' value='1'><br>"; } void Iotsa433ReceiveForwarder::formHandler_fields(String& message, const String& text, const String& f_name, bool includeConfig) { IotsaSerial.println("Iotsa433ReceiveForwarder::formHandler not implemented"); } void Iotsa433ReceiveForwarder::formHandler_TD(String& message, bool includeConfig) { IotsaRequest::formHandler_TD(message, includeConfig); message += "<td>"; message += telegram_tristate; message += "</td><td>"; message += brand; message += "</td><td>"; message += group; message += "</td><td>"; message += appliance; message += "</td><td>"; message += state; message += "</td><td>"; message += String((int)parameters); message += "</td>"; } #ifdef IOTSA_WITH_WEB bool Iotsa433ReceiveForwarder::formHandler_args(IotsaWebServer *server, const String& f_name, bool includeConfig) { if (f_name != "") IotsaSerial.println("Iotsa433ReceiveForwarder::formHandler_args got unexpected name argument"); bool anyChanged = IotsaRequest::formHandler_args(server, f_name, includeConfig); if (server->hasArg("telegram_tristate")) { telegram_tristate = server->arg("telegram_tristate"); anyChanged = true; } if (server->hasArg("brand")) { brand = server->arg("brand"); anyChanged = true; } if (server->hasArg("group")) { group = server->arg("group"); anyChanged = true; } if (server->hasArg("appliance")) { appliance = server->arg("appliance"); anyChanged = true; } if (server->hasArg("state")) { state = server->arg("state"); anyChanged = true; } if (server->hasArg("parameters")) { String parameterString = server->arg("parameters"); parameters = parameterString != "" && parameterString != "0"; anyChanged = true; } return anyChanged; } #endif #ifdef IOTSA_WITH_API void Iotsa433ReceiveForwarder::getHandler(JsonObject& reply) { IotsaRequest::getHandler(reply); reply["telegram_tristate"] = telegram_tristate; reply["brand"] = brand; reply["group"] = group; reply["appliance"] = appliance; reply["state"] = state; reply["parameters"] = parameters; } bool Iotsa433ReceiveForwarder::putHandler(const JsonVariant& request) { if (!request.is<JsonObject>()) return false; if (!IotsaRequest::putHandler(request)) return false; bool any = false; const JsonObject& reqObj = request.as<JsonObject>(); if (reqObj.containsKey("telegram_tristate")) { any = true; telegram_tristate = reqObj["telegram_tristate"].as<String>(); } if (reqObj.containsKey("brand")) { any = true; brand = reqObj["brand"].as<String>(); } if (reqObj.containsKey("group")) { any = true; group = reqObj["group"].as<String>(); } if (reqObj.containsKey("appliance")) { any = true; appliance = reqObj["appliance"].as<String>(); } if (reqObj.containsKey("state")) { any = true; state = reqObj["state"].as<String>(); } if (reqObj.containsKey("parameters")) { any = true; parameters = reqObj["parameters"].as<bool>(); } return any; } #endif bool Iotsa433ReceiveForwarder::matches(String& _tristate, String& _brand, String& _group, String& _appliance, String& _state) { if (telegram_tristate != "" && _tristate != telegram_tristate) return false; if (brand != "" && _brand != brand) return false; if (group != "" && _group != group) return false; if (appliance != "" && _appliance != appliance) return false; if (state != "" && _state != state) return false; return true; } bool Iotsa433ReceiveForwarder::send(String& _tristate, String& _brand, String& _group, String& _appliance, String& _state) { // This forwarder applies to this appliance press. const char *query = NULL; String queryStore; if (parameters) { if (_brand != "" && _group != "") { queryStore = "brand=" + _brand + "&group=" + _group + "&appliance=" + _appliance + "&state=" + _state; } else { queryStore = "telegram_tristate=" + _tristate; } // xxxjack should send binary if triState unavailable query = queryStore.c_str(); } IFDEBUG IotsaSerial.print("433recv: GET "); IFDEBUG IotsaSerial.println(url); bool ok = IotsaRequest::send(query); return ok; }
35.650602
130
0.677932
cwi-dis
0b795796369fa5c52e057bc4e67e18c8c0111f7c
404
cpp
C++
source/PyMaterialX/PyMaterialXGenOgsXml/PyModule.cpp
muenstc/MaterialX
b8365086a738fddae683065d78f65410aacd0dc4
[ "BSD-3-Clause" ]
101
2017-08-08T12:08:01.000Z
2022-03-17T06:37:58.000Z
source/PyMaterialX/PyMaterialXGenOgsXml/PyModule.cpp
testpassword/MaterialX
7c69782196b11fa43c67aee0707801983bb81e6c
[ "BSD-3-Clause" ]
1,002
2018-01-09T10:33:07.000Z
2022-03-31T18:35:04.000Z
source/PyMaterialX/PyMaterialXGenOgsXml/PyModule.cpp
testpassword/MaterialX
7c69782196b11fa43c67aee0707801983bb81e6c
[ "BSD-3-Clause" ]
24
2018-01-05T20:16:36.000Z
2022-02-03T15:40:14.000Z
// // TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <PyMaterialX/PyMaterialX.h> namespace py = pybind11; void bindPyOgsFragment(py::module& mod); PYBIND11_MODULE(PyMaterialXGenOgsXml, mod) { mod.doc() = "Module containing Python bindings for the MaterialXGenOgsXml library"; bindPyOgsFragment(mod); }
22.444444
87
0.742574
muenstc
0b7a364391459c9607fb675102d570ae65003254
8,254
cpp
C++
Test.cpp
dolevsaadia/wargame
a9fecab767337fe8b42d3712becdcfcf4c9507b2
[ "MIT" ]
null
null
null
Test.cpp
dolevsaadia/wargame
a9fecab767337fe8b42d3712becdcfcf4c9507b2
[ "MIT" ]
null
null
null
Test.cpp
dolevsaadia/wargame
a9fecab767337fe8b42d3712becdcfcf4c9507b2
[ "MIT" ]
null
null
null
#include "doctest.h" #include "FootSoldier.hpp" #include "FootCommander.hpp" #include"Paramedic.hpp" #include"ParamedicCommander.hpp" #include"Sniper.hpp" #include"SniperCommander.hpp" #include "Board.hpp" #include <iostream> using namespace std; namespace WarGame{ TEST_CASE("Test-1-soldiers") { Board board(8,8); CHECK(board.has_soldiers(1)==false); board[{0,0}] = new FootSoldier(1); board[{0,1}] = new FootSoldier(1); board[{0,2}] = new SniperCommander(1); board[{0,3}] = new FootCommander(1); board[{0,4}] = new FootSoldier(1); board[{0,5}] = new Sniper(1); board[{0,6}] = new ParamedicCommander(1); board[{0,7}] = new Paramedic(1); CHECK(board.has_soldiers(1)==true); CHECK(board.has_soldiers(2)==false); board[{7,0}] = new FootSoldier(2); board[{7,1}] = new FootSoldier(2); board[{7,2}] = new SniperCommander(2); board[{7,3}] = new FootCommander(2); board[{7,4}] = new FootSoldier(2); board[{7,5}] = new Sniper(2); board[{7,6}] = new ParamedicCommander(2); board[{7,7}] = new Paramedic(2); CHECK(board.has_soldiers(2)==true); CHECK(board[{0,0}]->_numOfplayer == 1); CHECK(board[{0,1}]->_numOfplayer == 1); CHECK(board[{0,2}]->_numOfplayer == 1); CHECK(board[{0,3}]->_numOfplayer == 1); CHECK(board[{0,4}]->_numOfplayer == 1); CHECK(board[{0,5}]->_numOfplayer == 1); CHECK(board[{0,6}]->_numOfplayer == 1); CHECK(board[{0,7}]->_numOfplayer == 1); CHECK(board[{7,0}]->_numOfplayer == 2); CHECK(board[{7,1}]->_numOfplayer == 2); CHECK(board[{7,2}]->_numOfplayer == 2); CHECK(board[{7,3}]->_numOfplayer == 2); CHECK(board[{7,4}]->_numOfplayer == 2); CHECK(board[{7,5}]->_numOfplayer == 2); CHECK(board[{7,6}]->_numOfplayer == 2); CHECK(board[{7,7}]->_numOfplayer == 2); CHECK(board[{0,2}]->_life == 120);//SniperCommander CHECK(board[{0,3}]->_life == 150);//FootCommander CHECK(board[{0,4}]->_life == 100);//FootSoldier CHECK(board[{0,5}]->_life == 100);//Sniper CHECK(board[{0,6}]->_life == 200);//ParamedicCommander CHECK(board[{0,7}]->_life == 100);//Paramedic CHECK(board[{0,2}]->_attack == 100);//SniperCommander CHECK(board[{0,3}]->_attack == 20);//FootCommander CHECK(board[{0,4}]->_attack == 10);//FootSoldier CHECK(board[{0,5}]->_attack == 50);//Sniper CHECK(board[{0,6}]->_attack == 0);//ParamedicCommander CHECK(board[{0,7}]->_attack == 0);//Paramedic CHECK(board[{7,2}]->_life == 120);//SniperCommander CHECK(board[{7,3}]->_life == 150);//FootCommander CHECK(board[{7,4}]->_life == 100);//FootSoldier CHECK(board[{7,5}]->_life == 100);//Sniper CHECK(board[{7,6}]->_life == 200);//ParamedicCommander CHECK(board[{7,7}]->_life == 100);//Paramedic CHECK(board[{7,2}]->_attack == 100);//SniperCommander CHECK(board[{7,3}]->_attack == 20);//FootCommander CHECK(board[{7,4}]->_attack == 10);//FootSoldier CHECK(board[{7,5}]->_attack == 50);//Sniper CHECK(board[{7,6}]->_attack == 0);//ParamedicCommander CHECK(board[{7,7}]->_attack == 0);//Pa board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); //59 } TEST_CASE("Test -2-soldiers") { Board board(10,10); CHECK(board.has_soldiers(1)==false); board[{0,0}] = new FootSoldier(1); board[{0,1}] = new FootSoldier(1); board[{0,2}] = new SniperCommander(1); board[{0,3}] = new FootCommander(1); board[{0,4}] = new FootSoldier(1); board[{0,5}] = new Sniper(1); board[{0,6}] = new ParamedicCommander(1); board[{0,7}] = new Paramedic(1); board[{0,8}] = new Paramedic(1); board[{0,9}] = new Sniper(1); board[{5,0}] = new FootSoldier(1); board[{1,0}] = new FootSoldier(1); CHECK(board.has_soldiers(1)==true); CHECK(board.has_soldiers(2)==false); board[{7,0}] = new FootSoldier(2); board[{7,1}] = new FootSoldier(2); board[{7,2}] = new SniperCommander(2); board[{7,3}] = new FootCommander(2); board[{1,3}] = new FootCommander(2); board[{4,3}] = new FootCommander(2); board[{7,4}] = new FootSoldier(2); board[{7,5}] = new Sniper(2); board[{7,6}] = new ParamedicCommander(2); board[{7,7}] = new Paramedic(2); board[{5,6}] = new ParamedicCommander(2); board[{6,7}] = new Paramedic(2); board[{6,6}] = new ParamedicCommander(2); CHECK(board.has_soldiers(2)==true); CHECK(board[{0,0}]->_numOfplayer == 1); CHECK(board[{0,1}]->_numOfplayer == 1); CHECK(board[{0,2}]->_numOfplayer == 1); CHECK(board[{0,3}]->_numOfplayer == 1); CHECK(board[{0,4}]->_numOfplayer == 1); CHECK(board[{0,5}]->_numOfplayer == 1); CHECK(board[{0,6}]->_numOfplayer == 1); CHECK(board[{0,7}]->_numOfplayer == 1); CHECK(board[{5,0}]->_numOfplayer == 1); CHECK(board[{1,0}]->_numOfplayer == 1); // CHECK(board[{6,5}]->_numOfplayer == 2); CHECK(board[{6,6}]->_numOfplayer == 2); CHECK(board[{6,7}]->_numOfplayer == 2); CHECK(board[{7,0}]->_numOfplayer == 2); CHECK(board[{7,1}]->_numOfplayer == 2); CHECK(board[{7,2}]->_numOfplayer == 2); CHECK(board[{7,3}]->_numOfplayer == 2); CHECK(board[{7,4}]->_numOfplayer == 2); CHECK(board[{7,5}]->_numOfplayer == 2); CHECK(board[{7,6}]->_numOfplayer == 2); CHECK(board[{7,7}]->_numOfplayer == 2); CHECK(board[{5,0}]->_life == 100);//FootSoldier CHECK(board[{1,0}]->_life == 100);//FootSoldier CHECK(board[{0,2}]->_life == 120);//SniperCommander CHECK(board[{0,3}]->_life == 150);//FootCommander CHECK(board[{0,4}]->_life == 100);//FootSoldier CHECK(board[{0,5}]->_life == 100);//Sniper CHECK(board[{0,6}]->_life == 200);//ParamedicCommander CHECK(board[{0,7}]->_life == 100);//Paramedic CHECK(board[{5,0}]->_attack == 10);//FootSoldier CHECK(board[{1,0}]->_attack == 10);//FootSoldier CHECK(board[{0,2}]->_attack == 100);//SniperCommander CHECK(board[{0,3}]->_attack == 20);//FootCommander CHECK(board[{0,4}]->_attack == 10);//FootSoldier CHECK(board[{0,5}]->_attack == 50);//Sniper CHECK(board[{0,6}]->_attack == 0);//ParamedicCommander CHECK(board[{0,7}]->_attack == 0);//Paramedic CHECK(board[{7,2}]->_life == 120);//SniperCommander CHECK(board[{7,3}]->_life == 150);//FootCommander CHECK(board[{7,4}]->_life == 100);//FootSoldier CHECK(board[{7,5}]->_life == 100);//Sniper CHECK(board[{7,6}]->_life == 200);//ParamedicCommander CHECK(board[{7,7}]->_life == 100);//Paramedic CHECK(board[{7,2}]->_attack == 100);//SniperCommander CHECK(board[{7,3}]->_attack == 20);//FootCommander CHECK(board[{7,4}]->_attack == 10);//FootSoldier CHECK(board[{7,5}]->_attack == 50);//Sniper CHECK(board[{7,6}]->_attack == 0);//ParamedicCommander CHECK(board[{7,7}]->_attack == 0);//Pa } };
32.242188
57
0.577417
dolevsaadia
0b7c14cb211d72dc1d324f42da9f1712af30bea4
1,447
cpp
C++
TreeSection.cpp
Scaarj/HappyNewYear
38a373e939c8aed400001914e283cc918c4cfa44
[ "MIT" ]
null
null
null
TreeSection.cpp
Scaarj/HappyNewYear
38a373e939c8aed400001914e283cc918c4cfa44
[ "MIT" ]
null
null
null
TreeSection.cpp
Scaarj/HappyNewYear
38a373e939c8aed400001914e283cc918c4cfa44
[ "MIT" ]
null
null
null
#include "TreeSection.h" #include <boost/range/adaptors.hpp> #include <cmath> #include "Pattern.h" #include "TreeLine.h" TreeSection::TreeSection(int offset, int maxWidth, int start) { for (int i = start; i < ceil(maxWidth / 2) + 1; ++i) { int treeItemCount = i * 2 + 1; _lines.push_back( std::make_unique<TreeLine>(offset, maxWidth, treeItemCount)); } } TreeSection::TreeSection(const TreeSection &other) { _lines.reserve(other._lines.size()); for (const auto &it : other._lines) { _lines.push_back(it->clone()); } } TreeSection &TreeSection::operator=(const TreeSection &other) { return *this; } void TreeSection::print() { for (const auto &it : _lines) { it->print(); } } int TreeSection::overall(const std::vector<std::unique_ptr<Symbol>> &items) { int sum = 0; for (const auto &it : _lines) { sum += it->overall(items); } return sum; } void TreeSection::decorate(int count) { int sum = overall(Pattern::tree()); int tempCount = count; for (const auto &it : boost::adaptors::reverse(_lines)) { int linesSum = it->overall(Pattern::tree()); float ratio = static_cast<float>(linesSum) / sum; int joyToSection = ceil(ratio * count); if (joyToSection > tempCount) { joyToSection = tempCount; } tempCount -= joyToSection; it->decorate(joyToSection); } } std::unique_ptr<Item> TreeSection::clone() { return std::make_unique<TreeSection>(*this); }
24.948276
79
0.658604
Scaarj
0b7cd1510054f5ea3ff5ac021bdb5363e25366d6
2,964
cpp
C++
gecode/global_contiguity.cpp
Wikunia/hakank
030bc928d2efe8dcbc5118bda3f8ae9575d0fd13
[ "MIT" ]
279
2015-01-10T09:55:35.000Z
2022-03-28T02:34:03.000Z
gecode/global_contiguity.cpp
Wikunia/hakank
030bc928d2efe8dcbc5118bda3f8ae9575d0fd13
[ "MIT" ]
10
2017-10-05T15:48:50.000Z
2021-09-20T12:06:52.000Z
gecode/global_contiguity.cpp
Wikunia/hakank
030bc928d2efe8dcbc5118bda3f8ae9575d0fd13
[ "MIT" ]
83
2015-01-20T03:44:00.000Z
2022-03-13T23:53:06.000Z
/* Global constraint global contiguity (decompositions) in Gecode. From Global constraint catalog http://www.emn.fr/x-info/sdemasse/gccat/Cglobal_contiguity.html """ Enforce all variables of the VARIABLES collection to be assigned to 0 or 1. In addition, all variables assigned to value 1 appear contiguously. """ For more about this constraint, see Michael J. Maher: "Analysis of a Global Contiguity Constraint" http://www.cse.unsw.edu.au/~mmaher/pubs/cp/contig.pdf This model implements two variants: 1) An implementation inspired by Toby Walsh's presentation "Sliding Constraints" http://www.cse.unsw.edu.au/~tw/samos/slide.ppt where he defines global cardinality in terms of the global constraint slide. 2) Simply use the regular expression "0*1*0*" Compare with the following models: * MiniZinc: http://www.hakank.org/minizinc/global_contiguity.mzn * Comet : http://www.hakank.org/comet/global_contiguity.co This Gecode model was created by Hakan Kjellerstrand (hakank@gmail.com) Also, see my Gecode page: http://www.hakank.org/gecode/ . */ #include <gecode/driver.hh> #include <gecode/int.hh> #include <gecode/minimodel.hh> using namespace Gecode; class GlobalContiguity : public Script { protected: const int n; // size of problem IntVarArray x; // the array public: enum { MODEL_WALSH, MODEL_REGEXP }; GlobalContiguity(const SizeOptions& opt) : n(opt.size()), x(*this, n, 0, 1) { if (opt.model() == MODEL_WALSH) { /** * * Model inspired by Toby Walsh's presentation * "Sliding Constraints" * http://www.cse.unsw.edu.au/~tw/samos/slide.ppt * */ IntVarArray y(*this, n, 0, 2); rel(*this, y, IRT_GQ, opt.icl()); for(int i = 0; i < n; i++) { rel(*this, (y[i] == 1) == (x[i] == 1), opt.icl()); } } else { /** * * Using the regular expression 0*1*0* * */ REG r0(0), r1(1); extensional(*this, x, *r0 + *r1 + *r0); } branch(*this, x, INT_VAR_SIZE_MIN(), INT_VAL_MIN()); } // Print solution virtual void print(std::ostream& os) const { os << "\t" << x << std::endl; } // Constructor for cloning s GlobalContiguity(bool share, GlobalContiguity& s) : Script(share,s), n(s.n) { x.update(*this, share, s.x); } // Copy during cloning virtual Space* copy(bool share) { return new GlobalContiguity(share,*this); } }; int main(int argc, char* argv[]) { SizeOptions opt("GlobalContiguity"); opt.solutions(1); opt.icl(ICL_VAL); opt.model(GlobalContiguity::MODEL_WALSH); opt.model(GlobalContiguity::MODEL_WALSH, "walsh"); opt.model(GlobalContiguity::MODEL_REGEXP, "regexp"); opt.parse(argc,argv); if (!opt.size()) { opt.size(100); } opt.c_d(opt.size()*2); Script::run<GlobalContiguity,DFS,SizeOptions>(opt); return 0; }
21.635036
79
0.633266
Wikunia
0b7d2ea70f3ff9682b259ef39f6d40831309d6cf
8,502
cc
C++
comm/leader_election.cc
wahidHarb/rdp-1
73a0813d9a08f0aad34b56ba678167e6387b5e74
[ "Apache-2.0" ]
112
2018-12-05T07:45:42.000Z
2022-01-24T11:28:11.000Z
comm/leader_election.cc
wahidHarb/rdp-1
73a0813d9a08f0aad34b56ba678167e6387b5e74
[ "Apache-2.0" ]
2
2020-02-29T02:34:59.000Z
2020-05-12T06:34:29.000Z
comm/leader_election.cc
wahidHarb/rdp-1
73a0813d9a08f0aad34b56ba678167e6387b5e74
[ "Apache-2.0" ]
88
2018-12-16T07:35:10.000Z
2022-03-09T17:41:16.000Z
// //Copyright 2018 vip.com. // //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 "leader_election.h" namespace rdp_comm { LeaderElection::LeaderElection() { zk_ = NULL; exit_flag_ = false; memset(&election_path_stat_, 0, sizeof(election_path_stat_)); working_mode_ = INIT_MODE; pthread_cond_init(&mode_change_cond_, NULL); pthread_mutex_init(&mode_lock_, NULL); } LeaderElection::~LeaderElection() {} bool LeaderElection::Initialize(const string &host, const string &leader_path, const string &leader_info_path) { if (leader_path.empty()) { LOG(ERROR) << "Leader Path: " << leader_path << ", Is Empty"; return false; } if (leader_info_path.empty()) { LOG(ERROR) << "Leader Store Info Path: " << leader_info_path << ", Is Empty"; return false; } this->host_ = host; this->zk_ = &Singleton<ZKProcess>::GetInstance(); this->leader_path_ = leader_path; this->leader_info_path_ = leader_info_path; this->working_mode_ = FOLLOWER_MODE; this->zk_->SetUserFuncAndCtx(&DefaultCallback, this); // Check the diretory of ephemeral node if (!CheckPath()) { return false; } // Start Election thread if (!Start()) { LOG(ERROR) << "Start LeaderElection thread start Failt"; return false; } LOG(INFO) << "LeaderElection Thread Start"; LOG(INFO) << "Zookeeper session timeout is " << zk_->GetRecvTimeout() << "ms"; // Create ephemeral node if (!CreateElectionNode()) { node_name_.clear(); return false; } // Create watch callback, and the watch will be triggered immediately if (!zk_->WatchChildren(leader_path_, &LeaderElection::ChildrenCallback, this, true)) { LOG(ERROR) << "Watch Path: " << leader_path_ << " Failt"; return false; } return true; } bool LeaderElection::CheckPathExists(const string &path) { // save all nodes path stat, because EphAndSeqNode maybe created return zk_->Exists(path, &election_path_stat_); } bool LeaderElection::CreatePath(const string &path) { return zk_->CreateNode(path, "", true).Ok(); } bool LeaderElection::CreateElectionNode() { if (!CheckPathExists(leader_path_)) { if (!CreatePath(leader_path_)) return false; // Sync path, confirm all zk nodes created if (!zk_->SyncPath(leader_path_)) { LOG(ERROR) << "Election Sync Zookeeper Path: " << leader_path_ << " Failt"; return false; } // Check all election nodes store path and update the election path stat if (!CheckPathExists(leader_path_)) { LOG(ERROR) << "Leader Election All Nodes Store Path: " << leader_path_ << ", Create Failt"; return false; } } string name = leader_path_; // value is the host name, node_name_ store return corrent node name if (!zk_->CreateEphAndSeqNode(name, host_, node_name_).Ok()) { LOG(ERROR) << "Create Leader Node: " << name << " Failt"; return false; } // Sync path, confirm all zk nodes created if (!zk_->SyncPath(node_name_)) { LOG(ERROR) << "Election Sync Zookeeper Path: " << node_name_ << " Failt"; return false; } return true; } void LeaderElection::Run() { char thd_name[16] = {0x0}; snprintf(thd_name, sizeof(thd_name), "election.thd"); rdp_comm::signalhandler::AddThread(pthread_self(), thd_name); WorkingMode old_mode = GetMode(); while (!exit_flag_ && rdp_comm::signalhandler::IsRunning()) { switch (old_mode) { case FOLLOWER_MODE: LOG(INFO) << "I am follower!"; break; case LEADER_MODE: LOG(INFO) << "I am leader!"; if (!SetLeaderInfoValue()) { // If failed, still a leader LOG(ERROR) << "Set leader info: " << leader_info_path_ << " failt"; } break; case SAFE_MODE: LOG(WARNING) << "I am leader in safe mode!"; // TODO: Handle the EINTR // Sleep 0.4 * session timeout LOG(WARNING) << "Going to sleep " << zk_->GetRecvTimeout()*1000*0.4 << " us"; usleep(zk_->GetRecvTimeout()*1000*0.4); if (SAFE_MODE == GetMode()) { LOG(ERROR) << "The zookeeper session is going to expired, exit now"; exit(1); } break; default: LOG(ERROR) << "Unexpected working mode: " << old_mode << ", abort now"; abort(); } // Wait for mode changed, or timeout pthread_mutex_lock(&mode_lock_); while (old_mode == working_mode_) { int zk_timeout = zk_->GetRecvTimeout(); struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += zk_timeout/1000; ts.tv_nsec = (zk_timeout%1000)*1000*1000; if (pthread_cond_timedwait(&mode_change_cond_, &mode_lock_, &ts) == ETIMEDOUT) { break; } } old_mode = working_mode_; pthread_mutex_unlock(&mode_lock_); } // Quit from signal thread rdp_comm::signalhandler::Wait(); return; } bool LeaderElection::CheckPath() { if (!CheckPathExists(leader_path_)) { if (!CreatePath(leader_path_)) { LOG(ERROR) << "Create Leader Path: " << leader_path_ << " Failt"; return false; } } if (!CheckPathExists(leader_info_path_)) { if (!CreatePath(leader_info_path_)) { LOG(ERROR) << "Create Leader Store Info Path: " << leader_info_path_ << " Failt"; return false; } } return true; } bool LeaderElection::SetLeaderInfoValue() const { return zk_->SetData(leader_info_path_, node_name_ + " " + StrTime(NULL)); } void LeaderElection::DefaultCallback(int type, int zk_state, const char *path, void *data) { LeaderElection *leader = static_cast<LeaderElection *>(data); if (ZOO_SESSION_EVENT == type) { if (ZOO_CONNECTING_STATE == zk_state) { // Have no effect on FOLLOWER_MODE if (leader->GetMode() == LEADER_MODE) { LOG(WARNING) << "I enter safe mode!"; leader->SetMode(SAFE_MODE); } } else if (ZOO_CONNECTED_STATE == zk_state) { // Have no effect on FOLLOWER_MODE if (leader->GetMode() == SAFE_MODE) { LOG(WARNING) << "I leave safe mode!"; leader->SetMode(LEADER_MODE); } } else if (ZOO_EXPIRED_SESSION_STATE == zk_state) { LOG(ERROR) << "Zookeeper ession expired, exit now"; exit(1); } else { LOG(ERROR) << "Unkown zookeeper session event, abort now"; abort(); } } } void LeaderElection::ChildrenCallback(const string &path, const vector<string> &children, void *ctx, const struct Stat *stat) { // no node create if (0 >= children.size()) return; assert(NULL != ctx); LeaderElection *leader = static_cast<LeaderElection *>(ctx); // The ephemeral node doesn't exist if (leader->GetNodeName().empty()) { LOG(ERROR) << "The ephemeral node doesn't exist, abort now"; abort(); } long min_child = atol(children[0].c_str()); for (unsigned int i = 0; i < children.size(); ++i) { min_child = min_child > atol(children[i].c_str()) ? atol(children[i].c_str()) : min_child; } string my_name = leader->GetNodeName(); // get my node name`s seq no long my_index = atol(my_name.substr(my_name.length() - children[0].length(), children[0].length()).c_str()); LOG(INFO) << "My Node Name: " << my_index << ", Minimum Sequence Node Name: " << min_child; //如果本节点创建的node的index为最小,则可以提升为leader if (my_index == min_child) { if (leader->IsFollower()) { LOG(INFO) << "I become leader!"; leader->SetMode(LEADER_MODE); } } else { if (leader->IsLeader()) { // Become follwer unexpectly LOG(ERROR) << "Become follower unexpectly, abort now"; abort(); } } } // Return current znode's cversion uint64_t LeaderElection::GetVersion() { return (uint64_t)election_path_stat_.cversion; } } // namespace rdp_comm
29.418685
117
0.626441
wahidHarb
0b7da4117c08905aaa6b33469d0846a312083e4c
4,397
cpp
C++
BlendNode.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
BlendNode.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
BlendNode.cpp
IvarJonsson/Project-Unknown
4675b41bbb5e90135c7bf3aded2c2e262b50f351
[ "BSL-1.0" ]
null
null
null
// Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved. /************************************************************************* ------------------------------------------------------------------------- $Id$ $DateTime$ Description: BlendNodes and BlendGroups for ScreenEffects ------------------------------------------------------------------------- History: - 23:1:2008 Created by Benito G.R. - Refactor'd from John N. ScreenEffects.h/.cpp *************************************************************************/ #include "StdAfx.h" #include "BlendNode.h" #include "BlendTypes.h" #include "BlendedEffect.h" #define MIN_BLEND_GROUP_SIZE 8 //------------------CBlendNode----------------------------- CBlendJobNode::CBlendJobNode(): m_speed(0.0f), m_progress(0.0f), m_myEffect(NULL), m_blendType(NULL) { } //-------------------------------------- void CBlendJobNode::Init(IBlendType* pBlend, IBlendedEffect* pFx, float speed) { m_blendType = pBlend; m_myEffect = pFx; m_speed = speed; } //------------------------------------------------- CBlendJobNode::~CBlendJobNode() { Reset(); } //-------------------------------------------- void CBlendJobNode::Reset() { if(m_myEffect) m_myEffect->Release(); if(m_blendType) m_blendType->Release(); m_myEffect = NULL; m_blendType = NULL; m_speed = m_progress = 0.0f; } //----------------------------------------------- void CBlendJobNode::Update(float frameTime) { float progressDifferential = m_speed * frameTime; m_progress = min(m_progress + progressDifferential, 1.0f); float point = 0.1f; if(m_blendType) point = m_blendType->Blend(m_progress); if(m_myEffect) m_myEffect->Update(point); } //-------------------CBlendGroup---------------------------- CBlendGroup::CBlendGroup(): m_currentJob(-1), m_nextFreeSlot(0), m_activeJobs(0), m_maxActiveJobs(0) { AllocateMinJobs(); } //--------------------------------- CBlendGroup::~CBlendGroup() { for(size_t i=0;i<m_jobs.size();i++) { delete m_jobs[i]; } } //--------------------------------- void CBlendGroup::AllocateMinJobs() { m_jobs.reserve(MIN_BLEND_GROUP_SIZE); for(int i=0;i<MIN_BLEND_GROUP_SIZE;i++) { CBlendJobNode *node = new CBlendJobNode(); m_jobs.push_back(node); } } //---------------------------------------- void CBlendGroup::Update(float frameTime) { int jobsSize = m_jobs.size(); if (m_currentJob>=0 && m_currentJob<jobsSize) { m_jobs[m_currentJob]->Update(frameTime); if (m_jobs[m_currentJob]->Done()) { m_jobs[m_currentJob]->Reset(); m_activeJobs--; if(m_activeJobs>0) { m_currentJob++; if(m_currentJob==jobsSize) m_currentJob = 0; if (m_jobs[m_currentJob]->m_myEffect) m_jobs[m_currentJob]->m_myEffect->Init(); } else { //Reset if there are no more jobs m_currentJob = -1; m_nextFreeSlot = 0; } } } } //-------------------------------------- bool CBlendGroup::HasJobs() { return (m_activeJobs>0); } //--------------------------------------------- void CBlendGroup::AddJob(IBlendType* pBlend, IBlendedEffect* pFx, float speed) { int jobsSize = m_jobs.size(); if(m_activeJobs==jobsSize) { //We need to add another slot CBlendJobNode* newJob = new CBlendJobNode(); newJob->Init(pBlend,pFx,speed); if(m_nextFreeSlot==0) { m_jobs.push_back(newJob); } else { TJobVector::iterator it = m_jobs.begin() + m_nextFreeSlot; m_jobs.insert(it,newJob); m_nextFreeSlot++; } GameWarning("CBlendGroup::AddJob() needs to add a new slot (You might want to reserve more on init). New size: %d",jobsSize+1); m_activeJobs++; } else { m_jobs[m_nextFreeSlot]->Init(pBlend,pFx,speed); m_activeJobs++; m_nextFreeSlot++; if(m_nextFreeSlot==jobsSize) m_nextFreeSlot=0; } if(m_currentJob==-1) { m_currentJob = 0; m_jobs[m_currentJob]->m_myEffect->Init(); } if(m_activeJobs>m_maxActiveJobs) m_maxActiveJobs=m_activeJobs; jobsSize = m_jobs.size(); assert(m_activeJobs>=0 && m_activeJobs<=m_jobs.size() && "CBlendGroup::AddJob() --> 0h, oh!"); } //----------------------------------- void CBlendGroup::Reset() { for(size_t i=0; i<m_jobs.size(); i++ ) { m_jobs[i]->Reset(); m_currentJob = -1; m_nextFreeSlot = 0; m_activeJobs = 0; } } //------------------------------------ void CBlendGroup::GetMemoryUsage(ICrySizer* s) const { s->Add(this); s->AddContainer(m_jobs); }
21.553922
129
0.556516
IvarJonsson
0b7e723f086bb4bfa9946d3dc14ab87dad3e87d8
581
cpp
C++
leetcode/medianSortedMatrix.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
leetcode/medianSortedMatrix.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
null
null
null
leetcode/medianSortedMatrix.cpp
vkashkumar/Competitive-Programming
c457e745208c0ca3e45b1ffce254a21504533f51
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
int Solution::findMedian(vector<vector<int> > &A) { int r=A.size(),c=A[0].size(); int req=(r*c+1)/2; int minm=INT_MAX,maxm=INT_MIN; //finding min and max elemnt in whole matrix for(int i=0;i<r;i++) { minm=min(minm,A[i][0]); maxm=max(maxm,A[i][c-1]); } while(minm<maxm) { int mid=minm+(maxm-minm)/2; int place=0; for(int i=0;i<r;i++) place+=upper_bound(A[i].begin(),A[i].end(),mid)-A[i].begin(); if(place<req) minm=mid+1; else maxm=mid; } return minm; }
24.208333
70
0.502582
vkashkumar
0b7f21f3201d1d09574c61cdcafaa81fd38e5ba9
917
hpp
C++
include/SSVOpenHexagon/Utils/Match.hpp
kiwec/SSVOpenHexagon
a421694146117e6457aadab22358c6be05a71c13
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Utils/Match.hpp
kiwec/SSVOpenHexagon
a421694146117e6457aadab22358c6be05a71c13
[ "AFL-3.0" ]
null
null
null
include/SSVOpenHexagon/Utils/Match.hpp
kiwec/SSVOpenHexagon
a421694146117e6457aadab22358c6be05a71c13
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2020 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #pragma once #include <type_traits> #include <variant> #include <utility> namespace hg::Utils { template <typename... Fs> struct overload_set : Fs... { template <typename... FFwds> constexpr overload_set(FFwds&&... fFwds) : Fs{std::forward<FFwds>(fFwds)}... { } using Fs::operator()...; }; template <typename... Fs> overload_set(Fs...) -> overload_set<Fs...>; template <typename... Fs> constexpr auto make_overload_set(Fs&&... fs) { return overload_set<std::decay_t<Fs>...>{std::forward<Fs>(fs)...}; } template <typename Variant, typename... Fs> constexpr decltype(auto) match(Variant&& v, Fs&&... fs) { return std::visit( make_overload_set(std::forward<Fs>(fs)...), std::forward<Variant>(v)); } } // namespace hg::Utils
21.833333
80
0.652126
kiwec
0b7f7ab32a28370dd95bb868670c9cb65fea0dba
8,442
cpp
C++
test/backend/batch_mat_mul.in.cpp
XReyRobert-IBM/ngraph
8cd9b5da9591f3e096b07ff21d8eaa2d2f0fb06f
[ "Apache-2.0" ]
null
null
null
test/backend/batch_mat_mul.in.cpp
XReyRobert-IBM/ngraph
8cd9b5da9591f3e096b07ff21d8eaa2d2f0fb06f
[ "Apache-2.0" ]
null
null
null
test/backend/batch_mat_mul.in.cpp
XReyRobert-IBM/ngraph
8cd9b5da9591f3e096b07ff21d8eaa2d2f0fb06f
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <algorithm> #include <cinttypes> #include <cmath> #include <cstdlib> #include <iterator> #include <limits> #include <random> #include <string> // clang-format off #ifdef ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS #define DEFAULT_FLOAT_TOLERANCE_BITS ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS #endif // clang-format on #include "gtest/gtest.h" #include "ngraph/check.hpp" #include "ngraph/ngraph.hpp" #include "ngraph/op/util/attr_types.hpp" #include "ngraph/pass/batch_fusion.hpp" #include "util/all_close.hpp" #include "util/all_close_f.hpp" #include "util/ndarray.hpp" #include "util/random.hpp" #include "util/test_case.hpp" #include "util/test_control.hpp" #include "util/test_tools.hpp" #include "util/autodiff/numeric_compare.hpp" using namespace std; using namespace ngraph; static string s_manifest = "${MANIFEST}"; NGRAPH_TEST(${BACKEND_NAME}, batch_mat_mul_transpose) { Shape shape0 = Shape{2, 2, 3}; Shape shape1 = Shape{2, 3, 4}; auto arg0 = make_shared<op::Parameter>(element::f32, shape0); auto arg1 = make_shared<op::Parameter>(element::f32, shape1); auto bmmt = make_shared<op::BatchMatMulTranspose>(arg0, arg1, false, false); auto f0 = make_shared<Function>(OutputVector{bmmt}, ParameterVector{arg0, arg1}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape0); copy_data(a, vector<float>{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4}); auto b = backend->create_tensor(element::f32, shape1); copy_data( b, vector<float>{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}); auto result0 = backend->create_tensor(element::f32, Shape{2, 2, 4}); auto handle = backend->compile(f0); handle->call_with_validate({result0}, {a, b}); vector<float> expected{6, 6, 6, 6, 12, 12, 12, 12, 18, 18, 18, 18, 24, 24, 24, 24}; EXPECT_EQ(expected, read_vector<float>(result0)); } NGRAPH_TEST(${BACKEND_NAME}, batch_mat_mul_transpose_with_transpose) { Shape shape0 = Shape{2, 3, 2}; Shape shape1 = Shape{2, 3, 4}; auto arg0 = make_shared<op::Parameter>(element::f32, shape0); auto arg1 = make_shared<op::Parameter>(element::f32, shape1); auto bmmt = make_shared<op::BatchMatMulTranspose>(arg0, arg1, true, false); auto f0 = make_shared<Function>(OutputVector{bmmt}, ParameterVector{arg0, arg1}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape0); copy_data(a, vector<float>{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4}); auto b = backend->create_tensor(element::f32, shape1); copy_data( b, vector<float>{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}); auto result0 = backend->create_tensor(element::f32, Shape{2, 2, 4}); auto handle = backend->compile(f0); handle->call_with_validate({result0}, {a, b}); vector<float> expected{9, 9, 9, 9, 11, 11, 11, 11, 21, 21, 21, 21, 23, 23, 23, 23}; EXPECT_EQ(expected, read_vector<float>(result0)); auto res = read_vector<float>(result0); } // This test operates against the INTERPRETER backend as a reference, so it is // disabled if INTERPRETER is disabled. #if NGRAPH_INTERPRETER_ENABLE NGRAPH_TEST(${BACKEND_NAME}, batch_mat_mul_forward) { auto make_dot = [](ParameterVector& a_params, ParameterVector& b_params) { Shape shape_a{2, 3}; Shape shape_b{3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto B = make_shared<op::Parameter>(element::f32, shape_b); a_params.push_back(A); b_params.push_back(B); return make_shared<op::Dot>(A, B); }; ParameterVector dot_a_params; ParameterVector dot_b_params; auto dot1 = make_dot(dot_a_params, dot_b_params); auto dot2 = make_dot(dot_a_params, dot_b_params); auto dot3 = make_dot(dot_a_params, dot_b_params); auto dot_concat = make_shared<op::Concat>(OutputVector{dot1, dot2, dot3}, 0); ParameterVector dot_params(dot_a_params); dot_params.insert(dot_params.end(), dot_b_params.begin(), dot_b_params.end()); auto ref_f = make_shared<Function>(dot_concat, dot_params); auto make_batchmatmul = [](ParameterVector& params) { Shape shape_a{3, 2, 3}; Shape shape_b{3, 3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto B = make_shared<op::Parameter>(element::f32, shape_b); params.push_back(A); params.push_back(B); return make_shared<op::BatchMatMul>(A, B); }; ParameterVector batchmatmul_params; auto batchmatmul = make_batchmatmul(batchmatmul_params); auto backend_f = make_shared<Function>(batchmatmul, batchmatmul_params); test::Uniform<float> dot_rng(-1.0f, 1.0f); vector<vector<float>> dot_args; for (shared_ptr<op::Parameter> param : dot_params) { vector<float> tensor_val(shape_size(param->get_output_shape(0))); dot_rng.initialize(tensor_val); dot_args.push_back(tensor_val); } test::Uniform<float> batchmatmul_rng(-1.0f, 1.0f); vector<vector<float>> batchmatmul_args; for (shared_ptr<op::Parameter> param : batchmatmul_params) { vector<float> tensor_val(shape_size(param->get_output_shape(0))); batchmatmul_rng.initialize(tensor_val); batchmatmul_args.push_back(tensor_val); } auto ref_results = execute(ref_f, dot_args, "INTERPRETER"); auto backend_results = execute(backend_f, batchmatmul_args, "${BACKEND_NAME}"); for (size_t i = 0; i < ref_results.size(); i++) { EXPECT_TRUE(test::all_close_f( ref_results.at(i), backend_results.at(i), DEFAULT_FLOAT_TOLERANCE_BITS + 3)); } } #ifndef NGRAPH_JSON_DISABLE NGRAPH_TEST(${BACKEND_NAME}, fuse_batch_mat_mul_transpose_forward) { pass::Manager pass_manager; pass_manager.register_pass<pass::BatchFusion>(); const std::string file_name("mxnet/batch_dot_3.json"); auto backend_f = make_function_from_file(file_name); auto int_f = make_function_from_file(file_name); pass_manager.run_passes(backend_f); test::Uniform<float> rng(0.0f, 1.0f); vector<vector<float>> args; for (shared_ptr<op::Parameter> param : int_f->get_parameters()) { vector<float> tensor_val(shape_size(param->get_output_shape(0))); rng.initialize(tensor_val); args.push_back(tensor_val); } auto int_results = execute(int_f, args, "INTERPRETER"); auto backend_results = execute(backend_f, args, "${BACKEND_NAME}"); for (size_t i = 0; i < int_results.size(); i++) { EXPECT_TRUE(test::all_close(backend_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f)); } } //#if defined(AUTODIFF_BACKEND_${BACKEND_NAME}) NGRAPH_TEST(${BACKEND_NAME}, backwards_batchmatmultranspose_tensor2_tensor2) { auto backend = runtime::Backend::create("${BACKEND_NAME}"); const std::string file_name("mxnet/batch_dot_3.json"); auto f = make_function_from_file(file_name); test::Uniform<float> rng(-1.0f, 1.0f); std::vector<std::shared_ptr<ngraph::runtime::Tensor>> args; for (shared_ptr<op::Parameter> param : f->get_parameters()) { args.push_back(rng.initialize(backend->create_tensor<float>(param->get_output_shape(0)))); } auto g = make_function_from_file(file_name); pass::Manager pass_manager; pass_manager.register_pass<ngraph::pass::BatchFusion>(); pass_manager.run_passes(g); EXPECT_TRUE(autodiff_numeric_compare<float>(backend.get(), f, g, args, .01f, .01f)); } //#endif #endif #endif
38.547945
98
0.675788
XReyRobert-IBM
0b81ac862e4da9817195d15bd80330bd552b38cc
1,458
cpp
C++
UVA/735.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/735.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
UVA/735.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define f first #define s second #define ll long long #define vi vector<int> #define pii pair<int, int> #define si set<int> #define y1 yy #define debug if(printDebug) using namespace std; bool printDebug=false; int main(){ //printDebug=true; /*freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);//*/ ios_base::sync_with_stdio(false); cin.tie(NULL);//*/ bool used[61][61][61]; set<int> nums; nums.insert(0); nums.insert(50); for(int i=1; i<=20; i++){ nums.insert(i); nums.insert(i*2); nums.insert(i*3); } int n; while(cin >> n){ if(n<=0) break; memset(used, 0, sizeof(used)); int comb=0; int permu=0; for(int v1 : nums){ for(int v2 : nums){ for(int v3 : nums){ if(v1+v2+v3==n){ permu++; if(!used[v1][v2][v3]){ used[v1][v2][v3]=1; used[v1][v3][v2]=1; used[v2][v1][v3]=1; used[v2][v3][v1]=1; used[v3][v1][v2]=1; used[v3][v2][v1]=1; comb++; } } } } } if(comb+permu>0){ cout << "NUMBER OF COMBINATIONS THAT SCORES " << n << " IS " << comb << ".\n"; cout << "NUMBER OF PERMUTATIONS THAT SCORES " << n << " IS " << permu << ".\n"; } else{ cout << "THE SCORE OF " << n << " CANNOT BE MADE WITH THREE DARTS.\n"; } cout << "**********************************************************************\n"; } cout << "END OF OUTPUT\n"; return 0; }
23.142857
85
0.500686
DT3264
0b81bf1a8f15c6dd3c8546e8d0505dad5c3e3db3
711
hpp
C++
include/lol/def/RosterItemDto.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/RosterItemDto.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/RosterItemDto.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct RosterItemDto { uint64_t accountId; std::string summonerName; int32_t summonerIconId; std::string clubRole; }; inline void to_json(json& j, const RosterItemDto& v) { j["accountId"] = v.accountId; j["summonerName"] = v.summonerName; j["summonerIconId"] = v.summonerIconId; j["clubRole"] = v.clubRole; } inline void from_json(const json& j, RosterItemDto& v) { v.accountId = j.at("accountId").get<uint64_t>(); v.summonerName = j.at("summonerName").get<std::string>(); v.summonerIconId = j.at("summonerIconId").get<int32_t>(); v.clubRole = j.at("clubRole").get<std::string>(); } }
32.318182
62
0.646976
Maufeat
0b82b4a677f754329da71f3ca9f361fad8c91abc
1,020
hpp
C++
source/framework/core/include/lue/framework/core/serialize/shared_buffer.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/core/include/lue/framework/core/serialize/shared_buffer.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/core/include/lue/framework/core/serialize/shared_buffer.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#pragma once #include "lue/framework/core/shared_buffer.hpp" #include <hpx/serialization/array.hpp> namespace hpx { namespace serialization { template< typename Element> void serialize( input_archive& archive, lue::SharedBuffer<Element>& buffer, unsigned int const /* version */) { // Read buffer from archive using Buffer = lue::SharedBuffer<Element>; using Size = typename Buffer::Size; // Read buffer size and make sure buffer has enough room for the elements Size size{}; archive & size; buffer.resize(size); // Read elements archive & hpx::serialization::make_array(buffer.data(), size); } template< typename Element> void serialize( output_archive& archive, lue::SharedBuffer<Element> const& buffer, unsigned int const /* version */) { // Write buffer to archive archive & buffer.size() & hpx::serialization::make_array(buffer.data(), buffer.size()) ; } } // namespace serialization } // namespace hpx
21.25
77
0.670588
computationalgeography
0b833a987af6dca1a64ebb374e42ed1a99d61341
11,694
cpp
C++
be/test/vec/function/function_geo_test.cpp
kuolei/incubator-doris
b14678c0021896f11efdfdaa3e2dad15b2d4868d
[ "Apache-2.0" ]
2
2022-01-26T15:24:34.000Z
2022-02-10T09:07:33.000Z
be/test/vec/function/function_geo_test.cpp
aiwenmo/incubator-doris
b33ab960a840553d2877d56c5c051a94df71917f
[ "Apache-2.0" ]
2
2018-08-27T07:42:21.000Z
2018-08-29T06:37:41.000Z
be/test/vec/function/function_geo_test.cpp
aiwenmo/incubator-doris
b33ab960a840553d2877d56c5c051a94df71917f
[ "Apache-2.0" ]
1
2022-01-14T17:35:25.000Z
2022-01-14T17:35:25.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <gtest/gtest.h> #include <time.h> #include <string> #include "function_test_util.h" #include "geo/geo_types.h" #include "vec/core/field.h" #include "vec/core/types.h" #include "vec/data_types/data_type_nullable.h" #include "vec/data_types/data_type_string.h" namespace doris::vectorized { using namespace ut_type; TEST(VGeoFunctionsTest, function_geo_st_point_test) { std::string func_name = "st_point"; { InputTypeSet input_types = {TypeIndex::Float64, TypeIndex::Float64}; GeoPoint point; auto cur_res = point.from_coord(24.7, 56.7); EXPECT_TRUE(cur_res == GEO_PARSE_OK); std::string buf; point.encode_to(&buf); DataSet data_set = {{{(double)24.7, (double)56.7}, buf}, {{Null(), (double)5}, Null()}, {{(double)5, Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_as_text) { std::string func_name = "st_astext"; { InputTypeSet input_types = {TypeIndex::String}; GeoPoint point; auto cur_res = point.from_coord(24.7, 56.7); EXPECT_TRUE(cur_res == GEO_PARSE_OK); std::string buf; point.encode_to(&buf); DataSet data_set = {{{buf}, std::string("POINT (24.7 56.7)")}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_as_wkt) { std::string func_name = "st_aswkt"; { InputTypeSet input_types = {TypeIndex::String}; GeoPoint point; auto cur_res = point.from_coord(24.7, 56.7); EXPECT_TRUE(cur_res == GEO_PARSE_OK); std::string buf; point.encode_to(&buf); DataSet data_set = {{{buf}, std::string("POINT (24.7 56.7)")}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_x) { std::string func_name = "st_x"; { InputTypeSet input_types = {TypeIndex::String}; GeoPoint point; auto cur_res = point.from_coord(24.7, 56.7); EXPECT_TRUE(cur_res == GEO_PARSE_OK); std::string buf; point.encode_to(&buf); DataSet data_set = {{{buf}, (double)24.7}, {{Null()}, Null()}}; check_function<DataTypeFloat64, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_y) { std::string func_name = "st_y"; { InputTypeSet input_types = {TypeIndex::String}; GeoPoint point; auto cur_res = point.from_coord(24.7, 56.7); EXPECT_TRUE(cur_res == GEO_PARSE_OK); std::string buf; point.encode_to(&buf); DataSet data_set = {{{buf}, (double)56.7}, {{Null()}, Null()}}; check_function<DataTypeFloat64, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_distance_sphere) { std::string func_name = "st_distance_sphere"; { InputTypeSet input_types = {TypeIndex::Float64, TypeIndex::Float64, TypeIndex::Float64, TypeIndex::Float64}; DataSet data_set = { {{(double)116.35620117, (double)39.939093, (double)116.4274406433, (double)39.9020987219}, (double)7336.9135549995917}, {{(double)116.35620117, (double)39.939093, (double)116.4274406433, Null()}, Null()}, {{(double)116.35620117, (double)39.939093, Null(), (double)39.9020987219}, Null()}, {{(double)116.35620117, Null(), (double)116.4274406433, (double)39.9020987219}, Null()}, {{Null(), (double)39.939093, (double)116.4274406433, (double)39.9020987219}, Null()}}; check_function<DataTypeFloat64, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_contains) { std::string func_name = "st_contains"; { InputTypeSet input_types = {TypeIndex::String, TypeIndex::String}; std::string buf1; std::string buf2; std::string buf3; GeoParseStatus status; std::string shape1 = std::string("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"); std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(shape1.data(), shape1.size(), &status)); EXPECT_TRUE(status == GEO_PARSE_OK); EXPECT_TRUE(shape != nullptr); shape->encode_to(&buf1); GeoPoint point1; status = point1.from_coord(5, 5); EXPECT_TRUE(status == GEO_PARSE_OK); point1.encode_to(&buf2); GeoPoint point2; status = point2.from_coord(50, 50); EXPECT_TRUE(status == GEO_PARSE_OK); point2.encode_to(&buf3); DataSet data_set = {{{buf1, buf2}, (uint8_t)1}, {{buf1, buf3}, (uint8_t)0}, {{buf1, Null()}, Null()}, {{Null(), buf3}, Null()}}; check_function<DataTypeUInt8, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_circle) { std::string func_name = "st_circle"; { InputTypeSet input_types = {TypeIndex::Float64, TypeIndex::Float64, TypeIndex::Float64}; GeoCircle circle; std::string buf; auto value = circle.init(111, 64, 10000); EXPECT_TRUE(value == GEO_PARSE_OK); circle.encode_to(&buf); DataSet data_set = {{{(double)111, (double)64, (double)10000}, buf}, {{Null(), (double)64, (double)10000}, Null()}, {{(double)111, Null(), (double)10000}, Null()}, {{(double)111, (double)64, Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_geometryfromtext) { std::string func_name = "st_geometryfromtext"; { InputTypeSet input_types = {TypeIndex::String}; GeoParseStatus status; std::string buf; std::string input = "LINESTRING (1 1, 2 2)"; std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(input.data(), input.size(), &status)); EXPECT_TRUE(shape != nullptr); EXPECT_TRUE(status == GEO_PARSE_OK); shape->encode_to(&buf); DataSet data_set = {{{std::string("LINESTRING (1 1, 2 2)")}, buf}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_geomfromtext) { std::string func_name = "st_geomfromtext"; { InputTypeSet input_types = {TypeIndex::String}; GeoParseStatus status; std::string buf; std::string input = "LINESTRING (1 1, 2 2)"; std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(input.data(), input.size(), &status)); EXPECT_TRUE(shape != nullptr); EXPECT_TRUE(status == GEO_PARSE_OK); shape->encode_to(&buf); DataSet data_set = {{{std::string("LINESTRING (1 1, 2 2)")}, buf}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_linefromtext) { std::string func_name = "st_linefromtext"; { InputTypeSet input_types = {TypeIndex::String}; GeoParseStatus status; std::string buf; std::string input = "LINESTRING (1 1, 2 2)"; std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(input.data(), input.size(), &status)); EXPECT_TRUE(shape != nullptr); EXPECT_TRUE(status == GEO_PARSE_OK); shape->encode_to(&buf); DataSet data_set = {{{std::string("LINESTRING (1 1, 2 2)")}, buf}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_linestringfromtext) { std::string func_name = "st_linestringfromtext"; { InputTypeSet input_types = {TypeIndex::String}; GeoParseStatus status; std::string buf; std::string input = "LINESTRING (1 1, 2 2)"; std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(input.data(), input.size(), &status)); EXPECT_TRUE(shape != nullptr); EXPECT_TRUE(status == GEO_PARSE_OK); shape->encode_to(&buf); DataSet data_set = {{{std::string("LINESTRING (1 1, 2 2)")}, buf}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_polygon) { std::string func_name = "st_polygon"; { InputTypeSet input_types = {TypeIndex::String}; GeoParseStatus status; std::string buf; std::string input = "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"; std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(input.data(), input.size(), &status)); EXPECT_TRUE(shape != nullptr); EXPECT_TRUE(status == GEO_PARSE_OK); shape->encode_to(&buf); DataSet data_set = {{{std::string("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")}, buf}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_polygonfromtext) { std::string func_name = "st_polygonfromtext"; { InputTypeSet input_types = {TypeIndex::String}; GeoParseStatus status; std::string buf; std::string input = "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"; std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(input.data(), input.size(), &status)); EXPECT_TRUE(shape != nullptr); EXPECT_TRUE(status == GEO_PARSE_OK); shape->encode_to(&buf); DataSet data_set = {{{std::string("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")}, buf}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } TEST(VGeoFunctionsTest, function_geo_st_polyfromtext) { std::string func_name = "st_polyfromtext"; { InputTypeSet input_types = {TypeIndex::String}; GeoParseStatus status; std::string buf; std::string input = "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"; std::unique_ptr<GeoShape> shape(GeoShape::from_wkt(input.data(), input.size(), &status)); EXPECT_TRUE(shape != nullptr); EXPECT_TRUE(status == GEO_PARSE_OK); shape->encode_to(&buf); DataSet data_set = {{{std::string("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")}, buf}, {{Null()}, Null()}}; check_function<DataTypeString, true>(func_name, input_types, data_set); } } } // namespace doris::vectorized
35.981538
100
0.613734
kuolei
0b85d0e46281e9184082f5cc2e856186bf03ea19
1,112
cpp
C++
src/ProjectsCpp/ImageStiching/Sticher/im_stitching.cpp
ShawnZhang31/OpenCV_Tutorials_ZH
fe151158291cb282539e969c38d47af38c37fd45
[ "MIT" ]
2
2020-02-21T19:16:41.000Z
2021-06-30T07:09:44.000Z
src/ProjectsCpp/ImageStiching/Sticher/im_stitching.cpp
ShawnZhang31/OpenCV_Tutorials_ZH
fe151158291cb282539e969c38d47af38c37fd45
[ "MIT" ]
null
null
null
src/ProjectsCpp/ImageStiching/Sticher/im_stitching.cpp
ShawnZhang31/OpenCV_Tutorials_ZH
fe151158291cb282539e969c38d47af38c37fd45
[ "MIT" ]
1
2021-04-16T05:17:27.000Z
2021-04-16T05:17:27.000Z
// // Created by 张晓民 on 2020/3/20. // #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/stitching.hpp> #include <iostream> using namespace std; using namespace cv; bool divide_images = false; Stitcher::Mode mode = Stitcher::PANORAMA; vector<Mat> imgs; string result_name = "result.jpg"; int main(int, char**) { VideoCapture cap("boats/boat%1d.jpg"); Mat frame; while (true){ cap >> frame; if (frame.empty()){ break; } // 为了防止图片不足,多切割点图片 Rect roi(0,0, frame.cols/2, frame.rows); imgs.push_back(frame(roi).clone()); roi.x = frame.cols / 3; imgs.push_back(frame(roi).clone()); roi.x = frame.cols/2; imgs.push_back(frame(roi).clone()); } cap.release(); Mat pano; Ptr<Stitcher> stitcher = Stitcher::create(mode); Stitcher::Status status = stitcher->stitch(imgs, pano); if (status != Stitcher::OK){ cout << "不能拼接图像,错误代码= " << int(status) << endl; return EXIT_FAILURE; } imwrite(result_name, pano); return EXIT_SUCCESS; }
21.803922
59
0.602518
ShawnZhang31
0b8b6c231485eed6921f1be89337c7b14088acdc
6,884
cpp
C++
xml/applications/xml-map.cpp
mission-systems-pty-ltd/comma
3ccec0b206fb15a8c048358a7fc01be61a7e4f1e
[ "BSD-3-Clause" ]
21
2015-05-07T06:11:09.000Z
2022-02-01T09:55:46.000Z
xml/applications/xml-map.cpp
mission-systems-pty-ltd/comma
3ccec0b206fb15a8c048358a7fc01be61a7e4f1e
[ "BSD-3-Clause" ]
17
2015-01-16T01:38:08.000Z
2020-03-30T09:05:01.000Z
xml/applications/xml-map.cpp
mission-systems-pty-ltd/comma
3ccec0b206fb15a8c048358a7fc01be61a7e4f1e
[ "BSD-3-Clause" ]
13
2016-01-13T01:29:29.000Z
2022-02-01T09:55:49.000Z
// This file is part of comma, a generic and flexible library // Copyright (c) 2011 The University of Sydney // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the University of Sydney nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT // HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // g++ -o xml-xpath-map xml-xpath-map.cpp -lstdc++ -lexpat // NOTE the original output format was thought to be used as arguments to cut // path1,s1,e1,s2,e2,s3,e3 // path2,s1,e1,s2,e2,s3,e3 // However this exploded to massively long lines and so could not be used. // Now it is one line per element #include <cassert> #include <iostream> #include <limits> #include <vector> #include <list> #include <map> #include <cstdio> #include <cstring> #include <expat.h> #include <boost/unordered_map.hpp> #include "../../application/command_line_options.h" #include "../../xpath/xpath.h" #include "stream_util.h" #include "expat_util.h" #define CMDNAME "xml-map" static bool options_compact = false; static unsigned options_depth_max = std::numeric_limits<unsigned>::max(); typedef std::pair<long long, long long> element_location_t; typedef std::vector<element_location_t> element_location_list_t; struct hash_t { std::size_t operator()( const comma::xpath& p ) const { std::size_t seed = 0; boost::hash_combine( seed, p.to_string() ); return seed; } }; typedef boost::unordered_map<comma::xpath, element_location_list_t, hash_t> element_location_map_t; static element_location_map_t element_location_map; // ~~~~~~~~~~~~~~~~~~ // UTILITIES // ~~~~~~~~~~~~~~~~~~ inline std::ostream & operator <<(std::ostream & os, comma::xpath const & p) { return p.output(os); } // ~~~~~~~~~~~~~~~~~~ // USER INTERFACE // ~~~~~~~~~~~~~~~~~~ static void XMLCALL usage(bool const verbose) { std::cerr << "Generates a byte map of each element in an xml file, for later use by xml-map-split" "\nUSAGE: " CMDNAME " [--compact] [--maxdepth=N] [--source=XMLFILE]" "\nRETURNS: 0 - on success" "\n 1 - on data error; like invalid xml" << std::endl; } // ~~~~~~~~~~~~~~~~~~ // APPLICATION // ~~~~~~~~~~~~~~~~~~ class xml_map_application : public simple_expat_application { public: xml_map_application(); protected: virtual void do_element_start(char const * const element, char const * const * const attributes); virtual void do_element_end(char const * const element); }; xml_map_application::xml_map_application() : simple_expat_application(CMDNAME) { } void xml_map_application::do_element_start(char const * const element, char const * const * const attributes) { if (element_depth > options_depth_max) return; ++element_found_count; comma::xpath const & element_path = current_xpath(); // get the start location long long const at = XML_GetCurrentByteIndex(parser); element_location_t loc(at, 0); // push the start location into the map element_location_map[element_path].push_back(loc); } void xml_map_application::do_element_end(char const * const element) { if (element_depth > options_depth_max) return; comma::xpath const & element_path = current_xpath(); element_location_t & entry = element_location_map[element_path].back(); { // force the use of the entry to prevent errors long long txtlen = 3 + std::strlen(element); long long const at = XML_GetCurrentByteIndex(parser) + txtlen; entry.second = at; } if (! options_compact) std::cout << element_path << ',' << entry.first << '-' << entry.second << std::endl; } // ~~~~~~~~~~~~~~~~~~ // MAIN // ~~~~~~~~~~~~~~~~~~ int main(int argc, char ** argv) { try { comma::command_line_options options( argc, argv ); bool const verbose = options.exists( "--verbose,-v" ); if (options.exists("--help,-h")) { usage(verbose); return 1; } std::string options_file; if (options.exists("--source")) { options_file = options.value<std::string>("--source"); } options_compact = options.exists("--compact"); options_depth_max = options.value<unsigned>("--maxdepth", std::numeric_limits<unsigned>::max()); xml_map_application app; int const code = app.run(options_file); if (options_compact) { element_location_map_t::const_iterator const end = element_location_map.end(); element_location_map_t::const_iterator itr = element_location_map.begin(); for (; itr != end; ++itr) { std::cout << itr->first; element_location_list_t::const_iterator const loc_end = itr->second.end(); element_location_list_t::const_iterator loc_itr = itr->second.begin(); for (; loc_itr != loc_end; ++loc_itr) { std::cout << ',' << loc_itr->first << '-' << loc_itr->second; } std::cout << '\n'; } } return code; } catch (std::exception const & ex) { std::cerr << CMDNAME ": Error: " << ex.what() << std::endl; } catch (...) { std::cerr << CMDNAME ": Error: Unknown Exception." << std::endl; } return 1; }
32.018605
104
0.643812
mission-systems-pty-ltd
0b8cf1e6294370b9912415e2cf4fce02a0161b05
2,124
cpp
C++
DecoderSDK/ISampleDecoder.cpp
MartinPulec/cineform-sdk
8fd6bbaf87a9ff99c13bc7978318a32b1549ba13
[ "Apache-2.0", "MIT-0", "MIT" ]
248
2017-10-25T16:14:07.000Z
2022-03-26T10:53:34.000Z
DecoderSDK/ISampleDecoder.cpp
MartinPulec/cineform-sdk
8fd6bbaf87a9ff99c13bc7978318a32b1549ba13
[ "Apache-2.0", "MIT-0", "MIT" ]
48
2017-10-25T21:48:39.000Z
2021-11-29T15:37:44.000Z
DecoderSDK/ISampleDecoder.cpp
MartinPulec/cineform-sdk
8fd6bbaf87a9ff99c13bc7978318a32b1549ba13
[ "Apache-2.0", "MIT-0", "MIT" ]
62
2017-10-25T21:45:36.000Z
2022-03-26T10:53:50.000Z
/*! @file ISampleDecoder.cpp @brief Interface for the sample decoder class. This class is used internally by CineForm software and is not currently mentioned in the documentation provided to customers. Modify this comment and add tags for Doxygen to publish this interface in customer documentation. The interface uses pure virtual methods to isolate applications that use the CineForm decoder from changes to the codec library. The interface includes macros (methods defined in the class declaration) for common calculations involving pixel formats. * * @version 1.0.0 * * (C) Copyright 2017 GoPro Inc (http://gopro.com/). * * Licensed under either: * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 * - MIT license, http://opensource.org/licenses/MIT * at your option. * * 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 "StdAfx.h" #if _WIN32 // Export the interface to the decoder #define DECODERDLL_EXPORTS 1 #elif __APPLE__ #ifdef DECODERDLL_API #undef DECODERDLL_API #endif #define DECODERDLL_API __attribute__((visibility("default"))) #include <CoreFoundation/CoreFoundation.h> #else // Code required by GCC on Linux to define the entry points #ifdef DECODERDLL_API #undef DECODERDLL_API #endif #define DECODERDLL_API __attribute__((visibility("default"))) #endif #if defined(__APPLE__) #include "decoder.h" #endif #include "CFHDDecoder.h" #include "SampleDecoder.h" #include "ISampleDecoder.h" CFHDDECODER_API ISampleDecoder *CFHD_CreateSampleDecoder(IAllocator *allocator, CFHD_LicenseKey license, FILE *logfile) { // No longer supporting this type of codec interface, it was only used by the old Premiere importers. return CSampleDecoder::CreateSampleDecoder(allocator, license, logfile); }
28.702703
120
0.749529
MartinPulec
0b8ff419a29e6d26aed51900a35f4a11cf20917a
992
cpp
C++
main/maximum-element/maximum-element.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/maximum-element/maximum-element.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/maximum-element/maximum-element.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#include <iostream> #include <set> #include <stack> #include <stdexcept> inline void push(std::stack<int>& s, std::multiset<int>& m) { auto x = 0; std::cin >> x; s.push(x); m.insert(x); } inline void pop(std::stack<int>& s, std::multiset<int>& m) { const auto x = s.top(); s.pop(); const auto p = m.find(x); auto q = p; m.erase(p, ++q); // remove just one x } inline void print_max(std::multiset<int>& m) { if (m.empty()) throw std::invalid_argument("empty multiset has no max"); std::cout << *m.crbegin() << '\n'; } int main() { std::stack<int> s; std::multiset<int> m; auto n = 0; for (std::cin >> n; n > 0; --n) { auto q = 0; std::cin >> q; switch (q) { case 1: push(s, m); continue; case 2: pop(s, m); continue; case 3: print_max(m); continue; default: throw std::out_of_range("invalid query type"); } } }
20.244898
76
0.506048
EliahKagan
0b939908b8c5996b9f58302df70f79ad877fdcaa
1,648
cpp
C++
common/test_case_builder.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
common/test_case_builder.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
common/test_case_builder.cpp
ultimatezen/felix
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
[ "MIT" ]
null
null
null
// test_case_builder.cpp: implementation of the test_case_builder class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "test_case_builder.h" #include "file_representation.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// test_case_builder::test_case_builder( const CString &header_file ) : m_header_file_name( header_file ) { CPath path( m_header_file_name ) ; ATLASSERT( path.FileExists() ) ; break_into_lines( m_header_file_name, m_header_lines ) ; file_representation file_rep ; file_rep.suss_file( m_header_lines ) ; path.RenameExtension( _T(".cpp") ) ; m_cpp_file_name = path.Path() ; if ( path.FileExists() ) { break_into_lines( path.Path(), m_cpp_lines ) ; } path.RemoveExtension() ; m_test_rig_file_name = path.Path() ; m_test_rig_file_name += _T("_testrig.cpp") ; path = m_test_rig_file_name ; if ( path.FileExists() ) { break_into_lines( path.Path(), m_testrig_lines ) ; } } test_case_builder::~test_case_builder() { } void test_case_builder::parse_header_file() { } void test_case_builder::break_into_lines(const CString &header_file, prog_lines &lines) { file::view fview ; LPCSTR file_text = (LPCSTR)fview.create_view( header_file ) ; ATLASSERT( file_text != NULL ) ; textstream_reader< char > reader ; reader.set_buffer( file_text ) ; string line ; while ( reader.getline(line)) { TRACE( line ) ; lines.push_back( line ) ; } }
23.211268
88
0.600728
ultimatezen
0b97f785489ca7902ed7cfbc952a0a82b7357f50
1,724
cpp
C++
webos/developertools/plugin/src/unifiedtimerwrapper.cpp
webosce/qml-webos-components
ac9db3de6214a6022c87be387a267b97e079fe00
[ "Apache-2.0" ]
5
2018-03-17T12:35:42.000Z
2020-07-18T03:51:21.000Z
webos/developertools/plugin/src/unifiedtimerwrapper.cpp
webosce/qml-webos-components
ac9db3de6214a6022c87be387a267b97e079fe00
[ "Apache-2.0" ]
1
2019-10-19T12:26:35.000Z
2019-10-19T12:26:35.000Z
webos/developertools/plugin/src/unifiedtimerwrapper.cpp
webosce/qml-webos-components
ac9db3de6214a6022c87be387a267b97e079fe00
[ "Apache-2.0" ]
3
2018-03-22T18:54:39.000Z
2020-03-04T19:20:03.000Z
// Copyright (c) 2014-2018 LG Electronics, Inc. // // 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. // // SPDX-License-Identifier: Apache-2.0 #include "unifiedtimerwrapper.h" #include <private/qabstractanimation_p.h> UnifiedTimerWrapper *UnifiedTimerWrapper::g_self = NULL; UnifiedTimerWrapper::UnifiedTimerWrapper(QObject *parent) : QObject (parent), m_slowMode (false), m_framerateThreshold (0) { g_self = this; } void UnifiedTimerWrapper::setSlowMode(bool enabled) { QUnifiedTimer::instance()->setSlowModeEnabled(enabled); m_slowMode = enabled; emit slowModeChanged(); } qint64 UnifiedTimerWrapper::framerateThreshold() const { return m_framerateThreshold; } void UnifiedTimerWrapper::setFramerateThreshold(qint64 framerateThreshold) { if (m_framerateThreshold == framerateThreshold) return; QUnifiedTimer::instance()->registerProfilerCallback(framerateThreshold > 0 ? &cb : NULL); m_framerateThreshold = framerateThreshold; emit framerateThresholdChanged(); } void UnifiedTimerWrapper::cb(qint64 delta) { if (g_self && g_self->m_framerateThreshold > 0 && g_self->m_framerateThreshold < delta) emit g_self->framerateDropDetected(delta); }
28.262295
93
0.74768
webosce
0b9801cb728b739f1e2523beb4d093583745c328
549
cpp
C++
CompilationTest/StrReplaceTest/results/StrReplaceTest.cpp
onelang/TestArtifacts
3f067308c8da3a6f95a001ff8b2d0a0421ae3285
[ "MIT" ]
null
null
null
CompilationTest/StrReplaceTest/results/StrReplaceTest.cpp
onelang/TestArtifacts
3f067308c8da3a6f95a001ff8b2d0a0421ae3285
[ "MIT" ]
null
null
null
CompilationTest/StrReplaceTest/results/StrReplaceTest.cpp
onelang/TestArtifacts
3f067308c8da3a6f95a001ff8b2d0a0421ae3285
[ "MIT" ]
null
null
null
#include <OneLang-Core-v0.1/one.hpp> #include <iostream> #include <string> class TestClass { public: void testMethod() { auto str = std::string("A x B x C x D"); auto result = OneStringHelper::replace(str, std::string("x"), std::string("y")); std::cout << std::string("R: ") + result + ", O: " + str << std::endl; } private: }; int main() { try { TestClass c; c.testMethod(); } catch(std::exception& err) { std::cout << "Exception: " << err.what() << '\n'; } return 0; }
21.96
88
0.528233
onelang
0b98701c5eb7abef8fb946ddf60dcc4ae7f5ea53
1,896
cpp
C++
source/profile/ReadClassification.cpp
a7420174/ExpansionHunterDenovo
cbe1306aa8ad7c4b33cdf981d64b3415aa057f91
[ "Apache-2.0", "BSD-3-Clause" ]
50
2019-09-20T18:37:38.000Z
2022-03-10T08:55:42.000Z
source/profile/ReadClassification.cpp
mfbennett/ExpansionHunterDenovo
abf1cc78535f572ec49d38a65f6e84f4104fae2a
[ "Apache-2.0", "BSD-3-Clause" ]
35
2019-09-20T18:38:20.000Z
2022-03-29T22:50:55.000Z
source/profile/ReadClassification.cpp
mfbennett/ExpansionHunterDenovo
abf1cc78535f572ec49d38a65f6e84f4104fae2a
[ "Apache-2.0", "BSD-3-Clause" ]
21
2019-09-20T20:54:43.000Z
2022-03-30T13:18:25.000Z
// // ExpansionHunter Denovo // Copyright 2016-2019 Illumina, Inc. // All rights reserved. // // Author: Egor Dolzhenko <edolzhenko@illumina.com>, // Michael Eberle <meberle@illumina.com> // // 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 "ReadClassification.hh" #include "reads/IrrFinder.hh" using std::string; ReadType classifyRead(Interval motifSizeRange, int max_irr_mapq, int min_anchor_mapq, const Read& read, string& unit) { const bool is_unmapped = read.flag & 0x4; const bool is_low_mapq = read.mapq <= max_irr_mapq; const bool is_irr = (is_unmapped || is_low_mapq) && IsInrepeatRead(read.bases, read.quals, unit, motifSizeRange); if (is_irr) { return ReadType::kIrrRead; } if (read.mapq >= min_anchor_mapq) { return ReadType::kAnchorRead; } return ReadType::kOtherRead; } PairType classifyPair(ReadType read_type, const string& read_unit, ReadType mate_type, const string& mate_unit) { if ((read_type == ReadType::kAnchorRead && mate_type == ReadType::kIrrRead) || (read_type == ReadType::kIrrRead && mate_type == ReadType::kAnchorRead)) { return PairType::kIrrAnchorPair; } if (read_type == ReadType::kIrrRead && mate_type == ReadType::kIrrRead && read_unit == mate_unit) { return PairType::kIrrIrrPair; } return PairType::kOtherPair; }
30.580645
117
0.699367
a7420174
0b991e0f1584baaf6f09a0254cd94898b23708c1
2,515
cpp
C++
src/youtubedl-cleanup.cpp
bansan85/youtube-dl-cleanup
33072a0b1cb5960a671f9ecb6bc048e4ea5c4002
[ "MIT" ]
null
null
null
src/youtubedl-cleanup.cpp
bansan85/youtube-dl-cleanup
33072a0b1cb5960a671f9ecb6bc048e4ea5c4002
[ "MIT" ]
null
null
null
src/youtubedl-cleanup.cpp
bansan85/youtube-dl-cleanup
33072a0b1cb5960a671f9ecb6bc048e4ea5c4002
[ "MIT" ]
null
null
null
// YoutubeDlCleanUp.cpp : Defines the entry point for the application. // #include <filesystem> #include <iostream> #include <map> #include <optional> #include <queue> namespace fs = std::filesystem; #include <windows.h> int main(int argc, char* argv[]) { std::queue<fs::path> folders; std::locale::global(std::locale("")); bool r = false; bool dry_run = false; for (int i = 1; i < argc; i++) { if (std::string_view("-r") == argv[i]) r = true; else if (std::string_view("--dry-run") == argv[i]) dry_run = true; else if (!fs::is_directory(argv[i])) { std::cerr << "\"" << argv[i] << "\" is not a folder.\n"; return 1; } else folders.push(argv[i]); } if (folders.empty()) { std::cout << "Usage: youtubedl-cleanup.exe [--dry-run] [-r] path [more_path]\n"; return 1; } while (!folders.empty()) { auto path = folders.front(); std::map<std::wstring, std::vector<fs::path>> file_ext; for (const auto& entry : fs::directory_iterator(path)) { try { if (entry.is_directory()) { if (r) folders.push(entry); } else { auto ext = entry.path().extension(); if (ext == ".mkv" || ext == ".mp4" || ext == ".webm") { auto root = (entry.path().parent_path() / entry.path().filename().replace_extension("")).wstring(); if (!file_ext.contains(root)) file_ext.insert({ root, {ext} }); else file_ext[root].push_back(ext); } } } catch (const std::system_error&) {} } for (const auto& [file, ext] : file_ext) { if (ext.size() < 2) continue; std::map<std::uint64_t, std::wstring> times; for (const auto& exti : ext) { HANDLE hFile; FILETIME ftCreate; std::wstring filei = file + exti.wstring(); hFile = CreateFileW(filei.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { std::wcerr << "Could not open file \"" << filei << "\", error " << GetLastError() << "\n"; return 1; } if (!GetFileTime(hFile, &ftCreate, NULL, NULL)) { std::wcerr << "Corrumpted file \"" << filei << "\"\n"; return 1; } CloseHandle(hFile); times.insert({ (static_cast<std::uint64_t>(ftCreate.dwHighDateTime) << 32L) + ftCreate.dwLowDateTime, exti.wstring() }); } std::wcout << file.c_str() << times.begin()->second << std::endl; if (!dry_run) fs::remove(file + times.begin()->second); } folders.pop(); } return 0; }
22.455357
124
0.580915
bansan85
0b9c133d3dac19203102602f7aaf82a762315cc2
787
cpp
C++
ReceiverTest/ReceiverTest.cpp
Engin-Boot/environment-case-s1b10
55ae0e03252502c58d9f843f1e5caea612dd97d4
[ "MIT" ]
null
null
null
ReceiverTest/ReceiverTest.cpp
Engin-Boot/environment-case-s1b10
55ae0e03252502c58d9f843f1e5caea612dd97d4
[ "MIT" ]
null
null
null
ReceiverTest/ReceiverTest.cpp
Engin-Boot/environment-case-s1b10
55ae0e03252502c58d9f843f1e5caea612dd97d4
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <iostream> #include<vector> #include "../Receiver/ReceiverCheck.h" #include "../catch.hpp" using namespace std; ReceiverClass obj; TEST_CASE("Generate warning if Temperature >= 37 C or if Temperature <= 4 C") { obj.temperatureWarningHigh(38.9); REQUIRE(option == 1); obj.temperatureWarningLow(3.7); REQUIRE(option == 1); } TEST_CASE("Generate error if Temperature >= 40 C or if Temperature <= 0 C") { obj.temperatureErrorLow(-5); REQUIRE(option == 2); obj.temperatureErrorHigh(48.6); REQUIRE(option == 2); } TEST_CASE("Generate warning if Humidity >= 70%") { obj.humidityWarning(85.2); REQUIRE(option == 3); } TEST_CASE("Generate error if Humidity >= 90%") { obj.humidityError(94.8); REQUIRE(option == 4); }
18.302326
77
0.682338
Engin-Boot
0b9c8724a1250030be70d581bc3c82c8e61114c1
420
cpp
C++
hdfileformat/src/ExplicitHierarchy.cpp
LLNL/hdtopology
303a0740d59831073b2af69be698dbe19932ec7b
[ "BSD-3-Clause" ]
null
null
null
hdfileformat/src/ExplicitHierarchy.cpp
LLNL/hdtopology
303a0740d59831073b2af69be698dbe19932ec7b
[ "BSD-3-Clause" ]
null
null
null
hdfileformat/src/ExplicitHierarchy.cpp
LLNL/hdtopology
303a0740d59831073b2af69be698dbe19932ec7b
[ "BSD-3-Clause" ]
null
null
null
#include "ExplicitHierarchy.h" namespace HDFileFormat{ ExplicitHierarchy::ExplicitHierarchy() { } ExplicitHierarchy::~ExplicitHierarchy() { } hNode *ExplicitHierarchy::root() { return mRoot; } void ExplicitHierarchy::setRawBuffer(void *buffer, int bufferSize) { } void ExplicitHierarchy::getRawBuffer(void* buffer, int& bufferSize) { } void ExplicitHierarchy::parseHierarchy() { } }//namespace
11.351351
67
0.730952
LLNL
0b9e1e6dcf403916ff7fc26889d01e969ac5aaab
2,235
cc
C++
case_studies/1dtreehpx/main.cc
luglio/dashmm
19d191576735345d66b450061a940a2738eed1d4
[ "BSD-3-Clause" ]
null
null
null
case_studies/1dtreehpx/main.cc
luglio/dashmm
19d191576735345d66b450061a940a2738eed1d4
[ "BSD-3-Clause" ]
null
null
null
case_studies/1dtreehpx/main.cc
luglio/dashmm
19d191576735345d66b450061a940a2738eed1d4
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================ // High Performance ParalleX Library (hpx-apps) // // Copyright (c) 2013-2016, Trustees of Indiana University, // All rights reserved. // // This software may be modified and distributed under the terms of the BSD // license. See the COPYING file for details. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================ #include <cstdio> #include <cstdlib> #include "hpx/hpx.h" #include "tree.h" void print_usage(FILE *fd, char *prog) { fprintf(fd, "Usage: %s <N parts> <Partition Limit> <theta> <domain size>\n", prog); } Particle *generate_parts(int n_parts, double domain_length) { Particle *parts = new Particle[n_parts]; for (int i = 0; i < n_parts; ++i) { parts[i].pos = ((double)rand() / (double)RAND_MAX) * domain_length; parts[i].mass = ((double)rand() / (double)RAND_MAX) * 0.9 + 0.1; } return parts; } int hpx_main(int n_parts, int n_partition, double theta_c, double domain_size) { Node *root = new Node(0.0, domain_size); Particle *parts = generate_parts(n_parts, domain_size); // Create the tree root->partition(parts, n_parts, n_partition); fprintf(stdout, "Done with partitioning!\n"); root->compute_moments(); fprintf(stdout, "Done computing moments.\n"); // Destroy the tree delete root; fprintf(stdout, "Done with tree deletion.\n"); // Destroy particles delete [] parts; hpx_exit(0, NULL); } HPX_ACTION(HPX_DEFAULT, 0, hpx_main_action, hpx_main, HPX_INT, HPX_INT, HPX_DOUBLE, HPX_DOUBLE); int main(int argc, char **argv) { Node::register_actions(); if (hpx_init(&argc, &argv)) { hpx_print_help(); return -1; } if (argc != 5) { print_usage(stderr, argv[0]); return 0; } int n_parts = atoi(argv[1]); int n_partition = atoi(argv[2]); double theta_c = atof(argv[3]); double domain_size = atof(argv[4]); int err = hpx_run(&hpx_main_action, NULL, &n_parts, &n_partition, &theta_c, &domain_size); hpx_finalize(); return err; }
23.526316
79
0.609843
luglio
0ba2eee16e686b8029b5c9a5846e07f51f8e673e
601
cpp
C++
P/1030.cpp
langonginc/cfile
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
[ "MIT" ]
1
2020-09-13T02:51:25.000Z
2020-09-13T02:51:25.000Z
P/1030.cpp
langonginc/cfile
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
[ "MIT" ]
null
null
null
P/1030.cpp
langonginc/cfile
46458897b8a4a8d58a2bc63ecb6ef84f76bdb61f
[ "MIT" ]
1
2021-06-05T03:37:57.000Z
2021-06-05T03:37:57.000Z
#include <iostream> #include <cstdio> #include <cstring> using namespace std; char mid[55], aft[55]; void dfs (int midl, int midr, int aftl, int aftr) { if (midl > midr || aftl > aftr) { return; } printf ("%c", aft[aftr]); for (int i = midl; i <= midr; i ++) { if (mid[i] == aft[aftr]) { dfs (midl, i - 1, aftl, aftl + i - midl - 1); dfs (i + 1, midr, aftl + i - midl, aftr - 1); break; } } } int main () { scanf ("%s%s", mid, aft); dfs (0, strlen(mid) - 1, 0, strlen(mid) - 1); return 0; }
19.387097
57
0.464226
langonginc
0ba4785770d1c2710060909c83f81e8b0287ceb1
694
hpp
C++
Sources/Part12/Game.hpp
marukrap/RoguelikeTutorial2020
6fbed9068dff6279f1e3a885329cc2dfaec1ad4a
[ "MIT" ]
25
2020-06-25T03:08:31.000Z
2022-01-30T15:38:48.000Z
Sources/Part12/Game.hpp
marukrap/RoguelikeTutorial2020
6fbed9068dff6279f1e3a885329cc2dfaec1ad4a
[ "MIT" ]
2
2020-08-10T17:52:45.000Z
2020-08-18T04:02:00.000Z
Sources/Part12/Game.hpp
marukrap/RoguelikeTutorial2020
6fbed9068dff6279f1e3a885329cc2dfaec1ad4a
[ "MIT" ]
2
2020-07-01T05:09:04.000Z
2020-08-04T02:19:04.000Z
#pragma once #include "Engine/Renderer.hpp" #include "World.hpp" class Console; class Game { public: Game(SDL_Window& window, Console& console); bool isRunning() const; void tick(); World* getWorld(); void createWorld(); void loadSavefile(); void closeMenu(); void openMenu(std::unique_ptr<Menu> menu); void openMainMenu(); void openPauseMenu(); void openInventory(SDL_Keycode key); bool isSaving(); void save(bool quit); private: void processInput(); void update(); void render(); private: SDL_Window& m_window; Console& m_console; Renderer m_renderer; bool m_running = true; std::unique_ptr<World> m_world = nullptr; std::unique_ptr<Menu> m_menu = nullptr; };
16.139535
44
0.71902
marukrap
2437fb635dfce2a779dfe830f1c189e321c0d80a
10,224
hpp
C++
WICWIU_src/Optimizer.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
WICWIU_src/Optimizer.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
WICWIU_src/Optimizer.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
[ "Apache-2.0" ]
null
null
null
#ifndef OPTIMIZER_H_ #define OPTIMIZER_H_ value #include "LossFunction_utils.hpp" enum OptimizeDirection { MAXIMIZE, MINIMIZE }; template<typename DTYPE> class Optimizer { private: float m_LearningRate; int m_OptimizeDirection; // 1 or -1 float m_weightDecayRate; Container<Operator<DTYPE> *> *m_ppParameters; int m_numOfParameter; int m_idOfDevice; #ifdef __CUDNN__ cudnnHandle_t m_pCudnnHandle; #endif // if __CUDNN__ public: Optimizer(Operator<DTYPE> **pParameters, float pLearningRate, OptimizeDirection pOptimizeDirection); Optimizer(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, OptimizeDirection pOptimizeDirection); Optimizer(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, float pWeightDecayRate, OptimizeDirection pOptimizeDirection); virtual ~Optimizer(); int Alloc(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, OptimizeDirection pOptimizeDirection); int Alloc(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, float pWeightDecayRate, OptimizeDirection pOptimizeDirection); int Delete(); virtual int UpdateParameter(); virtual int UpdateParameter(Operator<DTYPE> *pTrainableTensor) = 0; void SetLearningRate(float pLearningRate); void SetTrainableTensorDegree(int pTrainableTensorDegree); void SetWeightDecayRate(int pWeightDecayRate); float GetLearningRate() const; int GetOptimizeDirection() const; Container<Operator<DTYPE> *>* GetTrainableTensor(); int GetTrainableTensorDegree() const; float GetWeightDecayRate() const; int ResetParameterGradient(); #ifdef __CUDNN__ void SetDeviceGPU(cudnnHandle_t& pCudnnHandle, unsigned int idOfDevice); virtual void InitializeAttributeForGPU(unsigned int idOfDevice) = 0; virtual void SetCudnnHandle(cudnnHandle_t& pCudnnHandle); virtual int UpdateParameterOnGPU(); virtual int UpdateParameterOnGPU(Operator<DTYPE> *pTrainableTensor) = 0; cudnnHandle_t& GetCudnnHandle(); int GetDeviceID(); #endif // if __CUDNN__ }; /*! * @brief Optimizer 클래스 생성자 * @details 멤버 변수들을 0 또는 NULL로 초기화하고, * @details 전달받은 매개변수를 매개변수로 하여 Optimizer의 Alloc 메소드를 호출한다. * @param pParameters Optimizer 클래스의 alloc 메소드의 파라미터로 전달할 Trainable Tensor container * @param pLearningRate Optimizer 클래스의 alloc 메소드의 파라미터로 전달할 learning Rate * @param pOptimizeDirection Optimizer 클래스의 alloc 메소드의 파라미터로 전달할 optimize Direction * @return 없음 * @see Optimizer<DTYPE>::Alloc(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, OptimizeDirection pOptimizeDirection) */ template<typename DTYPE> Optimizer<DTYPE>::Optimizer(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, OptimizeDirection pOptimizeDirection) { #ifdef __DEBUG__ std::cout << "Optimizer::Optimizer(Operator<DTYPE> *, float, OptimizeDirection)" << '\n'; #endif // __DEBUG__ m_LearningRate = 0.f; m_OptimizeDirection = 1; m_ppParameters = NULL; m_numOfParameter = 0; m_weightDecayRate = 0.f; m_idOfDevice = -1; Alloc(pParameters, pLearningRate, pOptimizeDirection); } /*! * @brief Optimizer 클래스 생성자 * @details 멤버 변수들을 0 또는 NULL로 초기화하고, * @details 전달받은 매개변수를 매개변수로 하여 Optimizer의 Alloc 메소드를 호출한다. * @param pParameters Optimizer 클래스의 alloc 메소드의 파라미터로 전달할 Trainable Tensor container * @param pLearningRate Optimizer 클래스의 alloc 메소드의 파라미터로 전달할 learning Rate * @param pWeightDecayRate Optimizer 클래스의 alloc 메소드의 파라미터로 전달할 Weight Decay Rate * @param pOptimizeDirection Optimizer 클래스의 alloc 메소드의 파라미터로 전달할 optimize Direction * @return 없음 * @see Optimizer<DTYPE>::Alloc(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, float pWeightDecayRate, OptimizeDirection pOptimizeDirection) */ template<typename DTYPE> Optimizer<DTYPE>::Optimizer(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, float pWeightDecayRate, OptimizeDirection pOptimizeDirection) { #ifdef __DEBUG__ std::cout << "Optimizer::Optimizer(Operator<DTYPE> *, float, OptimizeDirection)" << '\n'; #endif // __DEBUG__ m_LearningRate = 0.f; m_OptimizeDirection = 1; m_ppParameters = NULL; m_numOfParameter = 0; m_weightDecayRate = 0.f; m_idOfDevice = -1; Alloc(pParameters, pLearningRate, pWeightDecayRate, pOptimizeDirection); } /*! * @brief Optimizer 클래스 소멸자 * @details Optimizer<DTYPE>::Delete() 메소드를 호출하고 클래스를 소멸시킨다. * @return 없음 */ template<typename DTYPE> Optimizer<DTYPE>::~Optimizer() { #ifdef __DEBUG__ std::cout << "Optimizer::~Optimizer()" << '\n'; #endif // __DEBUG__ this->Delete(); } /*! * @brief Optimizer 클래스의 멤버 변수들에 값을 할당하는 메소드 * @details 매개변수로 전달 받은 값들을 각각 Trainable Tensor Conatiner, learning rate, Optimize Direction, Weight Decay Rate 멤버 변수에 할당한다. * @param pParameters Optimizer 클래스에의 Trainable Tensor container 멤버 변수 * @param pLearningRate Optimizer 클래스의 learning Rate 멤버 변수 * @param pOptimizeDirection Optimizer 클래스의 optimize Direction 멤버 변수 * @return TRUE */ template<typename DTYPE> int Optimizer<DTYPE>::Alloc(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, OptimizeDirection pOptimizeDirection) { #ifdef __DEBUG__ std::cout << "Optimizer::Alloc(Container<Operator<DTYPE> *> *, float , OptimizeDirection )" << '\n'; #endif // __DEBUG__ m_ppParameters = pParameters; m_numOfParameter = pParameters->GetSize(); m_LearningRate = pLearningRate; if (pOptimizeDirection == MAXIMIZE) m_OptimizeDirection = 1; else if (pOptimizeDirection == MINIMIZE) m_OptimizeDirection = -1; return TRUE; } /*! * @brief Optimizer 클래스의 멤버 변수들에 값을 할당하는 메소드 * @details 매개변수로 전달 받은 값들을 각각 Trainable Tensor Conatiner, learning rate, Optimize Direction, Weight Decay Rate 멤버 변수에 할당한다. * @param pParameters Optimizer 클래스에의 Trainable Tensor container 멤버 변수 * @param pLearningRate Optimizer 클래스의 learning Rate 멤버 변수 * @param pWeightDecayRate Optimizer 클래스의 Weight Decay Rate 멤버 변수 * @param pOptimizeDirection Optimizer 클래스의 optimize Direction 멤버 변수 * @return TRUE */ template<typename DTYPE> int Optimizer<DTYPE>::Alloc(Container<Operator<DTYPE> *> *pParameters, float pLearningRate, float pWeightDecayRate, OptimizeDirection pOptimizeDirection) { #ifdef __DEBUG__ std::cout << "Optimizer::Alloc(Container<Operator<DTYPE> *> *, float , OptimizeDirection )" << '\n'; #endif // __DEBUG__ m_ppParameters = pParameters; m_numOfParameter = pParameters->GetSize(); m_LearningRate = pLearningRate; if (pOptimizeDirection == MAXIMIZE) m_OptimizeDirection = 1; else if (pOptimizeDirection == MINIMIZE) m_OptimizeDirection = -1; m_weightDecayRate = pWeightDecayRate; // std::cout << "m_weightDecayRate" << m_weightDecayRate << '\n'; return TRUE; } template<typename DTYPE> int Optimizer<DTYPE>::Delete() { return TRUE; } /*! * @brief Trainable Tensor Container의 Operator들의 파라미터들을 순서대로 업데이트하는 메소드 * @details 파생 클래스에서 오버라이드해서 사용하는 메소드 * @return TRUE */ template<typename DTYPE> int Optimizer<DTYPE>::UpdateParameter() { for (int i = 0; i < m_numOfParameter; i++) { if((*m_ppParameters)[i]->GetIsTrainable()) UpdateParameter((*m_ppParameters)[i]); } return TRUE; } #ifdef __CUDNN__ template<typename DTYPE> void Optimizer<DTYPE>::SetDeviceGPU(cudnnHandle_t& pCudnnHandle, unsigned int idOfDevice) { checkCudaErrors(cudaSetDevice(idOfDevice)); SetCudnnHandle(pCudnnHandle); m_idOfDevice = idOfDevice; InitializeAttributeForGPU(idOfDevice); } template<typename DTYPE> void Optimizer<DTYPE>::SetCudnnHandle(cudnnHandle_t& pCudnnHandle) { m_pCudnnHandle = pCudnnHandle; } template<typename DTYPE> int Optimizer<DTYPE>::GetDeviceID() { return m_idOfDevice; } template<typename DTYPE> cudnnHandle_t& Optimizer<DTYPE>::GetCudnnHandle() { return m_pCudnnHandle; } /*! * @brief GPU를 활용해 Trainable Tensor Container의 Operator들의 파라미터들을 순서대로 업데이트하는 메소드 * @details 파생 클래스에서 오버라이드해서 사용하는 메소드 * @return TRUE */ template<typename DTYPE> int Optimizer<DTYPE>::UpdateParameterOnGPU() { for (int i = 0; i < m_numOfParameter; i++) { if((*m_ppParameters)[i]->GetIsTrainable()) UpdateParameterOnGPU((*m_ppParameters)[i]); } return TRUE; } #endif // if __CUDNN__ template<typename DTYPE> void Optimizer<DTYPE>::SetLearningRate(float pLearningRate) { m_LearningRate = pLearningRate; } template<typename DTYPE> void Optimizer<DTYPE>::SetTrainableTensorDegree(int pTrainableTensorDegree) { m_numOfParameter = pTrainableTensorDegree; } template<typename DTYPE> void Optimizer<DTYPE>::SetWeightDecayRate(int pWeightDecayRate) { m_weightDecayRate = pWeightDecayRate; } template<typename DTYPE> float Optimizer<DTYPE>::GetLearningRate() const { return m_LearningRate; } template<typename DTYPE> int Optimizer<DTYPE>::GetOptimizeDirection() const { return m_OptimizeDirection; } template<typename DTYPE> float Optimizer<DTYPE>::GetWeightDecayRate() const { return m_weightDecayRate; } template<typename DTYPE> Container<Operator<DTYPE> *> *Optimizer<DTYPE>::GetTrainableTensor() { return m_ppParameters; } template<typename DTYPE> int Optimizer<DTYPE>::GetTrainableTensorDegree() const { return m_numOfParameter; } /*! * @brief Trainable Tensor Container의 Operator들의 Gradient를 초기화하는 메소드 * @return TRUE * @ref Operator<DTYPE>::ResetGradient() */ template<typename DTYPE> int Optimizer<DTYPE>::ResetParameterGradient() { for (int i = 0; i < m_numOfParameter; i++) { #if __RESET__ std::cout<<"Optimizer::ResetParameterGradient함수 호출 "<<i<<'\n'; #endif (*m_ppParameters)[i]->ResetGradient(); } return TRUE; } #endif // OPTIMIZER_H_
36.776978
180
0.702758
ChanhyoLee
24390a5d58651a882fcc4dae39937bf58154c46c
9,140
cpp
C++
libfastcgipp/request.cpp
xujintao/ratel
a1c3409872816510cca96a0e866c47260a315341
[ "MIT" ]
1
2018-01-08T02:13:04.000Z
2018-01-08T02:13:04.000Z
libfastcgipp/request.cpp
xujintao/ratel
a1c3409872816510cca96a0e866c47260a315341
[ "MIT" ]
null
null
null
libfastcgipp/request.cpp
xujintao/ratel
a1c3409872816510cca96a0e866c47260a315341
[ "MIT" ]
null
null
null
/*! * @file request.cpp * @brief Defines the Request class * @author Eddie Carle &lt;eddie@isatec.ca&gt; * @date May 20, 2017 * @copyright Copyright &copy; 2017 Eddie Carle. This project is released under * the GNU Lesser General Public License Version 3. */ /******************************************************************************* * Copyright (C) 2017 Eddie Carle [eddie@isatec.ca] * * * * This file is part of fastcgi++. * * * * fastcgi++ is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the Free * * Software Foundation, either version 3 of the License, or (at your option) * * any later version. * * * * fastcgi++ is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * * more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with fastcgi++. If not, see <http://www.gnu.org/licenses/>. * *******************************************************************************/ #include "fastcgi++/request.hpp" #include "fastcgi++/log.hpp" template<class charT> void Fastcgipp::Request<charT>::complete() { out.flush(); err.flush(); Block record(sizeof(Protocol::Header)+sizeof(Protocol::EndRequest)); Protocol::Header& header = *reinterpret_cast<Protocol::Header*>(record.begin()); header.version = Protocol::version; header.type = Protocol::RecordType::END_REQUEST; header.fcgiId = m_id.m_id; header.contentLength = sizeof(Protocol::EndRequest); header.paddingLength = 0; Protocol::EndRequest& body = *reinterpret_cast<Protocol::EndRequest*>(record.begin()+sizeof(header)); body.appStatus = 0; body.protocolStatus = m_status; m_send(m_id.m_socket, std::move(record), m_kill); } template<class charT> std::unique_lock<std::mutex> Fastcgipp::Request<charT>::handler(const std::function<bool(RequestPtr)> response) { std::unique_lock<std::mutex> lock(m_messagesMutex); while(!m_messages.empty()) { Message message = std::move(m_messages.front()); m_messages.pop(); lock.unlock(); if(message.type == 0) { const Protocol::Header& header = *reinterpret_cast<Protocol::Header*>(message.data.begin()); const auto body = message.data.begin()+sizeof(header); const auto bodyEnd = body+header.contentLength; if(header.type == Protocol::RecordType::ABORT_REQUEST) { complete(); goto exit; } if(header.type != m_state) { WARNING_LOG("Records received out of order from web server") errorHandler(); goto exit; } switch(m_state) { case Protocol::RecordType::PARAMS: { if(!( role()==Protocol::Role::RESPONDER || role()==Protocol::Role::AUTHORIZER)) { m_status = Protocol::ProtocolStatus::UNKNOWN_ROLE; WARNING_LOG("We got asked to do an unknown role") errorHandler(); goto exit; } if(header.contentLength == 0) { if(environment().contentLength > m_maxPostSize) { bigPostErrorHandler(); goto exit; } m_state = Protocol::RecordType::IN; lock.lock(); continue; } m_environment.fill(body, bodyEnd); lock.lock(); continue; } case Protocol::RecordType::IN: { if(header.contentLength==0) { if(!inProcessor() && !m_environment.parsePostBuffer()) { WARNING_LOG("Unknown content type from client") errorHandler(); goto exit; } m_environment.clearPostBuffer(); m_state = Protocol::RecordType::OUT; break; } if(m_environment.postBuffer().size()+(bodyEnd-body) > environment().contentLength) { bigPostErrorHandler(); goto exit; } m_environment.fillPostBuffer(body, bodyEnd); inHandler(header.contentLength); lock.lock(); continue; } default: { ERROR_LOG("Our request is in a weird state.") errorHandler(); goto exit; } } } m_message = std::move(message); if(response(shared_from_this())) { complete(); break; } lock.lock(); } exit: return lock; } template<class charT> void Fastcgipp::Request<charT>::errorHandler() { out << \ "Status: 500 Internal Server Error\n"\ "Content-Type: text/html; charset=utf-8\r\n\r\n"\ "<!DOCTYPE html>"\ "<html lang='en'>"\ "<head>"\ "<title>500 Internal Server Error</title>"\ "</head>"\ "<body>"\ "<h1>500 Internal Server Error</h1>"\ "</body>"\ "</html>"; complete(); } template<class charT> void Fastcgipp::Request<charT>::bigPostErrorHandler() { out << \ "Status: 413 Request Entity Too Large\n"\ "Content-Type: text/html; charset=utf-8\r\n\r\n"\ "<!DOCTYPE html>"\ "<html lang='en'>"\ "<head>"\ "<title>413 Request Entity Too Large</title>"\ "</head>"\ "<body>"\ "<h1>413 Request Entity Too Large</h1>"\ "</body>"\ "</html>"; complete(); } template<class charT> void Fastcgipp::Request<charT>::configure( const Protocol::RequestId& id, const Protocol::Role& role, bool kill, const std::function<void(const Socket&, Block&&, bool)> send, const std::function<void(Message)> callback) { //using namespace std::placeholders; m_kill=kill; m_id=id; m_role=role; m_callback=callback; m_send=send; m_outStreamBuffer.configure( id, Protocol::RecordType::OUT, std::bind(send, std::placeholders::_1, std::placeholders::_2, false)); m_errStreamBuffer.configure( id, Protocol::RecordType::ERR, std::bind(send, std::placeholders::_1, std::placeholders::_2, false)); } template<class charT> unsigned Fastcgipp::Request<charT>::pickLocale( const std::vector<std::string>& locales) { unsigned index=0; for(const std::string& language: environment().acceptLanguages) { if(language.size() <= 5) { const auto it = std::find_if( locales.cbegin(), locales.cend(), [&language] (const std::string& locale) { return std::equal( language.cbegin(), language.cend(), locale.cbegin()); }); if(it != locales.cend()) { index = it-locales.cbegin(); break; } } } return index; } template<class charT> void Fastcgipp::Request<charT>::setLocale( const std::string& locale) { try { out.imbue(std::locale(locale+codepage())); } catch(...) { ERROR_LOG("Unable to set locale") out.imbue(std::locale("C")); } } namespace Fastcgipp { template<> const char* Fastcgipp::Request<wchar_t>::codepage() const { return ".UTF-8"; } template<> const char* Fastcgipp::Request<char>::codepage() const { return ""; } } template class Fastcgipp::Request<char>; template class Fastcgipp::Request<wchar_t>;
31.958042
111
0.475274
xujintao
24395a7adb27e736c0472ad08e352db343f3e6c2
2,832
cpp
C++
stdshader_vulkan/src/shaders/ShaderParamNext.cpp
melvyn2/TF2Vulkan
a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4
[ "MIT" ]
null
null
null
stdshader_vulkan/src/shaders/ShaderParamNext.cpp
melvyn2/TF2Vulkan
a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4
[ "MIT" ]
null
null
null
stdshader_vulkan/src/shaders/ShaderParamNext.cpp
melvyn2/TF2Vulkan
a8cd1c49ecfe9d4dc31af0a50ba7690c61c255c4
[ "MIT" ]
null
null
null
#include "ShaderParamNext.h" using namespace TF2Vulkan; using namespace TF2Vulkan::Shaders; ShaderParamNext::ShaderParamNext(const char* name, ShaderParamType_t type, const char* defaultVal, const char* help, int flags) { m_Info.m_pName = name; m_Info.m_Type = type; m_Info.m_pDefaultValue = defaultVal; m_Info.m_pHelp = help; m_Info.m_nFlags = flags; } ShaderParamNext::ShaderParamNext(ShaderMaterialVars_t overrideVar, ShaderParamType_t type, const char* defaultVal, const char* help, int flags) : m_Index(overrideVar) { m_Info.m_pName = "override"; m_Info.m_Type = type; m_Info.m_pDefaultValue = defaultVal; m_Info.m_pHelp = help; m_Info.m_nFlags = flags; } const char* ShaderParamNext::GetName() const { return m_Info.m_pName; } const char* ShaderParamNext::GetHelp() const { return m_Info.m_pHelp; } const char* ShaderParamNext::GetDefault() const { return m_Info.m_pDefaultValue; } int ShaderParamNext::GetFlags() const { return m_Info.m_nFlags; } ShaderParamType_t ShaderParamNext::GetType() const { return m_Info.m_Type; } const ShaderParamInfo_t& ShaderParamNext::GetParamInfo() const { return m_Info; } int ShaderParamNext::GetIndex() const { assert(m_Index >= 0); // You must call InitShaderParamIndices on this block return m_Index; } ShaderParamNext::operator int() const { return GetIndex(); } bool ShaderParamNext::InitIndex(int index) { if (m_Index == -1) { m_Index = index; return true; } assert(m_Index >= 0 && m_Index < NUM_SHADER_MATERIAL_VARS); return false; } static bool CheckParamIndex(int index) { if (index < 0) { assert(!"Invalid param index"); return false; } return true; } void ShaderParamNext::InitParamInt(IMaterialVar** params, int defaultVal) const { if (CheckParamIndex(m_Index) && !params[m_Index]->IsDefined()) params[m_Index]->SetIntValue(defaultVal); } void ShaderParamNext::InitParamFloat(IMaterialVar** params, float defaultVal) const { if (CheckParamIndex(m_Index) && !params[m_Index]->IsDefined()) params[m_Index]->SetFloatValue(defaultVal); } void ShaderParamNext::InitParamVec(IMaterialVar** params, float defaultValX, float defaultValY) const { if (CheckParamIndex(m_Index) && !params[m_Index]->IsDefined()) params[m_Index]->SetVecValue(defaultValX, defaultValY); } void ShaderParamNext::InitParamVec(IMaterialVar** params, float defaultValX, float defaultValY, float defaultValZ) const { if (CheckParamIndex(m_Index) && !params[m_Index]->IsDefined()) params[m_Index]->SetVecValue(defaultValX, defaultValY, defaultValZ); } void ShaderParamNext::InitParamVec(IMaterialVar** params, float defaultValX, float defaultValY, float defaultValZ, float defaultValW) const { if (CheckParamIndex(m_Index) && !params[m_Index]->IsDefined()) params[m_Index]->SetVecValue(defaultValX, defaultValY, defaultValZ, defaultValW); }
23.6
139
0.759181
melvyn2
243d3825608d2ab307f4e99b9aa3b143963e9c5c
7,997
cpp
C++
Attic/AtomicEditorReference/Source/AEEditor.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
Attic/AtomicEditorReference/Source/AEEditor.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
Attic/AtomicEditorReference/Source/AEEditor.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/AtomicGameEngine/AtomicGameEngine #include "AtomicEditor.h" #include <Atomic/Engine/Engine.h> #include <Atomic/IO/FileSystem.h> #include <Atomic/Resource/ResourceCache.h> #include <Atomic/Input/Input.h> #include <Atomic/UI/UI.h> #include <Atomic/Core/CoreEvents.h> #include <AtomicJS/Javascript/Javascript.h> #include "AEEditor.h" #include "AEPreferences.h" #include "Project/AEProject.h" #include "AEJavascript.h" #include "AEEvents.h" #include "Player/AEPlayer.h" #ifdef USE_SPIDERMONKEY #include "Javascript/JSSpiderMonkeyVM.h" #endif #include "UI/UIMainFrame.h" #include "UI/UIProjectFrame.h" #include "UI/UIResourceFrame.h" #include "UI/Modal/UIMessageModal.h" #include "License/AELicenseSystem.h" #include "Resources/AEResourceOps.h" #include <TurboBadger/tb_message_window.h> #include <TurboBadger/animation/tb_animation.h> namespace AtomicEditor { Editor::Editor(Context* context) : Object(context), currentPlatform_(AE_PLATFORM_UNDEFINED), requestExit_(false) { RegisterEditorLibrary(context_); aejavascript_ = new AEJavascript(context_); aepreferences_ = new AEPreferences(context_); #ifdef USE_SPIDERMONKEY spidermonkey_ = new JSSpiderMonkeyVM(context_); #endif resourceCreator_ = new ResourceOps(context_); // Create the Main Editor Frame mainframe_ = new MainFrame(context_); SubscribeToEvent(E_EXITREQUESTED, HANDLER(Editor, HandleExitRequested)); SubscribeToEvent(E_PLAYERERROR, HANDLER(Editor, HandlePlayerError)); SubscribeToEvent(E_POSTUPDATE, HANDLER(Editor, HandlePostUpdate)); // the player handling might move SubscribeToEvent(E_EDITORPLAYREQUEST, HANDLER(Editor, HandlePlayRequest)); SubscribeToEvent(E_EDITORPLAYSTOP, HANDLER(Editor, HandlePlayStop)); SubscribeToEvent(E_EDITORPLAYSTARTED, HANDLER(Editor, HandlePlayStarted)); SubscribeToEvent(E_EDITORPLAYSTOPPED, HANDLER(Editor, HandlePlayStopped)); // BEGIN LICENSE MANAGEMENT GetSubsystem<LicenseSystem>()->Initialize(); // END LICENSE MANAGEMENT } Editor::~Editor() { } MainFrame* Editor::GetMainFrame() { return mainframe_; } Project* Editor::GetProject() { return project_; } AEPreferences* Editor::GetPreferences() { return aepreferences_; } void Editor::EditResource(const String& fullpath) { mainframe_->GetResourceFrame()->EditResource(fullpath); } void Editor::LoadProject(const String& fullpath) { aepreferences_->RegisterRecentProject(fullpath); String path = GetPath(fullpath); ResourceCache* cache = GetSubsystem<ResourceCache>(); cache->AddResourceDir(path, 0); String resourcePath = path; resourcePath += "Resources"; cache->AddResourceDir(resourcePath, 0); project_ = new Project(context_); project_->SetResourcePath(resourcePath); project_->Load(fullpath); mainframe_->ShowResourceFrame(); mainframe_->GetProjectFrame()->RefreshFolders(); mainframe_->UpdateJavascriptErrors(); } void Editor::CloseProject() { if (project_.Null()) return; ResourceCache* cache = GetSubsystem<ResourceCache>(); String projectPath = project_->GetProjectFilePath(); String resourcePath = project_->GetResourcePath(); mainframe_->GetProjectFrame()->Clear(); mainframe_->GetResourceFrame()->CloseAllResourceEditors(); project_ = 0; cache->RemoveResourceDir(resourcePath); cache->RemoveResourceDir(projectPath); cache->ReleaseAllResources(true); mainframe_->ShowWelcomeFrame(); } void Editor::SaveProject() { if (project_.Null()) return; project_->Save(project_->GetProjectFilePath()); } // Project Playing void Editor::HandlePlayStarted(StringHash eventType, VariantMap& eventData) { } void Editor::HandlePlayStop(StringHash eventType, VariantMap& eventData) { SendEvent(E_EDITORPLAYSTOPPED); if (!player_) return; //UI* tbui = GetSubsystem<UI>(); //tbui->SetKeyboardDisabled(false); if (player_->GetMode() != AE_PLAYERMODE_WIDGET) { //tbui->SetInputDisabled(false); } Input* input = GetSubsystem<Input>(); input->SetMouseVisible(true); mainframe_->UpdateJavascriptErrors(); player_->Invalidate(); player_ = NULL; } void Editor::HandlePlayStopped(StringHash eventType, VariantMap& eventData) { } void Editor::HandlePlayerError(StringHash eventType, VariantMap& eventData) { } void Editor::PostModalError(const String& title, const String& message) { using namespace EditorModal; VariantMap eventData; eventData[P_TYPE] = EDITOR_MODALERROR; eventData[P_TITLE] = title; eventData[P_MESSAGE] = message; SendEvent(E_EDITORMODAL, eventData); } void Editor::PostModalInfo(const String& title, const String& message) { using namespace EditorModal; VariantMap eventData; eventData[P_TYPE] = EDITOR_MODALINFO; eventData[P_TITLE] = title; eventData[P_MESSAGE] = message; SendEvent(E_EDITORMODAL, eventData); } void Editor::RequestPlatformChange(AEEditorPlatform platform) { // BEGIN LICENSE MANAGEMENT LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>(); if (!licenseSystem->RequestPlatformChange(platform)) { PostModalInfo("Platform License Required", "Platform License is required to switch to this deployment"); return; } if (currentPlatform_ == platform) return; // if we can switch platforms via some other event, may want to do this in a handler currentPlatform_ = platform; if (!project_.Null()) project_->Save(project_->GetProjectFilePath()); using namespace PlatformChange; VariantMap eventData; eventData[P_PLATFORM] = (unsigned) platform; SendEvent(E_PLATFORMCHANGE, eventData); // END LICENSE MANAGEMENT } void Editor::HandlePlayRequest(StringHash eventType, VariantMap& eventData) { if (player_ || project_.Null()) return; ResourceFrame* resourceFrame = mainframe_->GetResourceFrame(); if (resourceFrame->HasUnsavedModifications()) { PostModalError("Unsaved Modifications", "There are unsaved modications.\nPlease save before entering play mode"); return; } else if (mainframe_->UpdateJavascriptErrors()) { return; } assert(!player_); AEPlayerMode mode = (AEPlayerMode) eventData[EditorPlayStarted::P_MODE].GetUInt(); if (mode != AE_PLAYERMODE_WIDGET) { //tbui->SetInputDisabled(true); } player_ = new AEPlayer(context_); TBWidgetDelegate* tb = mainframe_->GetResourceFrame()->GetWidgetDelegate(); TBRect rect = tb->GetRect(); tb->ConvertToRoot(rect.x, rect.y); if (!player_->Play(mode, IntRect(rect.x, rect.y, rect.x + rect.w, rect.y + rect.h))) { player_->Invalidate(); player_ = 0; return; } SendEvent(E_EDITORPLAYSTARTED, eventData); } void Editor::HandlePostUpdate(StringHash eventType, VariantMap& eventData) { if (player_ && player_->HasErrors()) { SendEvent(E_EDITORPLAYSTOP); } if (requestExit_) { requestExit_ = false; SendEvent(E_EXITREQUESTED); } } void Editor::HandleExitRequested(StringHash eventType, VariantMap& eventData) { if (aepreferences_.NotNull()) { aepreferences_->Write(); } mainframe_ = 0; player_ = 0; project_ = 0; javascript_ = 0; aejavascript_ = 0; aepreferences_ = 0; TBAnimationManager::BeginBlockAnimations(); UI* tbui = GetSubsystem<UI>(); tbui->Shutdown(); context_->RemoveSubsystem(Javascript::GetBaseTypeStatic()); SendEvent(E_EDITORSHUTDOWN); SharedPtr<Editor> keepAlive(this); context_->RemoveSubsystem(GetType()); Engine* engine = GetSubsystem<Engine>(); engine->Exit(); } void RegisterEditorLibrary(Context* context) { } }
23.112717
121
0.709516
honigbeutler123
243e63871cfca3cf5c2c42d2bdcb9f3985742b21
1,966
cpp
C++
lab08/lab08es02/lab08es02/Source.cpp
MartinoMensio/SDP-Labs
61c5bb66345f94578bc79bae777d7344b3bb60af
[ "MIT" ]
1
2017-04-27T09:12:01.000Z
2017-04-27T09:12:01.000Z
lab08/lab08es02/lab08es02/Source.cpp
MartinoMensio/SDP-Labs
61c5bb66345f94578bc79bae777d7344b3bb60af
[ "MIT" ]
null
null
null
lab08/lab08es02/lab08es02/Source.cpp
MartinoMensio/SDP-Labs
61c5bb66345f94578bc79bae777d7344b3bb60af
[ "MIT" ]
4
2017-02-19T10:08:08.000Z
2021-12-01T16:17:10.000Z
#ifndef UNICODE #define UNICODE #define _UNICODE #endif // !UNICODE #include <Windows.h> #include <tchar.h> #include <stdio.h> #define STR_MAX_L 30+1 // extra 1 for \0 typedef struct _student { INT id; DWORD regNum; TCHAR surname[STR_MAX_L]; TCHAR name[STR_MAX_L]; INT mark; } student; INT _tmain(INT argc, LPTSTR argv[]) { HANDLE hOut; FILE *fInP; DWORD nOut; student s; if (argc != 3) { _ftprintf(stderr, _T("Usage: %s file_in file_out\n"), argv[0]); return 1; } fInP = _tfopen(argv[1], _T("rt")); if (fInP == NULL) { _ftprintf(stderr, _T("Cannot open input file %s. Error: %x\n"), argv[1], GetLastError()); return 2; } hOut = CreateFile(argv[2], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOut == INVALID_HANDLE_VALUE) { _ftprintf(stderr, _T("Cannot open output file %s. Error: %x\n"), argv[2], GetLastError()); fclose(fInP); return 3; } while (_ftscanf(fInP, _T("%d %ld %s %s %d"), &s.id, &s.regNum, s.surname, s.name, &s.mark) == 5) { WriteFile(hOut, &s, sizeof(s), &nOut, NULL); if (nOut != sizeof(s)) { _ftprintf(stderr, _T("Cannot write correctly the output. Error: %x\n"), GetLastError()); fclose(fInP); CloseHandle(hOut); return 4; } } _tprintf(_T("Correctly written the output file\n")); fclose(fInP); CloseHandle(hOut); _tprintf(_T("Now reading it back:\n")); HANDLE hIn; DWORD nIn; hIn = CreateFile(argv[2], GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hIn == INVALID_HANDLE_VALUE) { _ftprintf(stderr, _T("Cannot open the file %s. Error: %x\n"), argv[2], GetLastError()); return 5; } while (ReadFile(hIn, &s, sizeof(s), &nIn, NULL) && nIn > 0) { if (nIn != sizeof(s)) { _ftprintf(stderr, _T("Error reading, file shorter than expected\n")); } _tprintf(_T("id: %d\treg_number: %ld\tsurname: %10s\tname: %10s\tmark: %d\n"), s.id, s.regNum, s.surname, s.name, s.mark); } CloseHandle(hIn); return 0; }
25.868421
124
0.65412
MartinoMensio
244246f3f17d305ce8b5eccd1df4555821c16dea
1,110
cxx
C++
StRoot/StHighptPool/StHiMicroEvent/StHiMicroTrack.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StHighptPool/StHiMicroEvent/StHiMicroTrack.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StHighptPool/StHiMicroEvent/StHiMicroTrack.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id: StHiMicroTrack.cxx,v 1.2 2003/09/02 17:58:36 perev Exp $ * * Author: Bum Choi, UT Austin, Apr 2002 * *************************************************************************** * * Description: This is a uDST for highpt Analysis: Track Information * *************************************************************************** * * $Log: StHiMicroTrack.cxx,v $ * Revision 1.2 2003/09/02 17:58:36 perev * gcc 3.2 updates + WarnOff * * Revision 1.1 2002/04/02 19:36:15 jklay * Bums highpt uDST format * * **************************************************************************/ #include "StHiMicroTrack.h" #include "Stiostream.h" #define DEBUG 0 ClassImp(StHiMicroTrack) StHiMicroTrack::StHiMicroTrack() { if(DEBUG) cout << "StHiMicroTrack::StHiMicroTrack" << endl; } StHiMicroTrack::~StHiMicroTrack() { if(DEBUG) cout << "StHiMicroTrack::~StHiMicroTrack" << endl; } //______________________
25.227273
121
0.435135
xiaohaijin
24427cc6e7131c8fbbcd69b968f04cd7d8d82190
3,628
cpp
C++
libraries/Robot_Control/src/EasyTransfer2.cpp
Ropes/dawnpatrol
257e413f9151459bcd34a315cf7ec6c676d5ef90
[ "MIT" ]
43
2015-05-22T20:07:36.000Z
2022-02-23T04:28:23.000Z
libraries/Robot_Control/src/EasyTransfer2.cpp
Ropes/dawnpatrol
257e413f9151459bcd34a315cf7ec6c676d5ef90
[ "MIT" ]
52
2015-01-02T05:50:10.000Z
2021-07-23T20:34:50.000Z
libraries/Robot_Control/src/EasyTransfer2.cpp
Ropes/dawnpatrol
257e413f9151459bcd34a315cf7ec6c676d5ef90
[ "MIT" ]
80
2015-09-28T09:47:00.000Z
2020-02-04T16:04:04.000Z
#include "EasyTransfer2.h" //Captures address and size of struct void EasyTransfer2::begin(HardwareSerial *theSerial){ _serial = theSerial; //dynamic creation of rx parsing buffer in RAM //rx_buffer = (uint8_t*) malloc(size); resetData(); } void EasyTransfer2::writeByte(uint8_t dat){ if(position<20) data[position++]=dat; size++; } void EasyTransfer2::writeInt(int dat){ if(position<19){ data[position++]=dat>>8; data[position++]=dat; size+=2; } } uint8_t EasyTransfer2::readByte(){ if(position>=size)return 0; return data[position++]; } int EasyTransfer2::readInt(){ if(position+1>=size)return 0; int dat_1=data[position++]<<8; int dat_2=data[position++]; int dat= dat_1 | dat_2; return dat; } void EasyTransfer2::resetData(){ for(int i=0;i<20;i++){ data[i]=0; } size=0; position=0; } //Sends out struct in binary, with header, length info and checksum void EasyTransfer2::sendData(){ uint8_t CS = size; _serial->write(0x06); _serial->write(0x85); _serial->write(size); for(int i = 0; i<size; i++){ CS^=*(data+i); _serial->write(*(data+i)); //Serial.print(*(data+i)); //Serial.print(","); } //Serial.println(""); _serial->write(CS); resetData(); } boolean EasyTransfer2::receiveData(){ //start off by looking for the header bytes. If they were already found in a previous call, skip it. if(rx_len == 0){ //this size check may be redundant due to the size check below, but for now I'll leave it the way it is. if(_serial->available() >= 3){ //this will block until a 0x06 is found or buffer size becomes less then 3. while(_serial->read() != 0x06) { //This will trash any preamble junk in the serial buffer //but we need to make sure there is enough in the buffer to process while we trash the rest //if the buffer becomes too empty, we will escape and try again on the next call if(_serial->available() < 3) return false; } //Serial.println("head"); if (_serial->read() == 0x85){ rx_len = _serial->read(); //Serial.print("rx_len:"); //Serial.println(rx_len); resetData(); //make sure the binary structs on both Arduinos are the same size. /*if(rx_len != size){ rx_len = 0; return false; }*/ } } //Serial.println("nothing"); } //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned. if(rx_len != 0){ while(_serial->available() && rx_array_inx <= rx_len){ data[rx_array_inx++] = _serial->read(); } if(rx_len == (rx_array_inx-1)){ //seem to have got whole message //last uint8_t is CS calc_CS = rx_len; //Serial.print("len:"); //Serial.println(rx_len); for (int i = 0; i<rx_len; i++){ calc_CS^=data[i]; //Serial.print("m"); //Serial.print(data[i]); //Serial.print(","); } //Serial.println(); //Serial.print(data[rx_array_inx-1]); //Serial.print(" "); //Serial.println(calc_CS); if(calc_CS == data[rx_array_inx-1]){//CS good //resetData(); //memcpy(data,d,rx_len); for(int i=0;i<20;i++){ //Serial.print(data[i]); //Serial.print(","); } //Serial.println(""); size=rx_len; rx_len = 0; rx_array_inx = 0; return true; } else{ //Serial.println("CS"); resetData(); //failed checksum, need to clear this out anyway rx_len = 0; rx_array_inx = 0; return false; } } } //Serial.print(rx_len); //Serial.print(" "); //Serial.print(rx_array_inx); //Serial.print(" "); //Serial.println("Short"); return false; }
23.868421
120
0.621279
Ropes
2445024a556486602814e457fd0048989d859f5f
3,339
hpp
C++
Runtime/World/CStateMachine.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
1
2020-06-09T07:49:34.000Z
2020-06-09T07:49:34.000Z
Runtime/World/CStateMachine.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
6
2020-06-09T07:49:45.000Z
2021-04-06T22:19:57.000Z
Runtime/World/CStateMachine.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "Runtime/CToken.hpp" #include "Runtime/GCNTypes.hpp" #include "Runtime/IObj.hpp" #include "Runtime/IObjFactory.hpp" #include "Runtime/IOStreams.hpp" #include "Runtime/World/CAiFuncMap.hpp" namespace urde { class CAiState; class CStateManager; class CAiTrigger { CAiTriggerFunc x0_func; float xc_arg = 0.f; CAiTrigger* x10_andTrig = nullptr; CAiState* x14_state = nullptr; bool x18_lNot = false; public: CAiTrigger() = default; CAiTrigger* GetAnd() const { return x10_andTrig; } CAiState* GetState() const { return x14_state; } bool CallFunc(CStateManager& mgr, CAi& ai) const { if (x0_func) { bool ret = (ai.*x0_func)(mgr, xc_arg); return x18_lNot == !ret; } return true; } void Setup(CAiTriggerFunc func, bool lnot, float arg, CAiTrigger* andTrig) { x0_func = func; x18_lNot = lnot; xc_arg = arg; x10_andTrig = andTrig; } void Setup(CAiTriggerFunc func, bool lnot, float arg, CAiState* state) { x0_func = func; x18_lNot = lnot; xc_arg = arg; x14_state = state; } }; class CAiState { friend class CStateMachineState; CAiStateFunc x0_func; char xc_name[32] = {}; u32 x2c_numTriggers = 0; CAiTrigger* x30_firstTrigger = nullptr; public: CAiState(CAiStateFunc func, const char* name) { x0_func = func; strncpy(xc_name, name, 31); } s32 GetNumTriggers() const { return x2c_numTriggers; } CAiTrigger* GetTrig(s32 i) const { return &x30_firstTrigger[i]; } const char* GetName() const { return xc_name; } void SetTriggers(CAiTrigger* triggers) { x30_firstTrigger = triggers; } void SetNumTriggers(s32 numTriggers) { x2c_numTriggers = numTriggers; } void CallFunc(CStateManager& mgr, CAi& ai, EStateMsg msg, float delta) const { if (x0_func) (ai.*x0_func)(mgr, msg, delta); } }; class CStateMachine { std::vector<CAiState> x0_states; std::vector<CAiTrigger> x10_triggers; public: explicit CStateMachine(CInputStream& in); s32 GetStateIndex(std::string_view state) const; const std::vector<CAiState>& GetStateVector() const { return x0_states; } }; class CStateMachineState { friend class CPatterned; const CStateMachine* x0_machine = nullptr; CAiState* x4_state = nullptr; float x8_time = 0.f; float xc_random = 0.f; float x10_delay = 0.f; float x14_ = 0.f; bool x18_24_codeTrigger : 1 = false; public: CStateMachineState() = default; CAiState* GetActorState() const { return x4_state; } void Update(CStateManager& mgr, CAi& ai, float delta); void SetState(CStateManager&, CAi&, s32); void SetState(CStateManager&, CAi&, const CStateMachine*, std::string_view); const std::vector<CAiState>* GetStateVector() const; void Setup(const CStateMachine* machine); void SetDelay(float delay) { x10_delay = delay; } float GetTime() const { return x8_time; } float GetRandom() const { return xc_random; } float GetDelay() const { return x10_delay; } void SetCodeTrigger() { x18_24_codeTrigger = true; } const char* GetName() const { if (x4_state) return x4_state->GetName(); return nullptr; } }; CFactoryFnReturn FAiFiniteStateMachineFactory(const SObjectTag& tag, CInputStream& in, const CVParamTransfer& vparms, CObjectReference*); } // namespace urde
27.595041
117
0.696017
henriquegemignani
244524dd3e5144860de38298b12ea2eacbb36b4e
3,200
cpp
C++
1project/story.cpp
rianders/2016IntroToProgramming
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
[ "Apache-2.0" ]
3
2016-01-27T18:12:40.000Z
2016-02-03T20:27:19.000Z
1project/story.cpp
rianders/2016IntroToProgramming
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
[ "Apache-2.0" ]
3
2016-03-21T02:18:52.000Z
2016-03-21T03:02:51.000Z
1project/story.cpp
rianders/2016IntroToProgramming
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
[ "Apache-2.0" ]
16
2016-01-27T18:12:41.000Z
2019-09-15T01:42:28.000Z
/* * Hellow World Story. Modified from http://www.cplusplus.com/ * g++ story.cpp -o story.out * ./story.out */ #include <iostream> #include <string> #include <stdlib.h> using namespace std; int main () { int sentenceNumber; string story; string sent1; //sent1 stands for sentence1 string sent2; string sent3; string sent4; string sent5; string sent6; string sent7; string sent8; string sent9; string answer; string mystr; string animal = "monkey"; string instrument = "guitar"; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; cout << "What's your favorite animal? (" << animal <<") "; getline (cin, animal); if (animal == "") { animal = "monkey"; } while (1) { cout << "Do you like " << animal <<"?(yes/no)"; getline (cin, answer); if ( answer == "yes") { cout << "You like: " << animal << endl; break; } if (answer == "no") { cout << "You do not like: " << animal << endl; break; } } cout << "What's your favorite instrument? "; getline (cin, instrument); sent1 = "#this is the story: \n"; sent2 = "Once upon a time there was a **short** "; sent2.append( animal); sent2.append( " who liked to play the "); sent2.append( instrument); sent3 = " and solve equations while *solving* an equation he died."; sent4 = "a couple of scientist decided to clone the monkey so they cloned his genes. \ still dead because he was burned to ashes ."; sent5 = "all this was fake every thing was no more than a nightmare."; sent6 = "When he woke up he discovered that he was surrounded with dead monkeys in a zoo"; sent7 = "his friend the camel came to help him to escape."; sent8 = "After he escaped Nasa caught him"; sent9 = "and sent him to the space as the fifth monkey \ astronaut he died because of a parachute failure.\n" ; int sentUsed[9]; for (int nn = 0; nn < 9; nn++) { sentUsed[nn]=0; } for (int nn = 0; nn < 9; nn = nn + 1) { sentenceNumber = rand() % 9 + 1; sentUsed[sentenceNumber] = 1; cout << "sentence is: " << sentenceNumber << endl; if (sentenceNumber == 0 && sentUsed[nn] == 0) { cout << "Nothing; 0"; } if (sentenceNumber == 1 && sentUsed[nn] == 0) { cout << sent1; } if (sentenceNumber == 2 && sentUsed[nn] == 0) { cout << sent2; } if (sentenceNumber == 3 && sentUsed[nn] == 0) { cout << sent3; } if (sentenceNumber == 4 && sentUsed[nn] == 0) { cout << sent4; } if (sentenceNumber == 5 && sentUsed[nn] == 0) { cout << sent5; } if (sentenceNumber == 6 && sentUsed[nn] == 0) { cout << sent6; } if (sentenceNumber == 7 && sentUsed[nn] == 0) { cout << sent7; } if (sentenceNumber == 8 && sentUsed[nn] == 0) { cout << sent8; } if (sentenceNumber == 9 && sentUsed[nn] == 0) { cout << sent9; } cout << endl; } /* cout << sent1; cout << sent2; cout << sent3 << sent4 << sent5; cout << sent6; cout << sent7; cout << sent8; cout << sent9 << endl; */ return 0; }
22.535211
94
0.5575
rianders
2448fca4f87254ef6e8e0ac0a587990590b9dcea
1,158
cpp
C++
src/helics/network/tcp/TcpCommsCommon.cpp
GMLC-TDC/HELICS-src
5e37168bca0ea9e16b939e052e257182ca6e24bd
[ "BSD-3-Clause" ]
31
2017-06-29T19:50:25.000Z
2019-05-17T14:10:14.000Z
src/helics/network/tcp/TcpCommsCommon.cpp
GMLC-TDC/HELICS-src
5e37168bca0ea9e16b939e052e257182ca6e24bd
[ "BSD-3-Clause" ]
511
2017-08-18T02:14:00.000Z
2019-06-18T20:11:02.000Z
src/helics/network/tcp/TcpCommsCommon.cpp
GMLC-TDC/HELICS-src
5e37168bca0ea9e16b939e052e257182ca6e24bd
[ "BSD-3-Clause" ]
11
2017-10-27T15:03:37.000Z
2019-05-03T19:35:14.000Z
/* Copyright (c) 2017-2022, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include "TcpCommsCommon.h" #include "../../core/ActionMessage.hpp" #include "../CommsInterface.hpp" #include "../NetworkBrokerData.hpp" #include "gmlc/networking/TcpConnection.h" #include <memory> #include <string> namespace helics { namespace tcp { bool commErrorHandler(CommsInterface* comm, gmlc::networking::TcpConnection* /*connection*/, const std::error_code& error) { if (comm->isConnected()) { if ((error != asio::error::eof) && (error != asio::error::operation_aborted)) { if (error != asio::error::connection_reset) { comm->logError("error message while connected " + error.message() + "code " + std::to_string(error.value())); } } } return false; } } // namespace tcp } // namespace helics
31.297297
97
0.6019
GMLC-TDC
244f3d7cd571a12cf8cebd447290762048ce5a6d
2,131
cpp
C++
Rare Topics/Rare Algorithms/Sliding Window/Smallest Sub-Array.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
Rare Topics/Rare Algorithms/Sliding Window/Smallest Sub-Array.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
Rare Topics/Rare Algorithms/Sliding Window/Smallest Sub-Array.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; #define maxn 1000010 int tc, n, m, k; int a[maxn]; unordered_map <int, int> map1; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); cin >> tc; int cas = 1; while(tc--){ cin >> n >> m >> k; cout << "Case " << cas++ << ": "; a[0] = 1; a[1] = 2; a[2] = 3; for(int i=3; i<n; i++){ a[i] = (a[i-3]+a[i-2]+a[i-1]) % m + 1; } int l = 0, r = 1; int ans = 2*n; map1.clear(); if(a[l] <= k) map1[a[l]] = 1; while(r < n){ if(l == r){ if(a[r] <= k) map1[a[r]] = 1; r++; continue; } if(r - l > ans){ if(map1.count(a[l])){ if(map1[a[l]] == 1) map1.erase(a[l]); else map1[a[l]]--; } l++; continue; } if(map1.size() == k){ while(map1.size() == k && l <= r){ ans = min(ans, r - l); if(map1.count(a[l])){ if(map1[a[l]] == 1) map1.erase(a[l]); else map1[a[l]]--; } l++; } }else{ while(map1.size() != k && r < n){ if(a[r] <= k){ if(map1.count(a[r])) map1[a[r]]++; else map1[a[r]] = 1; } r++; } } } if(map1.size() == k){ while(map1.size() == k && l <= r){ ans = min(ans, r - l); if(map1.count(a[l])){ if(map1[a[l]] == 1) map1.erase(a[l]); else map1[a[l]]--; } l++; } } if(ans == 2*n) cout << "sequence nai\n"; else cout << ans << "\n"; } return 0; }
28.039474
61
0.313468
satvik007
244fe5f01a171799007c4864dc98f73f94950097
2,500
cc
C++
Ohm/Features/Glow.cc
ramadan8/Ohm
fe9dbbdc40dc4c85a2cb2d033627673cd72ade39
[ "MIT" ]
1
2021-07-28T11:30:14.000Z
2021-07-28T11:30:14.000Z
Ohm/Features/Glow.cc
ramadan8/Ohm
fe9dbbdc40dc4c85a2cb2d033627673cd72ade39
[ "MIT" ]
1
2021-07-26T01:36:58.000Z
2021-07-27T14:45:21.000Z
Ohm/Features/Glow.cc
ramadan8/Ohm
fe9dbbdc40dc4c85a2cb2d033627673cd72ade39
[ "MIT" ]
1
2021-09-11T07:43:53.000Z
2021-09-11T07:43:53.000Z
#include "./Glow.h" #include "../Config.h" #include "../Memory.h" #include "../GUI/Colors.h" #include "../Utility/Utilities.h" #include "../SDK/Class/CGlowObjectManager.h" #include "../SDK/Entities/CBasePlayer.h" void Glow::Shutdown() { for (int idx = 0; idx < memory->GlowObjectManager->glowObjectDefinitions.Count(); idx++) { GlowObjectDefinition_t& glowObject = memory->GlowObjectManager->glowObjectDefinitions[idx]; IClientEntity* entity = glowObject.entity; if (glowObject.IsUnused()) continue; if (!entity || entity->GetDormant()) continue; glowObject.glowAlpha = 0.f; } } void Glow::Render() { CBasePlayer* localPlayer = Utilities::getLocalPlayer(); static const float rgbMult = 1.f / 256.f; for (int idx = 0; idx < memory->GlowObjectManager->glowObjectDefinitions.Count(); idx++) { GlowObjectDefinition_t& glowObject = memory->GlowObjectManager->glowObjectDefinitions[idx]; IClientEntity* entity = glowObject.entity; if (glowObject.IsUnused()) continue; if (!entity || entity->GetDormant()) continue; int classId = entity->GetClientClass()->m_ClassID; Color color{}; if (classId == netvars->classIdentifiers.CCSPlayer) { CBasePlayer* thisPlayer = reinterpret_cast<CBasePlayer*>(entity); if (!config->visuals.glow.showPlayers) continue; if (!thisPlayer->isAlive()) continue; bool isEnemy = thisPlayer->getTeam() != localPlayer->getTeam(); if (isEnemy) { color = thisPlayer->hasC4() ? Colors::Green : Colors::Red; } else { color = Colors::Blue; } } else if (classId == netvars->classIdentifiers.CChicken) { if (!config->visuals.glow.showChickens) continue; *entity->shouldGlow() = true; color = Colors::Blue; } else if (classId == netvars->classIdentifiers.CBaseAnimating) { if (!config->visuals.glow.showDefuseKits) continue; color = Colors::Blue; } else if (classId == netvars->classIdentifiers.CPlantedC4) { if (!config->visuals.glow.showPlantedC4) continue; color = Colors::Blue; } else if (entity->isWeapon()) { if (!config->visuals.glow.showDroppedWeapons) continue; color = Colors::Blue; } glowObject.glowRed = color.r() * rgbMult; glowObject.glowGreen = color.g() * rgbMult; glowObject.glowBlue = color.b() * rgbMult; glowObject.glowAlpha = color.a() * rgbMult; glowObject.renderWhenOccluded = true; glowObject.renderWhenUnoccluded = false; glowObject.bloomAmount = config->visuals.glow.bloomAmount; } }
25
93
0.6868
ramadan8
24551b764cfdfd9ba0c8938706818eec81a7642e
897
cpp
C++
cpp/G3M/BufferDEMGrid.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
70
2015-02-06T14:39:14.000Z
2022-01-07T08:32:48.000Z
cpp/G3M/BufferDEMGrid.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
118
2015-01-21T10:18:00.000Z
2018-10-16T15:00:57.000Z
cpp/G3M/BufferDEMGrid.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
41
2015-01-10T22:29:27.000Z
2021-06-08T11:56:16.000Z
// // BufferDEMGrid.cpp // G3M // // Created by Diego Gomez Deck on 10/5/16. // // #include "BufferDEMGrid.hpp" #include "Projection.hpp" BufferDEMGrid::BufferDEMGrid(const Projection* projection, const Sector& sector, const Vector2I& extent, size_t bufferSize, double deltaHeight) : DEMGrid(sector, extent), _projection(projection), _bufferSize(bufferSize), _deltaHeight(deltaHeight) { _projection->_retain(); } BufferDEMGrid::~BufferDEMGrid() { _projection->_release(); #ifdef JAVA_CODE super.dispose(); #endif } const Projection* BufferDEMGrid::getProjection() const { return _projection; } double BufferDEMGrid::getElevation(int x, int y) const { const int index = ((_extent._y-1-y) * _extent._x) + x; return getValueInBufferAt( index ) + _deltaHeight; }
21.357143
58
0.637681
glob3mobile
24564f013a7c3797901041ff9ab50bf31168d7b0
2,334
hpp
C++
aagent/src/strategies/include/PerfDynamicsAnalysis.hpp
robert-mijakovic/readex-ptf
5514b0545721ef27de0426a7fa0116d2e0bb5eef
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2022-03-10T09:59:37.000Z
2022-03-10T09:59:37.000Z
aagent/src/strategies/include/PerfDynamicsAnalysis.hpp
robert-mijakovic/readex-ptf
5514b0545721ef27de0426a7fa0116d2e0bb5eef
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2020-04-21T07:57:32.000Z
2020-10-14T08:05:41.000Z
aagent/src/strategies/include/PerfDynamicsAnalysis.hpp
robert-mijakovic/readex-ptf
5514b0545721ef27de0426a7fa0116d2e0bb5eef
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-20T03:04:32.000Z
2020-11-20T03:04:32.000Z
/** @file PerfDynamicsAnalysis.hpp @ingroup PerfDynamicsAnalysis @brief Performance Dynamics Analysis strategy header @author Yury Oleynik @verbatim Revision: $Revision$ Revision date: Dec 10, 2013 Committed by: $Author$ This file is part of the Periscope performance measurement tool. See http://www.lrr.in.tum.de/periscope for details. Copyright (c) 2005-2015, Technische Universitaet Muenchen, Germany See the COPYING file in the base directory of the package for details. @endverbatim */ /** * @defgroup PerfDynamicsAnalysis Performance Dynamics Analysis Strategy * @ingroup Strategies */ #ifndef PERFDYNAMICSANALYSIS_HPP_ #define PERFDYNAMICSANALYSIS_HPP_ #include <string> #include <map> #include "global.h" #include "application.h" #include "Metric.h" #include "strategy.h" //#include "DSP_Engine.hpp" #include "TDA_QSequence.hpp" using namespace std; class PerfDynamicsStrategy : public Strategy { Region* phaseRegion; Prop_List candProperties; Prop_List foundPropertiesLastStep; Strategy* staticStrategy; string staticStrategyName; bool test_mode; std::map<std::string, TDA_Stuff*> tda_stuffs; //map<string, DSP_Engine*> engines; int burst_begin; int burst_length; public: PerfDynamicsStrategy( string staticStrategyName, Application* application, int duration, bool pedantic = false ); ~PerfDynamicsStrategy() { delete staticStrategy; map<string, TDA_Stuff*>::iterator it; for( it = tda_stuffs.begin(); it != tda_stuffs.end(); it++ ) { delete( it->second ); } } std::list <Property*>create_initial_candidate_properties_set( Region* initial_region ); std::list <Property*>create_next_candidate_properties_set( std::list< Property* > ev_set ); std::string name(); bool reqAndConfigureFirstExperiment( Region* initial_region ); // TRUE can start; FALSE not ready bool evaluateAndReqNextExperiment(); // TRUE requires next step; FALSE if done void configureNextExperiment(); void region_definition_received_callback( Region* reg ); }; #endif /* PERFDYNAMICSANALYSIS_HPP_ */
25.648352
108
0.67138
robert-mijakovic
2456904637077b7beca5a33258ddebda06368bb7
3,662
cpp
C++
Samples/WindowsAudioSession/cpp/Scenario1.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
Samples/WindowsAudioSession/cpp/Scenario1.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
Samples/WindowsAudioSession/cpp/Scenario1.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario1.xaml.cpp // Implementation of the Scenario1 class // #include "pch.h" #include "Scenario1.xaml.h" using namespace SDKSample; using namespace SDKSample::WASAPIAudio; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Media::Devices; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; Scenario1::Scenario1() { InitializeComponent(); m_DevicesList = safe_cast<ListBox^>(static_cast<IFrameworkElement^>(this)->FindName("DevicesList")); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void Scenario1::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() rootPage = MainPage::Current; } void Scenario1::ShowStatusMessage( Platform::String^ str, NotifyType messageType ) { rootPage->NotifyUser( str, messageType ); } void Scenario1::Enumerate_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e ) { Button^ b = safe_cast<Button^>(sender); if (b != nullptr) { m_DevicesList->Items->Clear(); EnumerateAudioDevicesAsync(); } } void Scenario1::EnumerateAudioDevicesAsync() { // Get the string identifier of the audio renderer String^ AudioSelector = MediaDevice::GetAudioRenderSelector(); // Add custom properties to the query auto PropertyList = ref new Platform::Collections::Vector<String^>(); PropertyList->Append( PKEY_AudioEndpoint_Supports_EventDriven_Mode ); // Setup the asynchronous callback Concurrency::task<DeviceInformationCollection^> enumOperation( DeviceInformation::FindAllAsync( AudioSelector, PropertyList ) ); enumOperation.then([this](DeviceInformationCollection^ DeviceInfoCollection) { if ( (DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0) ) { this->ShowStatusMessage( "No Devices Found.", NotifyType::ErrorMessage ); } else { try { // Enumerate through the devices and the custom properties for(unsigned int i = 0; i < DeviceInfoCollection->Size; i++) { DeviceInformation^ deviceInfo = DeviceInfoCollection->GetAt(i); String^ DeviceInfoString = deviceInfo->Name; if (deviceInfo->Properties->Size > 0) { // Pull out the custom property Object^ DevicePropString = deviceInfo->Properties->Lookup( PKEY_AudioEndpoint_Supports_EventDriven_Mode ); if (nullptr != DevicePropString) { DeviceInfoString = DeviceInfoString + " --> EventDriven(" + DevicePropString + ")"; } } this->m_DevicesList->Items->Append( DeviceInfoString ); } String^ strMsg = "Enumerated " + DeviceInfoCollection->Size + " Device(s)."; this->ShowStatusMessage( strMsg, NotifyType::StatusMessage ); } catch ( Platform::Exception^ e ) { this->ShowStatusMessage( e->Message, NotifyType::ErrorMessage ); } } }); }
31.299145
130
0.676406
dujianxin
245be162126af321cd1856d8ec3b2f29f4825d6c
6,020
cpp
C++
src/fuselage/CCPACSPressureBulkheadAssemblyPosition.cpp
pputin/tigl
886b723bdd753c0ebe05d22b44c2c5a4c8d323bb
[ "Apache-2.0" ]
null
null
null
src/fuselage/CCPACSPressureBulkheadAssemblyPosition.cpp
pputin/tigl
886b723bdd753c0ebe05d22b44c2c5a4c8d323bb
[ "Apache-2.0" ]
null
null
null
src/fuselage/CCPACSPressureBulkheadAssemblyPosition.cpp
pputin/tigl
886b723bdd753c0ebe05d22b44c2c5a4c8d323bb
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018 Airbus Defence and Space and RISC Software GmbH * * 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 "CCPACSPressureBulkheadAssemblyPosition.h" #include <gp_Pln.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <TopExp.hxx> #include <Bnd_Box.hxx> #include <BRepBndLib.hxx> #include <gp_Ax3.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <ShapeAnalysis_Wire.hxx> #include <ShapeFix_ShapeTolerance.hxx> #include <numeric> #include "CCPACSFuselage.h" #include "CCPACSFrame.h" #include "CCPACSPressureBulkhead.h" #include "CCPACSFuselageStringerFramePosition.h" #include "CTiglUIDManager.h" #include "tiglcommonfunctions.h" #include "CNamedShape.h" #include "to_string.h" namespace tigl { CCPACSPressureBulkheadAssemblyPosition::CCPACSPressureBulkheadAssemblyPosition(CCPACSPressureBulkheadAssembly* parent, CTiglUIDManager* uidMgr) : generated::CPACSPressureBulkheadAssemblyPosition(parent, uidMgr) , m_geometry(*this, &CCPACSPressureBulkheadAssemblyPosition::BuildGeometry) { } void CCPACSPressureBulkheadAssemblyPosition::SetFrameUID(const std::string& value) { generated::CPACSPressureBulkheadAssemblyPosition::SetFrameUID(value); Invalidate(); } void CCPACSPressureBulkheadAssemblyPosition::SetPressureBulkheadElementUID(const std::string& value) { generated::CPACSPressureBulkheadAssemblyPosition::SetPressureBulkheadElementUID(value); Invalidate(); } std::string CCPACSPressureBulkheadAssemblyPosition::GetDefaultedUID() const { return m_uID; } PNamedShape CCPACSPressureBulkheadAssemblyPosition::GetLoft() { return PNamedShape(new CNamedShape(GetGeometry(GLOBAL_COORDINATE_SYSTEM), GetDefaultedUID())); } TiglGeometricComponentType CCPACSPressureBulkheadAssemblyPosition::GetComponentType() const { return TIGL_COMPONENT_PHYSICAL | TIGL_COMPONENT_PRESSURE_BULKHEAD; } void CCPACSPressureBulkheadAssemblyPosition::Invalidate() { m_geometry.clear(); } TopoDS_Shape CCPACSPressureBulkheadAssemblyPosition::GetGeometry(TiglCoordinateSystem cs) const { if (cs == GLOBAL_COORDINATE_SYSTEM) { CTiglTransformation trafo = m_parent->GetParent()->GetParent()->GetTransformationMatrix(); return trafo.Transform(*m_geometry); } else { return *m_geometry; } } void CCPACSPressureBulkheadAssemblyPosition::BuildGeometry(TopoDS_Shape& cache) const { CCPACSFrame& frame = m_uidMgr->ResolveObject<CCPACSFrame>(m_frameUID); if (frame.GetFramePositions().size() == 1) { TopTools_IndexedMapOfShape wireMap; TopExp::MapShapes(frame.GetGeometry(true, FUSELAGE_COORDINATE_SYSTEM), TopAbs_WIRE, wireMap); if (wireMap.Extent() != 1) { throw CTiglError("1D frame geometry should have exactly one wire"); } cache = BRepBuilderAPI_MakeFace(TopoDS::Wire(wireMap(1))); } else if (frame.GetFramePositions().size() >= 2) { CCPACSFuselage& fuselage = *m_parent->GetParent()->GetParent(); std::vector<gp_Pnt> refPoints; for (size_t i = 0; i < frame.GetFramePositions().size(); i++) { const CCPACSFuselageStringerFramePosition& framePosition = *frame.GetFramePositions()[i]; const gp_Pnt refPoint = framePosition.GetRefPoint(); refPoints.push_back(refPoint); } // build wire, starting with frame wire BRepBuilderAPI_MakeWire wireMaker; wireMaker.Add(TopoDS::Wire(frame.GetGeometry(true, FUSELAGE_COORDINATE_SYSTEM))); if (!wireMaker.IsDone()) { throw CTiglError("Wire generation failed"); } if (wireMaker.Error() != BRepBuilderAPI_WireDone) { throw CTiglError("Wire generation failed: " + std_to_string(wireMaker.Error())); } TopoDS_Wire wire = wireMaker.Wire(); ShapeAnalysis_Wire analysis; analysis.Load(wire); if (analysis.CheckSelfIntersection()) { throw CTiglError("Wire is self-intersecting. This may be caused by an unfortunate positioning of the frame positions"); } wire = CloseWire(wire); BRepBuilderAPI_MakeFace makeFace(wire); if (!makeFace.IsDone()) { LOG(WARNING) << "Failed to create shape for bulkhead \"" << GetDefaultedUID() << "\", retrying planar one"; // retry with xz plane put at average ref point const gp_Pnt avgRefPoint = std::accumulate(refPoints.begin(), refPoints.end(), gp_Pnt(), [](gp_Pnt a, gp_Pnt b) { return gp_Pnt(a.XYZ() + b.XYZ()); }).XYZ() / static_cast<double>(refPoints.size()); const gp_Pln plane(avgRefPoint, gp_Dir(1, 0, 0)); makeFace = BRepBuilderAPI_MakeFace(plane, wire); if (!makeFace.IsDone()) { throw CTiglError("Face generation failed"); } if (makeFace.Error()) { throw CTiglError("Face generation failed: " + std_to_string(makeFace.Error())); } } TopoDS_Face face = makeFace.Face(); // for some rediculous reason, BRepBuilderAPI_MakeFace alters the tolerance of the underlying wire's edges and vertices, // causing subsequent boolean operations to fail (self intersections) ShapeFix_ShapeTolerance().SetTolerance(face, Precision::Confusion()); cache = face; } } } // namespace tigl
35.833333
131
0.699169
pputin
245fa41b101f0d31bfc3d67c8369825cba367b7f
6,393
cpp
C++
src/VulkanCommandManager.cpp
saucisse-royale/kudasai
fadf6786ad28a15a93dcae6228bc352ce46ffc0c
[ "MIT" ]
null
null
null
src/VulkanCommandManager.cpp
saucisse-royale/kudasai
fadf6786ad28a15a93dcae6228bc352ce46ffc0c
[ "MIT" ]
null
null
null
src/VulkanCommandManager.cpp
saucisse-royale/kudasai
fadf6786ad28a15a93dcae6228bc352ce46ffc0c
[ "MIT" ]
null
null
null
#include "VulkanCommandManager.hpp" #include "VulkanContext.hpp" #include "VulkanHelper.hpp" #include <iostream> #include <limits> namespace kds { VulkanCommandManager::VulkanCommandManager(VulkanContext* vulkanContext) noexcept : _vulkanContext{ vulkanContext } , _graphicsCommandPool{ vkDestroyCommandPool, _vulkanContext->_device, _graphicsCommandPool, nullptr } , _imageAvailableSemaphore{ vkDestroySemaphore, _vulkanContext->_device, _imageAvailableSemaphore, nullptr } , _renderFinishedSemaphore{ vkDestroySemaphore, _vulkanContext->_device, _renderFinishedSemaphore, nullptr } { } VulkanCommandManager::~VulkanCommandManager() noexcept { vkFreeCommandBuffers(_vulkanContext->_device, _graphicsCommandPool, _graphicsCommandBuffers.size(), _graphicsCommandBuffers.data()); } void VulkanCommandManager::draw() noexcept { // get next image from swapchain uint32_t imageIndex; auto result = vkAcquireNextImageKHR(_vulkanContext->_device, _vulkanContext->_vulkanSwapchain._swapchain, std::numeric_limits<uint64_t>::max(), _imageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex); KDS_CHECK_RESULT(result, "Failed to acquire next image from the swapchain."); std::array<VkSemaphore, 1> waitSemaphores{}; waitSemaphores[0] = _imageAvailableSemaphore; std::array<VkSemaphore, 1> signalSemaphores{}; signalSemaphores[0] = _renderFinishedSemaphore; std::array<VkPipelineStageFlags, 1> waitStages{}; waitStages[0] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.waitSemaphoreCount = waitSemaphores.size(); submitInfo.pWaitSemaphores = waitSemaphores.data(); submitInfo.signalSemaphoreCount = signalSemaphores.size(); submitInfo.pSignalSemaphores = signalSemaphores.data(); submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &_graphicsCommandBuffers[imageIndex]; submitInfo.pWaitDstStageMask = waitStages.data(); result = vkQueueSubmit(_vulkanContext->_graphicsQueues[0], 1, &submitInfo, VK_NULL_HANDLE); KDS_CHECK_RESULT(result, "Failed to submit buffer to a queue"); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = signalSemaphores.size(); presentInfo.pWaitSemaphores = signalSemaphores.data(); presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &_vulkanContext->_vulkanSwapchain._swapchain; presentInfo.pImageIndices = &imageIndex; result = vkQueuePresentKHR(_vulkanContext->_presentQueue, &presentInfo); KDS_CHECK_RESULT(result, "Failed to present queue"); } void VulkanCommandManager::createSemaphore() noexcept { VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphoreInfo.flags = 0; auto result = vkCreateSemaphore(_vulkanContext->_device, &semaphoreInfo, nullptr, _imageAvailableSemaphore.reset()); KDS_CHECK_RESULT(result, "Failed to create semaphores."); result = vkCreateSemaphore(_vulkanContext->_device, &semaphoreInfo, nullptr, _renderFinishedSemaphore.reset()); KDS_CHECK_RESULT(result, "Failed to create semaphores."); } void VulkanCommandManager::createCommandBuffers() noexcept { VkCommandPoolCreateInfo graphicsCommandPoolInfo{}; graphicsCommandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; graphicsCommandPoolInfo.flags = 0; graphicsCommandPoolInfo.queueFamilyIndex = _vulkanContext->_contextConfig.deviceQueueConfig.graphicsQueueInfos.index; auto result = vkCreateCommandPool(_vulkanContext->_device, &graphicsCommandPoolInfo, nullptr, _graphicsCommandPool.reset()); KDS_CHECK_RESULT(result, "Failed to create a command pool."); _graphicsCommandBuffers.resize(_vulkanContext->_vulkanSwapchain._swapchainImageViews.size()); VkCommandBufferAllocateInfo commandBufferInfo{}; commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; commandBufferInfo.commandPool = _graphicsCommandPool; commandBufferInfo.commandBufferCount = _graphicsCommandBuffers.size(); commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; result = vkAllocateCommandBuffers(_vulkanContext->_device, &commandBufferInfo, _graphicsCommandBuffers.data()); KDS_CHECK_RESULT(result, "Failed to allocater graphics command buffers."); } void VulkanCommandManager::recordCommandBuffers() noexcept { VkCommandBufferBeginInfo cmdBufferBeginInfo{}; cmdBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmdBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; VkImageSubresourceRange imageSubRessourceRange{}; imageSubRessourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imageSubRessourceRange.layerCount = 1; imageSubRessourceRange.baseArrayLayer = 0; imageSubRessourceRange.levelCount = 1; imageSubRessourceRange.baseMipLevel = 0; VkClearValue clearValue{ 0.3f, 0.2f, 0.6f, 0.0f }; VkResult result{}; for (size_t i{}; i < _graphicsCommandBuffers.size(); ++i) { result = vkBeginCommandBuffer(_graphicsCommandBuffers[i], &cmdBufferBeginInfo); KDS_CHECK_RESULT(result, "Failed to begin recording a command buffer."); VkRenderPassBeginInfo renderPassBeginInfo{}; renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassBeginInfo.clearValueCount = 1; renderPassBeginInfo.pClearValues = &clearValue; renderPassBeginInfo.framebuffer = _vulkanContext->_framebuffers[i]; renderPassBeginInfo.renderArea.offset = { 0, 0 }; renderPassBeginInfo.renderArea.extent = _vulkanContext->_vulkanSwapchain._swapchainExtent; renderPassBeginInfo.renderPass = _vulkanContext->_graphicsPipeline._renderPass; vkCmdBeginRenderPass(_graphicsCommandBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(_graphicsCommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, _vulkanContext->_graphicsPipeline._pipeline); vkCmdDraw(_graphicsCommandBuffers[i], 3, 1, 0, 0); vkCmdEndRenderPass(_graphicsCommandBuffers[i]); result = vkEndCommandBuffer(_graphicsCommandBuffers[i]); KDS_CHECK_RESULT(result, "Failed to end a graphics command buffer"); } } } // namespace kds
46.326087
203
0.785547
saucisse-royale
24600d0163aff7ae167f27437ee6f71e84f9e2e8
6,244
cxx
C++
sprokit/processes/core/initialize_object_tracks_process.cxx
judajake/kwiver
303a11ebb43c020ab8e48b6ef70407b460dba46b
[ "BSD-3-Clause" ]
null
null
null
sprokit/processes/core/initialize_object_tracks_process.cxx
judajake/kwiver
303a11ebb43c020ab8e48b6ef70407b460dba46b
[ "BSD-3-Clause" ]
null
null
null
sprokit/processes/core/initialize_object_tracks_process.cxx
judajake/kwiver
303a11ebb43c020ab8e48b6ef70407b460dba46b
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2017 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "initialize_object_tracks_process.h" #include <vital/vital_types.h> #include <vital/types/timestamp.h> #include <vital/types/timestamp_config.h> #include <vital/types/image_container.h> #include <vital/types/object_track_set.h> #include <vital/algo/initialize_object_tracks.h> #include <kwiver_type_traits.h> #include <sprokit/pipeline/process_exception.h> namespace kwiver { namespace algo = vital::algo; //------------------------------------------------------------------------------ // Private implementation class class initialize_object_tracks_process::priv { public: priv(); ~priv(); algo::initialize_object_tracks_sptr m_track_initializer; }; // end priv class // ============================================================================= initialize_object_tracks_process ::initialize_object_tracks_process( vital::config_block_sptr const& config ) : process( config ), d( new initialize_object_tracks_process::priv ) { // Attach our logger name to process logger attach_logger( vital::get_logger( name() ) ); make_ports(); make_config(); } initialize_object_tracks_process ::~initialize_object_tracks_process() { } // ----------------------------------------------------------------------------- void initialize_object_tracks_process ::_configure() { vital::config_block_sptr algo_config = get_config(); algo::initialize_object_tracks::set_nested_algo_configuration( "track_initializer", algo_config, d->m_track_initializer ); if( !d->m_track_initializer ) { throw sprokit::invalid_configuration_exception( name(), "Unable to create initialize_object_tracks" ); } algo::initialize_object_tracks::get_nested_algo_configuration( "track_initializer", algo_config, d->m_track_initializer ); // Check config so it will give run-time diagnostic of config problems if( !algo::initialize_object_tracks::check_nested_algo_configuration( "track_initializer", algo_config ) ) { throw sprokit::invalid_configuration_exception( name(), "Configuration check failed." ); } } // ----------------------------------------------------------------------------- void initialize_object_tracks_process ::_step() { vital::timestamp frame_id; vital::image_container_sptr image; vital::detected_object_set_sptr detections; vital::object_track_set_sptr old_tracks; vital::object_track_set_sptr new_tracks; if( process::has_input_port_edge( "timestamp" ) ) { frame_id = grab_from_port_using_trait( timestamp ); // Output frame ID LOG_DEBUG( logger(), "Processing frame " << frame_id ); } if( process::has_input_port_edge( "image" ) ) { image = grab_from_port_using_trait( image ); } detections = grab_from_port_using_trait( detected_object_set ); if( process::has_input_port_edge( "object_track_set" ) ) { old_tracks = grab_from_port_using_trait( object_track_set ); } // Compute new tracks new_tracks = d->m_track_initializer->initialize( frame_id, image, detections ); // Union optional input tracks if available if( old_tracks ) { std::vector< vital::track_sptr > net_tracks = old_tracks->tracks(); std::vector< vital::track_sptr > to_add = new_tracks->tracks(); net_tracks.insert( net_tracks.end(), to_add.begin(), to_add.end() ); vital::object_track_set_sptr joined_tracks( new vital::object_track_set( net_tracks ) ); push_to_port_using_trait( object_track_set, joined_tracks ); } else { push_to_port_using_trait( object_track_set, new_tracks ); } } // ----------------------------------------------------------------------------- void initialize_object_tracks_process ::make_ports() { // Set up for required ports sprokit::process::port_flags_t optional; sprokit::process::port_flags_t required; required.insert( flag_required ); // -- input -- declare_input_port_using_trait( timestamp, optional ); declare_input_port_using_trait( image, optional ); declare_input_port_using_trait( object_track_set, optional ); declare_input_port_using_trait( detected_object_set, required ); // -- output -- declare_output_port_using_trait( object_track_set, optional ); } // ----------------------------------------------------------------------------- void initialize_object_tracks_process ::make_config() { } // ----------------------------------------------------------------------------- void initialize_object_tracks_process ::_init() { } // ============================================================================= initialize_object_tracks_process::priv ::priv() { } initialize_object_tracks_process::priv ::~priv() { } } // end namespace
29.45283
81
0.675048
judajake