blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
38f6db52c1e7f1493fb6fdc0efbb811e4f9e3442
f935915fcf70920badf1701754f2018c2cdaf43d
/c/300.cpp
461c1f33e5c43299b760b3a797324867bd0daa1c
[]
no_license
youkochan/youko-leetcode
4a893c33f35f11d7105945c566c679dee805c8c5
f8eb41dd78df9eaa74e1e63d766e54e8a133091b
refs/heads/master
2020-12-29T01:31:53.630591
2016-08-20T13:12:52
2016-08-20T13:12:52
34,739,652
4
1
null
null
null
null
GB18030
C++
false
false
2,522
cpp
/** * Longest Increasing Subsequence * https://leetcode.com/problems/longest-increasing-subsequence/ * http://www.csie.ntnu.edu.tw/~u91029/LongestIncreasingSubsequence.html */ #include <iostream> #include <vector> #include <cstdlib> #include <climits> using namespace std; /*解法一,深度优先递归,结果超时*/ /*class Solution { public: int lengthOfLIS(vector<int>& nums) { return f(nums, 0, INT_MIN, 0); } int f(vector<int> &nums, int pos, int max_num, int len) { if (pos == nums.size()) return len; int result1 = 0, result2 = 0; if (nums[pos] > max_num) { result1 = f(nums, pos+1, nums[pos], len+1); } result2 = f(nums, pos+1, max_num, len); return max(result1, result2); } };*/ /*解法二,lens[j]记录j以前比nums[j]小的数目个数*/ /*class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); if (!n) return 0; vector<int> lens(n); for (int &len : lens) len = 1; for (int i = 0; i < n; i ++) for (int j = i + 1; j < n; j ++) if (nums[j] > nums[i]) lens[j] = max(lens[j], lens[i]+1); int result = 0; for (int len : lens) result = max(result, len); return result; } };*/ /*解法三,採取 Greedy 策略,以 Binary Search 加速,達到 O(NlogL) , N 是給定序列的長度, L 是 LIS 的長度。 *首先要明确 result 数组的长度是只增不减的, *在替换过程中有可能找到的结果不是一个LIS *但是结果的长度一定是最长子序列的长度*/ class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); if (!n) return 0; vector<int> result; for (int num : nums) { if (result.size() == 0) result.push_back(num); else { if (num > result.back()) { result.push_back(num); } else { *lower_bound(result.begin(), result.end(), num) = num; } } /*for (int r : result) { cout << r << " "; } cout << endl;*/ } return result.size(); } }; int main() { vector<int> nums = {-7, 10, -9, 2, 3, 8, 8, 1}; Solution s; cout << s.lengthOfLIS(nums) << endl; return 0; }
[ "youkochan233@gmail.com" ]
youkochan233@gmail.com
5028015bfb3e1c9cfabc058dc75b713c0ba51961
16dd0302383bdb56a1350e8683c17c7c09f6b0ef
/src/ProcessMonitor.h
78447ebf27570a110c7c0135083756bb285990ee
[ "BSD-2-Clause" ]
permissive
123ysys/keyfrog
8db9168b7a604b59c0cb27779d260c882d68dbef
28e010d18e5239e635a862a9a2f54456d6723c8a
refs/heads/master
2021-05-30T06:49:27.009613
2015-08-23T17:49:40
2015-08-24T18:21:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,971
h
/********************************************************************************* * Copyright (C) 2006-2013 by Sebastian Gniazdowski * * 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 Keyfrog 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 REGENTS 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 REGENTS 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. * *********************************************************************************/ #ifndef KEYFROG_PROCESSMONITOR_H #define KEYFROG_PROCESSMONITOR_H // For process tree #include "ProcessManager.h" #include <sys/types.h> #include <unistd.h> namespace keyfrog { /** * Monitors /proc for changes (process creation, deletion, etc.) * @author Sebastian Gniazdowski */ class ProcessMonitor { ProcessManager *m_procMan; public: /// Constructor ProcessMonitor(); /// Destructor ~ProcessMonitor(); /// Initializes inotify bool init(ProcessManager *procMan); /// Event loop (best for threads) void eventLoop(); }; } #endif
[ "sgniazdowski@gmail.com" ]
sgniazdowski@gmail.com
c506af1a8134d28ad9c0f885cc24a85e665beafa
a37e0c003e2587abc0a7e5592c6f25532ec1426f
/ChallengesQuestion/Charles_Elvira_59589255_BUSYMAN.cpp
6682f798c37b7d45cb5baa71e07c77619194c2ac
[]
no_license
CharlesElvira/COP3530-Algorithm
4ca55c1e14cda9a9cbab3dbeed466131294eadb9
6dc8d0470b2465d600a65710f47f572918418b85
refs/heads/master
2021-01-17T07:37:10.026711
2016-04-20T03:18:20
2016-04-20T03:18:20
49,438,350
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
#include <algorithm> #include <iostream> #include <vector> int main() { int testCase; std::cin>>testCase; while (testCase--) { int n; std::cin>>n; std::vector<std::pair<int, int> > length; for (int i = 0; i < n; i++) { int start, end; std::cin>>start; std::cin>> end; length.push_back(std::make_pair(start, -end)); } std::sort(length.begin(), length.end()); std::vector<std::pair<int, int> > length1; for (int i = 0; i < n; i++) { length[i].second = length[i].second * (-1); while (length1.size() > 0 && length1.back().second >= length[i].second) { length1.pop_back(); } length1.push_back(length[i]); } int begin = 0; int ending = -1; for (int i = 0; i < length1.size(); i++) { if (length1[i].first >= ending) { ending = length1[i].second; ++begin; } } std::cout<<begin<<std::endl; } }
[ "celvira@lin115-07.cise.ufl.edu" ]
celvira@lin115-07.cise.ufl.edu
aef50940b417b6758cefc2345bc4bbc42c60fe74
3790aefc92f31c1abbe5594d4ea020e15cb12aae
/tizen-sdk/platforms/tizen2.1/rootstraps/tizen-emulator-2.1.native/usr/include/osp/FGrpGlPlayer.h
0376f1654d89140de8407cd80db20075b78e765e
[]
no_license
abhijitrd/CppSharpTizen
e9871793c27acbb8ae0f599f2013ea56c7b2fca4
92e42a36cc3c5f2b1636061e82025feec4edda0d
refs/heads/master
2021-01-16T22:04:57.789905
2014-07-05T11:39:32
2014-07-05T11:39:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,667
h
// // Open Service Platform // Copyright (c) 2012-2013 Samsung Electronics Co., Ltd. // // Licensed under the Apache License, Version 2.0 (the License); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0/ // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** * @file FGrpGlPlayer.h * @brief This is the header file for the %GlPlayer class. * * This header file contains the declarations of the %GlPlayer class. * */ #ifndef _FGRP_GL_PLAYER_H_ #define _FGRP_GL_PLAYER_H_ #include <FBaseObject.h> #include <eglplatform.h> namespace Tizen { namespace Ui { class Control; } } namespace Tizen { namespace Graphics { namespace Opengl { class IGlRenderer; /** * @enum EglContextClientVersion * * Defines the Egl Context Client version of the player. * * @since 2.0 * */ enum EglContextClientVersion { EGL_CONTEXT_CLIENT_VERSION_1_X, /**< The version is 1.x */ EGL_CONTEXT_CLIENT_VERSION_2_X /**< The version is 2.x */ }; /** * @enum EglAttributesPreset * * Defines the preset of EGL attributes and configurations. * * @since 2.0 * */ enum EglAttributesPreset { EGL_ATTRIBUTES_PRESET_DONT_CARE, /**< Preset Don't care */ EGL_ATTRIBUTES_PRESET_RGB565, /**< Preset RGB565 */ EGL_ATTRIBUTES_PRESET_ARGB8888 /**< Preset ARGB8888 */ }; /** * @class GlPlayer * @brief This class provides a simple template for rendering 3D objects with OpenGL-ES APIs * @since 2.0 * @final This class is not intended for extension. * */ class _OSP_EXPORT_ GlPlayer : public Tizen::Base::Object { public: /** * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. * * @since 2.0 * */ GlPlayer(void); /** * This destructor overrides Tizen::Base::Object::~Object(void). * * @since 2.0 * */ virtual ~GlPlayer(void); /** * Initializes this instance of %GlPlayer. * * @since 2.0 * @return An error code * @param[in] version EGL Context Client Version @n * The version must be 1(OpenGL-ES 1.x) or 2(OpenGL-ES 2.x). * @param[in] pControl A pointer of the target control @n * Only Tizen::Ui::Controls::Frame and Tizen::Ui::Controls::Form are allowed as the target control. * @exception E_SUCCESS The method is successful. * @exception E_INVALID_ARG Either the @c pControl is not Form or Frame, or * the @c version is not @c EGL_CONTEXT_CLIENT_VERSION_1_X or @c EGL_CONTEXT_CLIENT_VERSION_2_X. * @exception E_INVALID_OPERATION The operation has failed, because of the duplicate call of Construct(). * */ result Construct(EglContextClientVersion version, Tizen::Ui::Control* pControl); /** * Starts the %GlPlayer, and initializes EGL status. * * @since 2.0 * @return An error code * @exception E_SUCCESS The method is successful. * @exception E_SYSTEM Player cannot be started properly due to a severe system error. * @exception E_INVALID_STATE The state of player is not suitable for start. For example, it is not allowable to start player when its state is pause. * @exception E_OPENGL_ERROR There occurs an EGL error during performing EGL function. * * @remarks In the case that this returns @c E_OPENGL_ERROR exception, developers can use eglGetError() to query which EGL error is raised. * */ result Start(void); /** * Pause the %GlPlayer. * * @since 2.0 * @return An error code * @exception E_SUCCESS The method is successful. * @exception E_SYSTEM Player cannot be paused properly due to a severe system error. * @exception E_INVALID_OPERATION Fail to perform the IGlRenderer::Pause() method which is implemented by developers. * @exception E_INVALID_STATE The state of player is not suitable for pause. For example, it is not allowable to pause player when it does not start after the initialization yet. * */ result Pause(void); /** * Resume the %GlPlayer. * * @since 2.0 * @return An error code * @exception E_SUCCESS The method is successful. * @exception E_SYSTEM Player cannot be resumed properly due to a severe system error. * @exception E_INVALID_OPERATION Fail to perform the IGlRenderer::Resume() method which is implemented by developers. * @exception E_INVALID_STATE The state of player is not suitable for resume. For example, it is not allowable to resume player when its state is stop. * */ result Resume(void); /** * Stop the %GlPlayer, and reset the EGL status. * * @since 2.0 * @return An error code * @exception E_SUCCESS The method is successful. * @exception E_SYSTEM Player cannot be stopped properly due to a severe system error. * @exception E_INVALID_OPERATION Fail to perform the IGlRenderer::Pause() method which is implemented by developers. * * @remarks Before starting to reset the EGL status, this method calls IGlRenderer::Pause() to prevent unexpected behavior. * */ result Stop(void); /** * Redraw the scene. * * @since 2.0 * @return An error code * @exception E_SUCCESS The method is successful. * @exception E_OPENGL_ERROR There occurs an EGL error during performing EGL function. * @exception E_INVALID_STATE The state of player is invalid and fails to pause properly. * * @remarks In the case that this returns @c E_OPENGL_ERROR exception, developers can use eglGetError() to query which EGL error is raised. * */ result Redraw(void); /** * Set the FPS(frames per second) of the player. * * @since 2.0 * @param[in] fps frames per second * * @remarks When you give negative integer for fps, then the %GlPlayer try to draw frames as fast as possible. * */ void SetFps(int fps); /** * Set the configuration list of EGL Attributes to initialize the EGL system. * * @since 2.0 * @return An error code * @param[in] pEglConfigList A list of EGL attributes and their values * @exception E_SUCCESS The method is successful. * @exception E_INVALID_ARG The specified input parameter is invalid. * * @remarks %GlPlayer initializes the EGL status with the given EGL attributes, which means that system does not guarantees to set EGL configurations with the given attributes but prefers them. * @remarks The format of eglConfigList is the same with the attribute list as the second input parameter of eglChooseConfig function. For detailed description, refer <a href="http://www.khronos.org/opengles/documentation/opengles1_0/html/eglChooseConfig.html">here</a>. * */ result SetEglAttributeList(const EGLint* pEglConfigList); /** * Set EGL configuration with the given preset. * * @since 2.0 * @return An error code * @param[in] preset Preset for attributes. * @exception E_SUCCESS The method is successful. * @exception E_INVALID_ARG The specified input parameter is invalid. * * @remarks %GlPlayer initializes the EGL status with the given EGL attributes, which means that system does not guarantees to set EGL configurations with the given attributes but prefers them. * */ result SetEglAttributePreset(EglAttributesPreset preset); /** * Set EGL configuration for the given Attribute with the given value. * * @since 2.0 * @return An error code * @param[in] key EGL attribute * @param[in] value Value for the attribute * @exception E_SUCCESS The method is successful. * @exception E_INVALID_ARG The specified input parameter is invalid. * * @remarks %GlPlayer initializes the EGL status with the given EGL attributes, which means that system does not guarantees to set EGL configurations with the given attributes but prefers them. * */ result SetEglAttribute(EGLint key, EGLint value); /** * Set the Renderer which implements %IGlRenderer interface. * * @since 2.0 * @return An error code * @param[in] pRenderer %IGlRenderer defines how to render the scene. * @exception E_SUCCESS The method is successful. * @exception E_INVALID_OPERATION Fail to perform the IGlRenderer::InitializeGl() method which is implemented by developers. * @see %IGlRenderer * * @remarks If %GlPlayer already has a renderer, then the previous renderer is replaced by the new one. * @remarks If input parameter is null, then the current renderer of %GlPlayer is detached and %GlPlayer does nothing. * @remarks When the %IGlRenderer is replaced with the input, the GL status have to be initialized for the input %IGlRenderer. For such purpose, when the input %IGlRenderer is attached, the overrided IGlRenderer::InitializedGl() method is called. On the other hand, the previous %IGlRenderer of %GlPlayer is detached after calling the overrided %IGlRenderer::TerminateGL() method. * */ result SetIGlRenderer(IGlRenderer* pRenderer); private: /* * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. * * @since 2.0 */ GlPlayer(const GlPlayer& rhs); /* * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. * * @since 2.0 */ GlPlayer& operator =(const GlPlayer& rhs); friend class _GlPlayerImpl; class _GlPlayerImpl* __pImpl; }; // GlPlayer }}} // Tizen::Graphics::Opengl #endif //_FGRP_GL_PLAYER_H_
[ "brighttwinsoftware@gmail.com" ]
brighttwinsoftware@gmail.com
6a4fe0bae5a036cdb9a47851f08f1f98b8e92c78
7b8a29b907c84490caefd5ecea1bc08981580332
/Program 3: Prefix Sum (Threads)/thread-main.cpp
33880c434da02f894ea2bb739e8af7a0256a44c9
[]
no_license
noahdelongpre/CS3331-ConcurrentComputing
f47702c02f679458f758a9fef11f2caa25638dba
f5957e0ac2ac199320f452173a3a03d4fc56fcd5
refs/heads/master
2020-05-04T18:27:40.677204
2019-04-04T16:33:44
2019-04-04T16:33:44
179,354,138
0
0
null
null
null
null
UTF-8
C++
false
false
3,640
cpp
// ----------------------------------------------------------- // NAME : Noah de Longpre' User ID: nkdelong // DUE DATE : 11/3/2017 // PROGRAM ASSIGNMENT 3 // FILE NAME : thread-main.cpp // PROGRAM PURPOSE : // Program runs the prefix sum algorithm concurrently using // Threads and ThreadMentor, as well as a global array. // // ----------------------------------------------------------- #include <iostream> #include "thread.h" #include <math.h> #include <stdlib.h> #include <unistd.h> #include "ThreadClass.h" //Actually needed from ThreadMentor #include <string.h> #include <stdio.h> using namespace std; int **B; //Global 2-D array //--------------------------------------------------------- // FUNCTION main : // This starts the program by initalizing the global 2-D array used for // the calculation of the Prefix Sum. For each iteration of summing // each thread is assigned to a one of n numbers, and the sum is calculated // then placed one row down in the 2-D array // PARAMETER USEAGE : // No parameters used. variables initailized from stdin // FUNCTION CALLED : // No outside functions are called. //--------------------------------------------------------- int main() { int n = 0; char buf[1000]; char print[1000]; cin >> n; //Number of elements in the Array int x[n]; int k = log2(n)+1; B = (int**) malloc( sizeof(int*) * k); // Array of Arrays for(int i = 0; i < k ; i++) { B[i] = (int*) malloc(sizeof(int) * n); //Opening the rest of the 2-D array } cout << "\n\nConcurrent Prefix Sum Computation" << endl; cout << "Number of input data = " << n << endl; cout << "Input Array: " << endl; strcpy(print, ""); for(int i = 0 ; i < n ; i++) { cin >> x[i]; //Reads in the values from the text doc strcpy(buf, ""); sprintf(buf, "%4d", x[i] ); strcat(print, buf); } strcat(print, "\n"); write(1, print, strlen(print)); // Prints the output array //First part of main is complete //Time to copy x[i] into the first line of B[i][j] for(int i = 0; i < n ; i++) { B[0][i] = x[i]; //Copies X into the first (0th) row of B. } cout << endl << endl << endl; PrefixSum *array[n]; // Makes n threads to run the sum int gap; int stage; for(int stage = 1; stage < k ; stage++) { sprintf(buf, "Run %d: \n", stage); //Printing which run we're on write(1, buf, strlen(buf)); gap = (int) pow(2, stage-1); for(int j = 0 ; j < n ; j++) { array[j] = new PrefixSum(n, k, gap, stage, j, B ); //Starting a thread to run for a value array[j]->Begin(); //Begins the thread } for(int j = 0 ; j < n ; j++) { array[j]->Join(); //Collects the threads } sprintf(buf, "Result after run %d: \n", stage); write(1, buf, strlen(buf)); strcpy(print, ""); for(int i = 0 ; i < n ; i++) { //Reads in what was just changed strcpy(buf, ""); sprintf(buf, "%4d", B[stage][i] ); strcat(print, buf); } strcat(print, "\n"); write(1, print, strlen(print)); // Prints the output array } sprintf(buf, "Final result after run %d: \n", k-1); write(1, buf, strlen(buf)); strcpy(print, ""); for(int i = 0 ; i < n ; i++) { //Final Array print strcpy(buf, ""); sprintf(buf, "%4d", B[k-1][i] ); strcat(print, buf); } strcat(print, "\n"); write(1, print, strlen(print)); // Prints the output array for(int i = 0 ; i < k ; i++) { free(B[i]); //Free of the intrim arrays } free(B); //Free the main 2-D array return 0; }
[ "nkdelong@mtu.edu" ]
nkdelong@mtu.edu
f14fcee611f83b8679b37d6ff4e86c6b71bfa1e0
00b979f12f13ace4e98e75a9528033636dab021d
/branches/ziis/src/core/thr_pool.cc
f42bb294153e4701da7a8066b4086a3b22874131
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
4,750
cc
// // thr_pool.cc for in // // Made by texane // Login <texane@gmail.com> // // Started on Tue Feb 14 02:00:09 2006 texane // Last update Wed Mar 22 21:38:51 2006 texane // #include <ziafs.hh> // thread cache function void* pool_cache_entry(void* param) { thr::pool::slot_t* p_slot; int err; p_slot = (thr::pool::slot_t*)param; pthread_mutex_lock(&p_slot->mtx_start); p_slot->thr_ready = true; // Execute the task while (p_slot->thr_done == false) { err = pthread_cond_wait(&p_slot->cond_start, &p_slot->mtx_start); if (err) p_slot->thr_ready = true; else if (p_slot->entry_fn) p_slot->entry_fn(p_slot); p_slot->locked = 0; } return 0; } // Internal pool slot management void thr::pool::reset_slot(thr::pool::slot_t& slot) { slot.locked = 0; slot.allocated = false; slot.thr_done = false; slot.thr_ready = false; slot.thr_blocked = false; slot.thr_lasterr = slot_t::e_success; slot.pool = this; // slot.cond_start = 0; // slot.mtx_start = 0; slot.entry_fn = 0; slot.uparam = 0; } bool thr::pool::allocate_slot(thr::pool::slot_t& slot) { // Create a thread that's // blocked on a condition // variable. bool ret; int err; ret = true; // slot.cond_start = 0; // slot.mtx_start = 0; err = pthread_mutex_init(&slot.mtx_start, 0); if (err) { ret = false; goto end_of_allocate; } err = pthread_cond_init(&slot.cond_start, 0); if (err) { ret = false; goto end_of_allocate; } slot.allocated = true; err = pthread_create(&slot.thr_id, 0, pool_cache_entry, (void*)&slot); if (err) { ret = false; goto end_of_allocate; } while (slot.thr_ready == false) ; end_of_allocate: if (ret == false) { release_slot(slot); reset_slot(slot); } return ret; } bool thr::pool::release_slot(thr::pool::slot_t& slot) { int ret; int* p_ret = &ret; if (slot.allocated == false) return false; // if (slot.mtx_start) pthread_mutex_destroy(&slot.mtx_start); // if (slot.cond_start) pthread_cond_destroy(&slot.cond_start); // ?? // pthread_detach(slot.thr_id); pthread_join(slot.thr_id, (void**)&p_ret); return true; } bool thr::pool::execute_task(thr::pool::slot_t& slot) { int err; // Wait for the thread pthread_mutex_lock(&slot.mtx_start); pthread_mutex_unlock(&slot.mtx_start); err = pthread_cond_signal(&slot.cond_start); if (err) return false; return true; } #ifdef _WIN32 static inline bool lock_the_slot(int* the_lock) { __asm { mov edx, dword ptr[the_lock] xor eax, eax xor ecx, ecx inc ecx lock cmpxchg dword ptr[edx], ecx jnz already_locked } return true; already_locked: return false; } #else static inline bool lock_the_slot(int* the_lock) { unsigned char owner; owner = 0; __asm__ __volatile__ ("xorl %%eax, %%eax\n\t" "xorl %%ecx, %%ecx\n\t" "incl %%ecx\n\t" "lock cmpxchg %%ecx, %0\n\t" "jnz already_locked\n\t" "incl %1\n\t" "already_locked:\n\t" : "=m"(*the_lock), "=m"(owner) : : "eax", "ecx"); if (owner == 1) return true; return false; } #endif // _WIN32 static inline bool unlock_the_slot(int* lock) { *lock = 0; return true; } // Exported thr::pool::pool(unsigned int nslots = 10) { unsigned int n; nr_ticks = 0; nr_slots = nslots; thr_slots = new slot_t[nr_slots]; for (n = 0; n < nslots; ++n) reset_slot(thr_slots[n]); } thr::pool::~pool() { delete[] thr_slots; } bool thr::pool::assign_task(void* (*entry_fn)(slot_t*), void* uparam) { unsigned int nslot; slot_t* p_slot; bool done; // Find a slot p_slot = 0; done = false; for (nslot = 0; done == false && nslot < nr_slots; ++nslot) { if (lock_the_slot(&thr_slots[nslot].locked) == true) { if (thr_slots[nslot].allocated == true) { if (p_slot) unlock_the_slot(&p_slot->locked); p_slot = &thr_slots[nslot]; done = true; } else if (p_slot == 0) { p_slot = &thr_slots[nslot]; } else { unlock_the_slot(&thr_slots[nslot].locked); } } } // no more slot available if (done == false && p_slot == 0) return false; // No slot has been found, allocate one if (done == false) allocate_slot(*p_slot); // Fill the slot p_slot->entry_fn = entry_fn; p_slot->uparam = uparam; // Start the thread execute_task(*p_slot); return true; }
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
texane@754ce95b-6e01-0410-81d0-8774ba66fe44
223dc6acab3f7e387eb255d1a6a6b7a3b514aca1
95c1a4002ce0f3b497c480b2e9378ff51c2d818f
/ComTrade/src/CComTradeFile.cpp
fb0c4b9a2eb2c5838801d40654e0dc5d651ba403
[]
no_license
lilinfeng124/LibPrinter
fa8a81c177089252f837ebf0e74287ca842938bd
5997eb816910c887168a63e31c1ebf783395f999
refs/heads/master
2021-01-20T19:33:55.058583
2016-06-15T08:14:54
2016-06-15T08:14:54
61,189,074
0
0
null
null
null
null
UTF-8
C++
false
false
37,568
cpp
#include "CComTradeFile.h" #include <QtDebug> #include "qmath.h" CComTradeFile::CComTradeFile () { m_nTrigger_ms = 0; m_nFrist_ms = 0; m_lFirstMicroSecs = 0; m_bDChanelAct = false; } CComTradeFile::~CComTradeFile() { } bool CComTradeFile::SampleDataToAnalogData(unsigned long nAIndex, const CChanelSampleData& chanelData,CAnalogData& aData) { if (chanelData.m_AChanelDataList.count()!= chanelData.m_AChanelDataValidList.count() || chanelData.m_AChanelDataList.count() != m_cfgFile.m_nAChanelCount) { m_ErrorList << QString("模拟采样通道数据与模拟通道配置不一致。"); return false; } aData.m_nIndex = nAIndex; aData.m_bValid = chanelData.m_AChanelDataValidList.at(nAIndex); aData.m_fRawValue = chanelData.m_AChanelDataList.at(nAIndex); aData.m_nTimeStamp = chanelData.m_nTimeStamp; return true; } bool CComTradeFile::SampleDataToDigitalData(unsigned long nDIndex, const CChanelSampleData& chanelData, CDigitalData& dData, bool& bChanged) { if ( chanelData.m_DChanelDataList.count() != m_cfgFile.m_nDChanelCount) { m_ErrorList << QString("数字采样通道数据与数字通道配置不一致。"); return false; } dData.m_nIndex = nDIndex; dData.m_nValue = chanelData.m_DChanelDataList.at(nDIndex); dData.m_nTimeStamp = chanelData.m_nTimeStamp; if (dData.m_nValue != 0) { bChanged = true; } return true; } void CComTradeFile::StaticAnalogData(CStaticAnalogData& staticAData,const CAnalogData& aData) { staticAData.m_nIndex = aData.m_nIndex; //原始 staticAData.m_fMaxRawValue = qMax(aData.m_fRawValue,staticAData.m_fMaxRawValue); staticAData.m_fMinRawValue = qMin(aData.m_fRawValue,staticAData.m_fMinRawValue); //原始实部 staticAData.m_fMaxRawRealValue = qMax(aData.m_fRawRealValue,staticAData.m_fMaxRawRealValue); staticAData.m_fMinRawRealValue = qMin(aData.m_fRawRealValue,staticAData.m_fMinRawRealValue); //原始虚部 staticAData.m_fMaxRawImgValue = qMax(aData.m_fRawImgValue,staticAData.m_fMaxRawImgValue); staticAData.m_fMinRawImgValue = qMin(aData.m_fRawImgValue,staticAData.m_fMinRawImgValue); //原始有效 staticAData.m_fMaxRawEffectValue = qMax(aData.m_fRawEffectValue,staticAData.m_fMaxRawEffectValue); staticAData.m_fMinRawEffectValue = qMin(aData.m_fRawEffectValue,staticAData.m_fMinRawEffectValue); //原始相角 staticAData.m_fMaxRawAngleValue = qMax(aData.m_fRawAngleValue,staticAData.m_fMaxRawAngleValue); staticAData.m_fMinRawAngleValue = qMin(aData.m_fRawAngleValue,staticAData.m_fMinRawAngleValue); //一次采样 staticAData.m_fPMaxSampleValue = qMax(aData.m_fPSampleValue,staticAData.m_fPMaxSampleValue); staticAData.m_fPMinSampleValue = qMin(aData.m_fPSampleValue,staticAData.m_fPMinSampleValue); //二次采样 staticAData.m_fSMaxSampleValue = qMax(aData.m_fSSampleValue,staticAData.m_fSMaxSampleValue); staticAData.m_fSMinSampleValue = qMin(aData.m_fSSampleValue,staticAData.m_fSMinSampleValue); //一次有效 staticAData.m_fPMaxEffectValue = qMax(aData.m_fPEffectValue,staticAData.m_fPMaxEffectValue); staticAData.m_fPMinEffectValue = qMin(aData.m_fPEffectValue,staticAData.m_fPMinEffectValue); //二次有效 staticAData.m_fSMaxEffectValue = qMax(aData.m_fSEffectValue,staticAData.m_fSMaxEffectValue); staticAData.m_fSMinEffectValue = qMin(aData.m_fSEffectValue,staticAData.m_fSMinEffectValue); //一次实部 staticAData.m_fPMaxRealValue = qMax(aData.m_fPRealValue,staticAData.m_fPMaxRealValue); staticAData.m_fPMinRealValue = qMin(aData.m_fPRealValue,staticAData.m_fPMinRealValue); //二次实部 staticAData.m_fSMaxRealValue = qMax(aData.m_fSRealValue,staticAData.m_fSMaxRealValue); staticAData.m_fSMinRealValue = qMin(aData.m_fSRealValue,staticAData.m_fSMinRealValue); //一次虚部 staticAData.m_fPMaxImgValue = qMax(aData.m_fPImgValue,staticAData.m_fPMaxImgValue); staticAData.m_fPMinImgValue = qMin(aData.m_fPImgValue,staticAData.m_fPMinImgValue); //二次虚部 staticAData.m_fSMaxImgValue = qMax(aData.m_fSImgValue,staticAData.m_fSMaxImgValue); staticAData.m_fSMinImgValue = qMin(aData.m_fSImgValue,staticAData.m_fSMinImgValue); //一次幅值 staticAData.m_fPMaxAmpValue = qMax(aData.m_fPAmpValue,staticAData.m_fPMaxAmpValue); staticAData.m_fPMinAmpValue = qMin(aData.m_fPAmpValue,staticAData.m_fPMinAmpValue); //二次幅值 staticAData.m_fSMaxAmpValue = qMax(aData.m_fSAmpValue,staticAData.m_fSMaxAmpValue); staticAData.m_fSMinAmpValue = qMin(aData.m_fSAmpValue,staticAData.m_fSMinAmpValue); //一次相角 staticAData.m_fPMaxAngleValue = qMax(aData.m_fPAngleValue,staticAData.m_fPMaxAngleValue); staticAData.m_fPMinAngleValue = qMin(aData.m_fPAngleValue,staticAData.m_fPMinAngleValue); //二次相角 staticAData.m_fSMaxAngleValue = qMax(aData.m_fSAngleValue,staticAData.m_fSMaxAngleValue); staticAData.m_fSMinAngleValue = qMin(aData.m_fSAngleValue,staticAData.m_fSMinAngleValue); } void CComTradeFile::TransformAnalogData(CStaticAnalogData& staticAData,AnalogDataList& aDataList, int nBlock,const CAChanelInfo& aInfo) { Fourier(aDataList,nBlock); for (int nIndex = 0; nIndex < aDataList.count(); nIndex++) { CAnalogData aData = aDataList.at(nIndex); //一次二次计算方法如下:fRaw = 采样值 //如果采样为一次,一次 = fRaw*m_dMultiplier+m_dOffsetAdder //二次 = (fRaw*m_dMultiplier+m_dOffsetAdder)*m_fSecondary/m_fPrimary; //如果采样为二次,二次 = feRaw*m_dMultiplier+m_dOffsetAdder //一次 = (fRaw*m_dMultiplier+m_dOffsetAdder)*m_fPrimary /m_fSecondary; if (IsAInfoPrimary(aInfo)) { aData.m_fPSampleValue = aData.m_fRawValue*aInfo.m_fA + aInfo.m_fB; aData.m_fSSampleValue = aData.m_fPSampleValue*aInfo.m_fSecondary/aInfo.m_fPrimary; aData.m_fPEffectValue = aData.m_fRawEffectValue*aInfo.m_fA + aInfo.m_fB; aData.m_fSEffectValue = aData.m_fPEffectValue*aInfo.m_fSecondary/aInfo.m_fPrimary; aData.m_fPRealValue = aData.m_fRawRealValue*aInfo.m_fA + aInfo.m_fB; aData.m_fSRealValue = aData.m_fPRealValue*aInfo.m_fSecondary/aInfo.m_fPrimary; aData.m_fPImgValue = aData.m_fRawImgValue*aInfo.m_fA + aInfo.m_fB; aData.m_fSImgValue = aData.m_fPImgValue*aInfo.m_fSecondary/aInfo.m_fPrimary; aData.m_fPAmpValue = aData.m_fRawEffectValue*M_SQRT2*aInfo.m_fA + aInfo.m_fB; aData.m_fSAmpValue = aData.m_fPAmpValue*aInfo.m_fSecondary/aInfo.m_fPrimary; aData.m_fPAngleValue = aData.m_fRawAngleValue*aInfo.m_fA + aInfo.m_fB; aData.m_fSAngleValue = aData.m_fPAngleValue*aInfo.m_fSecondary/aInfo.m_fPrimary; } else { aData.m_fSSampleValue = aData.m_fRawValue*aInfo.m_fA + aInfo.m_fB; aData.m_fPSampleValue = aData.m_fSSampleValue*aInfo.m_fPrimary/aInfo.m_fSecondary; aData.m_fSEffectValue = aData.m_fRawEffectValue*aInfo.m_fA + aInfo.m_fB; aData.m_fPEffectValue = aData.m_fSEffectValue*aInfo.m_fPrimary/aInfo.m_fSecondary; aData.m_fSRealValue = aData.m_fRawRealValue*aInfo.m_fA + aInfo.m_fB; aData.m_fPRealValue = aData.m_fSRealValue*aInfo.m_fPrimary/aInfo.m_fSecondary; aData.m_fSImgValue = aData.m_fRawImgValue*aInfo.m_fA + aInfo.m_fB; aData.m_fPImgValue = aData.m_fSImgValue*aInfo.m_fPrimary/aInfo.m_fSecondary; aData.m_fSAmpValue = aData.m_fRawEffectValue*M_SQRT2*aInfo.m_fA + aInfo.m_fB; aData.m_fPAmpValue = aData.m_fSAmpValue*aInfo.m_fPrimary/aInfo.m_fSecondary; aData.m_fSAngleValue = aData.m_fRawAngleValue*aInfo.m_fA + aInfo.m_fB; aData.m_fPAngleValue = aData.m_fSAngleValue*aInfo.m_fPrimary/aInfo.m_fSecondary; } if (m_AnalogDataMap.contains(aData.m_nTimeStamp)) { AnalogDataList& aMapDataList = m_AnalogDataMap[aData.m_nTimeStamp]; aMapDataList.append(aData); } else { AnalogDataList aMapDataList; aMapDataList.append(aData); m_AnalogDataMap[aData.m_nTimeStamp] = aMapDataList; } //统计数据 StaticAnalogData(staticAData,aData); } } void CComTradeFile::TransformDigitalData(DigitalDataList& dDataList, bool bChanged) { for ( int nIndex=0; nIndex < dDataList.count(); nIndex++) { CDigitalData dData = dDataList.at(nIndex); if (bChanged) { dData.m_bChanged = true; m_bDChanelAct = true; } if (m_DigitalDataMap.contains(dData.m_nTimeStamp)) { DigitalDataList& dMapDataList = m_DigitalDataMap[dData.m_nTimeStamp]; dMapDataList.append(dData); } else { DigitalDataList dMapDataList; dMapDataList.append(dData); m_DigitalDataMap[dData.m_nTimeStamp] = dMapDataList; } } } bool CComTradeFile::TransformData() { m_AnalogDataMap.clear(); m_DigitalDataMap.clear(); m_StaticValueMap.clear(); m_MidDigitalChangedMap.clear(); m_MidSampleDataMap.clear(); if (IsContinuous()) //连续采样 { return true; } unsigned int nCount = m_cfgFile.m_nAChanelCount>m_cfgFile.m_nDChanelCount?m_cfgFile.m_nAChanelCount:m_cfgFile.m_nDChanelCount; for (unsigned int nIndex = 0; nIndex < nCount;nIndex++) { unsigned int nStart = 0; bool bChanged = false; DigitalDataList dDataList; CStaticAnalogData staticAnalogData; for (unsigned short nBlock=0; nBlock < GetNrates();nBlock++) { unsigned int nCount = GetSampleCountByBlock(nBlock); AnalogDataList aDataList; for(unsigned int nSamTick = 0; nSamTick < nCount; nSamTick++) { CChanelSampleData chanelData = m_datFile.m_ChanelDataList.at(nSamTick+nStart); if (nIndex < m_cfgFile.m_nAChanelCount) { CAnalogData aData; if (!SampleDataToAnalogData(nIndex,chanelData,aData)) { return false; } aDataList.append(aData); } if (nIndex < m_cfgFile.m_nDChanelCount) { CDigitalData dData; if (!SampleDataToDigitalData(nIndex,chanelData,dData,bChanged)) { return false; } dDataList.append(dData); } } //a通道变换 if (nIndex < m_cfgFile.m_nAChanelCount) { CAChanelInfo aInfo = m_cfgFile.m_AChanelInfoList.at(nIndex); TransformAnalogData(staticAnalogData,aDataList,nBlock,aInfo); } nStart += nCount; } if (nIndex < m_cfgFile.m_nAChanelCount) { m_StaticValueMap[nIndex] = staticAnalogData; } //d通道变换 TransformDigitalData(dDataList,bChanged); if (nIndex < m_cfgFile.m_nDChanelCount) { if (bChanged) { m_DigitalChangedMap[nIndex] = true; } else { m_DigitalChangedMap[nIndex] = false; } } } m_TimeArray = m_AnalogDataMap.keys(); for (unsigned int nIndex = 0; nIndex < m_desFile.m_nDChanelCount;nIndex++) { for(int nMidIndex=0; nMidIndex < m_midFile.m_ChanelDataList.count();nMidIndex++) { CChanelSampleData samData = m_midFile.m_ChanelDataList.at(nMidIndex); if (samData.m_DChanelDataList.at(nIndex) != 0) { m_MidDigitalChangedMap[nIndex] = true; } else { m_MidDigitalChangedMap[nIndex] = false; } if (!m_MidSampleDataMap.contains(samData.m_nTimeStamp)) { m_MidSampleDataMap[samData.m_nTimeStamp] = samData; } } } return true; } QStringList CComTradeFile::GetErrorList() { return m_ErrorList; } //1 hdr 2 cfg 3 des 4dat 5 mid bool CComTradeFile::ReadComTradeFileList(const QStringList& fileList) { //读取hdr文件 QString strHdrFile = fileList.at(0); if (!m_hdrFile.ReadHdrFile(strHdrFile)) { m_ErrorList << m_hdrFile.m_ErrorList; return false; } //读取cfg文件和des文件 QString strCfgFile = fileList.at(1); if (!m_cfgFile.ReadCfgFile(strCfgFile)) { m_ErrorList << m_cfgFile.m_ErrorList; return false; } QString strDesFile = fileList.at(2); if (!m_desFile.ReadDesFile(strDesFile)) { m_ErrorList << m_desFile.m_ErrorList; return false; } int nCfgACount = m_cfgFile.m_nAChanelCount; int nCfgDCount = m_cfgFile.m_nDChanelCount; bool bBin = m_cfgFile.m_bBin; int nMidAcount = m_desFile.m_nAChanelCount; int nMidDCount = m_desFile.m_nDChanelCount; //根据类型读取dat和mid文件 QString strDatFile = fileList.at(3); if (!m_datFile.ReadDatFile(strDatFile,nCfgACount,nCfgDCount,bBin)) { m_ErrorList << m_datFile.m_ErrorList; return false; } QString strMidFile = fileList.at(4); if (!m_midFile.ReadDatFile(strMidFile,nMidAcount,nMidDCount,bBin)) { m_ErrorList << m_midFile.m_ErrorList; return false; } //变换数据 if (!TransformData()) { return false; } //时间变换为毫秒 TimeMSecond(); return true; } bool CComTradeFile::ReadComTradeFile(const QString& strFile) { //读取hdr文件 QString strHdrFile = FileNameFromType(strFile,Hdr); if (!m_hdrFile.ReadHdrFile(strHdrFile)) { m_ErrorList << m_hdrFile.m_ErrorList; return false; } //读取cfg文件和des文件 QString strCfgFile = FileNameFromType(strFile,Cfg); if (!m_cfgFile.ReadCfgFile(strCfgFile)) { m_ErrorList << m_cfgFile.m_ErrorList; return false; } QString strDesFile = FileNameFromType(strFile,Des); if (!m_desFile.ReadDesFile(strDesFile)) { m_ErrorList << m_desFile.m_ErrorList; return false; } int nCfgACount = m_cfgFile.m_nAChanelCount; int nCfgDCount = m_cfgFile.m_nDChanelCount; bool bBin = m_cfgFile.m_bBin; int nMidAcount = m_desFile.m_nAChanelCount; int nMidDCount = m_desFile.m_nDChanelCount; //根据类型读取dat和mid文件 QString strDatFile = FileNameFromType(strFile,Dat); if (!m_datFile.ReadDatFile(strDatFile,nCfgACount,nCfgDCount,bBin)) { m_ErrorList << m_datFile.m_ErrorList; return false; } QString strMidFile = FileNameFromType(strFile,Mid); if (!m_midFile.ReadDatFile(strMidFile,nMidAcount,nMidDCount,bBin)) { m_ErrorList << m_midFile.m_ErrorList; return false; } //变换数据 if (!TransformData()) { return false; } //时间变换为毫秒 TimeMSecond(); return true; } QList<unsigned long> CComTradeFile::GetTimeArray() { return m_TimeArray; } void CComTradeFile::TimeMSecond() { QTime trigerTime = m_cfgFile.m_dtTriggerTime.m_dtTime.time(); QTime fristTime = m_cfgFile.m_dtFirstDataTime.m_dtTime.time(); m_lFirstMicroSecs = m_cfgFile.m_dtFirstDataTime.m_nWs/1000; int nTriggerHour = trigerTime.hour(); int nFirstHour = fristTime.hour(); if(nTriggerHour==0) nTriggerHour = 24; if(nFirstHour==0) nFirstHour = 24; m_nTrigger_ms = ((nTriggerHour*60 + trigerTime.minute())*60 + trigerTime.second())*1000 + m_cfgFile.m_dtTriggerTime.m_nWs/1000; m_nFrist_ms = ((nFirstHour*60 + fristTime.minute())*60 + fristTime.second())*1000 + m_cfgFile.m_dtFirstDataTime.m_nWs/1000; m_nFrist_ms = m_nFrist_ms - m_nTrigger_ms; m_nTrigger_ms = 0; } int CComTradeFile::GetFirstDataTimeMs() { return m_nFrist_ms; } int CComTradeFile::GetTriggeredTimeMs() { return m_nTrigger_ms; } qint64 CComTradeFile::GetABSFirstDataTimeMs() { return m_lFirstMicroSecs; } double CComTradeFile::GetPointTime(unsigned int nPoint) { if (nPoint < (unsigned int)m_TimeArray.count()) { return m_TimeArray.at(nPoint); } return m_nFrist_ms; } int CComTradeFile::GetTotalPointCount() { QList<unsigned long> timeList = m_AnalogDataMap.keys(); return timeList.count(); } int CComTradeFile::GetStartPointByBlock(int nBlock) { int nStart = 0; for (int nIndex =0; nIndex < GetNrates()&&nIndex<nBlock;nIndex++) { nStart += m_cfgFile.m_SampleInfoList.at(nIndex).m_nCount; } return nStart; } int CComTradeFile::GetSampleCountByBlock(int nBlock) { int nStart = 0; if (GetNrates() == 0) { return m_cfgFile.m_SampleInfoList.at(0).m_nCount; } if (nBlock < GetNrates()) { nStart = m_cfgFile.m_SampleInfoList.at(nBlock).m_nCount; } return nStart; } double CComTradeFile::GetSampleRateByBlock(int nBlock) { int nStart = 0; if (GetNrates() == 0) { return m_cfgFile.m_SampleInfoList.at(0).m_fSamp; } if (nBlock < GetNrates()) { nStart = m_cfgFile.m_SampleInfoList.at(nBlock).m_fSamp; } return nStart; } double CComTradeFile::GetMaxAbsRawValue(unsigned int nAIndex) { double fMax = GetMaxRawValue(nAIndex); double fMin = GetMinRawValue(nAIndex); double fRet = qMax(qAbs(fMax),qAbs(fMin)); return fRet; } double CComTradeFile::GetMinRawValue(unsigned int nAIndex) { if (m_StaticValueMap.contains(nAIndex)) { return m_StaticValueMap[nAIndex].m_fMinRawValue; } return 0.0; } double CComTradeFile::GetMaxRawValue(unsigned int nAIndex) { if (m_StaticValueMap.contains(nAIndex)) { return m_StaticValueMap[nAIndex].m_fMaxRawValue; } return 0.0; } void CComTradeFile::SetMaxRawValue(unsigned int nAn,double fValue) { m_StaticValueMap[nAn].m_fMaxRawValue = fValue; } double CComTradeFile::GetMaxValue(unsigned int nIndex,int nValueType,int nWaveType) { double fValue = 0.0; CStaticAnalogData aData = m_StaticValueMap.value(nIndex); if (nValueType == PRIMARY) { if (nWaveType == SAMPLE) { fValue = aData.m_fPMaxSampleValue; } if (nWaveType == EFFECT) { fValue = aData.m_fPMaxEffectValue; } if (nWaveType == AMP) { fValue = aData.m_fPMaxAmpValue; } if (nWaveType == REAL) { fValue = aData.m_fPMaxRealValue; } if (nWaveType == ANGLE) { fValue = aData.m_fPMaxAngleValue; } if (nWaveType == IMG) { fValue = aData.m_fPMaxImgValue; } } else { if (nWaveType == SAMPLE) { fValue = aData.m_fSMaxSampleValue; } if (nWaveType == EFFECT) { fValue = aData.m_fSMaxEffectValue; } if (nWaveType == AMP) { fValue = aData.m_fSMaxAmpValue; } if (nWaveType == REAL) { fValue = aData.m_fSMaxRealValue; } if (nWaveType == ANGLE) { fValue = aData.m_fSMaxAngleValue; } if (nWaveType == IMG) { fValue = aData.m_fSMaxImgValue; } } return fValue; } double CComTradeFile::GetMinValue(unsigned int nIndex,int nValueType,int nWaveType) { double fValue = 0.0; CStaticAnalogData aData = m_StaticValueMap.value(nIndex); if (nValueType == PRIMARY) { if (nWaveType == SAMPLE) { fValue = aData.m_fPMinSampleValue; } if (nWaveType == EFFECT) { fValue = aData.m_fPMinEffectValue; } if (nWaveType == AMP) { fValue = aData.m_fPMinAmpValue; } if (nWaveType == REAL) { fValue = aData.m_fPMinRealValue; } if (nWaveType == ANGLE) { fValue = aData.m_fPMinAngleValue; } if (nWaveType == IMG) { fValue = aData.m_fPMinImgValue; } } else { if (nWaveType == SAMPLE) { fValue = aData.m_fSMinSampleValue; } if (nWaveType == EFFECT) { fValue = aData.m_fSMinEffectValue; } if (nWaveType == AMP) { fValue = aData.m_fSMinAmpValue; } if (nWaveType == REAL) { fValue = aData.m_fSMinRealValue; } if (nWaveType == ANGLE) { fValue = aData.m_fSMinAngleValue; } if (nWaveType == IMG) { fValue = aData.m_fSMinImgValue; } } return fValue; } bool CComTradeFile::IsDChanelAct() { return m_bDChanelAct; } bool CComTradeFile::IsDChanelAct(unsigned int nDIndex) { if (m_DigitalChangedMap.contains(nDIndex)) { return m_DigitalChangedMap[nDIndex]; } return false; } double CComTradeFile::GetAnalogValueByIndexPoint(unsigned int nIndex,unsigned int nPoint) { if (nPoint >=0 && nPoint < (unsigned int)m_TimeArray.count()) { unsigned int nTime = m_TimeArray.at(nPoint); AnalogDataList aDataList = m_AnalogDataMap.value(nTime); if (nIndex>=0 && nIndex < (unsigned int)aDataList.count()) { return aDataList.at(nIndex).m_fRawValue; } } return 0; } unsigned short CComTradeFile::GetDigitalValueByIndexPoint(unsigned int nIndex, unsigned int nPoint) { if (nPoint >=0 && nPoint < (unsigned int)m_TimeArray.count()) { unsigned int nTime = m_TimeArray.at(nPoint); DigitalDataList dDataList = m_DigitalDataMap.value(nTime); if (nIndex>=0 && nIndex < (unsigned int)dDataList.count()) { return dDataList.at(nIndex).m_nValue; } } return 0; } bool CComTradeFile::GetTypedAnalogValueByIndexPoint(unsigned int nIndex, unsigned int nPoint,int nValueType, int nWaveType,double& fValue) { if (nPoint >=0 && nPoint < (unsigned int)m_TimeArray.count()) { unsigned int nTime = m_TimeArray.at(nPoint); AnalogDataList aDataList = m_AnalogDataMap.value(nTime); if (nIndex>=0 && nIndex < (unsigned int)aDataList.count()) { CAnalogData aData = aDataList.at(nIndex); if (nValueType == PRIMARY) { if (nWaveType == SAMPLE) { fValue = aData.m_fPSampleValue; } if (nWaveType == EFFECT) { fValue = aData.m_fPEffectValue; } if (nWaveType == AMP) { fValue = aData.m_fPAmpValue; } if (nWaveType == REAL) { fValue = aData.m_fPRealValue; } if (nWaveType == ANGLE) { fValue = aData.m_fPAngleValue; } if (nWaveType == IMG) { fValue = aData.m_fPImgValue; } } else { if (nWaveType == SAMPLE) { fValue = aData.m_fSSampleValue; } if (nWaveType == EFFECT) { fValue = aData.m_fSEffectValue; } if (nWaveType == AMP) { fValue = aData.m_fSAmpValue; } if (nWaveType == REAL) { fValue = aData.m_fSRealValue; } if (nWaveType == ANGLE) { fValue = aData.m_fSAngleValue; } if (nWaveType == IMG) { fValue = aData.m_fSImgValue; } } return true; } } return false; } PHASE_TYPE CComTradeFile::GetAChanelPhase(unsigned int nIndex) { CAChanelInfo aInfo = GetAInfoByIndex(nIndex); if (aInfo.m_strCh_id.contains("A",Qt::CaseInsensitive)) { return PHASE_A; } else if (aInfo.m_strCh_id.contains("B",Qt::CaseInsensitive)) { return PHASE_B; } else if (aInfo.m_strCh_id.contains("C",Qt::CaseInsensitive)) { return PHASE_C; } return PHASE_NULL; } bool CComTradeFile::IsAInfoPrimary(unsigned int nIndex) { CAChanelInfo aInfo = GetAInfoByIndex(nIndex); return IsAInfoPrimary(aInfo); } QString CComTradeFile::FileNameFromType(const QString& strFile,FileType type) { QString strRet = strFile; QString strBefore = strRet.right(4); //.cfg .hdr ... switch (type) { case Hdr: { strRet.replace(strBefore,".hdr"); break; } case Cfg: { strRet.replace(strBefore,".cfg"); break; } case Dat: { strRet.replace(strBefore,".dat"); break; } case Des: { strRet.replace(strBefore,".des"); break; } case Mid: { strRet.replace(strBefore,".mid"); break; } default: break; } return strRet; } bool CComTradeFile::IsAInfoPrimary(const CAChanelInfo& aInfo) { if (aInfo.m_cPs.compare("P",Qt::CaseInsensitive)==0) { return true; } return false; } //对于每个采样块进行变换 bool CComTradeFile::Fourier(AnalogDataList& dataList,int nBlock) { //求取变换系数 unsigned int i; int nRate = int(0.5+GetSampleRateByBlock(nBlock)); int sampleDot = (nRate + 25) / 50;//基波采样点数,四舍五入处理 if(sampleDot == 0) { m_ErrorList << QString("采样点读取错误"); return false; } if((sampleDot > 2) && (1 > (sampleDot / 3)))//根据采样定律,至少3个点 { m_ErrorList << QString("根据采样定律,该算法最大只能计算到nn次谐波"); return false; } double rad = PI * 2.0 / sampleDot;//基波角速度 //傅式算法系数计算,固定取基波一周期的采样点,高次谐波系数不一定重复,以减小误差 double* fourier_coff_cos = new double[sampleDot]; double* fourier_coff_sin = new double[sampleDot]; for(i = 0; i < (unsigned int)sampleDot; i++) { double lv_harmonic_angle = rad * 1 * i;//谐波角度 = 谐波角速度 X i fourier_coff_cos[i] = cos(lv_harmonic_angle); fourier_coff_sin[i] = sin(lv_harmonic_angle); } //a通道值进行变换,使用采样值进行变换 double lv_sum_real; double lv_sum_imag; unsigned int j; for(j = (unsigned int)sampleDot; j < (unsigned int)GetSampleCountByBlock(nBlock); j++) { lv_sum_real = 0; lv_sum_imag = 0; for(i =0; i < (unsigned int)sampleDot; i++) { double lv_val_temp = dataList[j + i - sampleDot].m_fRawValue; lv_sum_real += lv_val_temp * fourier_coff_sin[i]; lv_sum_imag += lv_val_temp * fourier_coff_cos[i]; } dataList[j].m_fRawRealValue = 2 * lv_sum_real / sampleDot / SQRT_OF_2; dataList[j].m_fRawImgValue = 2 * lv_sum_imag / sampleDot / SQRT_OF_2; dataList[j].m_fRawEffectValue = sqrt(dataList[j].m_fRawRealValue * dataList[j].m_fRawRealValue + dataList[j].m_fRawImgValue * dataList[j].m_fRawImgValue); dataList[j].m_fRawAngleValue = atan2(dataList[j].m_fRawImgValue, dataList[j].m_fRawRealValue) * PI_TO_ANGLE; } for(j = 0; j < (unsigned int)sampleDot &&j < (unsigned int)dataList.count()&&j <(unsigned int)(dataList.count() - sampleDot); j++)//第一个周期使用第二个周期的重复 { dataList[j].m_fRawRealValue = dataList[j + sampleDot].m_fRawRealValue; dataList[j].m_fRawImgValue = dataList[j + sampleDot].m_fRawImgValue; dataList[j].m_fRawEffectValue = dataList[j + sampleDot].m_fRawEffectValue; dataList[j].m_fRawAngleValue = dataList[j + sampleDot].m_fRawAngleValue; } delete [] fourier_coff_cos; delete [] fourier_coff_sin; return true; } CComTradeFile & CComTradeFile::operator=( const CComTradeFile & srcFile) { m_cfgFile = srcFile.m_cfgFile; m_datFile = srcFile.m_datFile; m_hdrFile = srcFile.m_hdrFile; m_midFile = srcFile.m_midFile; m_desFile = srcFile.m_desFile; m_nTrigger_ms = srcFile.m_nTrigger_ms; m_nFrist_ms = srcFile.m_nFrist_ms; m_lFirstMicroSecs = srcFile.m_lFirstMicroSecs; m_AnalogDataMap = srcFile.m_AnalogDataMap; m_DigitalDataMap = srcFile.m_DigitalDataMap; m_StaticValueMap = srcFile.m_StaticValueMap; return *this; } bool CComTradeFile::IsContinuous() { return (m_cfgFile.m_nNrates == 0); } //配置 QString CComTradeFile::GetRevision() //版本年号 { return m_cfgFile.m_strVersion; } bool CComTradeFile::IsDatBin() //数据文件是否二进制 { return m_cfgFile.m_bBin; } QString CComTradeFile::GetSiteName() //厂站名称 { return m_cfgFile.m_strSite; } QString CComTradeFile::GetUnitName() //装置特征号 { return m_cfgFile.m_strDevice; } unsigned int CComTradeFile::GetChanelCount() //通道数量 { return m_cfgFile.m_nAChanelCount + m_cfgFile.m_nDChanelCount; } unsigned int CComTradeFile::GetACount() //A通道数量 { return m_cfgFile.m_nAChanelCount; } unsigned int CComTradeFile::GetDCount() //D通道数量 { return m_cfgFile.m_nDChanelCount; } CAChanelInfo CComTradeFile::GetAInfoByIndex(unsigned int nIndex) { if(nIndex>m_cfgFile.m_AChanelInfoList.count()-1) { return CAChanelInfo(); } return m_cfgFile.m_AChanelInfoList.at(nIndex); } CDChanelInfo CComTradeFile::GetDInfoByIndex(unsigned int nIndex) { if(nIndex>m_cfgFile.m_DChanelInfoList.count()-1) { return CDChanelInfo(); } return m_cfgFile.m_DChanelInfoList.at(nIndex); } CAChanelInfo CComTradeFile::GetAInfoByName(const QString& strName,bool& bOk) { for (int nIndex=0; nIndex < m_cfgFile.m_AChanelInfoList.count();nIndex++) { CAChanelInfo aInfo = m_cfgFile.m_AChanelInfoList.at(nIndex); if (!aInfo.m_strCh_id.compare(strName,Qt::CaseInsensitive)) { bOk = true; return aInfo; } } bOk = false; return CAChanelInfo(); } CDChanelInfo CComTradeFile::GetDInfoByName(const QString& strName,bool& bOk) { for (int nIndex=0; nIndex < m_cfgFile.m_DChanelInfoList.count();nIndex++) { CDChanelInfo dInfo = m_cfgFile.m_DChanelInfoList.at(nIndex); if (!dInfo.m_strCh_id.compare(strName,Qt::CaseInsensitive)) { bOk = true; return dInfo; } } bOk = false; return CDChanelInfo(); } AChanelInfoList CComTradeFile::GetAChanelInfoList() { return m_cfgFile.m_AChanelInfoList; } DChanelInfoList CComTradeFile::GetDChanelInfoList() { return m_cfgFile.m_DChanelInfoList; } double CComTradeFile::GetLineFreq() //线路频率 { return m_cfgFile.m_fIF; } unsigned short CComTradeFile::GetNrates() //采样率块数 { return m_cfgFile.m_nNrates; } SampleInfoList CComTradeFile::GetSampleInfos() //采样信息 { return m_cfgFile.m_SampleInfoList; } double CComTradeFile::GetTimeMult() //时间比例,正常1.0 { return m_cfgFile.m_fTimeMult; } CExDateTime CComTradeFile::GetFirstDataTime() //第一个采样数据时间 { return m_cfgFile.m_dtFirstDataTime; } CExDateTime CComTradeFile::GetTriggeredTime() //触发时间 { return m_cfgFile.m_dtTriggerTime; } //数据,这一部分数据将保存所有的 //一次,二次,数据采样,有效 ,幅值,实部,虚部,相角等等 //得到某个时间点某个模拟通道的值 double CComTradeFile::GetAnalogValue(unsigned long nTime,unsigned int nAIndex, ValueType valueType,ValueAttr valueAttr) { double fValue = 0.0; if (!m_AnalogDataMap.contains(nTime)) { return fValue; } AnalogDataList aDataList = m_AnalogDataMap.value(nTime); if (nAIndex>=0 && nAIndex < (unsigned int)aDataList.count()) { CAnalogData aData = aDataList.at(nAIndex); if (valueType == PRIMARY) { if (valueAttr == SAMPLE) { fValue = aData.m_fPSampleValue; } if (valueAttr == EFFECT) { fValue = aData.m_fPEffectValue; } if (valueAttr == AMP) { fValue = aData.m_fPAmpValue; } if (valueAttr == REAL) { fValue = aData.m_fPRealValue; } if (valueAttr == ANGLE) { fValue = aData.m_fPAngleValue; } if (valueAttr == IMG) { fValue = aData.m_fPImgValue; } } else { if (valueAttr == SAMPLE) { fValue = aData.m_fSSampleValue; } if (valueAttr == EFFECT) { fValue = aData.m_fSEffectValue; } if (valueAttr == AMP) { fValue = aData.m_fSAmpValue; } if (valueAttr == REAL) { fValue = aData.m_fSRealValue; } if (valueAttr == ANGLE) { fValue = aData.m_fSAngleValue; } if (valueAttr == IMG) { fValue = aData.m_fSImgValue; } } } return fValue; } //得到某个时间点某个数字通道的值 unsigned short CComTradeFile::GetDigitalValue(unsigned long nTime,unsigned int nDIndex) { unsigned short nValue = 0; if (!m_DigitalDataMap.contains(nTime)) { return nValue; } DigitalDataList dDataList = m_DigitalDataMap.value(nTime); if (nDIndex>=0 && nDIndex < (unsigned int)dDataList.count()) { return dDataList.at(nDIndex).m_nValue; } return nValue; } //得到某个时间点所有模拟通道的值 QVector<double> CComTradeFile::GetAValueList(unsigned long nTime, ValueType valueType, ValueAttr valueAttr) { QVector<double> valueList; if (!m_AnalogDataMap.contains(nTime)) { return valueList; } AnalogDataList aDataList = m_AnalogDataMap.value(nTime); for(int nAIndex=0 ; nAIndex < aDataList.count();nAIndex++) { CAnalogData aData = aDataList.at(nAIndex); if (valueType == PRIMARY) { if (valueAttr == SAMPLE) { valueList << aData.m_fPSampleValue; } if (valueAttr == EFFECT) { valueList << aData.m_fPEffectValue; } if (valueAttr == AMP) { valueList << aData.m_fPAmpValue; } if (valueAttr == REAL) { valueList << aData.m_fPRealValue; } if (valueAttr == ANGLE) { valueList << aData.m_fPAngleValue; } if (valueAttr == IMG) { valueList << aData.m_fPImgValue; } } else { if (valueAttr == SAMPLE) { valueList << aData.m_fSSampleValue; } if (valueAttr == EFFECT) { valueList << aData.m_fSEffectValue; } if (valueAttr == AMP) { valueList << aData.m_fSAmpValue; } if (valueAttr == REAL) { valueList << aData.m_fSRealValue; } if (valueAttr == ANGLE) { valueList << aData.m_fSAngleValue; } if (valueAttr == IMG) { valueList << aData.m_fSImgValue; } } } return valueList ; } //得到某个时间点所有数字通道的值 QVector<unsigned short> CComTradeFile::GetDValueList(unsigned long nTime) { QVector<unsigned short> valueList; if (!m_AnalogDataMap.contains(nTime)) { return valueList; } DigitalDataList dDataList = m_DigitalDataMap.value(nTime); for (int nDIndex=0; nDIndex < dDataList.count(); nDIndex++) { valueList << dDataList.at(nDIndex).m_nValue; } return valueList; } //HDR QDateTime CComTradeFile::GetFaultStartTime() //故障时间 { return m_hdrFile.m_dtFaultStartTime; } unsigned int CComTradeFile::GetDataFileSize() //数据长度 { return m_hdrFile.m_nDataFileSize; } unsigned int CComTradeFile::GetFaultKeepTime() //故障持续时间 { return m_hdrFile.m_nFaultKeepTime; } TripInfoList CComTradeFile::GetTripInfoList() { return m_hdrFile.m_TripInfoList; } CTripInfo CComTradeFile::GetTripInfoByTime(unsigned int nTime,bool& bOK) { for (int nIndex=0; nIndex< m_hdrFile.m_TripInfoList.count(); nIndex++) { CTripInfo tripInfo = m_hdrFile.m_TripInfoList.at(nIndex); if (tripInfo.m_nTime == nTime) { bOK = true; return tripInfo; } } bOK = false; return CTripInfo(); } FaultInfoList CComTradeFile::GetFaultInfoList() { return m_hdrFile.m_FaultInfoList; } DigitalStatusList CComTradeFile::GetDigitalStatusList() { return m_hdrFile.m_DigitalStatusList; } DigitalEventList CComTradeFile::GetDigitalEventList() { return m_hdrFile.m_DigitalEventList; } CDigitalEvent CComTradeFile::GetDigitalEventByTime(unsigned int nTime,bool& bOK) { for (int nIndex=0; nIndex< m_hdrFile.m_DigitalEventList.count(); nIndex++) { CDigitalEvent digitalEvent = m_hdrFile.m_DigitalEventList.at(nIndex); if (digitalEvent.m_nTime == nTime) { bOK = true; return digitalEvent; } } bOK = false; return CDigitalEvent(); } SettingValueList CComTradeFile::GetSettingValueList() { return m_hdrFile.m_SettingValueList; } //描述des CAChanelDes CComTradeFile::GetADesByIndex(unsigned int nIndex) { if(nIndex>m_desFile.m_DChanelDesList.count()) { CAChanelDes des; /* des.m_nAn=-1; //通道索引0~999999 des.m_strName=""; //名称 des.m_strType=""; //数据类型 des.m_strUu=""; //单位 des.m_fScale=0; //通道比例 des.m_nVisible=1;//是否显示“1”表示显示,”0”表示不显示*/ return des; } return m_desFile.m_AChanelDesList.at(nIndex); } CDChanelDes CComTradeFile::GetDDesByIndex(unsigned int nIndex) { if(nIndex>m_desFile.m_DChanelDesList.count()) { CDChanelDes des; /* des.m_nDn=-1; //通道索引0~999999 des.m_strName=""; //名称 des.m_strType=""; //固定为0 des.m_nVisible=1;//是否显示“1”表示显示,”0”表示不显示*/ return des; } return m_desFile.m_DChanelDesList.at(nIndex); } CAChanelDes CComTradeFile::GetADesByName(const QString& strName,bool& bOK) { for (int nIndex=0; nIndex< m_desFile.m_AChanelDesList.count(); nIndex++) { CAChanelDes aChanelDes = m_desFile.m_AChanelDesList.at(nIndex); if (!aChanelDes.m_strName.compare(strName,Qt::CaseInsensitive)) { bOK = true; return aChanelDes; } } bOK = false; return CAChanelDes(); } CDChanelDes CComTradeFile::GetDDesByName(const QString& strName,bool& bOK) { for (int nIndex=0; nIndex< m_desFile.m_DChanelDesList.count(); nIndex++) { CDChanelDes dChanelDes = m_desFile.m_DChanelDesList.at(nIndex); if (!dChanelDes.m_strName.compare(strName,Qt::CaseInsensitive)) { bOK = true; return dChanelDes; } } bOK = false; return CDChanelDes(); } AChanelDesList CComTradeFile::GetAChanelDesList() { return m_desFile.m_AChanelDesList; } DChanelDesList CComTradeFile::GetDChanelDesList() { return m_desFile.m_DChanelDesList; } //中间数据 mid double CComTradeFile::GetMidAnalogValue(unsigned long nTime,unsigned int nAIndex) { for (int nIndex=0; nIndex < m_midFile.m_ChanelDataList.count(); nIndex++) { CChanelSampleData samData = m_midFile.m_ChanelDataList.at(nIndex); if (samData.m_nTimeStamp == nTime && nAIndex < (unsigned int)samData.m_AChanelDataList.count()) { return samData.m_AChanelDataList.at(nAIndex); } } return 0.0; } //得到某个时间点某个数字通道的值 unsigned short CComTradeFile::GetMidDigitalValue(unsigned long nTime, unsigned int nDIndex) { if (m_MidSampleDataMap.contains(nTime)) { CChanelSampleData samData = m_MidSampleDataMap.value(nTime); if (nDIndex < (unsigned int)samData.m_DChanelDataList.count()) { return samData.m_DChanelDataList.at(nDIndex); } } return 0; } //得到某个时间点所有模拟通道的值 QVector<double> CComTradeFile::GetAMidValueList(unsigned long nTime) { QVector<double> valueList; for (int nIndex=0; nIndex < m_midFile.m_ChanelDataList.count(); nIndex++) { CChanelSampleData samData = m_midFile.m_ChanelDataList.at(nIndex); if (samData.m_nTimeStamp == nTime) { for (int nAIndex=0;nAIndex<samData.m_AChanelDataList.count();nAIndex++) { valueList << samData.m_AChanelDataList.at(nAIndex); } break; } } return valueList; } //得到某个时间点所有数字通道的值 QVector<unsigned short> CComTradeFile::GetDMidValueList(unsigned long nTime) { QVector<unsigned short> valueList; for (int nIndex=0; nIndex < m_midFile.m_ChanelDataList.count(); nIndex++) { CChanelSampleData samData = m_midFile.m_ChanelDataList.at(nIndex); if (samData.m_nTimeStamp == nTime) { valueList << samData.m_DChanelDataList; break; } } return valueList; } bool CComTradeFile::IsDMidChanelAct(unsigned int nDIndex) { if (m_MidDigitalChangedMap.contains(nDIndex)) { return m_MidDigitalChangedMap[nDIndex]; } return false; } unsigned short CComTradeFile::GetMidDigitalValueByIndexPoint(unsigned int nIndex,unsigned int nPoint) { if (nPoint >=0 && nPoint < (unsigned int)m_TimeArray.count()) { unsigned int nTime = m_TimeArray.at(nPoint); return GetMidDigitalValue(nTime,nIndex); } return 0; } //add by llf int CComTradeFile::GetPathNumByDesc(QString strContent,int src) { bool IsOk=false; if(src==0) { CDChanelInfo CDInfo = GetDInfoByName(strContent,IsOk); if(IsOk) { return CDInfo.m_nDn; } else { return -1; } } else { CDChanelDes CDDes = GetDDesByName(strContent,IsOk); if(IsOk) { return CDDes.m_nDn; } else { return -1; } } }
[ "lilinfeng124@sina.com" ]
lilinfeng124@sina.com
ad109d7bcb164fd28d4342dc2e40c11aad602ebd
543c86d3a493daf3e22cddcbf9dc5f00ad7eb3b9
/diamond-star-pattern.cpp
742cb3c941fe938de89797249392853b346da449
[]
no_license
Ajaysinghadiya/diamond-star-pattern.cpp
eb75c4fde3a03f9326665f28d54f4d58263415ad
c6d5f809e9ccf27c33fcd4a620d8e241e0deda54
refs/heads/main
2023-08-22T03:46:51.746404
2021-10-12T18:13:03
2021-10-12T18:13:03
416,447,669
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
cpp
#include <iostream> //header using namespace std; //standard int main() //execution begins { int raw; //declaring a variable name raw cout << "enter the number of raws" << endl; //printing a line cin >> raw; //taking input from user /* we have to print a star system looks like this for raw=5 * *** ***** ******* ********* ********* ******* ***** *** * in this pattern we have to use three inner loop 1st for spaces 2nd for left side upper stars 3rd for right side upper stars */ for (int i = 1; i <= raw; i++) //this is outer most loop to print the raws { for (int j = 1; j <= raw - i; j++) //1st inner loop to print the spaces { cout << " "; } for (int j = 1; j <= i; j++) //2nd inner loop to print the left side stars { cout << "*"; } for (int j = 2; j <= i; j++) //3rd inner loop to print the right side stars { cout << "*"; } cout << endl; //moving to the next line } // revers the code for downward pattern for (int i = raw; i >= 1; i--) { for (int j = 1; j <= raw - i; j++) { cout << " "; } for (int j = 1; j <= i; j++) { cout << "*"; } for (int j = 2; j <= i; j++) { cout << "*"; } cout << endl; } return 0; }
[ "noreply@github.com" ]
Ajaysinghadiya.noreply@github.com
e971016dd923f6966c2f8ac2c41cae725ce1421f
89ee4d15405f7d15a2dd03c2894f7baf9d4a817b
/CSES-SEARCHING AND SORTING/CSESplaylists.cp
7badba87f344cfc45ab4158d9a8874d2f7cecb56
[]
no_license
sr4saurabh/CSESsolutions
e1895c89888e11d158e00a7aa9565539b8b7f0bd
3f1ee4c7bb0948ccf6ecb950ec08b6b61fdcd462
refs/heads/master
2023-07-12T10:52:14.692898
2021-08-21T07:41:39
2021-08-21T07:41:39
291,441,199
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
cp
/*--ILRS-- sr4saurabh */ #include <bits/stdc++.h> using namespace std; typedef long long int ll; #define pb push_back #define popb pop_back #define mp make_pair #define ve vector #define vii vector < int > #define vll vector < ll > #define pii pair < int , int > #define pll pair < ll , ll > #define vpl vector < pll > #define fi first #define sz size #define len length #define se second //const ll mod=998244353; const ll mod = 1000000000+7; const ll N=10000000+6; #define M_PI 3.14159265358979323846 //-------------------------------------------- //-------------------------------------------- //============================================ int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen ("INPUT.txt" , "r" , stdin); freopen ("OUTPUT.txt", "w" , stdout); #endif //THE WATER WAS DEEP, I DROWNED AND THEN CAME FLOATING UP,DEAD!! return 0; }
[ "noreply@github.com" ]
sr4saurabh.noreply@github.com
ade29e43ad6ab5de4987fdbfa0727fa40c82ace3
44cb9bba7cb4292ee489fcea1fb4340ce3a1efda
/src/Material.cpp
4be7fd0af8932d08df58004d97f792f2d9460163
[ "MIT" ]
permissive
kanosawa/mmd-eigen
5d92d241fb4ddb02fa7123f8a4214a3c19f2240d
e0177f7761a85b9da506b7cc09246a5b2263b2c0
refs/heads/master
2021-05-09T14:33:24.427095
2018-02-24T18:11:14
2018-02-24T18:11:14
119,068,038
6
0
null
2018-02-23T18:18:40
2018-01-26T15:26:31
C++
UTF-8
C++
false
false
1,024
cpp
#include "Material.h" using namespace mmd; Material::Material() { } Material::~Material() { } Material::Material(const Eigen::Vector4f &diffuse, const Eigen::Vector3f &specular, const float specularCoef, const Eigen::Vector3f &ambient, const int ordinaryTextureIndex, const int surfaceNum) : diffuse_(diffuse), specular_(specular), specularCoef_(specularCoef), ambient_(ambient), ordinaryTextureIndex_(ordinaryTextureIndex), surfaceNum_(surfaceNum) { } const Eigen::Vector4f &Material::getDiffuse() const { return diffuse_; } const Eigen::Vector3f &Material::getSpecular() const { return specular_; } const float Material::getSpecularCoef() const { return specularCoef_; } const Eigen::Vector3f &Material::getAmbient() const { return ambient_; } const int Material::getOrdinaryTextureIndex() const { return ordinaryTextureIndex_; } const int Material::getSurfaceNum() const { return surfaceNum_; }
[ "kanokanosawasawa@gmail.com" ]
kanokanosawasawa@gmail.com
df36ec2d048dcf90959739fb3ad1d2a962d9af52
41578b9248dc2f5671fbf6c793f88ae61f75014e
/TFT_Dispaly/Nova-Touch/Module-Development/User-KeyPad-Input-Module/Project_Code/Oct-21/esp32-InputModule-04-10-21/UserInputkeyBoard.cpp
805fa28e77fa4169451485b1ac08d8388f289825
[]
no_license
axisElectronics/Axis_Company_Project
89fb56de1c1cd0d5044a36b64369127e01cba1d2
089e3e0c63ce9156e888738fd9262124c9345c1c
refs/heads/master
2023-08-26T19:41:18.505678
2021-11-08T09:33:26
2021-11-08T09:33:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,849
cpp
#include "UserInputKeyBoard.h" #include "keyBoardImage.h" extern TFT_eSPI tft; #define BlankRect() tft.fillRect( 208 , 18, 25, 40, TFT_BLACK); /******* MACROs declaration ********/ #define spacing 90 #define digitMargin 90 #define xdigitMargin digitMargin #define ydigitMargin digitMargin #define xClr 160 #define yClr 145 #define xOne ( xClr + spacing) #define yOne yClr #define xTwo ( xOne + spacing ) #define yTwo yOne #define xThree ( xTwo + spacing ) #define yThree yTwo #define xFour xOne #define yFour 60 #define xFive ( xOne + spacing ) #define yFive yFour #define xSix ( xTwo + spacing ) #define ySix yFive #define xSeven xOne #define ySeven 0 #define xEight ( xOne + spacing ) #define yEight ySeven #define xNine ( xTwo + spacing ) #define yNine yEight #define xBack 2 #define yBack 239 #define xDel (160) #define yDel yBack #define xDot ( xDel + spacing ) #define yDot yBack #define xZero ( xDot + spacing ) #define yZero yBack #define xEnt ( xZero + spacing ) #define yEnt yBack #define zeroTouch ( ( (xAxis > xZero ) && (xAxis < ( xZero + digitMargin ) ) ) && ( ( yAxis > yZero ) && ( yAxis < ( yZero + ydigitMargin ) ) ) ) #define oneTouch ( ( (xAxis > xOne ) && (xAxis < ( xOne + digitMargin ) ) ) && ( ( yAxis > yOne ) && ( yAxis < ( yOne + ydigitMargin ) ) ) ) #define twoTouch ( ( (xAxis > xTwo ) && (xAxis < ( xTwo + digitMargin ) ) ) && ( ( yAxis > yTwo ) && ( yAxis < ( yTwo + ydigitMargin ) ) ) ) #define threeTouch ( ( (xAxis > xThree ) && (xAxis < ( xThree + digitMargin ) ) ) && ( ( yAxis > yThree ) && ( yAxis < ( yThree + ydigitMargin ) ) ) ) #define fourTouch ( ( (xAxis > xFour ) && (xAxis < ( xFour + digitMargin ) ) ) && ( ( yAxis > yFour ) && ( yAxis < ( yFour + ydigitMargin ) ) ) ) #define fiveTouch ( ( (xAxis > xFive ) && (xAxis < ( xFive + digitMargin ) ) ) && ( ( yAxis > yFive ) && ( yAxis < ( yFive + ydigitMargin ) ) ) ) #define sixTouch ( ( (xAxis > xSix ) && (xAxis < ( xSix + digitMargin ) ) ) && ( ( yAxis > ySix ) && ( yAxis < ( ySix + ydigitMargin ) ) ) ) #define sevenTouch ( ( (xAxis > xSeven ) && (xAxis < ( xSeven + digitMargin ) ) ) && ( ( yAxis > ySeven ) && ( yAxis < ( ySeven + ydigitMargin ) ) ) ) #define eightTouch ( ( (xAxis > xEight ) && (xAxis < ( xEight + digitMargin ) ) ) && ( ( yAxis > yEight ) && ( yAxis < ( yEight + ydigitMargin ) ) ) ) #define nineTouch ( ( (xAxis > xNine ) && (xAxis < ( xNine + digitMargin ) ) ) && ( ( yAxis > yNine ) && ( yAxis < ( yNine + ydigitMargin ) ) ) ) #define dotTouch ( ( (xAxis > xDot ) && (xAxis < ( xDot + digitMargin ) ) ) && ( ( yAxis > yDot ) && ( yAxis < ( yDot + ydigitMargin ) ) ) ) #define delTouch ( ( (xAxis > xDel ) && (xAxis < ( xDel + digitMargin ) ) ) && ( ( yAxis > yDel ) && ( yAxis < ( yDel + ydigitMargin ) ) ) ) #define clrTouch ( ( (xAxis > xClr ) && (xAxis < ( xClr + digitMargin ) ) ) && ( ( yAxis > yClr ) && ( yAxis < ( yClr + ydigitMargin ) ) ) ) #define backTouch ( ( (xAxis > xBack ) && (xAxis < ( xBack + 135 ) ) ) && ( ( yAxis > yBack ) && ( yAxis < ( yBack + ydigitMargin ) ) ) ) #define entTouch ( ( (xAxis > xEnt ) && (xAxis < ( xEnt + digitMargin ) ) ) && ( ( yAxis > yEnt ) && ( yAxis < ( yEnt + ydigitMargin ) ) ) ) #define x1SW 65 #define x2SW 144 #define y1SW 153 #define y2SW 205 #define xSW ( ( xAxis >= x1SW ) && ( xAxis <= x2SW ) ) #define ySW ( ( yAxis >= y1SW ) && ( yAxis <= y2SW ) ) #define swTouch (xSW && ySW) #define findkey() zeroTouch ? zero : oneTouch ? one : twoTouch ? two : threeTouch ? three : fourTouch ? four : fiveTouch ? five :\ sixTouch ? six : sevenTouch ? seven : eightTouch ? eight : nineTouch ? nine : backTouch ? back :\ delTouch ? del : entTouch ? ent : dotTouch ? dot : clrTouch ? clr : swTouch ? sw : keepRunning; char keyArray[10][4] = { {'0', ' ', '/', '@' }, {'1', 'A', 'B', 'C' }, {'2', 'D', 'E', 'F' }, {'3', 'G', 'H', 'I' }, {'4', 'J', 'K', 'L' }, {'5', 'M', 'N', 'O' }, {'6', 'P', 'Q', 'R' }, {'7', 'S', 'T', 'U' }, {'8', 'V', 'W', 'X' }, {'9', 'Y', 'Z', '-' }, }; //#define ALPHANUM 0 //#define NUM 1 bool switchFlag = 0; /****************************************************************** * * * * *******************************************************************/ void userKeyBoard::tftInit(){ tft.init(); tft.fillScreen(TFT_BLACK); tft.setRotation(1); #ifdef ILI9486_DRIVER uint16_t calData[5] ={ 262, 3565, 1319, 2532, 2 }; #endif #ifdef ILI9488_DRIVER uint16_t calData[5] = { 299, 3592, 256, 3464, 7 }; #endif tft.setTouch(calData); } void userKeyBoard::init( ) { keypadParamInit( ); //============================================== // Initilise mapped Physical KeyBoard module //============================================== intiSEPL328_Keypad(); } void userKeyBoard :: keypadParamInit( ) { userInput.entIdx = 15; userInput.text_xAxis = 12; userInput.text_yAxis = 25; userInput.text_FGColor = TFT_GREEN; userInput.text_BGColor = TFT_BLACK; userInput.FieldLable_FGColor = TFT_RED; userInput.FieldLable_BGColor = TFT_YELLOW; userInput.noticBoard_FGColor = TFT_GREEN; userInput.noticBoard_BGColor = TFT_BLACK; userInput.customFont = mplus_R13; userInput.fixFormatstruct = &userFixFormat; strcpy( userInput.fieldLable, "Keypad"); /* By default every key is enable */ for ( uint8_t i = 0; i < 11; i++ ) userInput.invalidKey[i] = keepRunning;// -20; memset( userInput.userInputArray, '\0', userInput.userInputArray_Size); memset( userInput.userInputArray, ' ', userInput.entIdx ); userInput.userInputArray[ userInput.entIdx] = '_'; tft.setFreeFont( userInput.customFont ); tft.setTextSize(1); tft.setTextColor(userInput.text_FGColor, userInput.text_BGColor ); tft.drawString(userInput.userInputArray, userInput.text_xAxis, userInput.text_yAxis, 1); } int8_t userKeyBoard :: _findkeypadTouch( uint16_t xAxis, uint16_t yAxis) { return findkey(); } int userKeyBoard :: _getCharacter( int keyvalue, bool switchFlag ) { uint16_t xAxis = 0, yAxis = 0; int8_t entIdx = 0; uint8_t cnt = 0; int8_t tempKeyvalue = keepRunning; int tout = millis(); if ( !( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) ) { BlankRect() tft.drawChar( keyArray[keyvalue][cnt], 211, 44, 1); } if ( switchFlag ) { while ( ( millis() - tout ) < 1000 ) { xAxis = 0; yAxis = 0; tft.getTouch(&xAxis, &yAxis); tempKeyvalue = _findkeypadTouch( xAxis, yAxis); if ( keyvalue == tempKeyvalue ) { cnt++; tout = millis(); while ( cnt >= 4) cnt = cnt - 4; if ( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) { switch ( userInput.fixFormatstruct->fieldType ) { case stringType : case Password : DrawfixFormatChar( keyArray[keyvalue][cnt], userInput.fixFormatstruct->idx ); moveUrDash( userInput.fixFormatstruct->idx ); break; }//end-switch }//end-if else if ( !( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) ) { BlankRect() tft.drawChar( keyArray[keyvalue][cnt], 211, 44, 1); } delay(200); }//end-if yield(); }//end-while } if ( !( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) ) BlankRect() return keyArray[keyvalue][cnt]; } int userKeyBoard :: handleKeyPad( ) { uint16_t xAxis = 0, yAxis = 0; int keyvalue = -20; int PHY_keyvalue = -20; if ( tft.getTouch(&xAxis, &yAxis) ) keyvalue = _findkeypadTouch( xAxis, yAxis); else if ( ( PHY_keyvalue = getMappedKey() ) != keepRunning ){ keyvalue = PHY_keyvalue; // This piece of code is kind of fix. unknowly fixformat flag got currupt when I am using physical keypad. if ( ( userInput.fixFormatstruct->fieldType == Date ) || (userInput.fixFormatstruct->fieldType == Time ) ) userInput.fixFormatstruct->fixFormatFlag = fixformat = 1; } for (uint8_t i = 0; i < 11; i++) { if ( keyvalue == userInput.invalidKey[i] ) { keyvalue = keepRunning; break; } } if ( keyvalue != keepRunning ) { switch ( keyvalue ) { case keepRunning : goto END; case back : goto END; case del : goto END; case clr: goto END; case dot: delay(350); return '.'; case ent : goto END; case sw : if ( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) { switch ( userInput.fixFormatstruct->fieldType ) { case Date : case Time : break; case stringType : case Password : userInput.switchFlag = !userInput.switchFlag; delay(350); break; default : break; } } else if ( !( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) ) { if ( userInput.numericSwitchFlag ); else userInput.switchFlag = !userInput.switchFlag; delay(350); } break; case zero: case one: case two: case three: case four: case five: case six: case seven: case eight: case nine: return _getCharacter( keyvalue, userInput.switchFlag ); }//end-switch } END: return keyvalue; } void userKeyBoard :: keypadDataparser( ) { int i; for ( i = 0; i < userInput.entIdx - 15; i++ ) { userInput.userInputArray[ i ] = userInput.userInputArray[ 15 + i ]; } userInput.userInputArray[ i ] = '\0'; } bool userKeyBoard :: keypadImage() { tft.setSwapBytes(true); tft.pushImage(0, 0, PLAX_IT_KEYSImage_Width, PLAX_IT_KEYSImage_Hight, PLAX_IT_KEYSArray ); } void userKeyBoard :: noticBoard( uint16_t FGColor, uint16_t BGColor, bool switchFlag){ tft.setFreeFont( mplus_R8 ); tft.setTextSize(1); tft.setTextColor(FGColor, BGColor ); if ( switchFlag ) { tft.fillRect(0, 70, 240, 75, BGColor ); tft.drawString( "* Alpha Numeric Mode ", 5, 80, 1); } else { tft.fillRect(0, 70, 240, 75, BGColor ); tft.drawString( "* Numaric Mode ", 5, 80, 1); } tft.setFreeFont( mplus_R13 ); } void userKeyBoard :: noticBoard_Unit( uint16_t FGColor, uint16_t BGColor, char *buf ){ tft.setFreeFont( mplus_R13 ); tft.setTextSize(1); tft.setTextColor(FGColor, BGColor ); //tft.fillRect(0, 70, 240, 75, BGColor ); tft.drawString( buf, 180, 90, 1); } void userKeyBoard :: printkeypadLable( ){ tft.setFreeFont( mplus_R8 ); tft.setTextColor(userInput.FieldLable_FGColor, userInput.FieldLable_BGColor ); tft.drawString(" ", 15, 0, 1); tft.drawString(userInput.fieldLable, 15, 0, 1); tft.setFreeFont( mplus_R13 ); tft.setTextColor(TFT_GREEN, TFT_BLACK); } /* @ All Activities will be driven by this Function "userInputFixFormat". - This Function is supported by two basic function names are "DrawfixFormatChar" and "moveUrDash" -- These Function provides Felexiblity to Developer to print char at spacified Location. -- Screen is devided into 17 spaces. Developer can access by providing indexes. */ void userInputFixFormat( struct _userInput *userInput ){ } void userKeyBoard :: moveUrDash( int8_t idx ){ /* Draw dash charcter */ /* Remove all previous Dashes. It is must operation */ for ( int8_t idx = 0; idx < userInput.fixFormatstruct->maxLengthScreen; idx++ ) tft.fillRect( userInput.fixFormatstruct->charXDash + (userInput.fixFormatstruct->charWDash * idx), 47, userInput.fixFormatstruct->charWDash, userInput.fixFormatstruct->charHDash, TFT_BLACK); /* Print your Dash as per Index */ tft.drawChar( '-', userInput.fixFormatstruct->charXDash + (idx * userInput.fixFormatstruct->charWDash), userInput.fixFormatstruct->charYDash, 1); } void userKeyBoard :: DrawfixFormatChar(char fixChar, int8_t idx ) { tft.setTextColor(TFT_GREEN, TFT_BLACK); // Serial.println("idx-->> " + String(idx) ); tft.fillRect( userInput.fixFormatstruct->rectX + (userInput.fixFormatstruct->rectW * idx), userInput.fixFormatstruct->rectY, userInput.fixFormatstruct->rectW, userInput.fixFormatstruct->rectH, TFT_BLACK); tft.drawChar( fixChar, userInput.fixFormatstruct->charX + (idx * userInput.fixFormatstruct->rectW), userInput.fixFormatstruct->charY, 1); } String userKeyBoard :: takeStringInput(char *ptrbuff, int len){ userInput.userInputArray_Size =len; userInput.userInputArray = ptrbuff; userInput.numericSwitchFlag = ALPHANUM; init(); takeUserInput( NULL ); return String( ptrbuff ); } /* @ takeUserInput : * ---------------- * 1 -> This funcation is PUBLIC funcation. Which is responsible for taking user data into * Predefine Array. < userInput.userInputArray > * * 2 -> It is madatory to free dynamic memory allocation if user has used dyanmic array. */ char *userKeyBoard :: takeUserInput( char *argc ) { uint8_t inc = 0; int8_t temp = keepRunning; tft.fillScreen(TFT_BLACK); keypadImage(); if (userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) { configFormats( ); }//end-if else { tft.drawString( &userInput.userInputArray[inc], userInput.text_xAxis, userInput.text_yAxis, 1); noticBoard(userInput.noticBoard_FGColor, userInput.noticBoard_BGColor, userInput.switchFlag ); if( !strlen( userInput.fieldLable) ) strcpy( userInput.fieldLable, "Keypad"); printkeypadLable( ); if( strlen( userInput.unitbuf) ) noticBoard_Unit( userInput.noticBoard_FGColor,userInput.noticBoard_BGColor, userInput.unitbuf ); } if ( argc != NULL ) { while ( inc < strlen(argc) ) { temp = argc[inc]; if ( (userInput.fixFormatstruct->fieldType == Date ) || (userInput.fixFormatstruct->fieldType == Time ) ) if (userInput.fixFormatstruct->rollOverChar[0] == temp ) { ++inc; continue; } inc = step_default( temp, inc); }//end-while if ( (userInput.fixFormatstruct->fieldType == Date ) || (userInput.fixFormatstruct->fieldType == Time ) ) { inc = 0; userInput.fixFormatstruct->idx = 0; moveUrDash(userInput.fixFormatstruct->idx ); } } temp = keepRunning; while ( 1 ){ temp = handleKeyPad( ); // Serial.println("button pressed : " + String(temp)); switch ( temp ) { case keepRunning : break; case back : step_back(temp, inc); goto EXIT; // return; case clr : inc = step_clr( temp, inc); break; case ent: keypadDataparser(); /* Now userInput.userInputArray; buffer can we used as user final data */ if (userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) { userInput.fixFormatstruct->idx = 0; } goto EXIT; // return; case del : inc = step_del( temp, inc); break; case dot : break; case sw : step_sw( temp, inc); break; default : inc = step_default( temp, inc); break; }//end-switch }//end-while EXIT: return userInput.userInputArray; } void userKeyBoard :: step_back( char temp, uint8_t inc ) { if ( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) { memset( userInput.fixFormatstruct->fixFormatArray, '\0', userInput.fixFormatstruct->fixFormatArraySize ); userInput.fixFormatstruct->fixFormatFlag = 0; userInput.fixFormatstruct->idx = 0; delete[]userInput.fixFormatstruct->fixFormatArray; } memset( userInput.userInputArray, '\0', userInput.userInputArray_Size ); } uint8_t userKeyBoard :: step_clr( char temp, uint8_t inc ) { if ( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) { switch ( userInput.fixFormatstruct->fieldType ) { case Date : memset( userInput.fixFormatstruct->fixFormatArray, '\0', userInput.fixFormatstruct->fixFormatArraySize ); userInput.fixFormatstruct->fixFormatFlag = 1; userInput.fixFormatstruct->idx = 0; strcpy(userInput.fixFormatstruct->fixFormatArray, "DD/MM/YY"); { fixFormatFullBlankScreen int8_t lenght = ( userInput.fixFormatstruct->len < userInput.fixFormatstruct->maxLengthScreen ? userInput.fixFormatstruct->len : userInput.fixFormatstruct->maxLengthScreen ); for (int8_t i = 0; i < lenght ; i++ ) { DrawfixFormatChar( userInput.fixFormatstruct->fixFormatArray[i], i ); } moveUrDash( userInput.fixFormatstruct->idx ); } break; case Time : memset( userInput.fixFormatstruct->fixFormatArray, '\0', userInput.fixFormatstruct->fixFormatArraySize ); userInput.fixFormatstruct->fixFormatFlag = 1; userInput.fixFormatstruct->idx = 0; strcpy(userInput.fixFormatstruct->fixFormatArray, "HH:MM:SS"); { fixFormatFullBlankScreen int8_t lenght = ( userInput.fixFormatstruct->len < userInput.fixFormatstruct->maxLengthScreen ? userInput.fixFormatstruct->len : userInput.fixFormatstruct->maxLengthScreen ); for (int8_t i = 0; i < lenght ; i++ ) { DrawfixFormatChar( userInput.fixFormatstruct->fixFormatArray[i], i ); } moveUrDash( userInput.fixFormatstruct->idx ); } break; case Password : case stringType : memset( userInput.fixFormatstruct->fixFormatArray, '\0', userInput.fixFormatstruct->fixFormatArraySize); for ( userInput.fixFormatstruct->idx; userInput.fixFormatstruct->idx >= 0 ; --userInput.fixFormatstruct->idx ) DrawfixFormatChar( userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx], userInput.fixFormatstruct->idx ); userInput.fixFormatstruct->idx = 0; moveUrDash( userInput.fixFormatstruct->idx ); break; default : break; } } else { // userInput.userInputStructureParamInit( userInput ); inc = 0; userInput.entIdx = 15; memset( userInput.userInputArray, '\0', userInput.userInputArray_Size); memset( userInput.userInputArray, ' ', userInput.entIdx ); userInput.userInputArray[ userInput.entIdx] = '_'; tft.drawString( &userInput.userInputArray[inc], userInput.text_xAxis, userInput.text_yAxis, 1); } return inc; } uint8_t userKeyBoard :: step_del( char temp, uint8_t inc ) { if ( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag && ( userInput.fixFormatstruct->idx < userInput.fixFormatstruct->fixFormatArraySize ) ) { if ( userInput.fixFormatstruct->idx = ( ( userInput.fixFormatstruct->idx <= 0 ) ? 0 : userInput.fixFormatstruct->idx ) ) { switch ( userInput.fixFormatstruct->fieldType) { case Date : case Time : userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx] = '\0'; DrawfixFormatChar( userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx], userInput.fixFormatstruct->idx ); moveUrDash( --userInput.fixFormatstruct->idx ); if ( userInput.fixFormatstruct->rollOverChar[0] == userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx ] ) moveUrDash( --userInput.fixFormatstruct->idx ); break; case Password : if ( ( userInput.fixFormatstruct->idx < userInput.fixFormatstruct->maxLen ) && ( userInput.fixFormatstruct->idx < userInput.fixFormatstruct->maxLengthScreen - 1 )) { userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx] = '\0'; DrawfixFormatChar( userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx], userInput.fixFormatstruct->idx ); moveUrDash( --userInput.fixFormatstruct->idx ); } else if ( userInput.fixFormatstruct->idx >= userInput.fixFormatstruct->maxLengthScreen - 1 ) { userInput.fixFormatstruct->fixFormatArray[ --userInput.fixFormatstruct->idx ] = '\0'; } break; case stringType : if ( ( userInput.fixFormatstruct->idx < userInput.fixFormatstruct->maxLen ) && ( userInput.fixFormatstruct->idx < userInput.fixFormatstruct->maxLengthScreen - 1 )) { userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx] = '\0'; for (int8_t idx = 0; idx < strlen( userInput.fixFormatstruct->fixFormatArray ) ; idx++ ) DrawfixFormatChar( userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx], userInput.fixFormatstruct->idx ); moveUrDash( --userInput.fixFormatstruct->idx ); } else if ( userInput.fixFormatstruct->idx >= userInput.fixFormatstruct->maxLengthScreen - 1 ) { --userInput.fixFormatstruct->idx; moveUrDash( userInput.fixFormatstruct->maxLengthScreen - 1 ); for (int8_t idx = 0, j = userInput.fixFormatstruct->idx - 15; idx < userInput.fixFormatstruct->maxLengthScreen - 1 ; idx++ , j++) DrawfixFormatChar( userInput.fixFormatstruct->fixFormatArray[ j ], idx ); userInput.fixFormatstruct->fixFormatArray[ userInput.fixFormatstruct->idx ] = '\0'; }//end-else-if break; }//end-switch }//end-if delay(300); }//end-if else if ( !( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) ) { if ( userInput.entIdx <= 15 ) { // userInput.userInputStructureParamInit( userInput ); inc = 0; } else if ( userInput.entIdx > 15 ) { userInput.userInputArray[ userInput.entIdx-- ] = '\0'; userInput.userInputArray[ userInput.entIdx ] = '_'; --inc; } tft.drawString( &userInput.userInputArray[inc], userInput.text_xAxis, userInput.text_yAxis, 1); delay(300); }//end-if return inc; } uint8_t userKeyBoard :: step_default( char temp, uint8_t inc ) { if ( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag && ( userInput.fixFormatstruct->idx < userInput.fixFormatstruct->len ) ) { // Serial.print("Date Temp : " ); Serial.println(temp); userInputDate( temp ); inc++; } else if ( !( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) ) { if ( userInput.entIdx < userInput.userInputArray_Size - 1 ) { userInput.userInputArray[ userInput.entIdx++ ] = temp; userInput.userInputArray[ userInput.entIdx ] = '_'; if ( userInput.entIdx >= userInput.userInputArray_Size - 1 ) { userInput.userInputArray[ userInput.userInputArray_Size - 1 ] = '\0'; } tft.drawString( &userInput.userInputArray[++inc], userInput.text_xAxis, userInput.text_yAxis, 1); } }//end-if delay(350); return inc; } void userKeyBoard :: step_sw( char temp, uint8_t inc ) { if ( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) { switch ( userInput.fixFormatstruct->fieldType ) { case Date : noticBoard( userInput.noticBoard_FGColor, userInput.noticBoard_BGColor, userInput.fixFormatstruct->switchFlag ); tft.setTextColor(userInput.text_FGColor, userInput.text_BGColor ); break; case Time : noticBoard( userInput.noticBoard_FGColor, userInput.noticBoard_BGColor, userInput.fixFormatstruct->switchFlag ); tft.setTextColor(userInput.text_FGColor, userInput.text_BGColor ); break; case Password : case stringType : default : noticBoard( userInput.noticBoard_FGColor, userInput.noticBoard_BGColor, userInput.switchFlag ); tft.setTextColor(userInput.text_FGColor, userInput.text_BGColor ); break; }//end-switch }//end-if else if ( !( userInput.fixFormatstruct && userInput.fixFormatstruct->fixFormatFlag ) ) { noticBoard( userInput.noticBoard_FGColor, userInput.noticBoard_BGColor, userInput.switchFlag ); tft.setTextColor(userInput.text_FGColor, userInput.text_BGColor ); } }
[ "viveky1794@gmail.com" ]
viveky1794@gmail.com
5f9fe4a95042efe67797218f4c0e28779d2a25bc
0203e5a6d7beb1e0f83113dac4c167b171756f24
/src/metafs/tool/fio/meta_scheduler.h
18fe127f8aaec1ccf0d81c94e87b6ec7d7876f0b
[ "BSD-3-Clause" ]
permissive
Wonchul08Lee/poseidonos
eaafe277fc56a0f5b5fcca3b70acc9bfe5d5d1ae
6fe410cdf88f3243ad9210f763c2b5a2f7e8b46a
refs/heads/main
2023-03-30T13:41:09.660647
2021-04-08T06:43:26
2021-04-08T06:43:26
355,819,746
0
0
BSD-3-Clause
2021-04-08T08:17:27
2021-04-08T08:17:26
null
UTF-8
C++
false
false
3,664
h
/* * BSD LICENSE * Copyright (c) 2021 Samsung Electronics Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <stdint.h> #include <list> #include <mutex> #include "spdk/ibof_volume.h" extern const char* META_FIO_TARGET_FILE; class MetaIoHandler { public: explicit MetaIoHandler(int fd) { if (MetaIoHandler::index >= 4) return; if (submitHandlerList[0] == nullptr) { submitHandlerList[0] = &MetaIoHandler::IoSubmitHandler0; submitHandlerList[1] = &MetaIoHandler::IoSubmitHandler1; submitHandlerList[2] = &MetaIoHandler::IoSubmitHandler2; submitHandlerList[3] = &MetaIoHandler::IoSubmitHandler3; } MetaIoHandler::fdList[MetaIoHandler::index] = fd; } static int IoSubmitHandler0(struct ibof_io* io); static int IoSubmitHandler1(struct ibof_io* io); static int IoSubmitHandler2(struct ibof_io* io); static int IoSubmitHandler3(struct ibof_io* io); static void MetaFsIOCompleteHandler(void); static int MetaFsIOSubmitHandler(struct ibof_io* io, int fd); static unvmf_submit_handler submitHandlerList[4]; static int fdList[4]; static int index; }; class MetaIOScheduler { public: void SetMetaFIOTargetFD(int fd) { targetMetaFioFD = fd; } int GetMetaFIOTargetFD(void) { return targetMetaFioFD; } void HandleIOCallback(void* data); private: int targetMetaFioFD = INT_MAX; }; extern MetaIOScheduler metaioScheduler; #include "mfs_aiocb_cxt.h" class MetaFioAIOCxt : public MetaFsAioCbCxt { public: explicit MetaFioAIOCxt(MetaFsIoOpcode opcode, uint32_t fd, size_t soffset, size_t nbytes, void* buf, MetaFsAioCallbackPointer func, ibof_io* io, uint32_t reactor) : MetaFsAioCbCxt(opcode, fd, soffset, nbytes, buf, func), io(io), reactor(reactor) { } ibof_io* GetIBoFIOCxt(void) { return io; } uint32_t GetReactor(void) { return reactor; } private: ibof_io* io; uint32_t reactor; };
[ "poseidonos@samsung.net" ]
poseidonos@samsung.net
baa7203e3675eb313ad56297cf6b11e9bda55dae
10cf524fb5c8117fa6d9eee5816cee379b50cae2
/main.cpp
916700ec373b25eb9e31a7e628f8a513793512ed
[]
no_license
Pythonista7/DX-Ball-OpenGL
00fabbab28b2a0d3f0fd8afe924e39ef9fc2a657
69320ec0d7d40d8df29c37e816f95322210a9dec
refs/heads/master
2022-12-16T16:53:16.214574
2020-05-29T17:22:10
2020-05-29T17:22:10
247,769,838
0
0
null
null
null
null
UTF-8
C++
false
false
1,873
cpp
#include "LUtil.h" void runMainLoop(int val); /* Pre Condition: -Initialized freeGLUT Post Condition: -Calls the main loop functions and sets itself to be called back in 1000 / SCREEN_FPS milliseconds Side Effects: -Sets glutTimerFunc */ int game_state = 0; int main( int argc , char* args[] ) { //Initialize FreeGLUT glutInit(&argc,args); /* In this application, we're going to use a double buffered window. What this means is that we have two buffers, a front and back buffer. The front buffer is what the user sees. The back buffer is in memory. When we make rendering calls in a double buffered window, they are rendered to the back buffer. After we're done rendering what we want to show to the user,we swap the front buffer with the back buffer so the user sees what we originally rendered to the back buffer. Now in a single buffered window, everything is draw directly to the front buffer. This means the user will see geometry as it's being rendered, which means we may see unfinished rendering and tearing. */ glutInitDisplayMode( GLUT_SINGLE ); glutInitWindowSize(SCREEN_WIDTH,SCREEN_HEIGHT); glutCreateWindow("Breakout"); if(!initGL()) { printf("Unable to initalize graphics library!\n"); return 1; } //Set keyboard handler glutKeyboardFunc(handleKeys); //Set rendering function // if(game_state == 1) // { // glutDisplayFunc(render); // glutIdleFunc(update); // } // if(game_state==0) glutDisplayFunc(welcomeDisplay); //Setting up Idle func to update //Set main loop runMainLoop(game_state); //glutTimerFunc(5,runMainLoop,0); //Start GLUT main loop glutMainLoop();//This runs freeGLUT's internal main loop not our main loop return 0; }
[ "ashwin.mirskar@gmail.com" ]
ashwin.mirskar@gmail.com
3d2dc054adcf3cfc83f27a49c983526b8c3523f0
4b4b8dd2f0376c1b08faae39165bb731d8f2fbe7
/tensorflow/lite/tools/make/downloads/eigen/test/rvalue_types.cpp
5f52fb3bc1d05efe6dabe921de76b1ddb483e2f2
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LGPL-2.1-only", "MPL-2.0", "LGPL-2.1-or-later", "GPL-3.0-only", "Minpack", "Apache-2.0" ]
permissive
godot-extended-libraries/tensorflow
d0ce2e28d5908af0c9eb8897eb5d46d370dee1b6
b2234a88a4cbe1e71b6d1a0b02d20dca53e902a8
refs/heads/master
2022-12-29T14:07:32.044837
2020-01-11T16:20:27
2020-01-11T16:20:27
186,188,911
3
0
Apache-2.0
2020-10-13T13:13:15
2019-05-11T22:58:18
C++
UTF-8
C++
false
false
2,249
cpp
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2013 Hauke Heibel <hauke.heibel@gmail.com> // // 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/. #include "main.h" #include <Eigen/Core> using internal::UIntPtr; #if EIGEN_HAS_RVALUE_REFERENCES template <typename MatrixType> void rvalue_copyassign(const MatrixType& m) { typedef typename internal::traits<MatrixType>::Scalar Scalar; // create a temporary which we are about to destroy by moving MatrixType tmp = m; UIntPtr src_address = reinterpret_cast<UIntPtr>(tmp.data()); // move the temporary to n MatrixType n = std::move(tmp); UIntPtr dst_address = reinterpret_cast<UIntPtr>(n.data()); if (MatrixType::RowsAtCompileTime==Dynamic|| MatrixType::ColsAtCompileTime==Dynamic) { // verify that we actually moved the guts VERIFY_IS_EQUAL(src_address, dst_address); } // verify that the content did not change Scalar abs_diff = (m-n).array().abs().sum(); VERIFY_IS_EQUAL(abs_diff, Scalar(0)); } #else template <typename MatrixType> void rvalue_copyassign(const MatrixType&) {} #endif EIGEN_DECLARE_TEST(rvalue_types) { CALL_SUBTEST_1(rvalue_copyassign( MatrixXf::Random(50,50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( ArrayXXf::Random(50,50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Matrix<float,1,Dynamic>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Array<float,1,Dynamic>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Matrix<float,Dynamic,1>::Random(50).eval() )); CALL_SUBTEST_1(rvalue_copyassign( Array<float,Dynamic,1>::Random(50).eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,2,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,3,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,4,1>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,2,2>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,3,3>::Random().eval() )); CALL_SUBTEST_2(rvalue_copyassign( Array<float,4,4>::Random().eval() )); }
[ "ernest.lee@chibifire.com" ]
ernest.lee@chibifire.com
2f83b82874b55d304909a3ad49b3d3e119b73993
4bdc5faaccbafe03482e32910cc34e80276270fd
/openframework/ofApp.cpp
f3514d459c8df84316c5000620c80ed79692666d
[]
no_license
syh24/syh-project
13a176047cd8706a407ec79af2d3652a2b52714e
1ab33b294a966607a2bbf86666b887ca52b3aacb
refs/heads/master
2023-03-19T22:52:15.357306
2021-03-05T04:06:36
2021-03-05T04:06:36
285,436,608
1
0
null
null
null
null
UHC
C++
false
false
18,270
cpp
/* ofxWinMenu basic example - ofApp.cpp Example of using ofxWinMenu addon to create a menu for a Microsoft Windows application. Copyright (C) 2016-2017 Lynn Jarvis. https://github.com/leadedge http://www.spout.zeal.co ========================================================================= This program 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. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ========================================================================= 03.11.16 - minor comment cleanup 21.02.17 - rebuild for OF 0.9.8 */ #include "ofApp.h" #include <iostream> #include <stack> #include <queue> using namespace std; //-------------------------------------------------------------- void ofApp::setup() { ofSetWindowTitle("Maze Example"); // Set the app name on the title bar ofSetFrameRate(15); ofBackground(255, 255, 255); // Get the window size for image loading windowWidth = ofGetWidth(); windowHeight = ofGetHeight(); isdfs = false; isbfs = false; isOpen = 0; // Centre on the screen ofSetWindowPosition((ofGetScreenWidth()-windowWidth)/2, (ofGetScreenHeight()-windowHeight)/2); // Load a font rather than the default myFont.loadFont("verdana.ttf", 12, true, true); // Load an image for the example //myImage.loadImage("lighthouse.jpg"); // Window handle used for topmost function hWnd = WindowFromDC(wglGetCurrentDC()); // Disable escape key exit so we can exit fullscreen with Escape (see keyPressed) ofSetEscapeQuitsApp(false); // // Create a menu using ofxWinMenu // // A new menu object with a pointer to this class menu = new ofxWinMenu(this, hWnd); // Register an ofApp function that is called when a menu item is selected. // The function can be called anything but must exist. // See the example "appMenuFunction". menu->CreateMenuFunction(&ofApp::appMenuFunction); // Create a window menu HMENU hMenu = menu->CreateWindowMenu(); // // Create a "File" popup menu // HMENU hPopup = menu->AddPopupMenu(hMenu, "File"); // // Add popup items to the File menu // // Open an maze file menu->AddPopupItem(hPopup, "Open", false, false); // Not checked and not auto-checked // Final File popup menu item is "Exit" - add a separator before it menu->AddPopupSeparator(hPopup); menu->AddPopupItem(hPopup, "Exit", false, false); // // View popup menu // hPopup = menu->AddPopupMenu(hMenu, "View"); bShowInfo = true; // screen info display on menu->AddPopupItem(hPopup, "Show DFS",false,false); // Checked bTopmost = false; // app is topmost menu->AddPopupItem(hPopup, "Show BFS"); // Not checked (default) bFullscreen = false; // not fullscreen yet menu->AddPopupItem(hPopup, "Full screen", false, false); // Not checked and not auto-check // // Help popup menu // hPopup = menu->AddPopupMenu(hMenu, "Help"); menu->AddPopupItem(hPopup, "About", false, false); // No auto check // Set the menu to the window menu->SetWindowMenu(); } // end Setup // // Menu function // // This function is called by ofxWinMenu when an item is selected. // The the title and state can be checked for required action. // void ofApp::appMenuFunction(string title, bool bChecked) { ofFileDialogResult result; string filePath; size_t pos; // // File menu // if(title == "Open") { readFile(); } if(title == "Exit") { ofExit(); // Quit the application } // // Window menu // if(title == "Show DFS") { //bShowInfo = bChecked; // Flag is used elsewhere in Draw() if (isOpen) { isdfs = 1; draw_flag = 1; DFS(); bShowInfo = bChecked; } else cout << "you must open file first" << endl; } if(title == "Show BFS") { if (isOpen) { BFS(); draw_flag = 1; isbfs = 1; doTopmost(bChecked); // Use the checked value directly } else cout << "you must open file first" << endl; } if(title == "Full screen") { bFullscreen = !bFullscreen; // Not auto-checked and also used in the keyPressed function doFullScreen(bFullscreen); // But als take action immediately } // // Help menu // if(title == "About") { ofSystemAlertDialog("ofxWinMenu\nbasic example\n\nhttp://spout.zeal.co"); } } // end appMenuFunction //-------------------------------------------------------------- void ofApp::update() { } //-------------------------------------------------------------- void ofApp::draw() { char str[256]; //ofBackground(0, 0, 0, 0); ofSetColor(100); ofSetLineWidth(5); int i, j; // TO DO : DRAW MAZE; // 저장된 자료구조를 이용해 미로를 그린다. // add code here if (draw_flag) { int da = 5, db = 5; for (i = 0; i < maze_row; i++) { for (j = 0; j < maze_col; j++) { if (input[i][j].p == '1' && i%2 == 0 && j%2 == 1) { ofDrawLine(da, db, da + 40, db); da += 40; } if (input[i][j].p == '1' && i%2 == 1) { ofDrawLine(da, db, da, db + 40); if (j == maze_col - 1) db += 40; } if (input[i][j].p == '0') { if (j % 2) da += 40; } } da = 5; } } if (isdfs) { ofSetLineWidth(5); if (isOpen) dfsdraw(); else cout << "You must open file first" << endl; } if (isbfs) { ofSetLineWidth(5); if (isOpen) bfsdraw(); else cout << "You must open file first" << endl; } if(bShowInfo) { // Show keyboard duplicates of menu functions sprintf(str, " comsil project"); myFont.drawString(str, 15, ofGetHeight()-20); } } // end Draw void ofApp::doFullScreen(bool bFull) { // Enter full screen if(bFull) { // Remove the menu but don't destroy it menu->RemoveWindowMenu(); // hide the cursor ofHideCursor(); // Set full screen ofSetFullscreen(true); } else { // return from full screen ofSetFullscreen(false); // Restore the menu menu->SetWindowMenu(); // Restore the window size allowing for the menu ofSetWindowShape(windowWidth, windowHeight + GetSystemMetrics(SM_CYMENU)); // Centre on the screen ofSetWindowPosition((ofGetScreenWidth()-ofGetWidth())/2, (ofGetScreenHeight()-ofGetHeight())/2); // Show the cursor again ofShowCursor(); // Restore topmost state if(bTopmost) doTopmost(true); } } // end doFullScreen void ofApp::doTopmost(bool bTop) { if(bTop) { // get the current top window for return hWndForeground = GetForegroundWindow(); // Set this window topmost SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); ShowWindow(hWnd, SW_SHOW); } else { SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); ShowWindow(hWnd, SW_SHOW); // Reset the window that was topmost before if(GetWindowLong(hWndForeground, GWL_EXSTYLE) & WS_EX_TOPMOST) SetWindowPos(hWndForeground, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); else SetWindowPos(hWndForeground, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); } } // end doTopmost //-------------------------------------------------------------- void ofApp::keyPressed(int key) { // Escape key exit has been disabled but it can be checked here if(key == VK_ESCAPE) { // Disable fullscreen set, otherwise quit the application as usual if(bFullscreen) { bFullscreen = false; doFullScreen(false); } else { ofExit(); } } // Remove or show screen info if(key == ' ') { bShowInfo = !bShowInfo; // Update the menu check mark because the item state has been changed here menu->SetPopupItem("Show DFS", bShowInfo); } if(key == 'f') { bFullscreen = !bFullscreen; doFullScreen(bFullscreen); // Do not check this menu item // If there is no menu when you call the SetPopupItem function it will crash } } // end keyPressed //-------------------------------------------------------------- void ofApp::keyReleased(int key){ if (key == 'r') { bfsdraw(); } } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } bool ofApp::readFile() { ofFileDialogResult openFileResult = ofSystemLoadDialog("Select .maz file"); string filePath; size_t pos; // Check whether the user opened a file if (openFileResult.bSuccess) { ofLogVerbose("User selected a file"); //We have a file, check it and process it string fileName = openFileResult.getName(); //string fileName = "maze0.maz"; printf("file name is %s\n", fileName.c_str()); filePath = openFileResult.getPath(); printf("Open\n"); pos = filePath.find_last_of("."); if (pos != string::npos && pos != 0 && filePath.substr(pos + 1) == "maz") { ofFile file(fileName); if (!file.exists()) { cout << "Target file does not exists." << endl; return false; } else { cout << "We found the target file." << endl; isOpen = 1; } ofBuffer buffer(file); // Input_flag is a variable for indication the type of input. // If input_flag is zero, then work of line input is progress. // If input_flag is one, then work of dot input is progress. int input_flag = 0; // Idx is a variable for index of array. int idx = 0; // Read file line by line int cnt = 0; // TO DO // .maz 파일을 input으로 받아서 적절히 자료구조에 넣는다 freeMemory(); ofFile fp1(fileName); char a; string s; getline(fp1, s); idx = s.length() - 1; ofFile fp2(fileName); while (getline(fp2,s)) { cnt++; } ofFile fp3(fileName); input = new maze*[cnt]; for (int i = 0; i < cnt; i++) input[i] = new maze[idx]; for (int i = 0; i < cnt; i++) { getline(fp3, s); for (int j = 0; j < idx; j++) { if (s[j] == '+' || s[j] == '-' || s[j] == '|') input[i][j].p = '1'; else input[i][j].p = '0'; } } maze_col = idx; maze_row = cnt; init_maze(); construct_maze(); } else { printf(" Needs a '.maz' extension\n"); return false; } } } void ofApp::construct_maze() { for (int i = 1; i < maze_row; i += 2) { for (int j = 1; j < maze_col; j += 2) { if (input[i][j - 1].p == '0') input[i][j].l = 1; if (input[i][j + 1].p == '0') input[i][j].r = 1; if (input[i+1][j].p == '0') input[i][j].d = 1; if (input[i-1][j].p == '0') input[i][j].u = 1; } } } void ofApp::init_maze() { bfs = 0; a = 0; k = 0; for (int i = 1; i < maze_row; i+=2) { for (int j = 1; j < maze_col; j+=2) { input[i][j].u = 0; input[i][j].d = 0; input[i][j].l = 0; input[i][j].r = 0; } } visited = new int*[maze_row]; for (int i = 0; i < maze_row; i++) visited[i] = new int[maze_col]; for (int i = 0; i < maze_row; i++) for (int j = 0; j < maze_col; j++) visited[i][j] = -1; for (int i = 0; i < 1000; i++) { x[i] = 0; y[i] = 0; tr[i].x = 0; tr[i].y = 0; btr[i].x = 0; btr[i].y = 0; } } void ofApp::freeMemory() { //TO DO // malloc한 memory를 free해주는 함수 delete input; delete visited; } bool ofApp::DFS()//DFS탐색을 하는 함수 { //TO DO //DFS탐색을 하는 함수 ( 3주차) int cnt , k; int i=1, j=1; visited[1][1] = 0; s.push(make_pair(1, 1)); while (!s.empty()) { k = 1; i = s.top().first; j = s.top().second; tr[a].y = s.top().first; tr[a].x = s.top().second; a++; s.pop(); if (i == (maze_row - 2) && j == (maze_col - 2)) { s.push(make_pair(i, j)); break; } while (1) { cnt = 0; if (k) { s.push(make_pair(i, j)); k = 0; } if (i == (maze_row - 2) && j == (maze_col - 2)) break; if (input[i][j].d) { if (visited[i + 2][j] < 0) { s.push(make_pair(i + 2, j)); tr[a].y = s.top().first; tr[a].x = s.top().second; visited[i + 2][j]++; i += 2; a++; cnt++; } } if (i == (maze_row - 2) && j == (maze_col - 2)) break; if (input[i][j].u) { if (visited[i - 2][j] < 0) { s.push(make_pair(i - 2, j)); tr[a].y = s.top().first; tr[a].x = s.top().second; visited[i - 2][j]++; i -=2 ; a++; cnt++; } } if (i == (maze_row - 2) && j == (maze_col - 2)) break; if (input[i][j].l) { if (visited[i][j - 2] < 0) { s.push(make_pair(i, j - 2)); tr[a].y = s.top().first; tr[a].x = s.top().second; visited[i][j - 2]++; j -= 2; a++; cnt++; } } if (i == (maze_row - 2) && j == (maze_col - 2)) break; if (input[i][j].r) { if (visited[i][j + 2] < 0) { s.push(make_pair(i, j + 2)); tr[a].y = s.top().first; tr[a].x = s.top().second; visited[i][j + 2]++; j += 2; a++; cnt++; } } if (cnt == 0) { s.pop(); break; } } } return true; } bool ofApp::BFS() { int i, j,k,cnt; i = 1, j = 1; visited[1][1]++; tr[0].y = i; tr[0].x = j; a++; q.push(make_pair(i, j)); while (!q.empty()) { i = q.front().first; j = q.front().second; q.pop(); if (i == (maze_row - 2) && j == (maze_col - 2)) break; if (i == (maze_row - 2) && j == (maze_col - 2)) break; if (input[i][j].d) { if (visited[i + 2][j] < 0) { q.push(make_pair(i + 2, j)); tr[a].y = q.back().first; tr[a].x = q.back().second; visited[i + 2][j]++; a++; } } if (input[i][j].u) { if (visited[i - 2][j] < 0) { q.push(make_pair(i - 2, j)); tr[a].y = q.back().first; tr[a].x = q.back().second; visited[i - 2][j]++; a++; } } if (input[i][j].l) { if (visited[i][j - 2] < 0) { q.push(make_pair(i, j - 2)); tr[a].y = q.back().first; tr[a].x = q.back().second; visited[i][j - 2]++; a++; } } if (input[i][j].r) { if (visited[i][j + 2] < 0) { q.push(make_pair(i, j + 2)); tr[a].y = q.back().first; tr[a].x = q.back().second; visited[i][j + 2]++; a++; } } } int ta, tb; btr[bfs].x = maze_col - 2; btr[bfs].y = maze_row - 2; for (i = a - 2; i >= 0; i--) { ta = tr[i].x; tb = tr[i].y; if (btr[bfs].x == ta && btr[bfs].y - tb == 2) { if (input[btr[bfs].y][btr[bfs].x].u) { bfs++; btr[bfs].x = ta; btr[bfs].y = tb; continue; } } if (btr[bfs].x == ta && tb - btr[bfs].y == 2) { if (input[btr[bfs].y][btr[bfs].x].d) { bfs++; btr[bfs].x = ta; btr[bfs].y = tb; continue; } } if (btr[bfs].x - ta == 2 && btr[bfs].y == tb) { if (input[btr[bfs].y][btr[bfs].x].l) { bfs++; btr[bfs].x = ta; btr[bfs].y = tb; continue; } } if (btr[bfs].x - ta == -2 && btr[bfs].y == tb) { if (input[btr[bfs].y][btr[bfs].x].r) { bfs++; btr[bfs].x = ta; btr[bfs].y = tb; } } } btr[bfs].x = tr[0].x; btr[bfs].y = tr[0].y; return true; } void ofApp::dfsdraw() { //TO DO //DFS를 수행한 결과를 그린다. (3주차 내용) while (!s.empty()) { y[k] = s.top().first; x[k] = s.top().second; s.pop(); k++; } for (int i = 0; i < a - 1; i++) { ofSetColor(200); ofDrawLine(5 + tr[i].x * 20, 5 + tr[i].y * 20, 5 + tr[i + 1].x * 20, 5 + tr[i + 1].y * 20); } for (int i = 0; i< k-1; i++) { ofSetColor(ofColor::orangeRed); ofDrawLine(5 + x[i] * 20, 5 + y[i] * 20, 5 + x[i+1] * 20, 5 + y[i+1] * 20); } } void ofApp::bfsdraw() { for (int i = 0; i < a - 1; i++) { for (int j = i + 1; j < a; j++) { if (tr[i].x == tr[j].x && tr[i].y - tr[j].y == 2) { if (input[tr[i].y][tr[i].x].u) { ofSetColor(200); ofDrawLine(5+ 20* tr[i].x, 5+ 20 * tr[i].y, 5+ 20 * tr[j].x, 5+ 20 * tr[j].y); } } if (tr[i].x == tr[j].x && tr[j].y - tr[i].y == 2) { if (input[tr[i].y][tr[i].x].d) { ofSetColor(200); ofDrawLine(5+ 20 * tr[i].x, 5+ 20 * tr[i].y, 5+ 20 * tr[j].x,5+ 20 * tr[j].y); } } if (tr[i].x - tr[j].x ==2 && tr[i].y == tr[j].y) { if (input[tr[i].y][tr[i].x].l) { ofSetColor(200); ofDrawLine(5+ 20 * tr[i].x, 5+ 20 * tr[i].y, 5 + 20 * tr[j].x, 5 + 20 * tr[j].y); } } if (tr[j].x - tr[i].x == 2 && tr[i].y == tr[j].y) { if (input[tr[i].y][tr[i].x].r) { ofSetColor(200); ofDrawLine(5 + 20 * tr[i].x, 5 + 20 * tr[i].y, 5 + 20 * tr[j].x, 5 + 20 * tr[j].y); } } } } for (int i = 0; i < bfs; i++) { ofSetColor(ofColor::red); ofDrawLine(5 + btr[i].x * 20, 5 + btr[i].y * 20, 5 + btr[i + 1].x * 20, 5 + btr[i + 1].y * 20); } }
[ "noreply@github.com" ]
syh24.noreply@github.com
2758601d09b7b259fa672c726b7949f235a2cb82
72a40ec0886ac70c129d129dc54157541cc23cd2
/BUSseq_inference.cpp
9ae8965d579eb5b5ad15d9209a1be27b66ff8616
[]
no_license
songfd2018/BUSseq-1.0
b13734b9ed893c066707edc987d8825ec829d9d4
c667a1b36c1859f2504d5383bda1295be38a8e57
refs/heads/master
2020-06-22T08:26:32.951816
2019-11-06T07:53:49
2019-11-06T07:53:49
197,681,382
1
0
null
null
null
null
UTF-8
C++
false
false
27,755
cpp
#include <iostream> #include <iomanip> #include <fstream> #include <math.h> // pow, sqrt, lgamma #include <cmath> // #include "omprng.h" # include <chrono> // time #include <unistd.h> // getopt #include <stdlib.h> #include <string> #include <stdio.h> #include <sys/stat.h> //mkdir #include <algorithm> // sort #include <vector> // using namespace std; int rand_NB(double _r, double _mu, omprng _rng){ double lambda, nu, p, u; double STEP = 500;// steps for large lambda in Poisson distribution int res = 0; // sample lambda from gamma distribution lambda = _rng.rgamma(_r, _mu/_r); // sample x from Poisson distribution nu = lambda; p = 1.0; do{ res ++; u = _rng.runif(); p = p * u; while(p < 1 & nu > 0){ if(nu > STEP){ p = p * exp(STEP); nu = nu - STEP; }else{ p = p * exp(nu); nu = 0; } } }while(p > 1); res--; return res; } //Max value in a vector double vec_max(double* vec,int n){ double res = vec[0]; for (int i = 1; i < n; i++) { if (res < vec[i]) { res = vec[i]; } } return res; } // FDR calculation double fdrDEindicator(double **_PPI, double _kappa, int _G, int _K){ double xi, fdr; double sum_xi = 0.0; int count_intri = 0; if(_kappa > 0){ for(int g = 0; g < _G; g++){ for(int k = 1; k < _K; k++){ xi = 1 - _PPI[g][k]; if(xi <= _kappa){ sum_xi += xi; count_intri ++; } } } fdr = sum_xi/count_intri; }else{ fdr = 0.0; } return(fdr); } bool descreasing(double i,double j) { return (i>j); } // calculate the DE posterior probability threshold double postprob_DE_thr_fun(double **_PPI, double _fdr_threshold, int _G, int _K){ double kappa; double postprob_DE_thr = 0.5; double fdr = 0.0; vector<double> vec_PPI; for(int g = 0; g < _G; g++){ copy(_PPI[g]+1, _PPI[g] + _K, back_inserter(vec_PPI)); } // sort all PPIs decreasingly // cout << "The length of vec_PPI is " << vec_PPI.size() << endl; sort(vec_PPI.begin(),vec_PPI.end(),descreasing); // unique values in the PPI vector // cout << "The length of vec_PPI is " << vec_PPI.size() << endl; vector<double>::iterator it; it = unique (vec_PPI.begin(), vec_PPI.end()); // ^ vec_PPI.resize(distance(vec_PPI.begin(),it)); //cout << "The length of vec_PPI is " << vec_PPI.size() << endl; int i = 0; while(fdr <= _fdr_threshold & i < vec_PPI.size()){ kappa = 1 - vec_PPI[i]; fdr = fdrDEindicator(_PPI, kappa, _G, _K); // cout << "kappa = " << kappa << ", fdr = " << fdr << "." << endl; i++; } double PPI_thres; if(i < vec_PPI.size()){ i = i - 2;// the index of last i such that fdr <= _fdr_threshold to control FDR PPI_thres = vec_PPI[i]; }else{ i = 0; // Even the largest PPI_thres = postprob_DE_thr; } // cout << "vec_PPI[i] = " << vec_PPI[i] << endl; if(vec_PPI[i] > postprob_DE_thr){ postprob_DE_thr = vec_PPI[i]; } return postprob_DE_thr; } int IG_index(double *_PPI, double _postprob_DE_thr, int _K){ int IG_indicator = 0; for(int k = 1; k < _K; k++){ if(_PPI[k] >= _postprob_DE_thr){ IG_indicator = 1; } // cout << "PPI_" << k << " = " << _PPI[k] << ", "; } // cout << "IG_indicator = " << IG_indicator << "." << endl; return IG_indicator; } int main(int argc, char** argv) { ////////////////////////////////////////////////////////// // 0. Input the project and version from command line // ////////////////////////////////////////////////////////// string proj, wk_dir, readcount_dir; int ver, K, rep; int iter_max, iter_burnin; // the overall iteration number and the number of iterations to print the posterior sampling int seed; // seed for random number generator int nc; // number of codes for parallel int opt; //while ((opt = getopt(argc, argv, "p:v:N:G:B:K:r:i:s:")) != -1) { while ((opt = getopt(argc, argv, ":d::r::p:v:K:i:b:c:")) != -1) { switch (opt) { case 'd': if(optarg){ wk_dir.assign(optarg); }else{ wk_dir.assign("./"); } cout << "The working directory is " << wk_dir << endl; break; case 'r': if(optarg){ readcount_dir.assign(optarg); }else{ readcount_dir.assign("./"); } cout << "The directory to load read count data is " << readcount_dir << endl; break; case 'p': proj.assign(optarg); break; case 'v': ver = atoi(optarg); break; case 'K': K = atoi(optarg); break; case 'i': iter_max = atoi(optarg); break; case 'b': iter_burnin = atoi(optarg); break; case 'c': nc = atoi(optarg); break; case '?': cout << "Unknown option " << optarg << endl; break; case ':': cout << "Missing option for " << optarg << endl; break; default: /* '?' */ cout << "Error Usage: " << argv[0] <<" [-p ProjectName] [-v Version] [-K CellTypeNumber] [-r ReplicationIndex] [-i IterationNumber] [-b NumberBurnin] [-c Cores] name" << endl; exit(EXIT_FAILURE); } } // set count data matrix and the number of cells in each batch string fcount, fdim, output_dir, infer_dir; fcount = readcount_dir + "count_data_"; fcount = fcount + proj; fcount = fcount + "_v"; fcount = fcount + to_string(ver); fcount = fcount + ".txt"; fdim = readcount_dir + "dim_"; fdim = fdim + proj; fdim = fdim + "_v"; fdim = fdim + to_string(ver); fdim = fdim + ".txt"; auto start_overall = chrono::system_clock::now(); // result/Inference_simulation_v0_K3_r1/ output_dir = wk_dir; // + "result/"; infer_dir = output_dir + "Inference"; // infer_dir = infer_dir + proj; // infer_dir = infer_dir + "_v"; // infer_dir = infer_dir + to_string(ver); infer_dir = infer_dir + "_K"; infer_dir = infer_dir + to_string(K); // infer_dir = infer_dir + "_r"; // infer_dir = infer_dir + to_string(rep); infer_dir = infer_dir + "/"; // result/simulation_v0_K3_r1_c4/ output_dir = output_dir + "MCMC_sampling"; // output_dir = output_dir + "_v"; // output_dir = output_dir + to_string(ver); output_dir = output_dir + "_K"; output_dir = output_dir + to_string(K); // output_dir = output_dir + "_r"; // output_dir = output_dir + to_string(rep); // output_dir = output_dir + "_c"; // output_dir = output_dir + to_string(nc); output_dir = output_dir + "/"; int check = mkdir(infer_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (!check) cout << "Directory " << infer_dir << " is created." << endl; else { cout << "Directory " << infer_dir << " already exists." << endl; } cout << "The output directory of posterior sampling is: " << infer_dir << endl; //////////////////////// // 1. Load count data // //////////////////////// int N, G, B; ifstream countFile, dimFile; dimFile.open(fdim.c_str()); if(!dimFile){ cout << "Unable to open the file of dimensions from " << fdim << endl; exit(1); // terminate with error } dimFile >> N; cout << "There are totally " << N << " cells and "; dimFile >> G; cout << G << " genes in "; dimFile >> B; cout << B << " batches." << endl; cout << "Loading the number of cells in each batch from " << fdim << endl; int *nb = new int[B]; for(int b = 0; b < B; b++){ dimFile >> nb[b]; cout << "The " << (b+1) << "-th batch has "<< nb[b] <<" cells." << endl; } dimFile.close(); int **Y = new int*[G]; for(int g = 0; g < G; g++){ Y[g] = new int[N];// for parallel G } cout << "Loading the count data matrix from " << fcount << endl; countFile.open(fcount.c_str()); if (!countFile) { cout << "Unable to open count data file" << endl; exit(1); // terminate with error } for(int g = 0; g < G; g++){ for(int i = 0; i < N; i++){ countFile >> Y[g][i]; } } countFile.close(); //////////////////////////// // 2. Posterior inference // //////////////////////////// //////////////////////////////////////////////// // 1) load posterior sampling of parameters // ifstream load_File; ofstream est_File; string load_name, est_name; double temp; int iter; string row_dropped; // int burnin = 3000; // calculate alpha_est double *alpha_est = new double[G]; for(int g = 0; g < G; g++){ alpha_est[g] = 0.0; } load_name = output_dir + "alpha_post.txt"; cout << "Load alpha_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int g = 0; g < G; g++){ load_File >> temp; alpha_est[g] += temp; } } for(int g = 0; g < G; g++){ alpha_est[g] = alpha_est[g] / (iter_max - iter_burnin); } load_File.close(); // calculate beta_est double **beta_est = new double*[G]; for(int g = 0; g < G; g++){ beta_est[g] = new double[K]; for(int k = 0; k < K; k++){ beta_est[g][k] = 0.0; } } load_name = output_dir + "beta_post.txt"; cout << "Load beta_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int g = 0; g < G; g++){ for(int k = 0; k < K; k++){ load_File >> temp; beta_est[g][k] += temp; } } } for(int g = 0; g < G; g++){ for(int k = 0; k < K; k++){ beta_est[g][k] = beta_est[g][k] / (iter_max - iter_burnin); } } load_File.close(); // calculate nu_est double **nu_est = new double*[G]; for(int g = 0; g < G; g++){ nu_est[g] = new double[B]; for(int b = 0; b < B; b++){ nu_est[g][b] = 0.0; } } load_name = output_dir + "nu_post.txt"; cout << "Load nu_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int g = 0; g < G; g++){ for(int b = 0; b < B; b++){ load_File >> temp; nu_est[g][b] += temp; } } } for(int g = 0; g < G; g++){ for(int b = 0; b < B; b++){ nu_est[g][b] = nu_est[g][b] / (iter_max - iter_burnin); } } load_File.close(); // calculate delta_est double *delta_est = new double[N]; for(int i = 0; i < N; i++){ delta_est[i] = 0.0; } load_name = output_dir + "delta_post.txt"; cout << "Load delta_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int i = 0; i < N; i++){ load_File >> temp; delta_est[i] += temp; } } for(int i = 0; i < N; i++){ delta_est[i] = delta_est[i] / (iter_max - iter_burnin); } load_File.close(); // calculate gamma_est double **gamma_est = new double*[B]; for(int b = 0; b < B; b++){ gamma_est[b] = new double[2]; gamma_est[b][0] = 0.0; gamma_est[b][1] = 0.0; } load_name = output_dir + "gamma_post.txt"; cout << "Load gamma_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int b = 0; b < B; b++){ load_File >> temp; gamma_est[b][0] += temp; load_File >> temp; gamma_est[b][1] += temp; } } for(int b = 0; b < B; b++){ gamma_est[b][0] = gamma_est[b][0] / (iter_max - iter_burnin); gamma_est[b][1] = gamma_est[b][1] / (iter_max - iter_burnin); } load_File.close(); // calculate phi_est double **phi_est = new double*[G]; for(int g = 0; g < G; g++){ phi_est[g] = new double[B]; for(int b = 0; b < B; b++){ phi_est[g][b] = 0.0; } } load_name = output_dir + "phi_post.txt"; cout << "Load phi_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int g = 0; g < G; g++){ for(int b = 0; b < B; b++){ load_File >> temp; phi_est[g][b] += temp; } } } for(int g = 0; g < G; g++){ for(int b = 0; b < B; b++){ phi_est[g][b] = phi_est[g][b] / (iter_max - iter_burnin); } } load_File.close(); // calculate pi_est double **pi_est = new double*[B]; for(int b = 0; b < B; b++){ pi_est[b] = new double[K]; for(int k = 0; k < K; k++){ pi_est[b][k] = 0.0; } } load_name = output_dir + "pi_post.txt"; cout << "Load pi_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int b = 0; b < B; b++){ for(int k = 0; k < K; k++){ load_File >> temp; pi_est[b][k] += temp; } } } for(int b = 0; b < B; b++){ for(int k = 0; k < K; k++){ pi_est[b][k] = pi_est[b][k] / (iter_max - iter_burnin); } } load_File.close(); // calculate w_est int w_temp; int *w_est = new int[N]; for(int i = 0; i < N; i++){ w_est[i] = 0; } int **count_w = new int*[N]; // count the frequency of cell types after burnin for(int i = 0; i < N; i++){ count_w[i] = new int[K]; for(int k = 0; k < K; k ++){ count_w[i][k] = 0; } } load_name = output_dir + "w_post.txt"; cout << "Load w_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int i = 0; i < N; i++){ load_File >> w_temp; count_w[i][w_temp] ++; } } for(int i = 0; i < N; i++){ for(int k = 1; k < K; k++){ if(count_w[i][k] > count_w[i][w_est[i]]){ w_est[i] = k; // obtain the mode from burnin to the last iteration } } } load_File.close(); // calculate p_est double p_est = 0.0; load_name = output_dir + "p_post.txt"; cout << "Load p_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ load_File >> temp; p_est += temp; } p_est = p_est / (iter_max - iter_burnin); load_File.close(); // calculate tau0_est double tau0_est = 0.0; load_name = output_dir + "tau0_post.txt"; cout << "Load tau0_post from " << load_name << endl; load_File.open(load_name); iter = 0; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ load_File >> temp; tau0_est += temp; } tau0_est = tau0_est / (iter_max - iter_burnin); load_File.close(); // calculate PPI_est double **PPI_est = new double*[G]; for(int g = 0; g < G; g++){ PPI_est[g] = new double[K]; for(int k = 0; k < K; k++){ PPI_est[g][k] = 0.0; } } load_name = output_dir + "l_post.txt"; cout << "Load l_post from " << load_name << endl; load_File.open(load_name); iter = 0; int temp_int; while (iter < iter_burnin){ getline(load_File, row_dropped); iter ++; } for(; iter < iter_max; iter++){ for(int g = 0; g < G; g++){ for(int k = 0; k < K; k++){ load_File >> temp_int; PPI_est[g][k] += temp_int; } } // cout << "Finish loading " << iter << "-th iteration." << endl; } for(int g = 0; g < G; g++){ for(int k = 0; k < K; k++){ PPI_est[g][k] = PPI_est[g][k] / (iter_max - iter_burnin); } } load_File.close(); // Extract intrinsic genes double fdr_threshold = 0.05, postprob_DE_threshold; int count_gene = 0; int *D = new int[G];// intrinsic gene indicator postprob_DE_threshold = postprob_DE_thr_fun(PPI_est,fdr_threshold, G, K); cout << "The threshold of PPI to identify intrinsic genes is " << postprob_DE_threshold << " to control FDR at level "<< fdr_threshold << "." << endl; for(int g = 0; g < G; g++){ D[g] = IG_index(PPI_est[g], postprob_DE_threshold, K); count_gene += D[g]; } cout << "There are " << count_gene << " identified intrisic genes." << endl; // load x_imputed int **x_imputed = new int*[G]; for(int g = 0; g < G; g++){ x_imputed[g] = new int[N]; } load_name = output_dir + "x_imputed.txt"; cout << "Load x_imputed from " << load_name << endl; load_File.open(load_name); for(int g = 0; g < G; g++){ for(int i = 0; i < N; i++){ load_File >> x_imputed[g][i]; } } load_File.close(); // Calculate likelihood and BIC omprng Loglike_Rng; Loglike_Rng.fixedSeed(12345);// for Monte carlo estimation of E(exp(gamma_0+gamma_1x)/(1+exp(gamma_0+gamma_1x))) int cell_index; double loglike_obs; // auxiliary variables double *lpy = new double[K]; // log(pi_bk prod_{g=1}^G Pr(Y_big = y_big | Theta )) double lpy_max, sum_lpy; // lr0_temp, sum_lr0, lpy_max, sum_lpy; // Set the number of cores for parallel omp_set_num_threads(nc); // Calculate BIC auto start_BIC2 = chrono::system_clock::now(); double BIC; loglike_obs = 0.0; cell_index = 0; for (int b = 0; b < B; b++) { for (int i = 0; i < nb[b]; i++) { for (int k = 0; k < K; k++) { lpy[k] = log(pi_est[b][k]); } for (int k = 0; k < K; k++) { // auto start_bik = chrono::system_clock::now(); # pragma omp parallel { int read, x_max; double logmubikg, pbgk, logp, log1mp, lr0_temp, sum_lr0, lpy_thread; lpy_thread = 0.0; # pragma omp for for (int g = 0; g < G; g++) { read = Y[g][cell_index]; logmubikg = alpha_est[g] + beta_est[g][k] + nu_est[g][b] + delta_est[cell_index]; pbgk = exp(logmubikg) / (exp(logmubikg) + phi_est[g][b]); if(pbgk < pow(0.1, 100)){ logp = -100; log1mp = log(1-pbgk); }else if(1 - pbgk < pow(0.1, 100)){ logp = log(pbgk); log1mp = -100; }else{ logp = log(pbgk); log1mp = log(1 - pbgk); } if (read > 0) { lpy_thread += - log(1 + exp(gamma_est[b][0] + gamma_est[b][1] * read)); lpy_thread += lgamma(phi_est[g][b] + read) - lgamma(read + 1) - lgamma(phi_est[g][b]); lpy_thread += read * logp + phi_est[g][b] * log1mp; }else { x_max = (int)3 * exp(logmubikg); lr0_temp = phi_est[g][b] * log1mp; //x=0 sum_lr0 = lr0_temp; for (int x = 1; x < x_max; x++) { lr0_temp = gamma_est[b][0] + gamma_est[b][1] * x - log(1 + exp(gamma_est[b][0] + gamma_est[b][1] * x)); lr0_temp += lgamma(phi_est[g][b] + x) - lgamma(x + 1) - lgamma(phi_est[g][b]); lr0_temp += x * logp + phi_est[g][b] * log1mp; if (lr0_temp > sum_lr0) { sum_lr0 = lr0_temp + log(1 + exp(sum_lr0 - lr0_temp)); }else { sum_lr0 = sum_lr0 + log(1 + exp(lr0_temp - sum_lr0)); } } lpy_thread += sum_lr0; //Rprintf("y %d %d %d = 0 and sum_lr0 is %f if the cell belongs to %d-th subtype.\n",b, i ,j ,sum_lr0, k); } } # pragma omp critical { lpy[k] += lpy_thread; } } //Rprintf("lpy %d = %f for the %d-th cell.\n",k+1,lpy[k],index_n); // auto end_bik = chrono::system_clock::now(); // chrono::duration<double> elapsed_seconds_bik = end_bik-start_bik; // cout << "elapsed time of calculating the likelihood of Y_{" << b << "," << i << "} regarded in cell type "<< k << " is: " << elapsed_seconds_bik.count() << "s" << endl; }// end of k lpy_max = vec_max(lpy, K); sum_lpy = 0.0; for (int k = 0; k < K; k++) { sum_lpy = sum_lpy + exp(lpy[k] - lpy_max); //Rprintf("logproby[%d]=%f",k,lpy[k]); } loglike_obs += lpy_max + log(sum_lpy); cell_index ++; // printf("Finish the %d-th cell, lpy_max= %f, sum_lpy = %f, loglike = %f.\n", cell_index, lpy_max, sum_lpy, loglike_obs); } } BIC = - 2.0 * loglike_obs + log(G * N) * ((B + G) * K+ 2 * B + G * (B * 2 - 1) + N - B); // all parameters of interest contain pi_{bk}, gamma_{b0(1)}, alpha_g, beta_{gk}, nu_{bg}, delta_{bi}, phi_{bg} auto end_BIC2 = chrono::system_clock::now(); chrono::duration<double> elapsed_seconds_BIC2 = end_BIC2-start_BIC2; cout << "elapsed time of calculating previous BIC is: " << elapsed_seconds_BIC2.count() << "s" << endl; cout << "Writing posterior mean of alpha into the directory " << infer_dir << endl; est_name = infer_dir + "alpha_est.txt"; est_File.open(est_name.c_str()); for(int g = 0; g < G; g++){ est_File << alpha_est[g]; est_File << " "; } est_File << endl; est_File.close(); cout << "Writing posterior mean of beta into the directory " << infer_dir << endl; est_name = infer_dir + "beta_est.txt"; est_File.open(est_name.c_str()); for(int g = 0; g < G; g++){ for(int k = 0; k < K; k++){ est_File << beta_est[g][k]; est_File << " "; } est_File << endl; } est_File << endl; est_File.close(); cout << "Writing posterior mean of nu into the directory " << infer_dir << endl; est_name = infer_dir + "nu_est.txt"; est_File.open(est_name.c_str()); for(int g = 0; g < G; g++){ for(int b = 0; b < B; b++){ est_File << nu_est[g][b]; est_File << " "; } est_File << endl; } est_File << endl; est_File.close(); cout << "Writing posterior mean of delta into the directory " << infer_dir << endl; est_name = infer_dir + "delta_est.txt"; est_File.open(est_name.c_str()); for(int i = 0; i < N; i++){ est_File << delta_est[i]; est_File << " "; } est_File << endl; est_File.close(); cout << "Writing posterior mean of gamma into the directory " << infer_dir << endl; est_name = infer_dir + "gamma_est.txt"; est_File.open(est_name.c_str()); for(int b = 0; b < B; b++){ est_File << gamma_est[b][0]; est_File << " "; est_File << gamma_est[b][1]; est_File << " "; est_File << endl; } est_File << endl; est_File.close(); cout << "Writing posterior mean of phi into the directory " << infer_dir << endl; est_name = infer_dir + "phi_est.txt"; est_File.open(est_name.c_str()); for(int g = 0; g < G; g++){ for(int b = 0; b < B; b++){ est_File << phi_est[g][b]; est_File << " "; } est_File << endl; } est_File << endl; est_File.close(); cout << "Writing posterior mean of pi into the directory " << infer_dir << endl; est_name = infer_dir + "pi_est.txt"; est_File.open(est_name.c_str()); for(int b = 0; b < B; b++){ for(int k = 0; k < K; k++){ est_File << pi_est[b][k]; est_File << " "; } est_File << endl; } est_File << endl; est_File.close(); cout << "Writing posterior mode of w into the directory " << infer_dir << endl; est_name = infer_dir + "w_est.txt"; est_File.open(est_name.c_str()); for(int i = 0; i < N; i++){ est_File << w_est[i]; est_File << " "; } est_File << endl; est_File.close(); cout << "Writing posterior mean of p into the directory " << infer_dir << endl; est_name = infer_dir + "p_est.txt"; est_File.open(est_name.c_str()); est_File << p_est; est_File << endl; est_File.close(); cout << "Writing posterior mean of tau0 into the directory " << infer_dir << endl; est_name = infer_dir + "tau0_est.txt"; est_File.open(est_name.c_str()); est_File << tau0_est; est_File << endl; est_File.close(); cout << "Writing posterior mean of PPI into the directory " << infer_dir << endl; est_name = infer_dir + "PPI_est.txt"; est_File.open(est_name.c_str()); for(int g = 0; g < G; g++){ for(int k = 0; k < K; k++){ est_File << PPI_est[g][k]; est_File << " "; } est_File << endl; } est_File << endl; est_File.close(); cout << "Writing intrinsic gene indicators into the directory " << infer_dir << endl; est_name = infer_dir + "IG_est.txt"; est_File.open(est_name.c_str()); for(int g = 0; g < G; g++){ est_File << D[g]; est_File << endl; } est_File << endl; est_File.close(); cout << "Writing posterior mean of imputed X into the directory " << infer_dir << endl; est_name = infer_dir + "x_imputed.txt"; est_File.open(est_name.c_str()); for(int g = 0; g < G; g++){ for(int i = 0; i < N; i++){ est_File << x_imputed[g][i]; est_File << " "; } est_File << endl; } est_File << endl; est_File.close(); cout << "Writing BIC into the directory " << infer_dir << endl; est_name = infer_dir + "BIC.txt"; est_File.open(est_name.c_str()); est_File << BIC; est_File << endl; est_File.close(); delete [] alpha_est; for(int g = 0; g < G; g ++){ delete [] beta_est[g]; } delete [] beta_est; for(int g = 0; g < G; g ++){ delete [] nu_est[g]; } delete [] nu_est; delete [] delta_est; for(int b = 0; b < B; b ++){ delete [] gamma_est[b]; } delete [] gamma_est; for(int g = 0; g < G; g ++){ delete [] phi_est[g]; } delete [] phi_est; for(int b = 0; b < B; b ++){ delete [] pi_est[b]; } delete [] pi_est; delete [] w_est; for(int i = 0; i < N; i ++){ delete [] count_w[i]; } delete [] count_w; for(int g = 0; g < G; g ++){ delete [] PPI_est[g]; } delete [] PPI_est; delete [] D; delete [] lpy; for(int g = 0; g < G; g++){ delete [] Y[g]; } delete [] Y; delete [] nb; return 0; }
[ "noreply@github.com" ]
songfd2018.noreply@github.com
3f1705cd04bf937383257697c96fe3715a201e8e
bbcda48854d6890ad029d5973e011d4784d248d2
/trunk/win/Source/Includes/QtIncludes/src/3rdparty/webkit/WebCore/rendering/RenderFrameSet.h
15d6505506ce419e4872e7ab0e7e79f47c7c9472
[ "BSD-2-Clause", "LGPL-2.0-only", "LGPL-2.1-only", "MIT", "curl", "LGPL-2.1-or-later", "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "Zlib", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference", "MS-LPL" ]
permissive
dyzmapl/BumpTop
9c396f876e6a9ace1099b3b32e45612a388943ff
1329ea41411c7368516b942d19add694af3d602f
refs/heads/master
2020-12-20T22:42:55.100473
2020-01-25T21:00:08
2020-01-25T21:00:08
236,229,087
0
0
Apache-2.0
2020-01-25T20:58:59
2020-01-25T20:58:58
null
UTF-8
C++
false
false
4,548
h
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 2000 Simon Hausmann <hausmann@kde.org> * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef RenderFrameSet_h #define RenderFrameSet_h #include "RenderBox.h" namespace WebCore { class HTMLFrameSetElement; class MouseEvent; enum FrameEdge { LeftFrameEdge, RightFrameEdge, TopFrameEdge, BottomFrameEdge }; struct FrameEdgeInfo { FrameEdgeInfo(bool preventResize = false, bool allowBorder = true) : m_preventResize(4) , m_allowBorder(4) { m_preventResize.fill(preventResize); m_allowBorder.fill(allowBorder); } bool preventResize(FrameEdge edge) const { return m_preventResize[edge]; } bool allowBorder(FrameEdge edge) const { return m_allowBorder[edge]; } void setPreventResize(FrameEdge edge, bool preventResize) { m_preventResize[edge] = preventResize; } void setAllowBorder(FrameEdge edge, bool allowBorder) { m_allowBorder[edge] = allowBorder; } private: Vector<bool> m_preventResize; Vector<bool> m_allowBorder; }; class RenderFrameSet : public RenderBox { public: RenderFrameSet(HTMLFrameSetElement*); virtual ~RenderFrameSet(); const RenderObjectChildList* children() const { return &m_children; } RenderObjectChildList* children() { return &m_children; } FrameEdgeInfo edgeInfo() const; bool userResize(MouseEvent*); bool isResizingRow() const; bool isResizingColumn() const; bool canResizeRow(const IntPoint&) const; bool canResizeColumn(const IntPoint&) const; private: static const int noSplit = -1; class GridAxis : public Noncopyable { public: GridAxis(); void resize(int); Vector<int> m_sizes; Vector<int> m_deltas; Vector<bool> m_preventResize; Vector<bool> m_allowBorder; int m_splitBeingResized; int m_splitResizeOffset; }; virtual RenderObjectChildList* virtualChildren() { return children(); } virtual const RenderObjectChildList* virtualChildren() const { return children(); } virtual const char* renderName() const { return "RenderFrameSet"; } virtual bool isFrameSet() const { return true; } virtual void layout(); virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, int x, int y, int tx, int ty, HitTestAction); virtual void paint(PaintInfo&, int tx, int ty); virtual bool isChildAllowed(RenderObject*, RenderStyle*) const; inline HTMLFrameSetElement* frameSet() const; bool flattenFrameSet() const; void setIsResizing(bool); void layOutAxis(GridAxis&, const Length*, int availableSpace); void computeEdgeInfo(); void fillFromEdgeInfo(const FrameEdgeInfo& edgeInfo, int r, int c); void positionFrames(); void positionFramesWithFlattening(); int splitPosition(const GridAxis&, int split) const; int hitTestSplit(const GridAxis&, int position) const; void startResizing(GridAxis&, int position); void continueResizing(GridAxis&, int position); void paintRowBorder(const PaintInfo&, const IntRect&); void paintColumnBorder(const PaintInfo&, const IntRect&); RenderObjectChildList m_children; GridAxis m_rows; GridAxis m_cols; bool m_isResizing; bool m_isChildResizing; }; inline RenderFrameSet* toRenderFrameSet(RenderObject* object) { ASSERT(!object || object->isFrameSet()); return static_cast<RenderFrameSet*>(object); } // This will catch anyone doing an unnecessary cast. void toRenderFrameSet(const RenderFrameSet*); } // namespace WebCore #endif // RenderFrameSet_h
[ "anandx@google.com" ]
anandx@google.com
7ba07b8b48d6c0d7b60bd39416e674064e95640c
61bd1270ec9722a9519f0311cf1ecc01f401b2fe
/Codeforces/1341/A.cpp
3a792c511a8603067e253dab283f430f92cdfd27
[]
no_license
GonzaloPereira/CompetitiveProgramming
495aef87835d13b9f5491b8ac56ef0face9be428
ffc06d855ca021490cc071b92dd3aa84a978dd5b
refs/heads/main
2021-11-19T03:34:46.578008
2021-08-10T00:46:29
2021-08-10T00:46:29
190,089,378
2
1
null
null
null
null
UTF-8
C++
false
false
394
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define pb push_back #define FIO ios_base::sync_with_stdio(false), cin.tie(NULL); #define N int main(){ FIO; int t; cin >> t; while(t--){ int n,a,b,c,d; cin >> n >> a >> b >> c >> d; if(((a+b)*n >= (c-d))&&((a-b)*n <= (c+d))) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
[ "gonzaloapr45@gmail.com" ]
gonzaloapr45@gmail.com
ed53953be4c8064b479a23342c323ef16086d57e
09314acee987124b581add83a4c01e026e019375
/windows_explorer/Drives.cpp
a7c20aa5743cd18fb64727d3f090cd05b90d3b05
[]
no_license
Thuat1996/windows_ex
3e1d89278357b6476b523c8fd027f0f7ba0b02af
6b407ef1929422848b54648cdcea3f1a61ae7c5e
refs/heads/master
2020-03-29T06:42:33.207744
2019-01-06T15:39:55
2019-01-06T15:39:55
149,637,010
0
0
null
null
null
null
UTF-8
C++
false
false
3,529
cpp
#include "stdafx.h" #include "Drives.h" #include <shellapi.h> //dùng để sử dụng hàm Strcpy, StrCat #include <shlwapi.h> #pragma comment(lib, "shlwapi.lib") TCHAR* const DriveLetter[] = { _T("abc"), }; DriverSize *Drives::getDriveSize(int i) { __int64 totalSize; __int64 freeSpace; SHGetDiskFreeSpaceEx(getDriveLetter(i), NULL, (PULARGE_INTEGER)&totalSize, (PULARGE_INTEGER)&freeSpace); DriverSize* Size = new DriverSize(totalSize, freeSpace); return Size; } Drives::Drives() { } TCHAR* Drives::getDriveLetter(int i) { return mDirverLetter[i]; } TCHAR* Drives::getVolumeLabel(int i) { return mVolumeLabel[i]; } TCHAR* Drives::getDriveType(int i) { return mDriveType[i]; } LPWSTR Drives::getTotalSpace(int i) { return mDriverSize[i]->getTotalSpaceStr(); } LPWSTR Drives::getFreeSpace(int i) { return mDriverSize[i]->getFreeSpaceStr(); } int Drives::getDriverNumber() { return mDrivesNumber; } void Drives::getDiversFromSystem() { TCHAR buffer[105]; TCHAR *tempBuffer = new TCHAR[105]; mDrivesNumber = 0; DWORD bitmask_count = GetLogicalDrives(); int i = 0; while (bitmask_count) { // sue the bitwise AND,1 - available, 0- unvailable if (bitmask_count & 1) { mDrivesNumber++; } i++; bitmask_count >>= 1; } //cap phat bo nho mDirverLetter = new TCHAR*[mDrivesNumber]; mVolumeLabel = new TCHAR*[mDrivesNumber]; mDriveType = new TCHAR*[mDrivesNumber]; mDirverLetter = new TCHAR*[mDrivesNumber]; for (int i = 0; i < mDrivesNumber; ++i) { mDirverLetter[i] = new TCHAR[128]; mVolumeLabel[i] = new TCHAR[255]; mDriveType[i] = new TCHAR[255]; } //lay ki tu của ổ DWORD bitmask_getletter = GetLogicalDrives(); i = 0; int k = 0; while (bitmask_getletter) { //AND, 1- co, 0- khong if (bitmask_getletter & 1) { mDirverLetter[k] = DriveLetter[i]; k++; } i++; bitmask_getletter >>= 1; } int nType; for (int i = 0; i < mDrivesNumber; ++i) { //lay kieu o dia nType = GetDriveType(mDirverLetter[i]); switch (nType) { case DRIVE_FIXED: StrCpy(mDriveType[i], L"Local Disk"); break; case DRIVE_REMOVABLE: StrCpy(mDriveType[i], L"Removable Diver"); break; case DRIVE_CDROM: StrCpy(mDriveType[i], L"CD-ROM"); break; default: break; } //lay size cua o dia mDriverSize[i] = getDriveSize(i); StrCpy(buffer, _T("")); if ((nType == DRIVE_FIXED) || (nType == DRIVE_REMOVABLE) || (nType == DRIVE_REMOTE)) { //lay thong tin cua o GetVolumeInformation(mDirverLetter[i], buffer, 105, NULL, NULL, NULL, NULL, 0); StrCpy(tempBuffer, buffer); } else { if (nType == DRIVE_CDROM) { GetVolumeInformation(mDirverLetter[i], buffer, 105, NULL, NULL, NULL, NULL,0); if (wcslen(buffer) == 0) //khong co lable { StrCpy(tempBuffer, _T("CD_ROm")); } else StrCpy(tempBuffer, buffer); } else if (((i == 0) || (i == 1)) && (nType == DRIVE_REMOVABLE)) //floppy disk { StrCpy(tempBuffer, _T("3½ Floppy")); } } if (wcslen(tempBuffer) == 0) //khong co lable { StrCpy(mVolumeLabel[i], _T("Local Disk")); } else { //copy StrCpy(mVolumeLabel[i], tempBuffer); } //them() StrCat(mVolumeLabel[i], _T("(")); StrNCat(mVolumeLabel[i], mDirverLetter[i], 3); StrCat(mVolumeLabel[i], _T("(")); } } Drives::~Drives() { for (int i = 0; i < mDrivesNumber; ++i) { delete[] mDirverLetter[i]; delete[] mVolumeLabel[i]; delete[] mDriveType[i]; } delete[] mDirverLetter; delete[] mVolumeLabel; delete[] mDriveType; mDrivesNumber = 0; }
[ "nguyenvanthuat96bn@gmail.com" ]
nguyenvanthuat96bn@gmail.com
38c90e4141e4dbdb0dc0c5ee89bb8e07f042f4b9
d1a6d535f3378cca4463a0248e0dc6c641d92ab2
/ordermanagerview.h
4c17eb2f139a412c6d96eb95e51b642bd79a64a2
[]
no_license
gaoxiaojun/polluxus
354024b11200cceb544f318ec62c8e93c4043ae3
45d5e3485d9f75b5cc65a1c5d7caaf66d5aa02fb
refs/heads/master
2020-12-11T05:37:58.559054
2015-10-13T14:14:31
2015-10-13T14:14:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
516
h
#ifndef ORDERMANAGERVIEW_H #define ORDERMANAGERVIEW_H #include <QWidget> #include "ordermanagermodel.h" class QTableView; class QSettings; class OrderManagerView : public QWidget { Q_OBJECT public: explicit OrderManagerView(QWidget *parent = 0); virtual ~OrderManagerView(); QTableView *pTableView; OrderManagerModel *pModel; void loadWorkSpace(); void saveWorkSpace(); QString iniFileString; QSettings *wsSettings; signals: public slots: }; #endif // ORDERMANAGERVIEW_H
[ "yh.polluxus@gmail.com" ]
yh.polluxus@gmail.com
de8ca2e8ecd4aab990a8df9f87e5364532a3c668
221dabc26ab1327ebae77d0615bf9fce7ed154cb
/Prácticas Calificadas/PC2/main.cpp
3e38242c34ac58663cb32570175974c52bf9cd71
[]
no_license
christianledgard/POOII-UTEC-2019-1
9da68c340b08294674f1d19064744683e7cafea8
d0647fcb7b71905c246510f6bcc44986504a360b
refs/heads/master
2020-05-17T15:34:42.867626
2019-05-15T16:06:54
2019-05-15T16:06:54
183,793,586
0
0
null
null
null
null
UTF-8
C++
false
false
1,100
cpp
#include <iostream> #include "Process.cpp" int main() { //auto *carlos = new SyncProcess("Hola"); //carlos->run(); //auto *lucas = new AsyncProcess("Hola","jeje"); //lucas->run(); auto *fifo = new Queue<Process*,10>(); //Encolar 10 procesos: 5 Syn, 5 Async fifo->enqueue(new AsyncProcess("TestAsync","")); fifo->enqueue(new SyncProcess("TestSync")); fifo->enqueue(new AsyncProcess("TestAsync","")); fifo->enqueue(new SyncProcess("TestSync")); fifo->enqueue(new AsyncProcess("TestAsync","")); fifo->enqueue(new SyncProcess("TestSync")); fifo->enqueue(new AsyncProcess("TestAsync","")); fifo->enqueue(new SyncProcess("TestSync")); fifo->enqueue(new AsyncProcess("TestAsync","")); fifo->enqueue(new SyncProcess("TestSync")); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); fifo->dequeue()->run(); return 0; }
[ "christianledgard@gmail.com" ]
christianledgard@gmail.com
2b2cbdc455158df1c8585213798fd5eefac0ed28
20049d88e2e8f0e1904efc561103c1d84d21507a
/konev.ivan/A1/main.cpp
e30027e12c63bc5433aa456b648ecc246d96a6de
[]
no_license
gogun/Labs-for-SPbSPU-C-course-during-2019
5442a69152add3e66f02a7541e8dc8dd817f38a1
16ade47b859517a48d0fdb2e9704464bce4cc355
refs/heads/master
2022-01-09T16:02:54.728830
2019-06-06T11:06:33
2019-06-06T11:06:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include <iostream> #include "rectangle.hpp" #include "circle.hpp" int main() { Rectangle r1({1.0,1.0}, 3.0, 3.0); std::cout<<r1.getArea()<<std::endl; Rectangle r2({2.0,2.0}, 1.0, 4.0); r2.move(1.0,2.0); Circle c1({3.0,1.0}, 3.0); std::cout<<c1.getArea()<<std::endl; Circle c2({1.0,2.0}, 4.0); c2.move({3.0,5.0}); Shape *circP = &c2; rectangle_t tempRect = circP->getFrameRect(); std::cout<<tempRect.pos.x<<" "<<tempRect.pos.y<<" "<<tempRect.width<<" "<<tempRect.height<<std::endl; Shape *rectP = &r2; tempRect = rectP->getFrameRect(); std::cout<<tempRect.pos.x<<" "<<tempRect.pos.y<<" "<<tempRect.width<<" "<<tempRect.height<<std::endl; return 0; }
[ "kva19.2000@mail.ru" ]
kva19.2000@mail.ru
6f5f46e5c76eb5b6ce0a4fc191500a0cc8ae9d99
ece3d852c9c23229081872b61a2f617bf0576b7e
/sarturis-gtk/modules/gtkwidget-io/digitalradiobutton.cpp
808a43a4ae8df231335627525a93ab601c010065
[]
no_license
meisenmann77/sarturis
14ee6e7462ce84aa5dfc78b49190fb993e6051ec
bf8bcee735859667a1bdd1f67f2fa78ca938573b
refs/heads/master
2021-01-19T14:56:56.033733
2020-11-30T16:57:38
2020-11-30T16:57:38
37,017,592
0
0
null
null
null
null
UTF-8
C++
false
false
4,035
cpp
/******************************************************************************* * * Sarturis is (C) Copyright 2006-2011 by Dresden University of Technology * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This software 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this software; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * ******************************************************************************/ #include "include/digitalradiobutton.h" using namespace sarturis; using namespace sarturis::gtk; /******************************************************************************/ DigitalRadioButton::DigitalRadioButton(sarturis::ref<Widget> Label, sarturis::ref<DigitalRadioButton> GroupMember): radiobutton(0), label(Label), groupMember(GroupMember), value(0) /******************************************************************************/ {;} /******************************************************************************/ /******************************************************************************/ DigitalRadioButton::~DigitalRadioButton() /******************************************************************************/ {;} /******************************************************************************/ /******************************************************************************/ int DigitalRadioButton::Get() /******************************************************************************/ { return value; } /******************************************************************************/ /******************************************************************************/ void DigitalRadioButton::Update() /******************************************************************************/ { if (radiobutton) { value=(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radiobutton)) == (gboolean)TRUE); } } /******************************************************************************/ /******************************************************************************/ GtkWidget* DigitalRadioButton::setup() /******************************************************************************/ { // Toggle-Button erzeugen und anzeigen if(groupMember.valid()) radiobutton= gtk_radio_button_new(groupMember->GetGroup()); else radiobutton= gtk_radio_button_new(NULL); gtk_container_add(GTK_CONTAINER(radiobutton),label->GetWidget()); gtk_widget_show(radiobutton); return radiobutton; } /******************************************************************************/ /******************************************************************************/ //void DigitalRadioButton::Reset() /******************************************************************************/ /*{ gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(togglebutton),defaultValue); }*/ /******************************************************************************/ /******************************************************************************/ GSList* DigitalRadioButton::GetGroup() /******************************************************************************/ { return gtk_radio_button_get_group(GTK_RADIO_BUTTON (radiobutton)); } /******************************************************************************/
[ "meisenmann77@googlemail.com" ]
meisenmann77@googlemail.com
0c09f87f8809c96e9fbd4da7eccc44c760509193
2eabce5d4acebd57ab50e3258993cdc3320ce5f1
/4 - Objects/4e1-initializationList.cpp
d611e4544c356c5608ce0db49c972ac88daeb539
[]
no_license
ProfACarpenter/ProgrammingExampleCode
72787c3e3504e3c17cafd10900ed71549095958e
bd8934f86a6341d7ebebdba5a2cb9bb1fc4a222a
refs/heads/master
2021-05-20T12:43:35.252418
2020-12-16T20:11:16
2020-12-16T20:11:16
252,301,883
0
0
null
null
null
null
UTF-8
C++
false
false
2,283
cpp
/************* Initialization Lists are used in constructors to simplify the body of the code, and will be used more later for inheritance. *************/ #include <iostream> #include <string> class country_c{ private: int population; int GDP; //let's do this per capita, just for smaller numbers std::string name; public: void fillInformation(); void printInformation(); int getPopulation(){return population;} int getGDP(){return GDP;} std::string getName(){return name;} void setPopulation(int p){population = p;} void setGDP(int g){GDP = g;} void setName(std::string n){name = n;} public: ~country_c(){ std::cout << "This country object is being destructed: " << name << std::endl; } // initialization lists can be filled with hardcoded or filled by variables from the input country_c():name("Unknown"),population(0), GDP(0){ std::cout << "Country with no name/info created.\n"; } country_c(std::string n):name(n),population(0),GDP(0){ std::cout << name << " was created, but we don't know the population or GDP.\n"; } country_c(std::string n, int p, int g):name(n),population(p),GDP(g){ std::cout << name << " was created with a population of " << p << " and per capita GDP of " << g << std::endl; } }; int main(){ country_c unknownCountry; // calls the constructor with no inputs country_c justTheNameCountry("USA"); // calls the constructor with just a name country_c fullyInformedCountry("Canada",37590000,45447); // calls the constructor with name and other information std::cout << "--------------------------------\n"; unknownCountry.printInformation(); justTheNameCountry.printInformation(); fullyInformedCountry.printInformation(); } void country_c::fillInformation(){ // When we do the function definition, we need to give it the correct namespace std::cout << "Enter the name of the country, the population, and the GDP (in US dollars)\n"; std::cin >> name >> population >> GDP; // note you don't need to call the namespace here for the class, because it is identified in the function header return; } void country_c::printInformation(){ std::cout << "The country of " << name << " has " << population << " people and produces approximately " << GDP << " in US dollars\n"; }
[ "carpentera1@wit.edu" ]
carpentera1@wit.edu
f59d61dd6cedfcdebbb6564433bd6e29ae24fe81
ccb6d2726b7522af43004875e2e233bc1088774a
/carma/corba/Test/tWaitClient.cc
eed5dc54acb4707e9aee20a963a201033d3bb700
[ "FSFUL" ]
permissive
mpound/carma
a9ab28ed45b3114972d3f72bcc522c0010e80b42
9e317271eec071c1a53dca8b11af31320f69417b
refs/heads/master
2020-06-01T11:43:47.397953
2019-06-07T15:05:57
2019-06-07T15:05:57
190,763,870
2
0
null
null
null
null
UTF-8
C++
false
false
923
cc
#include "carma/corba/Client.h" #include "carma/corba/Test/Wait.h" #include "carma/util/ExceptionUtils.h" #include "carma/util/Program.h" #include <iostream> #include <string> using namespace carma; using namespace carma::util; using namespace carma::corba; using namespace std; // @version $Revision: 1.2 $ $Date: 2012/02/11 02:41:02 $ // // @usage tWait // // @logger TEST_FACILITY carma.test.corba.tWait // // @noKeys // // @description Simple server to test simultaneous access. int Program::main ( ) try { Client client( getExtraArgc(), getExtraArgv() ); test::Wait_var waiter = client.resolveName< test::Wait >( test::WAIT_NAME ); while ( true ) { cout << "Calling wait for 650 s" << endl; waiter->pause( 650000 ); // cout << "Sleeping for 5ms" << endl; // sleep( 5 ); } return 0; } catch (...) { cerr << getStringForCaught() << endl; return 1; }
[ "22331890+mpound@users.noreply.github.com" ]
22331890+mpound@users.noreply.github.com
504deb18100f20958f873e8cad5bffc5cefd073f
e142d8763d5e21342f5b4f0d82515ed898aac5bd
/jsk_interactive_markers/jsk_interactive_marker/src/transformable_torus.cpp
93e73380d617ffc25ea2779a04bbb1f24b7c3bba
[]
no_license
mmurooka/jsk_visualization
3fb4a3ead6ea762cd0444658f01dda9069a8c722
7bfbe29f1d2010633d261cecb1f14b7e46565421
refs/heads/master
2021-11-19T17:48:42.099657
2014-10-16T15:55:03
2014-10-16T15:55:03
25,336,097
0
0
null
2018-09-08T12:13:38
2014-10-17T03:25:57
null
UTF-8
C++
false
false
3,183
cpp
#include <jsk_interactive_marker/transformable_torus.h> #include <math.h> #define PI 3.14159265 namespace jsk_interactive_marker{ TransformableTorus::TransformableTorus( float radius, float small_radius, int u_div, int v_div, float r, float g, float b, float a, std::string frame, std::string name, std::string description){ torus_radius_ = radius; torus_small_radius_ = small_radius; torus_r_ = r; torus_g_ = g; torus_b_ = b; torus_a_ = a; marker_.type = visualization_msgs::Marker::TRIANGLE_LIST; frame_id_ = frame; name_ = name; description_ = description; u_division_num_ = u_div; v_division_num_ = v_div; } std::vector<geometry_msgs::Point > TransformableTorus::calcurateTriangleMesh(){ std::vector<geometry_msgs::Point> triangle_mesh; float center_x = 0; float center_y = 0; float u_division_num = u_division_num_; float v_division_num = v_division_num_; std::vector<std::vector<geometry_msgs::Point> > points_array; for (int i = 0; i < u_division_num; i ++){ std::vector<geometry_msgs::Point> points; float target_circle_x = torus_radius_ * cos( ( i / u_division_num) * 2 * PI) ; float target_circle_y = torus_radius_ * sin( ( i / u_division_num) * 2 * PI) ; for (int j = 0; j < v_division_num; j++){ geometry_msgs::Point new_point; new_point.x = target_circle_x + torus_small_radius_ * cos ( (j / v_division_num) * 2 * PI) * cos( ( i / u_division_num) * 2 * PI); new_point.y = target_circle_y + torus_small_radius_ * cos ( (j / v_division_num) * 2 * PI) * sin( ( i / u_division_num) * 2 * PI); new_point.z = torus_small_radius_ * sin ( (j / v_division_num) * 2 * PI); points.push_back(new_point); } points_array.push_back(points); } //create mesh list; for(int i = 0; i < u_division_num; i++){ std::vector<geometry_msgs::Point> target_points = points_array[i]; float prev_index = i - 1, next_index = i + 1; if(prev_index < 0) prev_index = u_division_num - 1; if(next_index > u_division_num - 1) next_index = 0; std::vector<geometry_msgs::Point> prev_points = points_array[prev_index]; std::vector<geometry_msgs::Point> next_points = points_array[next_index]; for(int j = 0; j < v_division_num; j++){ float next_point_index = j + 1; if( next_point_index > v_division_num - 1) next_point_index = 0; //first pushes triangle_mesh.push_back(target_points[j]); triangle_mesh.push_back(next_points[j]); triangle_mesh.push_back(target_points[next_point_index]); //second pushes triangle_mesh.push_back(target_points[j]); triangle_mesh.push_back(target_points[next_point_index]); triangle_mesh.push_back(prev_points[next_point_index]); } } return triangle_mesh; } visualization_msgs::Marker TransformableTorus::getVisualizationMsgMarker(){ marker_.points = calcurateTriangleMesh(); marker_.color.r = torus_r_; marker_.color.g = torus_g_; marker_.color.b = torus_b_; marker_.color.a = torus_a_; return marker_; } }
[ "inagaki@inagaki.mail" ]
inagaki@inagaki.mail
e0ce2d865bbf9209143444d091ff43d90126d77b
317a81568696842411132f64352d898a6a013226
/HeartBeatSensorUsingPPG/arduino/ppg_sender.ino
168d7f39640c57bfd9ae4644462c04760e087144
[]
no_license
hrit1995/HeartBeatSensorUsingPPG
f69437738f82e1a70c6d3c7f94c4a8cd4206bfe7
97ca3ce2e3474160515b34d8c1f297335009cc96
refs/heads/master
2020-09-11T10:36:33.027626
2020-01-21T03:37:48
2020-01-21T03:37:48
222,037,404
0
1
null
null
null
null
UTF-8
C++
false
false
2,995
ino
#include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <Wire.h> #include "MAX30105.h" #include "heartRate.h" MAX30105 particleSensor; const char* ssid = "OnePlus7"; const char* password = "lzp123456"; int counter = 0; const byte RATE_SIZE = 4; //Increase this for more averaging. 4 is good. byte rates[RATE_SIZE]; //Array of heart rates byte rateSpot = 0; long lastBeat = 0; //Time at which the last beat occurred float beatsPerMinute; int beatAvg; void setup() { Serial.begin(115200); Serial.println("Initializing..."); // Network Connection WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting.."); } // Initialize sensor if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed { Serial.println("MAX30105 was not found. Please check wiring/power. "); while (1); } Serial.println("Place your index finger on the sensor with steady pressure."); particleSensor.setup(); //Configure sensor with default settings particleSensor.setPulseAmplitudeRed(0x0A); //Turn Red LED to low to indicate sensor is running particleSensor.setPulseAmplitudeGreen(0); //Turn off Green LED } void loop() { if (counter == 100 && WiFi.status() == WL_CONNECTED) { //Check WiFi connection status // Send to cloud HTTPClient http; //Declare object of class HTTPClient http.begin("http://18.188.7.129:8080"); //Specify request destination http.addHeader("Content-Type", "text/plain"); //Specify content-type header http.setReuse(true); String bpm = String(beatsPerMinute); String avgbpm = String(beatAvg); String sender = String(bpm + "," + avgbpm); int httpCode = http.POST(sender); //Send the request //String payload = http.getString(); //Get the response payload //Serial.println(httpCode); //Print HTTP return code //Serial.println(payload); //Print request response payload //http.end(); //Close connection counter = 0; } long irValue = particleSensor.getIR(); if (checkForBeat(irValue) == true) { //We sensed a beat! long delta = millis() - lastBeat; lastBeat = millis(); beatsPerMinute = 60 / (delta / 1000.0); if (beatsPerMinute < 255 && beatsPerMinute > 20) { rates[rateSpot++] = (byte)beatsPerMinute; //Store this reading in the array rateSpot %= RATE_SIZE; //Wrap variable //Take average of readings beatAvg = 0; for (byte x = 0 ; x < RATE_SIZE ; x++) beatAvg += rates[x]; beatAvg /= RATE_SIZE; } } Serial.print("IR="); Serial.print(irValue); Serial.print(", BPM="); Serial.print(beatsPerMinute); Serial.print(", Avg BPM="); Serial.print(beatAvg); if (irValue < 50000) Serial.print(" No finger?"); Serial.println(); delay(10); counter++; }
[ "noreply@github.com" ]
hrit1995.noreply@github.com
a7f742f37a2d6edc5214194ae141d51afe2b0139
17be74dabd1552c8490469065d73b75b5a123615
/contest/977/a/a.cpp
289bf37b3849efceafcd495afab4392a7628c572
[]
no_license
gcie/code
4c25855de7c158c968bf85d9adf566383a823787
6962dc75cff527edac1ec76d32e1f6b50d534e46
refs/heads/master
2022-09-17T02:57:53.151363
2022-08-11T07:43:27
2022-08-11T07:43:27
223,413,103
0
0
null
null
null
null
UTF-8
C++
false
false
1,364
cpp
#pragma gcc optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include <bits/stdc++.h> #define pb push_back #define st first #define nd second #define all(x) (x).begin(), (x).end() #define sci(x) int x; cin >> x; #define scii(x, y) int x, y; cin >> x >> y; #define sciii(x, y, z) int x, y, z; cin >> x >> y >> z; #define TC(x) sci(x); while(x --) #define rep(i, x, y) for (__typeof(x) i = x; i < y; i ++) #define scvi(v, n) vector<int> v(n); rep(i, 0, n) cin >> v[i]; #define scvll(v, n) vector<long long> v(n); rep(i, 0, n) cin >> v[i]; #define SZ(x) ((int)(x).size()) #define er_dup(x) sort(all(x)); (x).resize(distance((x).begin(), unique(all(x)))); #define prv(v) for(auto& x: v) cout << x << ' '; cout << '\n'; #define prvv(v) for(auto& w: v) { for(auto& x: w) cout << x << ' '; cout << '\n'; } using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef long double ld; typedef vector<ll> vll; using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); scii(n, k); while(k-->0) { if(n % 10) { n--; } else n /= 10; } cout << n<< '\n'; return 0; }
[ "grzegorz.ciesielski@asseco.pl" ]
grzegorz.ciesielski@asseco.pl
104c9f5d5fac61f43058338e82e6ef5e9fe2ed4f
2da8db05b3c93bc3bf06162836c1f4289f8cc93b
/src/postprocess/FXAA.cpp
610245f6cbb6de8cdfecd2d3a9ff1a575eb045cb
[ "MIT" ]
permissive
jing-interactive/melo
fdc8aafa8d0ac62eab3fbfdc06d815e5c3296c47
67fa14d19fea157124edddead2ca3fc54d370691
refs/heads/master
2021-06-06T07:58:20.344383
2021-05-04T06:29:18
2021-05-04T06:29:18
147,344,373
19
2
null
null
null
null
UTF-8
C++
false
false
3,028
cpp
/* Copyright (c) 2014, Paul Houx - All rights reserved. This code is intended for use with the Cinder C++ library: http://libcinder.org 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/app/App.h" #include "cinder/Log.h" #include "postprocess/FXAA.h" #include "AssetManager.h" using namespace ci; using namespace std; FXAA::FXAA() { auto glsl = am::glslProg( "postprocess/fxaa.vert", "postprocess/fxaa.frag" ); glsl->uniform( "uTexture", 0 ); mBatch = gl::Batch::create( geom::Rect( Rectf( 0, 0, 1, 1 ) ), glsl ); } void FXAA::apply( const gl::FboRef &destination, const gl::FboRef &source ) { gl::ScopedFramebuffer fbo( destination ); gl::ScopedViewport viewport( 0, 0, destination->getWidth(), destination->getHeight() ); gl::ScopedMatrices matrices; gl::setMatricesWindow( destination->getSize(), false ); // Make sure our source is linearly interpolated. GLenum minFilter = source->getFormat().getColorTextureFormat().getMinFilter(); GLenum magFilter = source->getFormat().getColorTextureFormat().getMagFilter(); source->getColorTexture()->setMinFilter( GL_LINEAR ); source->getColorTexture()->setMagFilter( GL_LINEAR ); // Perform FXAA anti-aliasing. gl::clear( ColorA( 0, 0, 0, 0 ) ); draw( source->getColorTexture(), destination->getBounds() ); // Restore texture parameters. source->getColorTexture()->setMinFilter( minFilter ); source->getColorTexture()->setMagFilter( magFilter ); } void FXAA::draw( const gl::TextureRef &source, const Area &bounds ) { if( ! mBatch ) return; const float w = (float)bounds.getWidth(); const float h = (float)bounds.getHeight(); mBatch->getGlslProg()->uniform( "uExtents", vec4( 1.0f / w, 1.0f / h, w, h ) ); gl::ScopedTextureBind tex0( source ); gl::ScopedModelMatrix modelScope; gl::scale( w, h, 1.0f ); mBatch->draw(); }
[ "vinjn.z@gmail.com" ]
vinjn.z@gmail.com
fd6d4fc5591efab3f87797708ec00f2f95f71645
cc40d6b758088e9ba56641e91c35e1ea85b64e07
/third_party/spirv-tools/test/opt/combine_access_chains_test.cpp
a9ed91046ce801fa88f9179b891dd3e77e60f479
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
chinmaygarde/filament
1091b664f1ba4cc9b63c31c73f63ec8b449acd22
030ba324e0db96dfd31c0c1e016ae44001d92b00
refs/heads/master
2020-03-26T00:25:48.310901
2018-08-13T22:26:23
2018-08-13T22:26:23
144,320,013
1
0
Apache-2.0
2018-08-10T18:29:11
2018-08-10T18:29:11
null
UTF-8
C++
false
false
26,654
cpp
// Copyright (c) 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "assembly_builder.h" #include "gmock/gmock.h" #include "pass_fixture.h" #include "pass_utils.h" namespace spvtools { namespace opt { namespace { using CombineAccessChainsTest = PassTest<::testing::Test>; #ifdef SPIRV_EFFCEE TEST_F(CombineAccessChainsTest, PtrAccessChainFromAccessChainConstant) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int3:%\w+]] = OpConstant [[int]] 3 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: OpAccessChain [[ptr_int]] [[var]] [[int3]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpAccessChain %ptr_Workgroup_uint %var %uint_0 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromInBoundsAccessChainConstant) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int3:%\w+]] = OpConstant [[int]] 3 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: OpAccessChain [[ptr_int]] [[var]] [[int3]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpInBoundsAccessChain %ptr_Workgroup_uint %var %uint_0 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromAccessChainCombineConstant) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[int2:%\w+]] = OpConstant [[int]] 2 ; CHECK: OpAccessChain [[ptr_int]] [[var]] [[int2]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_1 = OpConstant %uint 1 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpAccessChain %ptr_Workgroup_uint %var %uint_1 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %uint_1 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromAccessChainNonConstant) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[ld1:%\w+]] = OpLoad ; CHECK: [[ld2:%\w+]] = OpLoad ; CHECK: [[add:%\w+]] = OpIAdd [[int]] [[ld1]] [[ld2]] ; CHECK: OpAccessChain [[ptr_int]] [[var]] [[add]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Function_uint = OpTypePointer Function %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %local_var = OpVariable %ptr_Function_uint Function %ld1 = OpLoad %uint %local_var %gep = OpAccessChain %ptr_Workgroup_uint %var %ld1 %ld2 = OpLoad %uint %local_var %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %ld2 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromAccessChainExtraIndices) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int1:%\w+]] = OpConstant [[int]] 1 ; CHECK: [[int2:%\w+]] = OpConstant [[int]] 2 ; CHECK: [[int3:%\w+]] = OpConstant [[int]] 3 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: OpAccessChain [[ptr_int]] [[var]] [[int1]] [[int2]] [[int3]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_1 = OpConstant %uint 1 %uint_2 = OpConstant %uint 2 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %uint_array_4_array_4 = OpTypeArray %uint_array_4 %uint_4 %uint_array_4_array_4_array_4 = OpTypeArray %uint_array_4_array_4 %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Function_uint = OpTypePointer Function %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %ptr_Workgroup_uint_array_4_array_4 = OpTypePointer Workgroup %uint_array_4_array_4 %ptr_Workgroup_uint_array_4_array_4_array_4 = OpTypePointer Workgroup %uint_array_4_array_4_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4_array_4_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpAccessChain %ptr_Workgroup_uint_array_4 %var %uint_1 %uint_0 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %uint_2 %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromPtrAccessChainCombineElementOperand) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int3:%\w+]] = OpConstant [[int]] 3 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[int6:%\w+]] = OpConstant [[int]] 6 ; CHECK: OpPtrAccessChain [[ptr_int]] [[var]] [[int6]] [[int3]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_3 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %uint_3 %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromPtrAccessChainOnlyElementOperand) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int4:%\w+]] = OpConstant [[int]] 4 ; CHECK: [[array:%\w+]] = OpTypeArray [[int]] [[int4]] ; CHECK: [[ptr_array:%\w+]] = OpTypePointer Workgroup [[array]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[int6:%\w+]] = OpConstant [[int]] 6 ; CHECK: OpPtrAccessChain [[ptr_array]] [[var]] [[int6]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_3 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromPtrAccessCombineNonElementIndex) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int3:%\w+]] = OpConstant [[int]] 3 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: OpPtrAccessChain [[ptr_int]] [[var]] [[int3]] [[int3]] [[int3]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %uint_array_4_array_4 = OpTypeArray %uint_array_4 %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Function_uint = OpTypePointer Function %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %ptr_Workgroup_uint_array_4_array_4 = OpTypePointer Workgroup %uint_array_4_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_3 %uint_0 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %uint_3 %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, AccessChainFromPtrAccessChainOnlyElementOperand) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int3:%\w+]] = OpConstant [[int]] 3 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: OpPtrAccessChain [[ptr_int]] [[var]] [[int3]] [[int3]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_3 %gep = OpAccessChain %ptr_Workgroup_uint %ptr_gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, AccessChainFromPtrAccessChainAppend) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int1:%\w+]] = OpConstant [[int]] 1 ; CHECK: [[int2:%\w+]] = OpConstant [[int]] 2 ; CHECK: [[int3:%\w+]] = OpConstant [[int]] 3 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: OpPtrAccessChain [[ptr_int]] [[var]] [[int1]] [[int2]] [[int3]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_1 = OpConstant %uint 1 %uint_2 = OpConstant %uint 2 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %uint_array_4_array_4 = OpTypeArray %uint_array_4 %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %ptr_Workgroup_uint_array_4_array_4 = OpTypePointer Workgroup %uint_array_4_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_1 %uint_2 %gep = OpAccessChain %ptr_Workgroup_uint %ptr_gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, AccessChainFromAccessChainAppend) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int1:%\w+]] = OpConstant [[int]] 1 ; CHECK: [[int2:%\w+]] = OpConstant [[int]] 2 ; CHECK: [[ptr_int:%\w+]] = OpTypePointer Workgroup [[int]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: OpAccessChain [[ptr_int]] [[var]] [[int1]] [[int2]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_1 = OpConstant %uint 1 %uint_2 = OpConstant %uint 2 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %uint_array_4_array_4 = OpTypeArray %uint_array_4 %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %ptr_Workgroup_uint_array_4_array_4 = OpTypePointer Workgroup %uint_array_4_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %ptr_gep = OpAccessChain %ptr_Workgroup_uint_array_4 %var %uint_1 %gep = OpAccessChain %ptr_Workgroup_uint %ptr_gep %uint_2 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, NonConstantStructSlide) { const std::string text = R"( ; CHECK: [[int0:%\w+]] = OpConstant {{%\w+}} 0 ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[ld:%\w+]] = OpLoad ; CHECK: OpPtrAccessChain {{%\w+}} [[var]] [[ld]] [[int0]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %struct = OpTypeStruct %uint %uint %ptr_Workgroup_struct = OpTypePointer Workgroup %struct %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Function_uint = OpTypePointer Function %uint %wg_var = OpVariable %ptr_Workgroup_struct Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %1 = OpLabel %func_var = OpVariable %ptr_Function_uint Function %ld = OpLoad %uint %func_var %ptr_gep = OpPtrAccessChain %ptr_Workgroup_struct %wg_var %ld %gep = OpAccessChain %ptr_Workgroup_uint %ptr_gep %uint_0 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, DontCombineNonConstantStructSlide) { const std::string text = R"( ; CHECK: [[int0:%\w+]] = OpConstant {{%\w+}} 0 ; CHECK: [[ld:%\w+]] = OpLoad ; CHECK: [[gep:%\w+]] = OpAccessChain ; CHECK: OpPtrAccessChain {{%\w+}} [[gep]] [[ld]] [[int0]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_4 = OpConstant %uint 4 %struct = OpTypeStruct %uint %uint %struct_array_4 = OpTypeArray %struct %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Function_uint = OpTypePointer Function %uint %ptr_Workgroup_struct = OpTypePointer Workgroup %struct %ptr_Workgroup_struct_array_4 = OpTypePointer Workgroup %struct_array_4 %wg_var = OpVariable %ptr_Workgroup_struct_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %1 = OpLabel %func_var = OpVariable %ptr_Function_uint Function %ld = OpLoad %uint %func_var %gep = OpAccessChain %ptr_Workgroup_struct %wg_var %uint_0 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %ld %uint_0 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, CombineNonConstantStructSlideElement) { const std::string text = R"( ; CHECK: [[int0:%\w+]] = OpConstant {{%\w+}} 0 ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[ld:%\w+]] = OpLoad ; CHECK: [[add:%\w+]] = OpIAdd {{%\w+}} [[ld]] [[ld]] ; CHECK: OpPtrAccessChain {{%\w+}} [[var]] [[add]] [[int0]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_4 = OpConstant %uint 4 %struct = OpTypeStruct %uint %uint %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Function_uint = OpTypePointer Function %uint %ptr_Workgroup_struct = OpTypePointer Workgroup %struct %wg_var = OpVariable %ptr_Workgroup_struct Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %1 = OpLabel %func_var = OpVariable %ptr_Function_uint Function %ld = OpLoad %uint %func_var %gep = OpPtrAccessChain %ptr_Workgroup_struct %wg_var %ld %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint %gep %ld %uint_0 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, PtrAccessChainFromInBoundsPtrAccessChain) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int4:%\w+]] = OpConstant [[int]] 4 ; CHECK: [[array:%\w+]] = OpTypeArray [[int]] [[int4]] ; CHECK: [[ptr_array:%\w+]] = OpTypePointer Workgroup [[array]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[int6:%\w+]] = OpConstant [[int]] 6 ; CHECK: OpPtrAccessChain [[ptr_array]] [[var]] [[int6]] OpCapability Shader OpCapability VariablePointers OpCapability Addresses OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpInBoundsPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_3 %ptr_gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, InBoundsPtrAccessChainFromPtrAccessChain) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int4:%\w+]] = OpConstant [[int]] 4 ; CHECK: [[array:%\w+]] = OpTypeArray [[int]] [[int4]] ; CHECK: [[ptr_array:%\w+]] = OpTypePointer Workgroup [[array]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[int6:%\w+]] = OpConstant [[int]] 6 ; CHECK: OpPtrAccessChain [[ptr_array]] [[var]] [[int6]] OpCapability Shader OpCapability VariablePointers OpCapability Addresses OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_3 %ptr_gep = OpInBoundsPtrAccessChain %ptr_Workgroup_uint_array_4 %gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, InBoundsPtrAccessChainFromInBoundsPtrAccessChain) { const std::string text = R"( ; CHECK: [[int:%\w+]] = OpTypeInt 32 0 ; CHECK: [[int4:%\w+]] = OpConstant [[int]] 4 ; CHECK: [[array:%\w+]] = OpTypeArray [[int]] [[int4]] ; CHECK: [[ptr_array:%\w+]] = OpTypePointer Workgroup [[array]] ; CHECK: [[var:%\w+]] = OpVariable {{%\w+}} Workgroup ; CHECK: [[int6:%\w+]] = OpConstant [[int]] 6 ; CHECK: OpInBoundsPtrAccessChain [[ptr_array]] [[var]] [[int6]] OpCapability Shader OpCapability VariablePointers OpCapability Addresses OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %main "main" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %uint_3 = OpConstant %uint 3 %uint_4 = OpConstant %uint 4 %uint_array_4 = OpTypeArray %uint %uint_4 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %ptr_Workgroup_uint_array_4 = OpTypePointer Workgroup %uint_array_4 %var = OpVariable %ptr_Workgroup_uint_array_4 Workgroup %void_func = OpTypeFunction %void %main = OpFunction %void None %void_func %main_lab = OpLabel %gep = OpInBoundsPtrAccessChain %ptr_Workgroup_uint_array_4 %var %uint_3 %ptr_gep = OpInBoundsPtrAccessChain %ptr_Workgroup_uint_array_4 %gep %uint_3 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, NoIndexAccessChains) { const std::string text = R"( ; CHECK: [[var:%\w+]] = OpVariable ; CHECK-NOT: OpConstant ; CHECK: [[gep:%\w+]] = OpAccessChain {{%\w+}} [[var]] ; CHECK: OpAccessChain {{%\w+}} [[var]] OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %func "func" %void = OpTypeVoid %uint = OpTypeInt 32 0 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %var = OpVariable %ptr_Workgroup_uint Workgroup %void_func = OpTypeFunction %void %func = OpFunction %void None %void_func %1 = OpLabel %gep1 = OpAccessChain %ptr_Workgroup_uint %var %gep2 = OpAccessChain %ptr_Workgroup_uint %gep1 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, NoIndexPtrAccessChains) { const std::string text = R"( ; CHECK: [[int0:%\w+]] = OpConstant {{%\w+}} 0 ; CHECK: [[var:%\w+]] = OpVariable ; CHECK: [[gep:%\w+]] = OpPtrAccessChain {{%\w+}} [[var]] [[int0]] ; CHECK: OpCopyObject {{%\w+}} [[gep]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %func "func" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %var = OpVariable %ptr_Workgroup_uint Workgroup %void_func = OpTypeFunction %void %func = OpFunction %void None %void_func %1 = OpLabel %gep1 = OpPtrAccessChain %ptr_Workgroup_uint %var %uint_0 %gep2 = OpAccessChain %ptr_Workgroup_uint %gep1 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, NoIndexPtrAccessChains2) { const std::string text = R"( ; CHECK: [[int0:%\w+]] = OpConstant {{%\w+}} 0 ; CHECK: [[var:%\w+]] = OpVariable ; CHECK: OpPtrAccessChain {{%\w+}} [[var]] [[int0]] OpCapability Shader OpCapability VariablePointers OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %func "func" %void = OpTypeVoid %uint = OpTypeInt 32 0 %uint_0 = OpConstant %uint 0 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %var = OpVariable %ptr_Workgroup_uint Workgroup %void_func = OpTypeFunction %void %func = OpFunction %void None %void_func %1 = OpLabel %gep1 = OpAccessChain %ptr_Workgroup_uint %var %gep2 = OpPtrAccessChain %ptr_Workgroup_uint %gep1 %uint_0 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } TEST_F(CombineAccessChainsTest, CombineMixedSign) { const std::string text = R"( ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0 ; CHECK: [[var:%\w+]] = OpVariable ; CHECK: [[uint2:%\w+]] = OpConstant [[uint]] 2 ; CHECK: OpInBoundsPtrAccessChain {{%\w+}} [[var]] [[uint2]] OpCapability Shader OpCapability VariablePointers OpCapability Addresses OpExtension "SPV_KHR_variable_pointers" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %func "func" %void = OpTypeVoid %uint = OpTypeInt 32 0 %int = OpTypeInt 32 1 %uint_1 = OpConstant %uint 1 %int_1 = OpConstant %int 1 %ptr_Workgroup_uint = OpTypePointer Workgroup %uint %var = OpVariable %ptr_Workgroup_uint Workgroup %void_func = OpTypeFunction %void %func = OpFunction %void None %void_func %1 = OpLabel %gep1 = OpInBoundsPtrAccessChain %ptr_Workgroup_uint %var %uint_1 %gep2 = OpInBoundsPtrAccessChain %ptr_Workgroup_uint %gep1 %int_1 OpReturn OpFunctionEnd )"; SinglePassRunAndMatch<CombineAccessChains>(text, true); } #endif // SPIRV_EFFCEE } // namespace } // namespace opt } // namespace spvtools
[ "romainguy@google.com" ]
romainguy@google.com
04f7231cbe02237a048c54408d5a91af92ff7247
a6f3094ac3ceab9fc5fce7de1eddd8f7b15fc5b3
/Atlas/Memory.cpp
9ceee834eb9664d7354671f9304d5450a35419d2
[]
no_license
LGSimulation/Atlas
7a1813e4816b578ff5c031c2f620ee1bd524f040
c8c0947d47f2b9c10d2284cebeece9de4231701c
refs/heads/main
2023-06-14T20:44:49.776419
2021-07-07T18:33:35
2021-07-07T18:33:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,074
cpp
#include <iostream> #include <Windows.h> #include <TlHelp32.h> #include "Memory.h" DWORD Memory::GetProcessID(const wchar_t* processName) { DWORD processID = 0; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { std::cout << "Couldn't get running processes." << std::endl; return 0; } PROCESSENTRY32 processEntry; processEntry.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(snapshot, &processEntry)) { CloseHandle(snapshot); std::cout << "Couldn't get info of processes." << std::endl; return 0; } do { if (!_wcsicmp(processEntry.szExeFile, processName)) { processID = processEntry.th32ProcessID; break; } } while (Process32Next(snapshot, &processEntry)); CloseHandle(snapshot); return processID; } DWORD Memory::GetModuleBaseAddress(DWORD processID, const wchar_t* moduleName) { DWORD moduleBaseAddress = 0; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, processID); if (snapshot == INVALID_HANDLE_VALUE) { std::cout << "Couldn't get running processes." << std::endl; return 0; } MODULEENTRY32 moduleEntry; moduleEntry.dwSize = sizeof(moduleEntry); if (!Module32First(snapshot, &moduleEntry)) { CloseHandle(snapshot); std::cout << "Couldn't get info of modules." << std::endl; return 0; } do { if (!_wcsicmp(moduleEntry.szModule, moduleName)) { moduleBaseAddress = (DWORD)moduleEntry.modBaseAddr; break; } } while (Module32Next(snapshot, &moduleEntry)); CloseHandle(snapshot); return moduleBaseAddress; } DWORD Memory::Scan(DWORD baseAddress, DWORD VFTableAddress) { SYSTEM_INFO systemInfo; DWORD pageSize; DWORD pageSize4ByteSplit; MEMORY_BASIC_INFORMATION memoryInfo; GetSystemInfo(&systemInfo); pageSize = systemInfo.dwPageSize; pageSize4ByteSplit = pageSize / 4; DWORD* buffer = new DWORD[pageSize]; for (DWORD addr = baseAddress; addr < 0x7FFFFFFF; addr += pageSize) { VirtualQueryEx(Globals::Handle, (LPCVOID)addr, &memoryInfo, pageSize); if (memoryInfo.Protect == PAGE_READWRITE) { ReadProcessMemory(Globals::Handle, (LPCVOID)addr, buffer, pageSize, 0); for (DWORD i = 0; i <= pageSize4ByteSplit; i++) { if (buffer[i] == VFTableAddress) { delete[] buffer; return (DWORD)(addr + (i * 4)); } } } } delete[] buffer; return 0; } DWORD Memory::GetPointerAddress(DWORD address) { DWORD pointerAddress = GetDMAAddress(address, { 0x0 }); return pointerAddress; } DWORD Memory::GetDMAAddress(DWORD pointer, std::vector<unsigned int> offsets) { DWORD address = pointer; for (unsigned int i = 0; i < offsets.size(); ++i) { address = Read<DWORD>((LPCVOID)address); address += offsets[i]; } return address; } std::string Memory::ReadStringOfUnknownLength(DWORD address) { std::string string; char character = 0; int charSize = sizeof(character); int offset = 0; while (true) { character = Read<char>((LPCVOID)(address + offset)); if (character == 0) break; offset += charSize; string.push_back(character); } return string; }
[ "mmdeen133@gmail.com" ]
mmdeen133@gmail.com
e154410887af2f2471287c2be82cebec7c685a4b
324822e2e779e3078e199b028736121cb8b254e2
/13.27/hasptr.cpp
934bf7862c7a8271f26714ea253174cfca3fc12d
[]
no_license
shidenggui/cplusplusprimer-answer
495bd22e7b4eb5f404c728bc9bafee8b077f8d10
f9c779ccfb57b94673c3aded4f65b91dd232610f
refs/heads/master
2020-05-30T14:33:39.618811
2015-01-24T09:25:48
2015-01-24T09:25:48
28,441,523
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
#include "hasptr.h" inline HasPtr::HasPtr(const string &s): ps(new string(s)), i(0), use(new size_t(1)){} inline HasPtr::HasPtr(const HasPtr &p): ps(p.ps), i(p.i), use(p.use){ ++*use; } HasPtr& HasPtr::operator=(const HasPtr& rhs){ ++*rhs.use; if(--*use == 0){ delete ps; delete use; } ps = rhs.ps; i = rhs.i; use = rhs.use; return *this; } HasPtr::~HasPtr(){ if(--*use == 0){ delete ps; delete use; } }
[ "903618848@qq.com" ]
903618848@qq.com
091cb565abe1a42fee8b20e00ca205aa174793b9
133b698e857e319d8f18be82c8b06c855dfbb98e
/back-end/PI4_Code/rpidmx512/lib-rdm/include/rdmdevicestore.h
ad973199d1dd107961874116fe92e5dce5b8eedf
[]
no_license
danielgonzalez3/CPE190
b8ed990c3451f03a7117ce5e241b0d2d53d6a415
00db90fa9a0b32856e3f5c5c052c1a8b1d0c5f5c
refs/heads/master
2023-04-14T17:43:03.591032
2021-04-26T20:06:23
2021-04-26T20:06:23
280,779,350
2
2
null
2020-08-31T21:34:25
2020-07-19T02:50:05
HTML
UTF-8
C++
false
false
1,422
h
/** * @file rdmdevicestore.h * */ /* Copyright (C) 2019-2020 by Arjan van Vught mailto:info@orangepi-dmx.nl * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef RDMDEVICESTORE_H_ #define RDMDEVICESTORE_H_ #include <stdint.h> class RDMDeviceStore { public: virtual ~RDMDeviceStore() {} virtual void SaveLabel(const char *pLabel, uint8_t nLength)=0; }; #endif /* RDMDEVICESTORE_H_ */
[ "danielgonzalez3@csus.edu" ]
danielgonzalez3@csus.edu
e26d69340f0262ee2fa62248041b3b9eab140054
b381bdb887487178bc095626c20be2426f3720c3
/Projekt/Mateusz/znajdz_polaczenia_miedzy_funkcjami.cpp
caf68c2375339a550944b56f3e7bcf7ab6bc97f1
[]
no_license
pazindorb/Projekt_Graf_v2.5
07efe18ff1d2f16bf22d651e63f779634fc97ad0
eea1d199aa6094aaf7d7b31c13e02bc40554ff2e
refs/heads/master
2023-05-12T18:02:00.409000
2021-05-28T15:04:03
2021-05-28T15:04:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,325
cpp
#pragma once #include "..\Graf.h" #include <iostream> #include <fstream> #include <string> using namespace std; void graf::Graf::znajdz_polaczenia_miedzy_funkcjami() { for (auto& _aktualny_plik : pliki) { if (_aktualny_plik.nazwa_pliku.find(".h") == std::string::npos){ for (auto& _funkcja_w_pliku : _aktualny_plik.funkcje) { for (auto& _sprawdzana_fun : wszystkie_funkcje_we_wszystkich_plikach) { if (_funkcja_w_pliku.nazwa_funkcji != _sprawdzana_fun.nazwa_funkcji) { std::fstream otwarty_plik; otwarty_plik.open("..\\temp\\" + _aktualny_plik.nazwa_pliku, std::ios::in); _funkcja_w_pliku.znajdz_polaczone_funkcje(_sprawdzana_fun, otwarty_plik); otwarty_plik.close(); } } } } /*for (int i = 0; i < pliki[aktualny_plik].funkcje[0].polaczenia_miedzy_funkcjami.size(); i++) { std::cout << pliki[aktualny_plik].funkcje[i].polaczenia_miedzy_funkcjami[0].nazwa_polaczonego_elementu << std::endl; }*/ for (const auto& _fun_plik : _aktualny_plik.funkcje) { if (_aktualny_plik.nazwa_pliku.find(".h") == std::string::npos) { for (auto& _wsz_fun : wszystkie_funkcje_we_wszystkich_plikach) { if (_fun_plik.nazwa_funkcji == _wsz_fun.nazwa_funkcji) { _wsz_fun.polaczenia_miedzy_funkcjami = _fun_plik.polaczenia_miedzy_funkcjami; } } } } } }
[ "xxpazindorxx@gmial.com" ]
xxpazindorxx@gmial.com
47c3f2fb516b10ae0283fc75012ed26a82fda70b
c342a474e91c4b11194f984d9e16ae25e481f645
/src/Classes/Engine.cpp
83bf30e2e330667e7ecae42fcf3fcc9a97002066
[]
no_license
Kloox/ft_vox_42
094f7d8272af8584b2331d8aa0511838b2a166b8
71d3c3db80d49f7aa2b440dc259a1713e596400f
refs/heads/master
2023-03-25T22:06:43.327791
2021-03-25T17:03:10
2021-03-25T17:03:10
347,616,564
0
0
null
null
null
null
UTF-8
C++
false
false
36,823
cpp
#include "vox.hpp" #include "Cpu.hpp" Engine::Engine(void) { this->world = NULL; this->next_world = NULL; this->noiser = NULL; // GL states this->ogl_state.program = 0; this->ogl_state.attribute_coord = 0; this->ogl_state.attribute_sky_coord = 0; this->ogl_state.t_vbo = 0; this->ogl_state.t_vao = 0; this->ogl_state.sky_vao = 0; this->ogl_state.sky_vbo = 0; this->ogl_state.uniform_mvp = 0; this->ogl_state.cursor_vbo = 0; this->ogl_state.uniform_texture = 0; this->ogl_state.attribute_sky_coord = 0; this->ogl_state.texture = 0; this->ogl_state.skybox_cubemap = 0; // Libs class this->sound = irrklang::createIrrKlangDevice(); // Engine states this->state.volume = 0.4f; this->state.i_display = 0; this->state.anchor_cam = false; this->state.loading = true; this->state.threads = std::thread::hardware_concurrency(); this->state.precompute_timer = 0; this->state.timebase = 0; this->state.doSwap = false; this->state.debug_show = 0; this->state.worker = false; this->state.verbose = false; this->state.focus_on_transparent = false; this->state.speedmult = 0; this->state.collision = true; this->state.warp = false; this->state.exiting = false; //world size this->scx = 64; this->scy = 8; this->scz = 64; this->scxf = 64.0f; this->scyf = 8.0f; this->sczf = 64.0f; // debug this->elements_world_one = 0; this->elements_world_two = 0; // Hook state this->shift = false; this->keys = 0; this->autowalk = false; this->infinite = true; this->mousespeed = 0.001; this->focus = 9999; // Precompute state this->computing = false; this->chunk_index = new int[3]; this->new_center = new int[3]; this->barrier = 0; this->edit_size = 0; // Engine graphics states this->g_state.window = 0; this->g_state.ww = RES_X; this->g_state.wh = RES_Y; this->g_state.aa = false; this->g_state.vsync = true; this->g_state.transparency = true; this->g_state.fov = glm::radians(80.0f); this->g_state.frame = 0; this->g_state.fullscreen = false; this->g_state.framerate = 10000; this->g_state.maxi = 2; this->g_state.renderDistance = 15; this->g_state.target_fps = 0; this->g_state.fpsToShow = 0; int k = 0; glutInit(&k, NULL); } Engine::~Engine(void) { delete[] this->chunk_index; delete[] this->new_center; delete this->noiser; glDeleteTextures(1, &(this->ogl_state.texture)); if (this->sound) this->sound->drop(); glutDestroyWindow(this->g_state.window); glDeleteProgram(this->ogl_state.program); } int Engine::init_glew(void) { if (this->g_state.vsync) putenv( (char *) "__GL_SYNC_TO_VBLANK=1" ); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(this->g_state.ww, this->g_state.wh); this->g_state.window = glutCreateWindow("ft_vox - jjaouen & drimo"); glewExperimental = GL_TRUE; GLenum glew_status = glewInit(); if (this->g_state.fullscreen) glutFullScreen(); if (GLEW_OK != glew_status) { fprintf(stderr, "Error: %s\n", glewGetErrorString(glew_status)); return 1; } if (!GLEW_VERSION_4_6) { fprintf(stderr, "Warning: No support for OpenGL 4.6 found."); if (!GLEW_VERSION_4_0) { fprintf(stderr, "Warning: No support for OpenGL 4.0 found\n"); if (!GLEW_VERSION_3_3) { fprintf(stderr, "Warning: No support for OpenGL 3.3 found\n"); if (!GLEW_VERSION_3_0) { fprintf(stderr, "Warning: No support for OpenGL 3.0 found\n"); if (!GLEW_VERSION_2_0) { fprintf(stderr, "Fatal Error: No support for OpenGL 2.0 found\n"); return 1; } } } } } if (this->state.verbose) { int major; int minor; CPUInfo cpu; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); fprintf(stderr, "CPU: %s\nCPU Specs: %d Core(s) %d Thread(s)\n", cpu.model().c_str(), cpu.cores(), cpu.logicalCpus()); fprintf(stderr, "Renderer: %s\nVendor : %s\n", glGetString(GL_VENDOR), glGetString(GL_RENDERER)); fprintf(stderr, "OpenGL Version: %s\nShaders Version: %s\nGLEW Version: %d.%d\n", glGetString(GL_VERSION), this->state.shader_version, GLEW_VERSION_MAJOR, GLEW_VERSION_MAJOR); } return 0; } void Engine::load_world_texture(void) { glGenTextures(1, &(this->ogl_state.texture)); glBindTexture(GL_TEXTURE_2D, this->ogl_state.texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textures.width, textures.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textures.pixel_data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glGenerateMipmap(GL_TEXTURE_2D); } unsigned int Engine::load_skybox(void) { float skybox_vertices[] = { // positions -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f}; // Create VAO/VBO for skybox glGenVertexArrays(1, &(this->ogl_state.sky_vao)); glGenBuffers(1, &(this->ogl_state.sky_vbo)); glBindVertexArray(this->ogl_state.sky_vao); glBindBuffer(GL_ARRAY_BUFFER, this->ogl_state.sky_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(skybox_vertices), &skybox_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); glUniform1i(glGetUniformLocation(this->ogl_state.program, "skybox"), 2); // create Skybox texture glGenTextures(1, &(this->ogl_state.skybox_cubemap)); glBindTexture(GL_TEXTURE_CUBE_MAP, this->ogl_state.skybox_cubemap); // RIGHT glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 0, 0, GL_RGB, skyboxRight.width, skyboxRight.height, 0, GL_RGB, GL_UNSIGNED_BYTE, skyboxRight.pixel_data); // LEFT glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 1, 0, GL_RGB, skyboxLeft.width, skyboxLeft.height, 0, GL_RGB, GL_UNSIGNED_BYTE, skyboxLeft.pixel_data); // TOP glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 2, 0, GL_RGB, skyboxTop.width, skyboxTop.height, 0, GL_RGB, GL_UNSIGNED_BYTE, skyboxTop.pixel_data); // BOTTOM glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 3, 0, GL_RGB, skyboxBottom.width, skyboxBottom.height, 0, GL_RGB, GL_UNSIGNED_BYTE, skyboxBottom.pixel_data); // FRONT glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 4, 0, GL_RGB, skyboxFront.width, skyboxFront.height, 0, GL_RGB, GL_UNSIGNED_BYTE, skyboxFront.pixel_data); // BACK glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 5, 0, GL_RGB, skyboxBack.width, skyboxBack.height, 0, GL_RGB, GL_UNSIGNED_BYTE, skyboxBack.pixel_data); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return this->ogl_state.skybox_cubemap; } void Engine::RenderText(std::string text, float x, float y, float scale, glm::vec3 color) { glm::mat4 mvp = glm::ortho(0.0f, static_cast<float>(this->g_state.ww), 0.0f, static_cast<float>(this->g_state.wh)); glUniformMatrix4fv(this->ogl_state.uniform_mvp, 1, GL_FALSE, glm::value_ptr(mvp)); // activate corresponding render state glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUniform1i(glGetUniformLocation(this->ogl_state.program, "text_render"), 1); glUniform3f(glGetUniformLocation(this->ogl_state.program, "textColor"), color.x, color.y, color.z); glBindVertexArray(this->ogl_state.t_vao); // iterate through all characters std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { Character ch = Characters[*c]; float xpos = x + ch.Bearing.x * scale; float ypos = y - (ch.Size.y - ch.Bearing.y) * scale; float w = ch.Size.x * scale; float h = ch.Size.y * scale; // update VBO for each character float vertices[6][4] = { {xpos, ypos + h, 0.0f, 0.0f}, {xpos, ypos, 0.0f, 1.0f}, {xpos + w, ypos, 1.0f, 1.0f}, {xpos, ypos + h, 0.0f, 0.0f}, {xpos + w, ypos, 1.0f, 1.0f}, {xpos + w, ypos + h, 1.0f, 0.0f}}; // render glyph texture over quad glBindTexture(GL_TEXTURE_2D, ch.TextureID); glBindBuffer(GL_ARRAY_BUFFER, this->ogl_state.t_vao); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); glBindBuffer(GL_ARRAY_BUFFER, 0); glDrawArrays(GL_TRIANGLES, 0, 6); // now advance cursors for next glyph (note that advance is number of 1/64 pixels) x += (ch.Advance >> 6) * scale; // bitshift by 6 to get value in pixels (2^6 = 64 (divide amount of 1/64th pixels by 64 to get amount of pixels)) } glUniform1i(glGetUniformLocation(this->ogl_state.program, "text_render"), 0); glDisable(GL_BLEND); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, this->ogl_state.texture); } void Engine::draw_loading_screen(std::string str, bool clear) { static int c; static int t = glutGet(GLUT_ELAPSED_TIME); int x, y; x = this->g_state.ww / 2 - 48; y = this->g_state.wh / 2; int ct = glutGet(GLUT_ELAPSED_TIME); if (ct - t > 200) { c++; if (c > 2) c = 0; t = ct; } if (clear) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (c == 0) RenderText(str + ".", x, y, 1.0, glm::vec3(0.0f, 0.0f, 0.0f)); else if (c == 1) RenderText(str + "..", x, y, 1.0, glm::vec3(0.0f, 0.0f, 0.0f)); else if (c == 2) { RenderText(str + "...", x, y, 1.0, glm::vec3(0.0f, 0.0f, 0.0f)); } if (clear) glutSwapBuffers(); } int Engine::get_framerate(void) { this->g_state.frame++; int time; time = glutGet(GLUT_ELAPSED_TIME); int fps = 0; if (time - this->state.timebase > 1000) { fps = this->g_state.frame * 1000.0 / (time - this->state.timebase); this->state.timebase = time; this->g_state.frame = 0; } return fps; } void Engine::apply_collision(glm::vec3 lastP) { int x = floorf(this->world->position.x); int y = floorf(this->world->position.y); int z = floorf(this->world->position.z); uint8_t block = this->world->getChunk(x, y, z); if (block != 0 && block != 8) { int mx = floorf(lastP.x); int my = floorf(lastP.y); int mz = floorf(lastP.z); if (y - my == 1 || y - my == -1) { this->world->position.y = lastP.y; this->apply_collision(lastP); return; } if (x - mx == 1 || x - mx == -1) { this->world->position.x = lastP.x; this->apply_collision(lastP); return; } if (z - mz == 1 || z - mz == -1) { this->world->position.z = lastP.z; this->apply_collision(lastP); return; } } } void Engine::draw_hud(glm::mat4 &mvp, bool draw) { /* Very naive ray casting algorithm to find out which block we are looking at */ glm::vec3 testpos = this->world->position; glm::vec3 prevpos = this->world->position; for (int i = 0; i < RAYCAST_LENGTH; i++) { /* Advance from our currect position to the direction we are looking at, in small steps */ prevpos = testpos; testpos += this->world->lookat * 0.1f; this->world->mx = floorf(testpos.x); this->world->my = floorf(testpos.y); this->world->mz = floorf(testpos.z); uint8_t block = this->world->getChunk(this->world->mx, this->world->my, this->world->mz); if (!(this->state.focus_on_transparent) && (block == 8 || block == 9)) continue; /* If we find a block that is not air or unrange, we are done */ if (this->world->mx > (this->scx * CX) / 2 || this->world->mx < ((this->scx * CX) / 2) * -1 || this->world->mz > (this->scz * CZ) / 2 || this->world->mz < ((this->scz * CZ) / 2) * -1 || this->world->my > (this->scy * CY) / 2 || this->world->my < ((this->scy * CY) / 2) * -1) continue; if (block) break; } /* Find out which face of the block we are looking at */ int px = floorf(prevpos.x); int py = floorf(prevpos.y); int pz = floorf(prevpos.z); if (px > this->world->mx) this->world->face = 0; else if (px < this->world->mx) this->world->face = 3; else if (py > this->world->my) this->world->face = 1; else if (py < this->world->my) this->world->face = 4; else if (pz > this->world->mz) this->world->face = 2; else if (pz < this->world->mz) this->world->face = 5; /* If we are looking at air, move the cursor out of sight */ if (!this->world->getChunk(this->world->mx, this->world->my, this->world->mz)) this->world->mx = this->world->my = this->world->mz = 99999; float bx = this->world->mx; float by = this->world->my; float bz = this->world->mz; float distance = glm::length(testpos - this->world->position); if (distance > 100) distance = 100; /* Change the eye's focus distance smoothly */ if (this->focus / 1.01 > distance) this->focus /= 1.01; else if (this->focus * 1.01 < distance) this->focus *= 1.01; /* Render a box around the block we are pointing at */ float box[24][4] = { {bx + 0, by + 0, bz + 0, 14}, {bx + 1, by + 0, bz + 0, 14}, {bx + 0, by + 1, bz + 0, 14}, {bx + 1, by + 1, bz + 0, 14}, {bx + 0, by + 0, bz + 1, 14}, {bx + 1, by + 0, bz + 1, 14}, {bx + 0, by + 1, bz + 1, 14}, {bx + 1, by + 1, bz + 1, 14}, {bx + 0, by + 0, bz + 0, 14}, {bx + 0, by + 1, bz + 0, 14}, {bx + 1, by + 0, bz + 0, 14}, {bx + 1, by + 1, bz + 0, 14}, {bx + 0, by + 0, bz + 1, 14}, {bx + 0, by + 1, bz + 1, 14}, {bx + 1, by + 0, bz + 1, 14}, {bx + 1, by + 1, bz + 1, 14}, {bx + 0, by + 0, bz + 0, 14}, {bx + 0, by + 0, bz + 1, 14}, {bx + 1, by + 0, bz + 0, 14}, {bx + 1, by + 0, bz + 1, 14}, {bx + 0, by + 1, bz + 0, 14}, {bx + 0, by + 1, bz + 1, 14}, {bx + 1, by + 1, bz + 0, 14}, {bx + 1, by + 1, bz + 1, 14}, }; glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_CULL_FACE); glUniformMatrix4fv(this->ogl_state.uniform_mvp, 1, GL_FALSE, glm::value_ptr(mvp)); glBindBuffer(GL_ARRAY_BUFFER, this->ogl_state.cursor_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof box, box, GL_DYNAMIC_DRAW); glVertexAttribPointer(this->ogl_state.attribute_coord, 4, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_LINES, 0, 36); /* Draw a cross in the center of the screen */ float cross[4][4] = { {-0.05, 0, 0, 13}, {+0.05, 0, 0, 13}, {0, -0.05, 0, 13}, {0, +0.05, 0, 13}, }; glDisable(GL_DEPTH_TEST); glm::mat4 one(1); glUniformMatrix4fv(this->ogl_state.uniform_mvp, 1, GL_FALSE, glm::value_ptr(one)); glBindBuffer(GL_ARRAY_BUFFER, this->ogl_state.cursor_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof cross, cross, GL_DYNAMIC_DRAW); glVertexAttribPointer(this->ogl_state.attribute_coord, 4, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_LINES, 0, 36); if (this->state.debug_show) this->draw_debug(draw); } debug_value Engine::update_debug_values(bool draw, int init) { static debug_value vles; // Const str if (!init) { vles.color = glm::vec3(1.0f, 1.0f, 1.0f); vles.wp = std::string("World Position:"); vles.wcp = std::string("World Chunk Position"); vles.lp = std::string("Local Position"); vles.lcp = std::string("Local Chunk Position:"); vles.vs = this->g_state.vsync ? vles.vs = std::string("Vsync: true") : vles.vs = std::string("Vsync: false"); } if (!draw && init) return vles; // Fps counter this->set_debug_world_size(); vles.fps = std::string("FPS: " + std::to_string(this->g_state.fpsToShow) + " | Memory usage: " + std::to_string(get_mem_usage()) + "M"); if (this->state.debug_show > 1) // Display info { vles.rd = std::string("Render Distance: " + std::to_string(this->g_state.renderDistance)); vles.ft = this->g_state.target_fps ? std::string("Framerate target: " + std::to_string(this->g_state.target_fps) + " (" + std::to_string(this->g_state.framerate) + ")") : std::string("Framerate target: No limit"); vles.sampling = std::string("Sampling: " + std::to_string(this->g_state.maxi)); vles.aa = this->g_state.aa ? std::string("Antialiasing: true") : std::string("Antialiasing: false"); } if (this->state.debug_show > 2) // Precomputing info { vles.infinite = this->infinite ? std::string("Infinite world (" + std::to_string(this->scx) + "x" + std::to_string(this->scy) + "x" + std::to_string(this->scz) + "): true") : std::string("Infinite world (" + std::to_string(this->scx) + "x" + std::to_string(this->scy) + "x" + std::to_string(this->scz) + "): false"); vles.barrierl = std::string("Barrier limit: " + std::to_string(this->barrier) + " chunks"); vles.lpt = std::string("Last precompute timer (" + std::to_string(this->state.threads) + " threads): " + std::to_string(this->state.precompute_timer) + "ms"); vles.cxn = this->computing ? std::string("Computing next world: true") : std::string("Computing next world: false"); } if (this->state.debug_show > 3) // Positions & Cam info { vles.wpp = std::string("X: " + std::to_string(this->world->position.x + ((this->world->shiftX) * 16.0f)) + " Y: " + std::to_string(this->world->position.y) + " Z: " + std::to_string(this->world->position.z + ((this->world->shiftZ) * 16.0f))); glm::vec3 pos_chunk = this->get_chunk_position(this->world->position); vles.wcpp = std::string("X: " + std::to_string(int(pos_chunk.x) + this->world->shiftX) + " Y: " + std::to_string(int(pos_chunk.y)) + " Z: " + std::to_string(int(pos_chunk.z) + this->world->shiftZ)); vles.lpp = std::string("X: " + std::to_string(this->world->position.x) + " Y: " + std::to_string(this->world->position.y) + " Z: " + std::to_string(this->world->position.z)); vles.lcpp = std::string("X: " + std::to_string(int(pos_chunk.x)) + " Y: " + std::to_string(int(pos_chunk.y)) + " Z: " + std::to_string(int(pos_chunk.z))), vles.forward = std::string("Forward: X: " + std::to_string(this->world->forward.x) + " Y: " + std::to_string(this->world->forward.y) + " Z: " + std::to_string(this->world->forward.z)); vles.right = std::string("Right: X: " + std::to_string(this->world->right.x) + " Y: " + std::to_string(this->world->right.y) + " Z: " + std::to_string(this->world->right.z)); vles.up = std::string("Up: X: " + std::to_string(this->world->up.x) + " Y: " + std::to_string(this->world->up.y) + " Z: " + std::to_string(this->world->up.z)); vles.lookat = std::string("LookAt: X: " + std::to_string(this->world->lookat.x) + " Y: " + std::to_string(this->world->lookat.y) + " Z: " + std::to_string(this->world->lookat.z)); vles.angle = std::string("Angle: X: " + std::to_string(this->world->angle.x) + " Y: " + std::to_string(this->world->angle.y) + " Z: " + std::to_string(this->world->angle.z)); if (this->world->angle.x < 0.75 && this->world->angle.x > -0.75) vles.facing = std::string("Facing: North"); else if (this->world->angle.x > 0.75 && this->world->angle.x < 2.25) vles.facing = std::string("Facing: West"); else if (this->world->angle.x < -0.75 && this->world->angle.x > -2.25) vles.facing = std::string("Facing: East"); else vles.facing = std::string("Facing: South"); vles.velocity = std::string("Max velocity: " + std::to_string(int((this->state.speedmult + PLAYER_SPEED) * PLAYER_SPRINT_SPEED_MULT)) + " ((" + std::to_string(PLAYER_SPEED) + " + " + std::to_string(this->state.speedmult)) + ") * " + std::to_string(int(PLAYER_SPRINT_SPEED_MULT)) + ")"; } return vles; } void Engine::draw_debug(bool draw) { debug_value vles; static int init = 0; vles = this->update_debug_values(draw, init); if (!init) init++; // Fps counter this->RenderText(vles.fps, 5, this->g_state.wh - 24, 1.0, vles.color); if (this->state.debug_show == 1) return; if (this->state.debug_show > 1) // Display info { // Vsync this->RenderText(vles.vs, 5, 5, 1.0, vles.color); // Anti aliasing this->RenderText(vles.aa, 5, 24, 1.0, vles.color); // Sampling this->RenderText(vles.sampling, 5, 48, 1.0, vles.color); // Fps Target this->RenderText(vles.ft, 5, 72, 1.0, vles.color); // Render Distance this->RenderText(vles.rd, 5, 96, 1.0, vles.color); } if (this->state.debug_show > 2) // Precomputing info { // Compute next world bool this->RenderText(vles.cxn, 5, 144, 1.0, vles.color); // Last precompute timer this->RenderText(vles.lpt, 5, 168, 1.0, vles.color); // Barrier info this->RenderText(vles.barrierl, 5, 192, 1.0, vles.color); // infinite bool this->RenderText(vles.infinite, 5, 216, 1.0, vles.color); } if (this->state.debug_show > 3) // Positions & cam info { // World Position str this->RenderText(vles.wp, 5, this->g_state.wh - 48, 1.0, vles.color); // World Positions this->RenderText(vles.wpp, 5, this->g_state.wh - 72, 1.0, vles.color); // World Chunk pos str this->RenderText(vles.wcp, 5, this->g_state.wh - 96, 1.0, vles.color); // World Chunk positions this->RenderText(vles.wcpp, 5, this->g_state.wh - 120, 1.0, vles.color); // Local pos str this->RenderText(vles.lp, 5, this->g_state.wh - 144, 1.0, vles.color); // Local Positions this->RenderText(vles.lpp, 5, this->g_state.wh - 168, 1.0, vles.color); // Local Chunk pos str this->RenderText(vles.lcp, 5, this->g_state.wh - 192, 1.0, vles.color); // Local Chunk Positions this->RenderText(vles.lcpp, 5, this->g_state.wh - 214, 1.0, vles.color); // Forward this->RenderText(vles.forward, 5, this->g_state.wh - 238, 1.0, vles.color); // Right this->RenderText(vles.right, 5, this->g_state.wh - 262, 1.0, vles.color); // Up this->RenderText(vles.up, 5, this->g_state.wh - 286, 1.0, vles.color); // LookAt this->RenderText(vles.lookat, 5, this->g_state.wh - 310, 1.0, vles.color); // Angle this->RenderText(vles.angle, 5, this->g_state.wh - 334, 1.0, vles.color); // Facing this->RenderText(vles.facing, 5, this->g_state.wh - 358, 1.0, vles.color); // Max velocity this->RenderText(vles.velocity, 5, this->g_state.wh - 382, 1.0, vles.color); } } void Engine::draw_scene(glm::mat4 &mvp, glm::mat4 &view, glm::mat4 &projection, bool draw) { glEnable(GL_DEPTH_TEST); glEnable(GL_POLYGON_OFFSET_FILL); glEnable(GL_CULL_FACE); this->render_skybox(view, projection); this->world->render(mvp, this->g_state.renderDistance, this->ogl_state.uniform_mvp); /* Then draw HUD */ this->draw_hud(mvp, draw); if (this->state.exiting) this->draw_loading_screen(std::string("Exiting"), false); } bool Engine::display_frame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Calculate the translation matrix used for anti-aliasing */ glm::mat4 aamat(1.0f); if (this->g_state.aa) aamat = glm::translate(aamat, glm::vec3((float)(this->state.i_display % 4) / (4 * this->g_state.ww), (float)(this->state.i_display / 4) / (4 * this->g_state.wh), 0.0f)); /* If transparency is enabled, we use a different alpha cutoff for every frame */ float alpha = 0.5; if (this->g_state.transparency) alpha = this->state.cutoff[this->state.i_display]; glUniform1f(this->ogl_state.attribute_sky_coord, alpha); /* Calculate the MVP matrix */ glm::mat4 view = glm::lookAt(this->world->position, this->world->position + this->world->lookat * this->focus, this->world->up); glm::mat4 projection = glm::perspective(this->g_state.fov, 1.0f * this->g_state.ww / this->g_state.wh, 0.01f, 1000.0f); glm::mat4 mvp = aamat * projection * view; glUniformMatrix4fv(this->ogl_state.uniform_mvp, 1, GL_FALSE, glm::value_ptr(mvp)); this->draw_scene(mvp, view, projection, (this->state.i_display + 1) >= this->g_state.maxi ? true : false); glAccum(this->state.i_display ? GL_ACCUM : GL_LOAD, 1.0 / this->g_state.maxi); /* And we are done */ this->state.i_display++; if (this->state.i_display >= this->g_state.maxi) { int f = this->get_framerate(); if (f) { this->g_state.fpsToShow = f; } glAccum(GL_RETURN, 1); glutSwapBuffers(); this->state.i_display = 0; } return this->state.i_display; } void Engine::render_skybox(glm::mat4 &view, glm::mat4 &projection) { glUniform1i(glGetUniformLocation(this->ogl_state.program, "text_render"), 2); glDepthMask(GL_FALSE); glm::mat4 skybox_mvp = projection * glm::mat4(glm::mat3(view)); glUniformMatrix4fv(glGetUniformLocation(this->ogl_state.program, "sky_mvp"), 1, GL_FALSE, glm::value_ptr(skybox_mvp)); // skybox cube glBindVertexArray(this->ogl_state.sky_vao); glBindBuffer(GL_ARRAY_BUFFER, this->ogl_state.sky_vbo); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_CUBE_MAP, this->ogl_state.skybox_cubemap); glDrawArrays(GL_TRIANGLES, 0, 36); glUniform1i(glGetUniformLocation(this->ogl_state.program, "text_render"), 0); // RESET GL states glDepthMask(GL_TRUE); glBindVertexArray(0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->ogl_state.texture); } void Engine::move(float movespeed) { static int pt = 0; if (this->shift) movespeed *= PLAYER_SPRINT_SPEED_MULT; int t = glutGet(GLUT_ELAPSED_TIME); float dt = (t - pt) * 1.0e-3; pt = t; glm::vec3 lastP = this->world->position; if (this->keys & 1) this->world->position -= this->world->right * movespeed * dt; if (this->keys & 2) this->world->position += this->world->right * movespeed * dt; if (this->keys & 4) { this->world->position += (this->world->forward) * movespeed * dt; this->world->position.y += (this->world->angle.y) * movespeed * dt; } if (this->keys & 8) { this->world->position -= (this->world->forward) * movespeed * dt; this->world->position.y -= (this->world->angle.y) * movespeed * dt; } if (this->keys & 16) { this->world->position.y += movespeed * dt; } if (this->keys & 32) { this->world->position.y -= movespeed * dt; } if (this->state.collision && lastP != this->world->position) this->apply_collision(lastP); } void Engine::init_freetype_chars(void) { glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(this->g_state.ww), 0.0f, static_cast<GLfloat>(this->g_state.wh)); glUseProgram(this->ogl_state.program); glUniformMatrix4fv(glGetUniformLocation(this->ogl_state.program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); if (FT_Init_FreeType(&freetypeLib)) std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl; if (FT_New_Face(freetypeLib, FONT_PATH, 0, &face)) std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl; FT_Set_Pixel_Sizes(face, 0, 24); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); for (GLubyte c = 0; c < 128; c++) { if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl; continue; } GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); Character character = { tex, glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows), glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top), static_cast<unsigned int>(face->glyph->advance.x)}; Characters.insert(std::pair<GLchar, Character>(c, character)); } glBindTexture(GL_TEXTURE_2D, 0); FT_Done_Face(face); FT_Done_FreeType(freetypeLib); glGenVertexArrays(1, &(this->ogl_state.t_vao)); glGenBuffers(1, &(this->ogl_state.t_vbo)); glBindVertexArray(this->ogl_state.t_vao); glBindBuffer(GL_ARRAY_BUFFER, this->ogl_state.t_vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void Engine::noise_and_update_all(World *world, bool doBind) { int start = glutGet(GLUT_ELAPSED_TIME); if (this->state.threads == 0) world->noise_all(); else world->noise_all_multithread(this->state.threads); int noise_ok = glutGet(GLUT_ELAPSED_TIME); int create_ok = glutGet(GLUT_ELAPSED_TIME); world->update_all_multithread(false, this->state.threads); int start_bind = glutGet(GLUT_ELAPSED_TIME); if (doBind) world->bind_all_buffers(); int end_bind = glutGet(GLUT_ELAPSED_TIME); int final = glutGet(GLUT_ELAPSED_TIME); if (this->state.verbose) fprintf(stderr, "Loading time (%dx%dx%d - %d threads - Infinite world: %s) : %dms\nNoise: %dms\nCreate buffers: %dms\nUpdate: %dms\nBind: %dms\n", this->scx, this->scy, this->scz, this->state.threads, this->infinite ? "True" : "False", final - start, noise_ok - start, create_ok - noise_ok, final - noise_ok, end_bind - start_bind); else fprintf(stderr, "Loading time (%dx%dx%d): %dms\n", this->scx, this->scy, this->scz, final - start); if (this->barrier == 0) this->set_limit_by_time(final - start); } void Engine::load_ressources(void) { this->world->update_vectors(); this->noise_and_update_all(this->world, false); if (this->state.exiting) { this->state.loading = false; return; } this->next_world->update_vectors(); this->noise_and_update_all(this->next_world, false); this->next_world->copy_world(this->world); this->state.loading = false; } int Engine::init_resources(void) { this->ogl_state.program = create_program("shaders/ft_vox.v.glsl", "shaders/ft_vox.f.glsl"); if (this->ogl_state.program == 0) return 0; this->init_freetype_chars(); this->ogl_state.attribute_coord = get_attrib(this->ogl_state.program, "coord"); this->ogl_state.uniform_mvp = get_uniform(this->ogl_state.program, "mvp"); this->ogl_state.attribute_sky_coord = get_uniform(this->ogl_state.program, "alpha"); this->ogl_state.uniform_texture = get_uniform(this->ogl_state.program, "texture_2d"); if (this->ogl_state.attribute_coord == -1 || this->ogl_state.attribute_sky_coord == -1 || this->ogl_state.uniform_mvp == -1 || this->ogl_state.attribute_sky_coord == -1 || this->ogl_state.uniform_texture == -1) return 0; /* Upload the texture */ this->load_world_texture(); this->load_skybox(); /* Create worlds */ if (this->noiser == NULL) { this->noiser = new Noiser; this->noiser->set_seed(SEED); this->noiser->create_seed(); } this->world = new World; this->world->create_all_buffers(); this->next_world = new World; this->next_world->create_all_buffers(); std::thread loader(&Engine::load_ressources, this); loader.detach(); glGenBuffers(1, &(this->ogl_state.cursor_vbo)); glUseProgram(this->ogl_state.program); glEnableVertexAttribArray(this->ogl_state.attribute_coord); glPolygonOffset(1, 1); glClearColor(0.6, 0.8, 1.0, 0.0); return 1; } glm::vec3 Engine::get_chunk_position(glm::vec3 position) { return glm::vec3( (((this->scxf * CXF) / 2.0f + position.x) / CX), (((this->scyf * CYF) / 2.0f + position.y) / CY), (((this->sczf * CZF) / 2.0f + position.z) / CZ)); } void Engine::set_chunk_index_by_pos(glm::vec3 pos) { glm::vec3 index = this->get_chunk_position(pos); this->chunk_index[0] = static_cast<int>(index.x); this->chunk_index[1] = static_cast<int>(index.y); this->chunk_index[2] = static_cast<int>(index.z); } void Engine::print_false_enable(void) { for (int x = 0; x < this->scx; x++) for (int y = 0; y < this->scy; y++) for (int z = 0; z < this->scz; z++) { if (this->world->c[x][y][z]->enable == false) fprintf(stderr, "Chunk (%d %d %d) enable == false\n", x, y, z); } for (int x = 0; x < this->scx; x++) for (int y = 0; y < this->scy; y++) for (int z = 0; z < this->scz; z++) { if (this->next_world->c[x][y][z]->enable == false) fprintf(stderr, "Next Chunk (%d %d %d) enable == false\n", x, y, z); } } void Engine::set_debug_world_size(void) { int ctr_one, ctr_two; ctr_one = 0; ctr_two = 0; for (int x = 0; x < this->scx; x++) for (int y = 0; y < this->scy; y++) for (int z = 0; z < this->scz; z++) { ctr_one += this->world->c[x][y][z]->elements; ctr_two += this->world->c[x][y][z]->elements; } this->elements_world_one = ctr_one; this->elements_world_two = ctr_two; } bool Engine::must_recompute_world(void) { this->set_chunk_index_by_pos(this->world->position); if (this->chunk_index[0] >= this->scx - this->barrier || this->chunk_index[0] <= this->barrier || this->chunk_index[2] >= this->scz - this->barrier || this->chunk_index[2] <= this->barrier) { this->new_center[0] = this->chunk_index[0]; this->new_center[1] = this->chunk_index[1]; this->new_center[2] = this->chunk_index[2]; if (this->new_center[0] < 0) this->new_center[0] = 0; if (this->new_center[2] < 0) this->new_center[2] = 0; if (this->new_center[0] > this->scx - 1) this->new_center[0] = this->scx - 1; if (this->new_center[2] > this->scz - 1) this->new_center[2] = this->scz - 1; if (this->state.verbose) fprintf(stderr, "Cross barrier (%d): New center = %d %d %d\n", this->barrier, this->new_center[0], this->new_center[1], this->new_center[2]); return true; } return false; } void Engine::set_limit_by_time(int time) { this->barrier = ((((time / 2) / 1000) * 20) / 16) + (this->g_state.renderDistance) + 4; if (this->barrier > this->scx / 2) this->barrier = this->scx / 2 - 2; if (this->barrier > 45) this->barrier = 45; } void Engine::swap_worlds(void) { World *tmpW; tmpW = this->world; this->world = this->next_world; this->next_world = tmpW; this->world->adjust_camera(this->next_world); if (this->edit_size > 0) this->apply_player_edits(); } void Engine::apply_player_edits(void) { for (int i = 0; i < this->edit_size; i++) { this->world->setChunk(this->edit_to_apply[i].x + -((this->world->shiftX - this->next_world->shiftX) * CX), this->edit_to_apply[i].y, this->edit_to_apply[i].z + -((this->world->shiftZ - this->next_world->shiftZ) * CZ), this->edit_to_apply[i].blk); } this->edit_size = 0; } void Engine::write_keys(void) { printf("Use ZQSD/WASD to move around, A to go up, E to go down and shift to go fast.\n"); printf("Use home and end to go to two predetermined positions.\n"); printf("Use PageUp And PageDown to up/down the sound volume.\n"); printf("Press the left mouse button to build a block.\n"); printf("Press the right mouse button to remove a block.\n"); printf("Use the scrollwheel to select different types of blocks.\n"); printf("Press +/- to change player speed\n"); printf("Press insert to toggle anchor camera.\n"); printf("Press F1 to change sampling value.\n"); printf("Press F2 to toggle anti-aliasing.\n"); printf("Press F3 to toggle transparency.\n"); printf("Press F4 to toggle collision.\n"); printf("Press F5 to toggle focussing on transparent blocks.\n"); printf("Press F6 to change the framerate limit.\n"); printf("Press F7 to change the render distance limit.\n"); printf("Press F8 to swap the both worlds.\n"); printf("Press F9 to show debug info\n"); printf("Press F10 to desactivate infinite world.\n"); printf("Press F11 to activate autowalk.\n"); printf("Press F12 to use breakpoint with gdb\n"); } void Engine::write_usage(void) { fprintf(stderr, "usage : ./ft_vox [options]\n"); fprintf(stderr, "optional parameters :\n"); fprintf(stderr, "\t<-w> or <--width> to specify the window width\n"); fprintf(stderr, "\t\tmin: %d, max: %d\n", WIDTH_MIN, WIDTH_MAX); fprintf(stderr, "\n"); fprintf(stderr, "\t<-h> or <--height> to specify the window height\n"); fprintf(stderr, "\t\tmin: %d, max: %d\n", HEIGHT_MIN, HEIGHT_MAX); fprintf(stderr, "\n"); fprintf(stderr, "\t<-s> or <--seed> to speciy the seed of the map\n"); fprintf(stderr, "\n"); fprintf(stderr, "\t<-ws> or <--world-size> to specify size of the saved world\n"); fprintf(stderr, "\t\tDefault value is 128\n"); fprintf(stderr, "\t\tmin: %d, max: %d, and must be a multiple of 8\n", WORLD_MIN, WORLD_MAX); fprintf(stderr, "\t\tThe lower the value is, the lower the RAM usage and loading time will be\n"); fprintf(stderr, "\n"); fprintf(stderr, "\t<--sync> to disable the VSync\n"); fprintf(stderr, "\n"); fprintf(stderr, "\t<-f> or <--fullscreen> to activate fullscreen\n"); fprintf(stderr, "\n"); fprintf(stderr, "\t<-d> or <--debug> to display debug mode\n"); fprintf(stderr, "\n"); fprintf(stderr, "\t<-v> or <--version> to specify shader version\n"); fprintf(stderr, "\t\tmin: 100, max: 999\n"); fprintf(stderr, "\t\tThe right version to give is at your discretion\n"); fprintf(stderr, "\t\tDefault value is 460\n"); }
[ "jjaouen@student.42.fr" ]
jjaouen@student.42.fr
942c2e16439436e8eeead3dcc0ab845277ee792b
c7c7fac4da3f5f6078955c15558959b88d939dc0
/dual_4051_analog_2_digital_sensor/dual_4051_analog_2_digital_sensor.ino
386533968728023a3bc41e89f49299213cd82bc8
[]
no_license
Jundullah-IA/Program-dasar
861cd8d0b5b05ec43e9ebfda45f553cc20422bb1
46f3c9881ef128d6ab9f884aa1e142277694598e
refs/heads/main
2023-07-08T02:09:15.787841
2021-08-14T07:26:52
2021-08-14T07:26:52
328,570,960
0
2
null
null
null
null
UTF-8
C++
false
false
1,202
ino
void setup() { Serial.begin(9600); pinMode(A0, INPUT); pinMode(A4, INPUT); pinMode(A1, OUTPUT); pinMode(A2, OUTPUT); pinMode(A3, OUTPUT); } bool readPin(byte pin, byte potition) { digitalWrite(A1, bitRead(potition, 2)); digitalWrite(A2, bitRead(potition, 1)); digitalWrite(A3, bitRead(potition, 0)); return analogRead(pin) > 750 ? 1 : 0; } unsigned int data() { unsigned int data; /*0*/ bitWrite(data, 9, readPin(A4, 0)); bitWrite(data, 1, readPin(A0, 0)); /*1*/ bitWrite(data, 10, readPin(A4, 1)); bitWrite(data, 2, readPin(A0, 1)); /*2*/ bitWrite(data, 11, readPin(A4, 2)); bitWrite(data, 3, readPin(A0, 2)); /*3*/ bitWrite(data, 8, readPin(A4, 3)); bitWrite(data, 0, readPin(A0, 3)); /*4*/ bitWrite(data, 12, readPin(A4, 4)); bitWrite(data, 4, readPin(A0, 4)); /*5*/ bitWrite(data, 15, readPin(A4, 5)); bitWrite(data, 7, readPin(A0, 5)); /*6*/ bitWrite(data, 13, readPin(A4, 6)); bitWrite(data, 5, readPin(A0, 6)); /*7*/ bitWrite(data, 14, readPin(A4, 7)); return bitWrite(data, 6, readPin(A0, 7)); } void loop() { int start = millis(); Serial.print(data(), BIN); Serial.print(" "); Serial.println(millis() - start); }
[ "noreply@github.com" ]
Jundullah-IA.noreply@github.com
e73a0e4f043acbb4e5b0d9b1ce2390aa443be925
933e4b63b4e6828a2ee0e862ae1b3fa8d6d6bd36
/LocalServer and Client/loacl_server/mainwindow.h
7692f9b23359516884fa6c090c0c56081cfdebf5
[]
no_license
fengxieye/Qt-item
dd6886a49ba2aa365c764c0f111de3caa7ceb2e4
bd8aef429322a3ec0b77576ceb713356977dc366
refs/heads/master
2020-04-30T20:52:58.974314
2019-05-27T06:11:26
2019-05-27T06:11:26
177,080,412
3
0
null
null
null
null
UTF-8
C++
false
false
446
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "local/ctlprocesscommunicationserver.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void slotGCConnected(QString name); private: Ui::MainWindow *ui; CTLProcessCommunicationServer *m_ProcessGCServer = Q_NULLPTR; }; #endif // MAINWINDOW_H
[ "jianhui.zhong@teimelink.cn" ]
jianhui.zhong@teimelink.cn
d0803247476be507441e40e8f7ba5cd5f5e29845
1b38af12a5cc0493efc96d791e0b0ea5cb98389b
/KindAgmrs/src/KMersiData.cpp
a5012878172d70f363c55c8eaeb7390e4a58a8e6
[]
no_license
shenyczz/KLibrary
efce0689d496f2097d00da7faf46fb73f5102eb7
98eab1108f650253d243795222044989432c4d0e
refs/heads/master
2022-12-14T10:05:58.636127
2020-09-18T02:05:17
2020-09-18T02:05:17
296,487,674
1
0
null
null
null
null
GB18030
C++
false
false
1,446
cpp
#include "StdAfx.h" #include "KMersiData.h" #include "KMersiDataProcessor.h" namespace Agmrs { namespace Mersi { KMersiData::KMersiData(void) { this->SetType(AgmrsDataSource::Mersi); m_pDataProcessor = new KMersiDataProcessor(); m_pDataProcessor->SetOwner(this); } KMersiData::~KMersiData(void) { } // 设置默认的显示通道 void KMersiData::SetDefaultDisplayChannel() { KLDFile::SetDefaultDisplayChannel(); // 数据信息 KDataInfo* pDataInfo = GetDataInfo(); // 通道数量 int iChannelNums = pDataInfo->ChannelNumbers(); if(this->IsDay()) {// 白天 SetDataChannelDef(3,4,3); } else {// 晚上 int ch = this->ChannelCode2Channel(pDataInfo->ChannelCode(0)); SetDataChannelDef(ch,ch,ch); } return; } // 通道转换为通道代码 int KMersiData::Channel2ChannelCode(int iChannel) { return iChannel + 50; } // 通道代码转换为通道 int KMersiData::ChannelCode2Channel(int iChannelCode) { return iChannelCode - 50; } // 通道转换为字符串 LPCTSTR KMersiData::ChannelCode2String(int iChannelCode) { KDataInfo* pDataInfo = this->GetDataInfo(); int iChannelNums = pDataInfo->ChannelNumbers(); _stprintf(m_szChannel,_T("%2d 通道"),ChannelCode2Channel(iChannelCode)); return m_szChannel; } //--------------------------------------------------------- }}// namespace Agmrs::Mersi - end //---------------------------------------------------------
[ "shenyczz@163.com" ]
shenyczz@163.com
70f0bf56cb4f9a6b42cf728ae8f47732650502b7
3d608dd1c81b8a41dfc133035d2c7992a5b5383d
/OpenGL_Template/Texture.cpp
93ba0a87f4e5ce165af56643e6806bb8aeb41794
[]
no_license
kvickz/GAP275_SolarSystem
f6b042ba96f5c4e609ceba40cb7b2420f86bbea5
46d600d2633b8ef80a5c183425a9fb2cca15d074
refs/heads/master
2021-01-10T08:00:58.019681
2015-12-19T08:01:18
2015-12-19T08:01:18
47,047,079
0
0
null
2015-11-29T02:35:14
2015-11-29T02:31:02
null
UTF-8
C++
false
false
1,544
cpp
//Texture.cpp #include "Texture.h" #include <SDL.h> #include <gl\glew.h> #include <SDL_opengl.h> #include "Simple OpenGL Image Library\src\SOIL.h" Texture::Texture(std::string pFilePath) { //Create texture object glGenTextures(1, &m_textureObject); m_fileName = pFilePath; //Load The Image glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_textureObject); //Load Image unsigned char* pImage; pImage = SOIL_load_image(m_fileName.c_str(), &m_width, &m_height, 0, SOIL_LOAD_RGB); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_width, m_height, 0, GL_RGB, GL_UNSIGNED_BYTE, pImage); SOIL_free_image_data(pImage); //Unbind glBindTexture(GL_TEXTURE_2D, 0); } Texture::~Texture() { glDeleteTextures(1, &m_textureObject); } void Texture::InitTexture(GLuint shaderProgram) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_textureObject); //Get uniform m_textureUniform = glGetUniformLocation(shaderProgram, "objectTexture"); glUniform1i(m_textureUniform, 0); if (m_textureUniform == -1) { SDL_Log("Error in InitTexture()"); } //WRAPPING PARAMETERS glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLint uniforms; glGetProgramiv(shaderProgram, GL_ACTIVE_UNIFORMS, &uniforms); }
[ "mkn665@yahoo.com" ]
mkn665@yahoo.com
8f72a567b0268a19576c552a21d835eeb10caac7
3844678a0fb3b1f0838fb04bc57fd93dee6ee631
/siteApps/PVAccessGW/v4workspace/pvAccess/testApp/utils/configurationTest.cpp
1cee21546fbcab2b249d603bbfab7afef81f4210
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
jeonghanlee/Work
daa9295da3af3ff6c3a68daf51fac804dd1942cd
bef817911ea29fe091547f001ac35ac3765d8258
refs/heads/master
2022-09-28T03:59:29.435017
2022-09-15T18:26:34
2022-09-15T18:26:34
91,843,357
3
0
null
2019-01-08T16:10:37
2017-05-19T20:34:36
VHDL
UTF-8
C++
false
false
5,889
cpp
/* * configurationTest.cpp * */ #include <pv/configuration.h> #include <iostream> #include <string> #include <memory> #include <stdlib.h> #include <epicsAssert.h> #include <epicsExit.h> #include <envDefs.h> #include <epicsString.h> #include <osiSock.h> #include <epicsUnitTest.h> #include <testMain.h> #ifdef _WIN32 void setenv(char * a, char * b, int c) { char buf[1024]; sprintf(buf, "%s=%s", a, b); _putenv(buf); } #endif using namespace epics::pvAccess; using namespace epics::pvData; static const char indata[] = "hello = world \n" " # oops\n" " #dd=da\n" " empty = \n" " this = is a test\n\n" ; static const char expectdata[] = "empty = \n" "hello = world\n" "this = is a test\n" ; static void showEscaped(const char *msg, const std::string& s) { std::vector<char> chars(epicsStrnEscapedFromRawSize(s.c_str(), s.size())+1); epicsStrnEscapedFromRaw(&chars[0], chars.size(), s.c_str(), s.size()); testDiag("%s: '%s", msg, &chars[0]); } static void testProp() { Properties plist; { std::istringstream input(indata); plist.load(input); testOk1(!input.bad()); testOk1(input.eof()); } testOk1(plist.size()==3); testOk1(plist.getProperty("hello")=="world"); testOk1(plist.getProperty("this")=="is a test"); testOk1(!plist.hasProperty("foobar")); { std::ostringstream output; plist.store(output); std::string expect(expectdata), actual(output.str()); testOk1(!output.bad()); testOk(expect.size()==actual.size(), "%u == %u", (unsigned)expect.size(), (unsigned)actual.size()); testOk1(actual==expectdata); showEscaped("actual", actual); showEscaped("expect", expect); } } static void showEnv(const char *name) { testDiag("%s = \"%s\"", name, getenv(name)); } static void setEnv(const char *name, const char *val) { epicsEnvSet(name, val); testDiag("%s = \"%s\"", name, getenv(name)); } static void testBuilder() { Configuration::shared_pointer C(ConfigurationBuilder() .add("TESTKEY","value1") .push_map() .push_env() .add("OTHERKEY","value3") .push_map() .build()); testOk1(C->getPropertyAsString("key", "X")=="X"); testOk1(C->getPropertyAsString("TESTKEY", "X")=="value1"); testOk1(C->getPropertyAsString("OTHERKEY", "X")=="value3"); setEnv("TESTKEY", "value2"); setEnv("OTHERKEY","value2"); testOk1(C->getPropertyAsString("TESTKEY", "X")=="value2"); testOk1(C->getPropertyAsString("OTHERKEY", "X")=="value3"); } static void showAddr(const osiSockAddr& addr) { char buf[40]; sockAddrToDottedIP(&addr.sa, buf, sizeof(buf)); testDiag("%s", buf); } #define TESTVAL(TYPE, VAL1, VAL2, VAL1S) do {\ showEnv(#TYPE "Property"); \ testOk1(configuration->getPropertyAs##TYPE(#TYPE "Property", VAL1) == VAL1); \ testOk1(configuration->getPropertyAs##TYPE(#TYPE "Property", VAL2) == VAL2); \ setEnv(#TYPE "Property", VAL1S); \ testOk1(configuration->getPropertyAs##TYPE(#TYPE "Property", VAL1) == VAL1); \ testOk1(configuration->getPropertyAs##TYPE(#TYPE "Property", VAL2) == VAL1); \ } while(0) static void testConfig() { testDiag("Default configuration"); Configuration::shared_pointer configuration(new SystemConfigurationImpl()); TESTVAL(String, "one", "two", "one"); TESTVAL(Boolean, true, false, "true"); TESTVAL(Integer, 100, 321, "100"); TESTVAL(Float, 42.0e3, 44.0e3, "42.0e3"); TESTVAL(Double, 42.0e3, 44.0e3, "42.0e3"); testDiag("IP Address w/o default or explicit port"); showEnv("AddressProperty"); osiSockAddr addr; memset(&addr, 0, sizeof(addr)); addr.ia.sin_family = AF_INET+1; // something not IPv4 addr.ia.sin_port = htons(42); testOk1(configuration->getPropertyAsAddress("AddressProperty", &addr)==false); setEnv("AddressProperty", "127.0.0.1"); // no port testOk1(configuration->getPropertyAsAddress("AddressProperty", &addr)==true); showAddr(addr); testOk1(addr.ia.sin_family==AF_INET); testOk1(ntohl(addr.ia.sin_addr.s_addr)==INADDR_LOOPBACK); testOk1(ntohs(addr.ia.sin_port)==0); testDiag("IP Address w/ default port"); memset(&addr, 0, sizeof(addr)); addr.ia.sin_family = AF_INET; addr.ia.sin_port = htons(42); testOk1(configuration->getPropertyAsAddress("AddressProperty", &addr)==true); showAddr(addr); testOk1(addr.ia.sin_family==AF_INET); testOk1(ntohl(addr.ia.sin_addr.s_addr)==INADDR_LOOPBACK); testOk1(ntohs(addr.ia.sin_port)==42); testDiag("IP Address w/ default and explicit port"); setEnv("AddressProperty", "127.0.0.1:43"); // no port testOk1(configuration->getPropertyAsAddress("AddressProperty", &addr)==true); showAddr(addr); memset(&addr, 0, sizeof(addr)); addr.ia.sin_family = AF_INET; addr.ia.sin_port = htons(42); testOk1(configuration->getPropertyAsAddress("AddressProperty", &addr)==true); showAddr(addr); testOk1(addr.ia.sin_family==AF_INET); testOk1(ntohl(addr.ia.sin_addr.s_addr)==INADDR_LOOPBACK); testOk1(ntohs(addr.ia.sin_port)==43); testDiag("register with global configuration listings"); ConfigurationProvider::shared_pointer configProvider(ConfigurationFactory::getProvider()); configProvider->registerConfiguration("conf1", configuration); Configuration::shared_pointer configurationOut(configProvider->getConfiguration("conf1")); testOk1(configurationOut.get() == configuration.get()); } MAIN(configurationTest) { testPlan(49); testProp(); testBuilder(); testConfig(); return testDone(); }
[ "silee7103@gmail.com" ]
silee7103@gmail.com
0299c852fea1fe40e8522fe4328a728f97cf7c2c
521b1719c9d3da52dfb63635b638771075a095a6
/Random-Engine/include/DebugDraw.h
eb237fb2ae312e1adf229e06cb805534a8c0e771
[]
no_license
fdfragoso/GameEngines
836ea2787c9b90b3bb6e0593a0feda4ce44ab3a5
c1dfcb03e009b0aca9803a9de5806e003aaf364e
refs/heads/master
2020-07-16T20:29:40.503249
2019-09-02T14:00:28
2019-09-02T14:00:28
205,862,573
3
0
null
null
null
null
UTF-8
C++
false
false
1,270
h
#include "Box2D/Box2D.h" struct Camera { Camera() { m_center.Set(0.0f, 20.0f); m_extent = 25.0f; m_zoom = 1.0f; m_width = 1280; m_height = 800; } b2Vec2 ConvertScreenToWorld(const b2Vec2& screenPoint); b2Vec2 ConvertWorldToScreen(const b2Vec2& worldPoint); void BuildProjectionMatrix(float32* m, float32 zBias); b2Vec2 m_center; float32 m_extent; float32 m_zoom; int32 m_width; int32 m_height; }; //! DebugDraw /*! DebugDraw is our custom class that draws physics debug with SRE */ /*! The structure of the class is based on the correspondent tutorial of Box2D */ class DebugDraw : public b2Draw { public: void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) override; void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) override; void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override; void DrawTransform(const b2Transform& xf) override; void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color) override; }; extern Camera g_camera;
[ "fefragoso@gmail.com" ]
fefragoso@gmail.com
b15200db86f64435f0fd491b397a1c109550eac9
6a408c6754e8cad8376ff030570129963a0f7b2c
/lesson21/l21-7/l21-7/main.cpp
ff2a767494e03f4a681fc246fac0e8d2fc4607b8
[]
no_license
dimmkan/MSHP
e4ed8cb6528747f10900c6fe5bcf650238d3f9f6
956629ee2b83df28caacc2554bf7a00e1aad848c
refs/heads/master
2020-09-07T00:56:01.756864
2020-05-30T08:54:08
2020-05-30T08:54:08
220,607,366
1
0
null
2020-01-31T15:52:26
2019-11-09T07:29:26
C++
UTF-8
C++
false
false
359
cpp
#include <iostream> using namespace std; int digitSum(int n){ int sum = 0; do{ sum += n%10; n /= 10; }while(n); return sum; } int digitRoot(int n){ return digitSum(n); } int main() { int n; cin >> n; while(abs(n) > 9){ n = digitRoot(n); } cout << n; return 0; }
[ "dimmkan@mail.ru" ]
dimmkan@mail.ru
369ccd0aa5180cae88d396a9b7b06b6c7681eb76
e037f0f7f3206a185cec1a9f4774b491ad30772b
/ConcreteMdp.h
743b7a40073d27dde6bd46d691c1e8d270ce6d94
[]
no_license
mfiore/pomdp
6f6e53e1e2e57b6142c7606365987ee1efbf3863
2b4978b6e2c29d6154b45cdd120e7526cf180f32
refs/heads/master
2020-04-05T23:47:42.456783
2016-11-07T15:01:25
2016-11-07T15:01:25
50,672,324
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: ConcreteMdp.h * Author: theworld * * Created on September 2, 2016, 4:48 PM */ #include "Mdp.h" #ifndef CONCRETEMDP_H #define CONCRETEMDP_H class ConcreteMdp : public Mdp { public: ConcreteMdp(); ConcreteMdp(const ConcreteMdp& orig); virtual ~ConcreteMdp(); //create the mdp. If rewrite is false it won't overwrite an existing file, but read the model void create(string name, bool rewrite); //to override in subclasses. virtual bool isStartingState(VariableSet state) = 0; virtual bool isGoalState(VariableSet state) = 0; virtual int rewardFunction(VariableSet state, string action) = 0; virtual VarStateProb transitionFunction(VariableSet state, string action)=0; protected: //learning functions virtual int bellmanBackup(int i, std::vector<double> vhi); virtual void valueIteration(); //will call the transition reward function etc. and save the results in the Mdp variables virtual void enumerateFunctions(); virtual void enumerateGoalAndStartStates(); //functions to actually write the model and policy file in the same format read by the Mdp class void writeModel(string file_name); void writePolicy(string file_name); }; #endif /* CONCRETEMDP_H */
[ "mfiore@laas.fr" ]
mfiore@laas.fr
59352e81986a66cdb8bb802c59303f6a8fc7ffdc
f92d75e01756005ad49264fa9fec780a46b2abf8
/8_String_to_Integer.cpp
a317f75438efaad31837af54b8a88a3928f6438e
[]
no_license
hansx7/LeetCode
a676bc561086d0b78399b83123c9ad945041619a
91b36240712f67feca63c61a255d955e6cfa0baa
refs/heads/master
2021-04-27T00:12:51.249114
2018-10-28T10:51:46
2018-10-28T10:51:46
123,771,986
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
#include<bits/stdc++.h> using namespace std; int myAtoi(string s) { int max_int = 2147483647; int min_int = -max_int-1; if (s=="") return 0; while (s[0] != '+' && s[0] != '-' && !isdigit(s[0])) { if (s[0]!=' ') while (s[0]!=' ') { s.erase(0, 1); if (s.length() == 0) return 0; } else s.erase(0, 1); if (s.length() == 0) return 0; } bool flag = 0; if (s[0]=='-') { s.erase(0,1); flag = 1; } else if (s[0] == '+') s.erase(0,1); long long ans = 0; while (s.length() > 0) { if (!isdigit(s[0])) break; int t = s[0] - '0'; ans = ans * 10 + t; s.erase(0, 1); if (ans > max_int || ans < min_int) break; } if (flag == 1) ans = -ans; if (ans>max_int) ans = max_int; if (ans<min_int) ans = min_int; return ans; } int main() { string s; cin>>s; cout<<myAtoi(s)<<endl; return 0; }
[ "harryhan.1996@163.com" ]
harryhan.1996@163.com
f1e7abef5cb89fdcb97b69adaed5400729f79b19
1ed046feef46d52738a8c9a987f7daf5e0af997a
/sdk/core/azure-core-amqp/test/ut/amqp_value_tests.cpp
c18b723ecffcb36fb1e63be0d20c294800639350
[ "LGPL-2.1-or-later", "BSD-3-Clause", "Apache-2.0", "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
Azure/azure-sdk-for-cpp
72809cf59d2a6f262a6dd01d6f78661f81e70b93
dd236311193c6a3debf3b12c47f14e49a20c72c7
refs/heads/main
2023-08-25T11:57:56.773041
2023-08-23T23:33:32
2023-08-23T23:33:32
233,147,271
159
134
MIT
2023-09-14T21:25:14
2020-01-10T23:29:08
C++
UTF-8
C++
false
false
59,220
cpp
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "azure/core/amqp/common/global_state.hpp" #include "azure/core/amqp/models/amqp_error.hpp" #include "azure/core/amqp/models/amqp_value.hpp" #include <algorithm> #include <random> #include <gtest/gtest.h> using namespace Azure::Core::Amqp::Models; class TestValues : public testing::Test { protected: void SetUp() override { // Ensure that our logger is hooked up to global state. auto globalInstance = Azure::Core::Amqp::Common::_detail::GlobalStateHolder::GlobalStateInstance(); (void)globalInstance; } void TearDown() override {} }; TEST_F(TestValues, SimpleCreate) { { AmqpValue value; EXPECT_EQ(AmqpValueType::Null, value.GetType()); } { AmqpValue value{true}; EXPECT_EQ(AmqpValueType::Bool, value.GetType()); EXPECT_TRUE(value); } { AmqpValue value{false}; EXPECT_EQ(AmqpValueType::Bool, value.GetType()); EXPECT_FALSE(value); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<char>(value)); EXPECT_ANY_THROW((void)static_cast<std::int8_t>(value)); } { EXPECT_LT(AmqpValue(false), AmqpValue(true)); } { AmqpValue value{}; EXPECT_TRUE(value.IsNull()); } { AmqpValue value{static_cast<int8_t>(-17)}; EXPECT_EQ(AmqpValueType::Byte, value.GetType()); EXPECT_EQ(-17, static_cast<int8_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_LT(AmqpValue{static_cast<int8_t>(-18)}, value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_ANY_THROW((void)static_cast<unsigned char>(value)); EXPECT_ANY_THROW((void)static_cast<uint16_t>(value)); EXPECT_ANY_THROW((void)static_cast<int16_t>(value)); EXPECT_ANY_THROW((void)static_cast<uint32_t>(value)); EXPECT_ANY_THROW((void)static_cast<int32_t>(value)); EXPECT_ANY_THROW((void)static_cast<uint64_t>(value)); EXPECT_ANY_THROW((void)static_cast<int64_t>(value)); EXPECT_ANY_THROW((void)static_cast<float>(value)); EXPECT_ANY_THROW((void)static_cast<double>(value)); EXPECT_ANY_THROW((void)static_cast<std::string>(value)); EXPECT_ANY_THROW((void)static_cast<Azure::Core::Uuid>(value)); } { AmqpValue value{static_cast<uint8_t>(255)}; EXPECT_EQ(AmqpValueType::Ubyte, value.GetType()); EXPECT_EQ(255, static_cast<uint8_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue{static_cast<uint8_t>(254)}, value); } { AmqpValue value{'D'}; EXPECT_EQ(AmqpValueType::Byte, value.GetType()); EXPECT_EQ(static_cast<char>(68), static_cast<std::int8_t>(value)); EXPECT_TRUE(AmqpValue() < value); char ch{value}; EXPECT_EQ('D', ch); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue('B'), value); } { AmqpValue value{static_cast<uint16_t>(65535)}; EXPECT_EQ(AmqpValueType::Ushort, value.GetType()); EXPECT_EQ(65535, static_cast<uint16_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue{static_cast<uint16_t>(65534)}, value); } { AmqpValue value{static_cast<int16_t>(32767)}; EXPECT_EQ(AmqpValueType::Short, value.GetType()); EXPECT_EQ(32767, static_cast<int16_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue{static_cast<int16_t>(32766)}, value); } { AmqpValue value(32); EXPECT_EQ(AmqpValueType::Int, value.GetType()); EXPECT_EQ(32, static_cast<int32_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue(31), value); } { AmqpValue value(32u); EXPECT_EQ(AmqpValueType::Uint, value.GetType()); EXPECT_EQ(32u, static_cast<uint32_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue(31u), value); } { AmqpValue value(static_cast<int64_t>(32ll)); EXPECT_EQ(AmqpValueType::Long, value.GetType()); EXPECT_EQ(32ll, static_cast<int64_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue(static_cast<int64_t>(31ll)), value); } { AmqpValue value(static_cast<uint64_t>(39ull)); EXPECT_EQ(AmqpValueType::Ulong, value.GetType()); EXPECT_EQ(39ull, static_cast<uint64_t>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue(static_cast<uint64_t>(38ull)), value); } { AmqpValue value(39.0f); EXPECT_EQ(AmqpValueType::Float, value.GetType()); EXPECT_EQ(39.0f, static_cast<float>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue(38.0f), value); } { AmqpValue value(39.0); EXPECT_EQ(AmqpValueType::Double, value.GetType()); EXPECT_EQ(39.0, static_cast<double>(value)); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue(38.0), value); } { AmqpValue value(39.0); double d{value}; EXPECT_EQ(39.0, d); EXPECT_TRUE(AmqpValue() < value); } { AmqpValue value(std::string("Fred")); std::string fredP(value); EXPECT_EQ(AmqpValueType::String, value.GetType()); EXPECT_EQ(std::string("Fred"), fredP); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); EXPECT_LT(AmqpValue("ABC"), value); } { AmqpValue value("Fred"); std::string fredP(value); EXPECT_EQ(AmqpValueType::String, value.GetType()); EXPECT_EQ(std::string("Fred"), fredP); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); } { Azure::Core::Uuid uuid = Azure::Core::Uuid::CreateUuid(); AmqpValue value(uuid); EXPECT_EQ(AmqpValueType::Uuid, value.GetType()); EXPECT_EQ(uuid.ToString(), static_cast<Azure::Core::Uuid>(value).ToString()); EXPECT_TRUE(AmqpValue() < value); EXPECT_ANY_THROW((void)static_cast<bool>(value)); } { AmqpValue value1{29}; AmqpValue value2(std::move(value1)); AmqpValue value3(value2); AmqpValue value4; value4 = value2; EXPECT_EQ(value4, value2); GTEST_LOG_(INFO) << value4; AmqpValue value5 = std::move(value3); GTEST_LOG_(INFO) << value5; EXPECT_NE(value5, value3); } } TEST_F(TestValues, TestBinary) { { AmqpBinaryData binaryData; binaryData.push_back('a'); binaryData.push_back(3); AmqpValue value(static_cast<_detail::UniqueAmqpValueHandle>(binaryData).get()); EXPECT_FALSE(value < AmqpValue(static_cast<_detail::UniqueAmqpValueHandle>(binaryData).get())); AmqpBinaryData data2(value); EXPECT_EQ(2, data2.size()); EXPECT_TRUE(AmqpValue() < value); AmqpBinaryData data3(std::vector<uint8_t>(50)); GTEST_LOG_(INFO) << "data3.size()=" << data3.size(); GTEST_LOG_(INFO) << "data3:" << data3; } } TEST_F(TestValues, TestList) { { AmqpList list1; EXPECT_EQ(0, list1.size()); } { AmqpValue boolValue{false}; EXPECT_ANY_THROW(AmqpList list(boolValue)); } // Put some things in the list. { const AmqpList list1{123, 23.97f, "ABCD", 'a'}; EXPECT_EQ(4, list1.size()); EXPECT_EQ(23.97f, static_cast<float>(list1.at(1))); EXPECT_EQ(123, static_cast<int32_t>(list1.at(0))); EXPECT_EQ(AmqpValue("ABCD"), list1.at(2)); EXPECT_EQ(AmqpValueType::Byte, list1[3].GetType()); EXPECT_EQ(AmqpValue('a'), list1[3]); AmqpValue value(static_cast<_detail::UniqueAmqpValueHandle>(list1).get()); const AmqpList list2(value); EXPECT_FALSE(value < AmqpValue(static_cast<_detail::UniqueAmqpValueHandle>(list1).get())); EXPECT_EQ(4, list2.size()); EXPECT_EQ(23.97f, static_cast<float>(list2.at(1))); EXPECT_EQ(123, static_cast<int32_t>(list2.at(0))); EXPECT_EQ(AmqpValue("ABCD"), list2.at(2)); EXPECT_EQ(AmqpValue('a'), list2.at(3)); EXPECT_FALSE(list1 < list2); } { AmqpList test; AmqpDescribed desc{ static_cast<uint64_t>(29), static_cast<AmqpValue>(AmqpList{AmqpValue{"test:error"}, AmqpValue{"test description"}})}; test.push_back(AmqpValue{desc}); EXPECT_EQ(1, test.size()); EXPECT_EQ(AmqpValueType::Described, test[0].GetType()); AmqpList list2{test}; EXPECT_EQ(1, list2.size()); EXPECT_EQ(AmqpValueType::Described, list2[0].GetType()); AmqpDescribed desc2{list2[0].AsDescribed()}; EXPECT_EQ(desc2.GetDescriptor(), AmqpValue{static_cast<uint64_t>(29ll)}); } { AmqpList test; _internal::AmqpError error; error.Condition = _internal::AmqpErrorCondition("test:error"); error.Description = "test description"; test.push_back(_internal::AmqpErrorFactory::ToAmqp(error)); EXPECT_EQ(1, test.size()); EXPECT_EQ(AmqpValueType::Composite, test[0].GetType()); AmqpComposite testAsComposite{test[0].AsComposite()}; EXPECT_EQ(testAsComposite.GetDescriptor(), AmqpValue{static_cast<uint64_t>(29ll)}); { AmqpValue testAsValue{test}; EXPECT_EQ(AmqpValueType::List, testAsValue.GetType()); auto testAsList{testAsValue.AsList()}; EXPECT_EQ(AmqpValueType::Composite, testAsList[0].GetType()); EXPECT_EQ(test[0], testAsList[0]); } } } TEST_F(TestValues, TestMap) { { AmqpMap map1; EXPECT_EQ(0, map1.size()); } { AmqpMap map1{{"key1", 23}, {3, "ABC"}}; EXPECT_EQ(2, map1.size()); } { AmqpValue boolValue{false}; EXPECT_ANY_THROW(AmqpMap map{boolValue}); } // Put some things in the map. { AmqpMap map1; map1["key1"] = 23; map1[AmqpValue(3)] = "ABC"; map1["ABC"] = 5; EXPECT_EQ(3, map1.size()); EXPECT_EQ(5, static_cast<int32_t>(map1["ABC"])); EXPECT_EQ(std::string("ABC"), static_cast<std::string>(map1[AmqpValue(3)])); // Now round-trip the map through an AMQP value and confirm that the values persist. AmqpValue valueOfMap = static_cast<_detail::UniqueAmqpValueHandle>(map1).get(); AmqpMap map2(valueOfMap); EXPECT_FALSE(valueOfMap < AmqpValue(static_cast<_detail::UniqueAmqpValueHandle>(map1).get())); EXPECT_EQ(5, static_cast<int32_t>(map2["ABC"])); EXPECT_EQ(std::string("ABC"), static_cast<std::string>(map2[AmqpValue(3)])); EXPECT_FALSE(map1 < map2); } } TEST_F(TestValues, TestArray) { { AmqpArray array1{1, 3, 5, 4, 553991123}; EXPECT_EQ(5, array1.size()); AmqpValue value = static_cast<AmqpValue>(array1); EXPECT_EQ(AmqpValueType::Array, value.GetType()); const AmqpArray array2 = value.AsArray(); EXPECT_EQ(5, array2.size()); EXPECT_EQ(1, static_cast<std::int32_t>(array2.at(0))); EXPECT_EQ(3, static_cast<std::int32_t>(array2.at(1))); EXPECT_EQ(5, static_cast<std::int32_t>(array2.at(2))); EXPECT_FALSE(array1 < array2); EXPECT_FALSE(value < AmqpValue(static_cast<_detail::UniqueAmqpValueHandle>(array2).get())); } { // Because EXPECT_ANY_THROW is a macro, the commas in the lambda below confuse the // preprocessor. So explicitly capture the lambda and then execute it in the EXPECT_ANY_THROW. auto v = []() { AmqpArray testArray{3.1, 2.9, 14}; }; EXPECT_ANY_THROW(v()); } } TEST_F(TestValues, TestChar) { { AmqpValue value{U'\U0001f34c'}; EXPECT_EQ(U'\U0001f34c', static_cast<char32_t>(value)); EXPECT_EQ(AmqpValueType::Char, value.GetType()); EXPECT_FALSE(static_cast<char32_t>(value) < U'\U0001f34c'); } { AmqpValue boolValue{false}; EXPECT_ANY_THROW((void)static_cast<char32_t>(boolValue)); } } TEST_F(TestValues, TestTimestamp) { { std::chrono::milliseconds timeNow{std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch())}; AmqpTimestamp value{timeNow}; EXPECT_EQ(static_cast<std::chrono::milliseconds>(value), timeNow); AmqpValue av{value}; AmqpTimestamp ts2{av.AsTimestamp()}; EXPECT_EQ(timeNow, static_cast<std::chrono::milliseconds>(ts2)); EXPECT_FALSE(value < ts2); } { AmqpValue boolValue{false}; EXPECT_ANY_THROW(boolValue.AsTimestamp()); } } TEST_F(TestValues, TestSymbol) { { AmqpSymbol value("timeNow"); EXPECT_EQ(value, "timeNow"); EXPECT_FALSE(value < AmqpSymbol("timeNow")); GTEST_LOG_(INFO) << "Symbol value: " << value; } { AmqpValue boolValue{false}; EXPECT_ANY_THROW(boolValue.AsSymbol()); } } TEST_F(TestValues, TestCompositeValue) { { AmqpComposite value("My Composite Type", {1, 2, 5.5, "ABC", 5}); EXPECT_EQ(AmqpValueType::Composite, AmqpValue(value).GetType()); EXPECT_EQ(5, value.size()); } { AmqpValue boolValue{false}; EXPECT_ANY_THROW(AmqpComposite value(boolValue)); } // Put some things in the map. { AmqpComposite val("CompType", {25, 25.0f}); EXPECT_EQ(25, static_cast<int32_t>(val.at(0))); EXPECT_EQ(25.0f, static_cast<float>(val.at(1))); } // Put some things in the map. { AmqpComposite compositeVal(static_cast<uint64_t>(116ull), {25, 25.0f}); AmqpValue value = static_cast<AmqpValue>(compositeVal); AmqpComposite testVal(value.AsComposite()); EXPECT_EQ(compositeVal.size(), testVal.size()); EXPECT_EQ(compositeVal.GetDescriptor(), testVal.GetDescriptor()); EXPECT_EQ(compositeVal[0], testVal[0]); EXPECT_EQ(compositeVal[1], testVal[1]); EXPECT_EQ(25, static_cast<int32_t>(testVal.at(0))); EXPECT_EQ(25.0f, static_cast<float>(testVal.at(1))); EXPECT_FALSE(compositeVal < testVal); } } TEST_F(TestValues, TestDescribed) { // Described types with symbol descriptors. { AmqpDescribed described1(AmqpSymbol{"My Composite Type"}, 5); EXPECT_EQ(AmqpSymbol("My Composite Type"), described1.GetDescriptor().AsSymbol()); EXPECT_EQ(5, static_cast<int32_t>(described1.GetValue())); AmqpValue value = static_cast<AmqpValue>(described1); EXPECT_EQ(AmqpValueType::Described, value.GetType()); AmqpDescribed described2 = value.AsDescribed(); EXPECT_EQ(AmqpValueType::Described, value.GetType()); EXPECT_EQ(5, static_cast<int32_t>(described2.GetValue())); EXPECT_EQ(described2.GetDescriptor().AsSymbol(), "My Composite Type"); EXPECT_FALSE(described1 < described2); // EXPECT_TRUE(described1 == described2); } // Described types with long descriptors. { AmqpDescribed value(937, 5); EXPECT_EQ(937, static_cast<uint64_t>(value.GetDescriptor())); EXPECT_EQ(5, static_cast<int32_t>(value.GetValue())); AmqpValue value2 = static_cast<AmqpValue>(value); AmqpDescribed described2 = value2.AsDescribed(); EXPECT_EQ(AmqpValueType::Described, value2.GetType()); EXPECT_EQ(5, static_cast<int32_t>(described2.GetValue())); EXPECT_EQ(937, static_cast<uint64_t>(described2.GetDescriptor())); EXPECT_EQ(AmqpValue(described2.GetValue()), AmqpValue(value.GetValue())); EXPECT_EQ(AmqpValue(described2.GetDescriptor()), AmqpValue(value.GetDescriptor())); } } class TestValueSerialization : public testing::Test { protected: void SetUp() override {} void TearDown() override {} }; // AMQP values are serialized as described in the AMQP spec. // Test deserializing a null value (0x40) - section 1.6.1. TEST_F(TestValueSerialization, SerializeNull) { std::vector<uint8_t> testVector{0x40}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Null); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x40, val[0]); } // Test deserializing a boolean value (0x56/0x00 or 0x56/0x01) - section 1.6.2. TEST_F(TestValueSerialization, SerializeBoolean) { // There are two possible encodings for Boolean values: 0x56 followed by a byte with the value // 0x00 for false, or 0x56 followed by a byte with the value 0x01 for true. // The other possible encoding for Boolean values is 0x41 for true and 0x42 for false. { std::vector<uint8_t> testVector{0x56, 0x01}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Bool); EXPECT_TRUE(value); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x41, val[0]); } { std::vector<uint8_t> testVector{0x56, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Bool); EXPECT_FALSE(value); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x42, val[0]); } { std::vector<uint8_t> testVector{0x41}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Bool); EXPECT_TRUE(value); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x41, val[0]); } { std::vector<uint8_t> testVector{0x42}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Bool); EXPECT_FALSE(value); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x42, val[0]); } } // Test deserializing a UByte value (0x50/0xXX) - section 1.6.3. TEST_F(TestValueSerialization, SerializeUbyte) { { std::vector<uint8_t> testVector{0x50, 0x25}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ubyte); EXPECT_EQ(0x25, static_cast<uint8_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x50, val[0]); EXPECT_EQ(0x25, val[1]); } { std::vector<uint8_t> testVector{0x50, 0x89}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ubyte); EXPECT_EQ(0x89, static_cast<uint8_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x50, val[0]); EXPECT_EQ(0x89, val[1]); } } // Test deserializing a UShort value (0x60/0xXX/0xXX) - section 1.6.4. // Note: Serialized value is in network byte order. TEST_F(TestValueSerialization, SerializeUShort) { { std::vector<uint8_t> testVector{0x60, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ushort); EXPECT_EQ(0, static_cast<std::uint16_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } { std::vector<uint8_t> testVector{0x60, 0x04, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ushort); EXPECT_EQ(0x400, static_cast<std::uint16_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } { std::vector<uint8_t> testVector{0x60, 0x04, 0x80}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ushort); EXPECT_EQ(0x480, static_cast<std::uint16_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing a UInt value (0x70/0xXX/0xXX) - section 1.6.5. // Note that there are three serializations for UInt values: // The first is as a fixed width value in the form of 0x70/0xXX/0xYY/0xZZ/0xAA with the values in // network byte order. // The second applies to values in the range 0..255: 0x52/0xXX // The third applies to the specific value of 0: 0x43. TEST_F(TestValueSerialization, SerializeUint) { { // Input first form with value == 0. Expected output: 3rd form. std::vector<uint8_t> testVector{0x70, 0x00, 0x00, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Uint); EXPECT_EQ(0, static_cast<std::uint32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x43, val[0]); } { // Third form, value == 0. std::vector<uint8_t> testVector{0x43}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Uint); EXPECT_EQ(0, static_cast<std::uint32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x43, val[0]); } { // First form, value < 255, expected output: 2nd form. std::vector<uint8_t> testVector{0x70, 0x00, 0x00, 0x00, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Uint); EXPECT_EQ(0x85, static_cast<std::uint32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x52, val[0]); EXPECT_EQ(0x85, val[1]); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x52, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Uint); EXPECT_EQ(0x85, static_cast<std::uint32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x52, val[0]); EXPECT_EQ(0x85, val[1]); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x70, 0x12, 0x34, 0x56, 0x78}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Uint); EXPECT_EQ(0x12345678, static_cast<std::uint32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing a ULong value - section 1.6.6. // Note that there are three serializations for UInt values: // The first is as a fixed width value in the form of 0x80/0xXX/0xYY/0xZZ/0xAA with the values in // network byte order. // The second applies to values in the range 0..255: 0x53/0xXX // The third applies to the specific value of 0: 0x44. TEST_F(TestValueSerialization, SerializeUlong) { { // Input first form with value == 0. Expected output: 3rd form. std::vector<uint8_t> testVector{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ulong); EXPECT_EQ(0, static_cast<std::uint64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x44, val[0]); } { // Third form, value == 0. std::vector<uint8_t> testVector{0x44}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ulong); EXPECT_EQ(0, static_cast<std::uint64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(1, val.size()); EXPECT_EQ(0x44, val[0]); } { // First form, value < 255, expected output: 2nd form. std::vector<uint8_t> testVector{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ulong); EXPECT_EQ(0x85, static_cast<std::uint64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x53, val[0]); EXPECT_EQ(0x85, val[1]); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x53, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ulong); EXPECT_EQ(0x85, static_cast<std::uint64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x53, val[0]); EXPECT_EQ(0x85, val[1]); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x80, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Ulong); EXPECT_EQ(0x1234567812345678, static_cast<std::uint64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing a Byte value (0x51/0xXX) - section 1.6.7. TEST_F(TestValueSerialization, SerializeByte) { { std::vector<uint8_t> testVector{0x51, 0x25}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Byte); EXPECT_EQ(0x25, static_cast<int8_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x51, val[0]); EXPECT_EQ(0x25, val[1]); } { std::vector<uint8_t> testVector{0x51, 0x89}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Byte); EXPECT_EQ(-119, static_cast<int8_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x51, val[0]); EXPECT_EQ(0x89, val[1]); } } // Test deserializing a UShort value (0x61/0xXX/0xXX) - section 1.6.8. // Note: Serialized value is in network byte order. TEST_F(TestValueSerialization, SerializeShort) { { std::vector<uint8_t> testVector{0x61, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Short); EXPECT_EQ(0, static_cast<std::int16_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } { std::vector<uint8_t> testVector{0x61, 0x04, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Short); EXPECT_EQ(0x400, static_cast<std::int16_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } { std::vector<uint8_t> testVector{0x61, 0x04, 0x80}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Short); EXPECT_EQ(0x480, static_cast<std::int16_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing a Int value - section 1.6.9. // Note that there are two serializations for Int values: // The first is as a fixed width value in the form of 0x71/0xXX/0xYY/0xZZ/0xAA with the values in // network byte order. // The second applies to values in the range -128..127: 0x54/0xXX TEST_F(TestValueSerialization, SerializeInt) { { // Input first form with value == 0. Expected output: 2nd form. std::vector<uint8_t> testVector{0x71, 0x00, 0x00, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Int); EXPECT_EQ(0, static_cast<std::int32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x54, val[0]); EXPECT_EQ(0x00, val[1]); } { // First form, value < 255, expected output: 2nd form. std::vector<uint8_t> testVector{0x71, 0x00, 0x00, 0x00, 0x75}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Int); EXPECT_EQ(0x75, static_cast<std::int32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x54, val[0]); EXPECT_EQ(0x75, val[1]); } { // First form, value < 255, expected output: 2nd form. Note that the value of 0x85 is greater // than 127 so it cannot be represented in the second form. std::vector<uint8_t> testVector{0x71, 0x00, 0x00, 0x00, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Int); EXPECT_EQ(0x85, static_cast<std::int32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x54, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Int); EXPECT_EQ(-123, static_cast<std::int32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x54, val[0]); EXPECT_EQ(0x85, val[1]); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x71, 0x12, 0x34, 0x56, 0x78}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Int); EXPECT_EQ(0x12345678, static_cast<std::int32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing a Long value - section 1.6.10. // Note that there are two serializations for Long values: // The first is as a fixed width value in the form of 0x81/0xXX/0xYY/0xZZ/0xAA with the values in // network byte order. // The second applies to values in the range 0..255: 0x55/0xXX TEST_F(TestValueSerialization, SerializeLong) { { // First form, value < 255, expected output: 2nd form. std::vector<uint8_t> testVector{0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x75}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Long); EXPECT_EQ(0x75, static_cast<std::int64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x55, val[0]); EXPECT_EQ(0x75, val[1]); } { // First form, value < 255, expected output: First form because 0x85 cannot be expressed as a // signed byte. std::vector<uint8_t> testVector{0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Long); EXPECT_EQ(133, static_cast<std::int64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x55, 0x85}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Long); EXPECT_EQ(-123, static_cast<std::int64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(2, val.size()); EXPECT_EQ(0x55, val[0]); EXPECT_EQ(0x85, val[1]); } { // Second form, value < 255. std::vector<uint8_t> testVector{0x81, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Long); EXPECT_EQ(0x1234567812345678, static_cast<std::int64_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing a Float value - section 1.6.11. TEST_F(TestValueSerialization, SerializeFloat) { std::vector<uint8_t> testVector{0x72, 0x40, 0x49, 0x0f, 0xda}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Float); EXPECT_FLOAT_EQ(3.1415926f, static_cast<float>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Test deserializing a Double value - section 1.6.12. TEST_F(TestValueSerialization, SerializeDouble) { std::vector<uint8_t> testVector{0x82, 0x40, 0x09, 0x21, 0xFB, 0x4D, 0x12, 0xD8, 0x4A}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Double); EXPECT_DOUBLE_EQ(3.1415926, static_cast<double>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Test deserializing a Char value - section 1.6.16. // Note uAMQP does not appear to have support for encoding and decoding Char values. #if 0 TEST_F(TestValueSerialization, SerializeChar) { std::vector<uint8_t> testVector{0x73, 0x4D, 0x12, 0xD8, 0x4A}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Char); EXPECT_EQ(0x4d12d84a, static_cast<char32_t>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } #endif // Test deserializing a Milliseconds value - section 1.6.17. TEST_F(TestValueSerialization, SerializeMilliseconds) { std::vector<uint8_t> testVector{0x83, 0x00, 0x00, 0x00, 0x00, 0x64, 0x41, 0xc0, 0x79}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Timestamp); EXPECT_EQ(0x6441c079, static_cast<std::chrono::milliseconds>(value.AsTimestamp()).count()); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Test deserializing a Uuid value - section 1.6.18. TEST_F(TestValueSerialization, SerializeUuid) { Azure::Core::Uuid testUuid{Azure::Core::Uuid::CreateUuid()}; std::vector<uint8_t> testVector{0x98}; testVector.insert(testVector.end(), testUuid.AsArray().begin(), testUuid.AsArray().end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Uuid); EXPECT_EQ(testUuid.ToString(), static_cast<Azure::Core::Uuid>(value).ToString()); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Test deserializing a Binary value - section 1.6.19. // Note that there are two serializations for Binary values: // The first is as a variable width value in the form of 0xa0/<1 byte length>/<binary data> // The second is as a variable width value in the form of 0xb0/<4 byte length>/<binary data> TEST_F(TestValueSerialization, SerializeBinary) { // First form, serialized as first form. { Azure::Core::Uuid testUuid{Azure::Core::Uuid::CreateUuid()}; std::vector<uint8_t> testVector{0xa0, 0x10}; testVector.insert(testVector.end(), testUuid.AsArray().begin(), testUuid.AsArray().end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Binary); EXPECT_EQ(value.AsBinary().size(), 16); auto binary(value.AsBinary()); std::array<uint8_t, 16> valueAsArray{}; std::copy_n(binary.begin(), 16, valueAsArray.begin()); EXPECT_EQ(valueAsArray, testUuid.AsArray()); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Second form, serialized as first form. { Azure::Core::Uuid testUuid{Azure::Core::Uuid::CreateUuid()}; std::vector<uint8_t> testVector{0xb0, 0x00, 0x00, 0x00, 0x10}; testVector.insert(testVector.end(), testUuid.AsArray().begin(), testUuid.AsArray().end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Binary); EXPECT_EQ(value.AsBinary().size(), 16); auto binary(value.AsBinary()); std::array<uint8_t, 16> valueAsArray{}; std::copy_n(binary.begin(), 16, valueAsArray.begin()); EXPECT_EQ(valueAsArray, testUuid.AsArray()); auto val = AmqpValue::Serialize(value); EXPECT_EQ(18, val.size()); EXPECT_EQ(0xa0, val[0]); EXPECT_EQ(0x10, val[1]); } { char values[255]{}; std::vector<uint8_t> testVector{0xa0, sizeof(values)}; testVector.insert(testVector.end(), values, values + sizeof(values)); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Binary); EXPECT_EQ(value.AsBinary().size(), 255); auto val = AmqpValue::Serialize(value); EXPECT_EQ(257, val.size()); EXPECT_EQ(0xa0, val[0]); EXPECT_EQ(0xff, val[1]); } { char values[256]{}; std::vector<uint8_t> testVector{0xb0, 0x00, 0x00, 0x01, 0x00}; testVector.insert(testVector.end(), values, values + sizeof(values)); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Binary); EXPECT_EQ(value.AsBinary().size(), 256); auto val = AmqpValue::Serialize(value); EXPECT_EQ(261, val.size()); EXPECT_EQ(0xb0, val[0]); EXPECT_EQ(0x00, val[1]); EXPECT_EQ(0x00, val[2]); EXPECT_EQ(0x01, val[3]); EXPECT_EQ(0x00, val[4]); } } // Test deserializing a String value - section 1.6.20. // Note that there are two serializations for String values: // The first is as a variable width value in the form of 0xa1/<1 byte length>/<binary data> // The second is as a variable width value in the form of 0xb1/<4 byte length>/<binary data> TEST_F(TestValueSerialization, SerializeString) { // First form, serialized as first form. { std::string stringValue; for (int i = 0; i < 255; i += 1) { stringValue.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % 25]); } std::vector<uint8_t> testVector{0xa1, 0xff}; testVector.insert(testVector.end(), stringValue.begin(), stringValue.end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::String); EXPECT_EQ(static_cast<std::string>(value).size(), 255); EXPECT_EQ(stringValue, static_cast<std::string>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Second form, serialized as first form. { std::string stringValue; for (int i = 0; i < 255; i += 1) { stringValue.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % 26]); } std::vector<uint8_t> testVector{0xb1, 0x00, 0x00, 0x00, 0xff}; testVector.insert(testVector.end(), stringValue.begin(), stringValue.end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::String); EXPECT_EQ(static_cast<std::string>(value).size(), 255); EXPECT_EQ(stringValue, static_cast<std::string>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 257); EXPECT_EQ(val[0], 0xa1); EXPECT_EQ(val[1], 0xff); EXPECT_EQ(val[2], 'A'); } // Second form, serialized as second form. { std::string stringValue; for (int i = 0; i < 256; i += 1) { stringValue.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % 25]); } std::vector<uint8_t> testVector{0xb1, 0x00, 0x00, 0x01, 0x00}; testVector.insert(testVector.end(), stringValue.begin(), stringValue.end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::String); EXPECT_EQ(static_cast<std::string>(value).size(), 256); EXPECT_EQ(stringValue, static_cast<std::string>(value)); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing a Symbol value - section 1.6.21. // Note that there are two serializations for Symbol values: // The first is as a variable width value in the form of 0xa3/<1 byte length>/<binary data> // The second is as a variable width value in the form of 0xb3/<4 byte length>/<binary data> TEST_F(TestValueSerialization, SerializeSymbol) { // First form, serialized as first form. { std::string stringValue; for (int i = 0; i < 255; i += 1) { stringValue.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % 25]); } std::vector<uint8_t> testVector{0xa3, 0xff}; testVector.insert(testVector.end(), stringValue.begin(), stringValue.end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Symbol); EXPECT_EQ(value.AsSymbol().size(), 255); EXPECT_EQ(AmqpSymbol(stringValue), value.AsSymbol()); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Second form, serialized as first form. { std::string stringValue; for (int i = 0; i < 255; i += 1) { stringValue.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % 26]); } std::vector<uint8_t> testVector{0xb3, 0x00, 0x00, 0x00, 0xff}; testVector.insert(testVector.end(), stringValue.begin(), stringValue.end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Symbol); EXPECT_EQ(value.AsSymbol().size(), 255); EXPECT_EQ(AmqpSymbol(stringValue), value.AsSymbol()); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 257); EXPECT_EQ(val[0], 0xa3); EXPECT_EQ(val[1], 0xff); EXPECT_EQ(val[2], 'A'); } // Second form, serialized as second form. { std::string stringValue; for (int i = 0; i < 256; i += 1) { stringValue.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % 26]); } std::vector<uint8_t> testVector{0xb3, 0x00, 0x00, 0x01, 0x00}; testVector.insert(testVector.end(), stringValue.begin(), stringValue.end()); AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Symbol); EXPECT_EQ(value.AsSymbol().size(), 256); EXPECT_EQ(AmqpSymbol(stringValue), value.AsSymbol()); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } template <typename T> T GenerateRandomValue() { // Generate a random value of type T using std::random_device. // This is not a cryptographically secure random number generator, but it is good enough for our // purposes. The random number generator is seeded with a random value from std::random_device. // The random number generator is then used to generate a random value of type T. std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<T> dis( std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); return dis(gen); } // Append a value of type T to a buffer. // The value is appended in network byte order. // The value is appended as a fixed width value. // T void AppendValue(std::vector<uint8_t>& buffer, uint16_t value) { buffer.push_back((value >> 8) & 0xff); buffer.push_back(value & 0xff); } void AppendValue(std::vector<uint8_t>& buffer, uint32_t value) { buffer.push_back((value >> 24) & 0xff); buffer.push_back((value >> 16) & 0xff); buffer.push_back((value >> 8) & 0xff); buffer.push_back(value & 0xff); } // Test deserializing a List value - section 1.6.22. // Note that there are three serializations for List values: // The first is a fixed value in the form of 0x45 which represents an empty list. // The second is a compound value in the form of 0xc0/<1 byte size>/<1 byte count>/<list of values> // for list elements with a total size less than 255 octets. The third is a compound value in the // form of 0xd0/<4 byte size in network byte order>/<4 byte count in network byte order>/<list of // values> for list elements with a total size less than 2^32 octets. TEST_F(TestValueSerialization, SerializeList) { // First form, serialized as first form. { std::vector<unsigned char> testVector{0x45}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; AmqpList list(value.AsList()); EXPECT_EQ(list.size(), 0); } // First form, serialized as first form. { AmqpList emptyList; AmqpValue value{emptyList}; std::vector<uint8_t> val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 1); EXPECT_EQ(0x45, val[0]); } // Second form, serialized as first form. { std::vector<uint8_t> testVector{0xc0, 0x01, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::List); AmqpList list(value.AsList()); EXPECT_EQ(list.size(), 0); std::vector<uint8_t> val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 1); EXPECT_EQ(0x45, val[0]); } // THird form, serialized as first form. { std::vector<uint8_t> testVector{0xd0, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::List); AmqpList list(value.AsList()); EXPECT_EQ(list.size(), 0); std::vector<uint8_t> val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 1); EXPECT_EQ(0x45, val[0]); } // Second form serialized as second form. { constexpr size_t valueCount = 0x15; // Create an array of random values. std::vector<AmqpValue> values; for (size_t i = 0; i < valueCount; i += 1) { values.push_back(AmqpValue(static_cast<uint32_t>(GenerateRandomValue<long>()))); } size_t totalSize = 1; // Include the size of the list count in the size for (auto const& val : values) { totalSize += AmqpValue::GetSerializedSize(val); } EXPECT_LE(totalSize, 255); std::vector<uint8_t> testVector{0xc0}; testVector.push_back(static_cast<uint8_t>(totalSize)); testVector.push_back(static_cast<uint8_t>(valueCount)); // Now append all the values to the list. for (auto const& val : values) { auto serializedVal{AmqpValue::Serialize(val)}; testVector.insert(testVector.end(), serializedVal.begin(), serializedVal.end()); } AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::List); AmqpList list(value.AsList()); EXPECT_EQ(list.size(), values.size()); EXPECT_TRUE(std::equal(values.begin(), values.end(), list.begin(), list.end())); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } // Third form, serialized as second form. { constexpr size_t valueCount = 0x10; // Create an array of random values. std::vector<AmqpValue> values; for (size_t i = 0; i < valueCount; i += 1) { values.push_back(AmqpValue(static_cast<int64_t>(GenerateRandomValue<long long>()))); } size_t totalSize = 4; // Include the size of the list count in the size for (auto const& val : values) { totalSize += AmqpValue::GetSerializedSize(val); } EXPECT_LE(totalSize, 255); std::vector<uint8_t> testVector{0xd0}; AppendValue(testVector, static_cast<uint32_t>(totalSize)); AppendValue(testVector, static_cast<uint32_t>(valueCount)); // Now append all the values to the list. for (auto const& val : values) { auto serializedVal{AmqpValue::Serialize(val)}; testVector.insert(testVector.end(), serializedVal.begin(), serializedVal.end()); } AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::List); AmqpList list(value.AsList()); EXPECT_EQ(list.size(), values.size()); EXPECT_TRUE(std::equal(values.begin(), values.end(), list.begin(), list.end())); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 147); EXPECT_EQ(val[0], 0xc0); EXPECT_EQ( val[1], totalSize - 3 /* Account for the difference in size between the input and output size.*/); EXPECT_EQ(val[2], valueCount); } // Third form, serialized as third form. { constexpr size_t valueCount = 0x210; // Create an array of random values. std::vector<AmqpValue> values; for (size_t i = 0; i < valueCount; i += 1) { values.push_back(AmqpValue(static_cast<int64_t>(GenerateRandomValue<long long>()))); } size_t totalSize = 4; // Include the size of the list count in the size for (auto const& val : values) { totalSize += AmqpValue::GetSerializedSize(val); } EXPECT_GE(totalSize, 256); std::vector<uint8_t> testVector{0xd0}; AppendValue(testVector, static_cast<uint32_t>(totalSize)); AppendValue(testVector, static_cast<uint32_t>(valueCount)); // Now append all the values to the list. for (auto const& val : values) { auto serializedVal{AmqpValue::Serialize(val)}; testVector.insert(testVector.end(), serializedVal.begin(), serializedVal.end()); } AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::List); AmqpList list(value.AsList()); EXPECT_EQ(list.size(), values.size()); EXPECT_TRUE(std::equal(values.begin(), values.end(), list.begin(), list.end())); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing an Array value - section 1.6.24. // Note that there are two serializations for Arrayvalues: // The first is an array value in the form of 0xe0/<1 byte count>/<list of values> // for arrays with a total count of less than 255 octets. The second is an array value in the // form of 0xf0/<4 byte count in network byte order>/<list of // values> for list elements with a total size less than 2^32 octets. TEST_F(TestValueSerialization, SerializeArray) { // First form, serialized as first form. { std::vector<uint8_t> testVector{0xe0, 0x01, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Array); AmqpArray array(value.AsArray()); EXPECT_EQ(array.size(), 0); std::vector<uint8_t> val = AmqpValue::Serialize(value); EXPECT_EQ(testVector, val); } // Second form, serialized as first form. { std::vector<uint8_t> testVector{0xf0, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Array); AmqpArray array(value.AsArray()); EXPECT_EQ(array.size(), 0); std::vector<uint8_t> val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 3); EXPECT_EQ(0xe0, val[0]); EXPECT_EQ(0x01, val[1]); EXPECT_EQ(0x00, val[2]); } // Second form, serialized as first form. { constexpr size_t valueCount = 0x10; // Create an array of random values. std::vector<AmqpValue> values; for (size_t i = 0; i < valueCount; i += 1) { values.push_back(AmqpValue(static_cast<int64_t>(GenerateRandomValue<long long>()))); } size_t totalSize = (static_cast<size_t>(4) + 1); // Include the size of the list count in the size for (auto const& val : values) { totalSize += (AmqpValue::GetSerializedSize(val) - 1); // We're not going to serialize the constructor on the serialized values. } EXPECT_LE(totalSize, 255); std::vector<uint8_t> testVector{0xf0}; AppendValue(testVector, static_cast<uint32_t>(totalSize)); AppendValue(testVector, static_cast<uint32_t>(valueCount)); testVector.push_back(0x81); // Insert the constructor for the elements. // Now append all the values to the list. for (auto const& val : values) { auto serializedVal{AmqpValue::Serialize(val)}; // We want to skip over the constructor value in the serialized constructor. testVector.insert(testVector.end(), serializedVal.begin() + 1, serializedVal.end()); } AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Array); AmqpArray array(value.AsArray()); EXPECT_EQ(array.size(), values.size()); EXPECT_TRUE(std::equal(values.begin(), values.end(), array.begin(), array.end())); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 132); EXPECT_EQ(val[0], 0xe0); EXPECT_EQ( val[1], totalSize - 3 /* Account for the difference in size between the input and output size.*/); EXPECT_EQ(val[2], valueCount); } // Second form, serialized as second form. { constexpr size_t valueCount = 0x210; // Create an array of random values. std::vector<AmqpValue> values; for (size_t i = 0; i < valueCount; i += 1) { values.push_back(AmqpValue(static_cast<int64_t>(GenerateRandomValue<long long>()))); } size_t totalSize = (static_cast<size_t>(4) + 1); // Include the size of the list count in the size for (auto const& val : values) { totalSize += (AmqpValue::GetSerializedSize(val) - 1); } EXPECT_GE(totalSize, 256); std::vector<uint8_t> testVector{0xf0}; AppendValue(testVector, static_cast<uint32_t>(totalSize)); AppendValue(testVector, static_cast<uint32_t>(valueCount)); testVector.push_back(0x81); // element constructor - 0x80 == long. // Now append all the values to the list. for (auto const& val : values) { auto serializedVal{AmqpValue::Serialize(val)}; testVector.insert(testVector.end(), serializedVal.begin() + 1, serializedVal.end()); } AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Array); AmqpArray array(value.AsArray()); EXPECT_EQ(array.size(), values.size()); size_t i = 0; for (auto const& val : array) { if (val != values[i]) { GTEST_LOG_(ERROR) << "Mismatch in decoded array at offset " << i << "Original value: " << values[i] << " Transformed value: " << val; } i += 1; } EXPECT_TRUE(std::equal(values.begin(), values.end(), array.begin(), array.end())); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } } // Test deserializing an Map value - section 1.6.23. // Note that there are two serializations for Map values: // The first is an array value in the form of 0xc1/<1 byte count>/<list of values> // for maps with a total count of less than 255 values. The second is a value in the // form of 0xd1/<4 byte count in network byte order>/<list of // values> for map elements with a total size less than 2^32 octets. TEST_F(TestValueSerialization, SerializeMap) { // First form, serialized as first form. { std::vector<uint8_t> testVector{0xc1, 0x01, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Map); AmqpMap map(value.AsMap()); EXPECT_EQ(map.size(), 0); std::vector<uint8_t> val = AmqpValue::Serialize(value); EXPECT_EQ(testVector, val); } // Second form, serialized as first form. { std::vector<uint8_t> testVector{0xd1, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00}; AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Map); AmqpMap map(value.AsMap()); EXPECT_EQ(map.size(), 0); std::vector<uint8_t> val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 3); EXPECT_EQ(0xc1, val[0]); EXPECT_EQ(0x01, val[1]); EXPECT_EQ(0x00, val[2]); } // Second form, serialized as first form. { constexpr size_t valueCount = 0x10; // Create an map of random values. std::map<AmqpValue, AmqpValue> values; for (size_t i = 0; i < valueCount; i += 1) { values.emplace( AmqpValue(std::to_string(i)), AmqpValue(static_cast<int64_t>(GenerateRandomValue<long long>()))); } size_t totalSize = 4; // Include the size of the list count in the size for (auto const& val : values) { totalSize += (AmqpValue::GetSerializedSize(val.first) + AmqpValue::GetSerializedSize(val.second)); // We're not going to serialize the // constructor on the serialized values. } EXPECT_LE(totalSize, 255); std::vector<uint8_t> testVector{0xd1}; AppendValue(testVector, static_cast<uint32_t>(totalSize)); AppendValue(testVector, static_cast<uint32_t>(valueCount * 2)); // Now append all the values to the list. for (auto const& val : values) { { auto serializedVal{AmqpValue::Serialize(val.first)}; testVector.insert(testVector.end(), serializedVal.begin(), serializedVal.end()); } { auto serializedVal{AmqpValue::Serialize(val.second)}; testVector.insert(testVector.end(), serializedVal.begin(), serializedVal.end()); } } AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Map); AmqpMap map(value.AsMap()); EXPECT_EQ(map.size(), values.size()); EXPECT_TRUE(std::equal(values.begin(), values.end(), map.begin(), map.end())); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val.size(), 201); EXPECT_EQ(val[0], 0xc1); EXPECT_EQ(val[1], totalSize - 3); EXPECT_EQ(val[2], valueCount * 2); } // Second form, serialized as second form. { constexpr size_t valueCount = 0x210; // Create an map of random values. std::map<AmqpValue, AmqpValue> values; for (size_t i = 0; i < valueCount; i += 1) { values.emplace( AmqpValue(std::to_string(i)), AmqpValue(static_cast<int64_t>(GenerateRandomValue<long long>()))); } size_t totalSize = 4; // Include the size of the list count in the size for (auto const& val : values) { totalSize += (AmqpValue::GetSerializedSize(val.first) + AmqpValue::GetSerializedSize(val.second)); } EXPECT_GE(totalSize, 256); std::vector<uint8_t> testVector{0xd1}; AppendValue(testVector, static_cast<uint32_t>(totalSize)); AppendValue(testVector, static_cast<uint32_t>(valueCount * 2)); // Now append all the values to the list. for (auto const& val : values) { { auto serializedVal{AmqpValue::Serialize(val.first)}; testVector.insert(testVector.end(), serializedVal.begin(), serializedVal.end()); } { auto serializedVal{AmqpValue::Serialize(val.second)}; testVector.insert(testVector.end(), serializedVal.begin(), serializedVal.end()); } } AmqpValue value{AmqpValue::Deserialize(testVector.data(), testVector.size())}; EXPECT_EQ(value.GetType(), AmqpValueType::Map); AmqpMap map(value.AsMap()); EXPECT_EQ(map.size(), values.size()); int i = 0; auto valIterator = values.begin(); for (auto const& val : map) { EXPECT_NE(valIterator, values.end()); if (val.first != valIterator->first) { GTEST_LOG_(ERROR) << "Key Mismatch in decoded map at offset " << i << ". Original key: " << i << " Transformed key: " << val.first; } if (val.second != valIterator->second) { GTEST_LOG_(ERROR) << "Value Mismatch in decoded map at offset " << i << ". Original value: " << values[i] << " Transformed value: " << val.first; } i += 1; valIterator++; } EXPECT_TRUE(std::equal(values.begin(), values.end(), map.begin(), map.end())); auto val = AmqpValue::Serialize(value); EXPECT_EQ(val, testVector); } }
[ "noreply@github.com" ]
Azure.noreply@github.com
4eb79464e4952f2d28954caa1a59aaa43fdd1842
1e5535ff55accbffcfb8ce566231b8eb5cc81cbc
/email.cpp
35d7f81de18e7e49a6edfc48854ae896919d8715
[]
no_license
codebrane/groupwise
3f0cacb5b837f26303d9d4c584f9e6ccac78af62
040de133e2d22d218588d25ccddfb9d64fb1cc90
refs/heads/master
2016-09-06T21:54:29.195807
2011-03-10T08:52:01
2011-03-10T08:52:01
1,435,339
0
0
null
null
null
null
UTF-8
C++
false
false
12,098
cpp
#include "stdafx.h" #include "gwadapi.h" #include "email.h" // Return codes #define OK 0 #define OK_WITH_UPDATED_VISIBILITY 1 #define ERROR_COM_INIT -1 #define ERROR_CANT_CONNECT_TO_SERVER -2 #define ERROR_CANT_GET_USERS_INTERFACE -3 #define ERROR_CANT_ADD_USER -4 #define ERROR_CANT_SET_DOMAIN_VISIBILITY -5 #define ERROR_CANT_GET_USER_INTERFACE -6 #define ERROR_CANT_COMMIT_USER_OBJECT -7 #define ERROR_USER_ALREADY_EXISTS -8 #define ERROR_CANT_COMMIT_SYSTEM_OBJECT -9 #define ERROR_USER_NOT_FOUND -10 #define ERROR_CANT_GET_USER_OBJECT -11 // Mode definitions for the commandline #define MODE_ADD_USER "adduser" #define MODE_DELETE_USER_GW "delgw" #define MODE_DELETE_USER_NDS "delnds" #define MODE_DELETE_USER_GWNDS "delgwnds" // Command line parameters - argv[0] is always the program name #define INDEX_GWSERVER 1 // UNC path to the server that holds the domain/post offices #define INDEX_GWID 2 // ID to log into Groupwise with. Should be the same as the Novell ID #define INDEX_NDSDN 3 // DN of the user in NDS (e.g. 666666.students.here.there.someorg) #define INDEX_PASSWORD 4 // Password for the Groupwise account. Should be the same as the Novell password #define INDEX_DOMAIN 5 // Domain where the post office is #define INDEX_POSTOFFICE 6 // Post office to create the user in #define INDEX_VISIBILITY 7 // Visibility of the user. Can be "po", "domain", "none" or "system" #define INDEX_MODE 8 // Can be MODE_DELETE_USER_GW, MODE_DELETE_USER_NDS, MODE_DELETE_USER_GWNDS, MODE_ADD_USER #define INDEX_RETRY_WAIT 9 // Number of seconds to wait before trying to commit the user object // User visibility #define VISIBILITY_SYSTEM "system" #define VISIBILITY_DOMAIN "domain" #define VISIBILITY_PO "po" #define VISIBILITY_NONE "none" // For the log file #define NEWLINE "\n" #define DATE_SEPARATOR "," #define TIME_SEPARATOR ":" #define FILENAME_SEPARATOR "-" #define FILENAME_EXT ".txt" // For GetTime() #define FILENAME 1 #define LOGFILE 2 // Dummy Groupwise mailbox ID. Groupwise will create it's own one #define DUMMY_MAILBOX_ID "o0o" // Number of times we'll try to add the user - to account for NDS delays #define NO_OF_ATTEMPTS 60 TCHAR* ConvertToAnsi(OLECHAR* szW) { static char achA[STRCONVERT_MAXLEN]; WideCharToMultiByte(CP_ACP, 0, szW, -1, achA, STRCONVERT_MAXLEN, NULL, NULL); return achA; } OLECHAR* ConvertToUnicode(TCHAR* szA) { static OLECHAR achW[STRCONVERT_MAXLEN]; MultiByteToWideChar(CP_ACP, 0, szA, -1, achW, STRCONVERT_MAXLEN); return achW; } /* GWInit * * This function will set up COM and the groupwise client * * Params: * lpszDomain - Pointer to the name of the domain to connect to, e.g. \\sm_srv1\mail\grpwise\sm_dom * * Returns: * If the function succeeds it returns OK, otherwise an error value less than 0 */ int GWInit (char* lpszDomain) { VARIANT txtPath; // Initialize COM CoInitialize (NULL); // Create an instance of the Groupwise System object if (FAILED (CoCreateInstance (CLSID_System, NULL, CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER, IID_IADSystem, (void**)&pIGWSystem))) return ERROR_COM_INIT; // Initialize and handle OLE strings VariantInit (&txtPath); V_VT(&txtPath) = VT_BSTR; V_BSTR(&txtPath) = SysAllocString (TO_OLE_STRING (lpszDomain)); // Connect to the Groupwise server if(!SUCCEEDED (pIGWSystem->Connect (txtPath))) { GWExit(); return ERROR_CANT_CONNECT_TO_SERVER; } return OK; } /* GWExit * * This function cleans everything up - COM, Groupwise client, memory etc. * * Params: * NONE * * Returns: * NOTHING */ void GWExit() { // Release the System object... if (pIGWSystem) pIGWSystem->Release(); // ...the Users object if (pIGWUsers) pIGWUsers->Release(); // ...and the User object if (pIGWUser) pIGWUser->Release(); // Unintialize COM CoUninitialize(); } /* UserExistsInPostoffice * * This function will check to see if the specified user exists in the system * * Params: * gwID - The Groupwise ID of the user, e.g. SM000009 * vPostoffice - The name of the postoffice to search, e.g. stu1 * vDomain - The name of the domain to search, e.g. student * * Returns: * TRUE = user exists * FALSE = user doesn't exist */ BOOL UserExistsInPostoffice (BSTR gwID, VARIANT vPostoffice, VARIANT vDomain) { DIADUser *pDIADUser = NULL; BOOL bReturn; // Search for the user if (SUCCEEDED (pIGWUsers->Item (gwID, vPostoffice, vDomain, &pDIADUser))) bReturn = true; else bReturn = false; return bReturn; } int StringToInt (char* pString) { int result = 0; while (*pString >= '0' && *pString <= '9') { result = (result * 10) + (*pString - '0'); pString++; } return result; } /* _tmain * * Main program entry point. Action starts here! * * Params: * argv - our commandline parameters in an array * * Returns: * The program returns one of the return codes listed at the top of this file */ int _tmain (int argc, _TCHAR* argv[]) { int result; DIADUsers *pDIADUsers = NULL; DIADUser *pDIADUser = NULL; VARIANT password; VARIANT postOffice; VARIANT domain; VARIANT mailboxID; VARIANT tree; BOOL userAdded = false; BOOL userValid = false; int attempts = 0; int retry_interval = (1000 * StringToInt (argv[INDEX_RETRY_WAIT])); char szDateAndTime[255]; // Initialise and connect to the Groupwise server result = GWInit (argv[INDEX_GWSERVER]); // If we didn't initialise report the error and shutdown if (result < OK) { return result; } // Initialise the params for sending to Groupwise VariantInit (&password); VariantInit (&postOffice); VariantInit (&domain); VariantInit (&mailboxID); VariantInit (&tree); V_VT(&password) = VT_BSTR; V_VT(&postOffice) = VT_BSTR; V_VT(&domain) = VT_BSTR; V_VT(&mailboxID) = VT_BSTR; V_VT(&tree) = VT_BSTR; // Get a pointer to the Users Dispatch interface... pIGWSystem->get_Users (&pDIADUsers); // ...to get a pointer to the Users interface if (SUCCEEDED (pDIADUsers->QueryInterface (IID_IADUsers, (void**)&pIGWUsers))) pDIADUsers->Release(); else { //logFile << "Failed to get a pointer to the Users Dispatch interface"; GWExit(); return ERROR_CANT_GET_USERS_INTERFACE; } // Get ready to talk to Groupwise V_BSTR(&password) = SysAllocString (TO_OLE_STRING (argv[INDEX_PASSWORD])); V_BSTR(&postOffice) = SysAllocString (TO_OLE_STRING (argv[INDEX_POSTOFFICE])); V_BSTR(&domain) = SysAllocString (TO_OLE_STRING (argv[INDEX_DOMAIN])); V_BSTR(&mailboxID) = SysAllocString (TO_OLE_STRING (DUMMY_MAILBOX_ID)); V_BSTR(&tree) = SysAllocString (TO_OLE_STRING ("YOUR_NDS_TREE")); BSTR gwUserID = SysAllocString (TO_OLE_STRING (argv[INDEX_GWID])); BSTR ndsDN = SysAllocString (TO_OLE_STRING (argv[INDEX_NDSDN])); BSTR gwID = SysAllocString (TO_OLE_STRING (argv[INDEX_GWID])); // Do we just need to delete the user? if ( (!(strcmp (argv[INDEX_MODE], MODE_DELETE_USER_GW))) || (!(strcmp (argv[INDEX_MODE], MODE_DELETE_USER_NDS))) || (!(strcmp (argv[INDEX_MODE], MODE_DELETE_USER_GWNDS))) ) { StoreTypeConstants deleteMode; BSTR givenname; BSTR sn; // Find the user in the postoffice if (SUCCEEDED (pIGWUsers->ItemByDN (ndsDN, tree, &pDIADUser))) { // If we found them, get a pointer to the user object for them if (SUCCEEDED (pDIADUser->QueryInterface (IID_IADUser, (void**)&pIGWUser))) { // Release the interface - don't need it now pDIADUser->Release(); // Get their details pIGWUser->get_GivenName (&givenname); pIGWUser->get_Surname (&sn); // Delete the user... eadNDS eadGW eadBothNDSandGW if (!(strcmp (argv[INDEX_MODE], MODE_DELETE_USER_GW))) deleteMode = eadGW; if (!(strcmp (argv[INDEX_MODE], MODE_DELETE_USER_NDS))) deleteMode = eadNDS; if (!(strcmp (argv[INDEX_MODE], MODE_DELETE_USER_GWNDS))) deleteMode = eadBothNDSandGW; if (SUCCEEDED (pIGWUser->Delete (deleteMode))) { // ...and update the system if (SUCCEEDED (pIGWSystem->Commit())) { result = OK; } else { result = ERROR_CANT_COMMIT_SYSTEM_OBJECT; } } } else { result = ERROR_CANT_GET_USER_OBJECT; } } else { result = ERROR_USER_NOT_FOUND; } // Clean up... GWExit(); // ...and return the result return result; } // if ( (argv[INDEX_MODE] == MODE_DELETE_USER_GW) ... // Default mode is adding a user so first check if the user already exists in all possible postoffices if (UserExistsInPostoffice (gwID, postOffice, domain)) { GWExit(); return ERROR_USER_ALREADY_EXISTS; } // Create the account. We'll try up to 100 times to take care of NDS delays while ((!userAdded) && (attempts < NO_OF_ATTEMPTS)) { HRESULT hResult = pIGWUsers->AddExistingUser (gwUserID, ndsDN, password, postOffice, domain, mailboxID, &pDIADUser); if (SUCCEEDED(hResult)) { userAdded = true; /* There is apparently a delay between Groupwise accepting the user and the user becoming a * valid entity with attributes that can be manipulated. We'll know if it's become valid as the * commit function will work. We'll try a few times to call commit. If it works then we can set * various attributes of the user. * We only need to do this if we've been told to set the user to a visibility other than system, * which is the default visibility. */ if (strcmp (argv[INDEX_VISIBILITY], VISIBILITY_SYSTEM)) { // Get a handle on the User interface - this represents the user we've just added... if (SUCCEEDED (pDIADUser->QueryInterface (IID_IADUser, (void**)&pIGWUser))) { // ...and release the dispatch interface. Don't need it any more pDIADUser->Release(); VisibilityTypeConstants vis; attempts = 0; // What visibility is required? if (argv[INDEX_VISIBILITY] == VISIBILITY_DOMAIN) vis = eadVisDomain; if (argv[INDEX_VISIBILITY] == VISIBILITY_PO) vis = eadVisPostOffice; if (argv[INDEX_VISIBILITY] == VISIBILITY_NONE) vis = eadVisNone; // Keep trying... while ((!userValid) && (attempts < NO_OF_ATTEMPTS)) { // ...to commit the User object... if (SUCCEEDED (pIGWUser->Commit())) { if (SUCCEEDED (pIGWUser->put_Visibility (eadVisDomain))) { // ...then commit the user again if (SUCCEEDED (pIGWUser->Commit())) { userValid = true; result = OK_WITH_UPDATED_VISIBILITY; } } } // Try to commit the User object again attempts++; Sleep (retry_interval); } if (!userValid) result = ERROR_CANT_COMMIT_USER_OBJECT; } // if (SUCCEEDED (pDIADUser->QueryInterface (IID_IADUser, (void**)&pIGWUser))) else result = ERROR_CANT_GET_USER_INTERFACE; } // if (argv[INDEX_VISIBILITY] != VISIBILITY_SYSTEM) else result = OK; } // if (SUCCEEDED (pIGWUsers->AddExistingUser ... else { attempts++; result = ERROR_CANT_ADD_USER; Sleep (retry_interval); } } // while ((!userAdded) && (attempts < NO_OF_ATTEMPTS)) // Update the system. Failure to do this will result in a delay before Groupwise displays the user in Console1 pIGWSystem->Commit(); // Clean up GWExit(); // Return the result code return result; }
[ "alistair@codebrane.com" ]
alistair@codebrane.com
bd8202b865094b27c104066ea3e17b0fa05b215b
e2eb06f706c1d1264ac9b52127a5f8923bc3a044
/IditarodChallenge8/IditarodChallenge8/Explorer.hpp
c295d3ac54654ac1b464db627fc1fce5b2db31b9
[]
no_license
SarahFDAK/cs202
224b47fde8191eb18ec9e6c3894743a8845e7361
5e478484d3d372b04d174776af9c5ae95d2d17d6
refs/heads/master
2020-12-11T18:09:15.824435
2020-04-26T21:07:54
2020-04-26T21:07:54
233,920,464
0
0
null
null
null
null
UTF-8
C++
false
false
885
hpp
// // Explorer.hpp // hw04Wumpus // // Created by Sarah Carter on 3/8/20. // Copyright © 2020 Sarah Carter. All rights reserved. // #ifndef Explorer_hpp #define Explorer_hpp #include <stdio.h> #include "Cave.hpp" #include "Hazards.hpp" #include "Wumpus.hpp" class Explorer { int _lifeStat = 0; int _yourRoom = 0; int _arrows = 5; public: Explorer(); Explorer(const int room); void setCurrentRoom(const int room); void move(const Cave& cave); void setLifeStat(const int alive); void missed(const int usedArrow); void shoot(Cave& cave, Wumpus& wompa); int event(const Cave& cave, const Hazards& bat1, const Hazards& bat2, const Hazards& pit1, const Hazards& pit2, Wumpus& wompa); int getExplorerLife() const; int getExplorerRoom() const; int getArrowNum() const; }; #endif /* Explorer_hpp */
[ "sarah.c@fdak.net" ]
sarah.c@fdak.net
8148771552d3f5fd912ef8b6038f7684ada6bcd0
8421c2e403e253a41547e7e9ba9cc7aa4996a283
/BatteryCollector/Pickup.h
a4afde645c1045c35e8e6027f281d2685b546d95
[]
no_license
hackertron/BatteryBot
0f52af2467a140c2512f61a01ec996be17ef83f0
fcf0b6a9d73153b3e9f7d32024c9d41242b9240d
refs/heads/master
2021-03-24T10:23:42.459341
2017-07-30T09:54:17
2017-07-30T09:54:17
86,799,975
3
0
null
null
null
null
UTF-8
C++
false
false
1,389
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/Actor.h" #include "Pickup.generated.h" UCLASS() class BATTERYCOLLECTOR_API APickup : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties APickup(); // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick( float DeltaSeconds ) override; // Return the mesh for pickup FORCEINLINE class UStaticMeshComponent * GetMesh() const { return PickupMesh; } /* Return whether or not the pickup is active*/ UFUNCTION(BlueprintPure, Category = "Pickup") bool IsActive(); /* Allows other classes to safely change whether or not pickup is active */ UFUNCTION(BlueprintCallable, Category = "Pickup") void SetActive(bool NewPickupState); /* Function to call when pickup is collected */ UFUNCTION(BlueprintNativeEvent) void WasCollected(); virtual void WasCollected_Implementation(); protected: /* True when the pickup can be used and false when pickup is deactivated */ bool bIsActive; private: /* static mesh to represent pickup and levels */ UPROPERTY(VisibleAnywhere, BluePrintReadOnly, Category = "Pickup", meta = (AllowPrivateAccess = "true")) class UStaticMeshComponent* PickupMesh; };
[ "noreply@github.com" ]
hackertron.noreply@github.com
02cbc5f18a8db5df2d5f1af6e80109f08bc527df
cefa1d8cd71392c1f431edd786a96a41f471a1a3
/api/core/cpp/StringCallback.hpp
0044db766c1aafb1680fde9a46ffe5afa176e96c
[]
no_license
KhalilBellakrid/ledger-core-api
c4a54a8acbd2c5aa7da5d06160b6f463efd80d60
a8f03d37943d0e34e3fbc1661bb31248126979a1
refs/heads/master
2020-03-06T23:35:41.549194
2018-04-08T11:06:49
2018-04-08T11:06:49
127,136,242
0
0
null
null
null
null
UTF-8
C++
false
false
923
hpp
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from callback.djinni #ifndef DJINNI_GENERATED_STRINGCALLBACK_HPP #define DJINNI_GENERATED_STRINGCALLBACK_HPP #include "../../../../core/src/utils/optional.hpp" #include <string> namespace ledger { namespace core { namespace api { struct Error; /** *Callback triggered by main completed task, *returns optional result of template type T */ class StringCallback { public: virtual ~StringCallback() {} /** * Method triggered when main task complete * @params result optional of type T, non null if main task failed * @params error optional of type Error, non null if main task succeeded */ virtual void onCallback(const std::experimental::optional<std::string> & result, const std::experimental::optional<Error> & error) = 0; }; } } } // namespace ledger::core::api #endif //DJINNI_GENERATED_STRINGCALLBACK_HPP
[ "khalil.bellakrid@ledger.fr" ]
khalil.bellakrid@ledger.fr
515564dc489f3699004997ba6741e0467ba93cf0
970eafb1f12f5773b3c22e0eb483d46c99dc5c82
/PicesLibraries/PicesLibrary/SipperBuffBinary.cpp
801c58991f1be8e2b9d120664f9fae7654f075e0
[]
no_license
PalakDave/Pices
9a533f29b33d2b338fbc34a7b8a5db94908bddc0
8c1953f68a848ebd9a80500ac6dd49f528cc1c94
refs/heads/master
2021-01-20T13:23:55.408840
2017-04-23T21:54:00
2017-04-23T21:54:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,600
cpp
#include "FirstIncludes.h" #include <stdio.h> #include <string.h> #include <ctype.h> #include <iostream> #include <fstream> #include <vector> #include "MemoryDebug.h" using namespace std; #include "KKBaseTypes.h" #include "OSservices.h" #include "RunLog.h" #include "KKStr.h" using namespace KKB; #include "SipperBuffBinary.h" using namespace MLL; SipperBuffBinary::SipperBuffBinary (InstrumentDataManagerPtr _instrumentDataManager, RunLog& _log ): SipperBuff (_instrumentDataManager, _log) { byteOffset = 0; } SipperBuffBinary::SipperBuffBinary (KKStr _fileName, uchar _selCameraNum, InstrumentDataManagerPtr _instrumentDataManager, RunLog& _log ): SipperBuff (_fileName, _instrumentDataManager, _log), selCameraNum (_selCameraNum) { byteOffset = 0; } SipperBuffBinary::~SipperBuffBinary () { this->SipperBuff::~SipperBuff (); } typedef struct { KKB::uchar b1; KKB::uchar b2; } SplitRec; typedef SplitRec* SplitRecPtr; void SipperBuffBinary::GetNextSipperRec (kkint32& spaceLeft, uchar& cameraNum, bool& raw, bool& eol, bool& flow, uchar& pix0, uchar& pix1, uchar& pix2, uchar& pix3, uchar& pix4, uchar& pix5, uchar& pix6, uchar& pix7, uchar& pix8, uchar& pix9, uchar& pix10, uchar& pix11, kkint32& numOfBlanks, bool& moreRecs) { SipperBinaryRec sipperRec; kkint32 recsRead; curRowByteOffset = byteOffset; do { recsRead = (kkint32)fread (&sipperRec, sizeof (sipperRec), 1, inFile); if (recsRead < 1) { eof = true; moreRecs = false; return; } } while (sipperRec.cameraNum != selCameraNum); bool exitLoop = false; while (!exitLoop) { byteOffset = byteOffset + sizeof (sipperRec); cameraNum = sipperRec.cameraNum; raw = sipperRec.raw; eol = sipperRec.eol; flow = sipperRec.flow; pix0 = sipperRec.pix0; pix1 = sipperRec.pix1; pix2 = sipperRec.pix2; pix3 = sipperRec.pix3; pix4 = sipperRec.pix4; pix5 = sipperRec.pix5; pix6 = sipperRec.pix6; pix7 = sipperRec.pix7; pix8 = sipperRec.pix8; pix9 = sipperRec.pix9; pix10 = sipperRec.pix10; pix11 = sipperRec.pix11; numOfBlanks = pix0 * 2048 + pix1 * 1024 + pix2 * 512 + pix3 * 256 + pix4 * 128 + pix5 * 64 + pix6 * 32 + pix7 * 16 + pix8 * 8 + pix9 * 4 + pix10 * 2 + pix11; if (numOfBlanks == 0) numOfBlanks = 4096; if (false) { exitLoop = false; SplitRecPtr tsr = (SplitRecPtr)&sipperRec; tsr->b1 = tsr->b2; recsRead = (kkint32)fread (&(tsr->b2), 1, 1, inFile); if (recsRead == 0) { moreRecs = false; return; } else { bytesDropped++; } } else { exitLoop = true; } } moreRecs = true; return; } /* GetNextSipperRec */ kkint32 linesInRowThatExceededBuffLen = 0; void SipperBuffBinary::GetNextLine (uchar* lineBuff, kkuint32 lineBuffSize, kkuint32& lineSize, kkuint32 colCount[], kkuint32& pixelsInRow, bool& flow ) { uchar cameraNum; bool eol; bool exceededBuffLen = false; bool moreRecs; kkint32 numOfBlanks; uchar pix1, pix2, pix3, pix4, pix5, pix6, pix7, pix8, pix9, pix10, pix11, pix0; bool raw; kkint32 spaceLeft = lineBuffSize; memset (lineBuff, 0, lineBuffSize); GetNextSipperRec (spaceLeft, cameraNum, raw, eol, flow, pix0, pix1, pix2, pix3, pix4, pix5, pix6, pix7, pix8, pix9, pix10, pix11, numOfBlanks, moreRecs); bool notFinished = moreRecs; lineSize = 0; pixelsInRow = 0; bool pauseAtEol = false; while (notFinished) { if (raw) { if (spaceLeft <= 0) { cerr << "*** Warning ***" << endl; if (spaceLeft < 0) exceededBuffLen = true; } else { if (pix0 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; if (spaceLeft > 0) { if (pix1 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix2 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix3 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix4 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix5 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix6 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix7 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix8 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix9 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix10 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } if (spaceLeft > 0) { if (pix11 > 0) { lineBuff[lineSize] = 255; colCount[lineSize]++; pixelsInRow++; } lineSize++; spaceLeft--; } } } else { // cout << setw (6) << numOfBlanks; if (numOfBlanks > spaceLeft) { numOfBlanks = 0; exceededBuffLen = true; } lineSize = lineSize + numOfBlanks; spaceLeft = spaceLeft - numOfBlanks; } // cout << setw (6) << lineSize << endl; if (exceededBuffLen) { exceededBuffLen = false; pauseAtEol = true; cerr << "*"; } if (eol) { notFinished = false; } else { GetNextSipperRec (spaceLeft, cameraNum, raw, eol, flow, pix0, pix1, pix2, pix3, pix4, pix5, pix6, pix7, pix8, pix9, pix10, pix11, numOfBlanks, moreRecs); notFinished = moreRecs; } } // if (pauseAtEol) // WaitForEnter (); if (exceededBuffLen) linesInRowThatExceededBuffLen++; else linesInRowThatExceededBuffLen = 0; if (linesInRowThatExceededBuffLen > 1) { linesInRowThatExceededBuffLen = 0; cout << "ReSinking Buffer" << endl; // WaitForEnter (); } if (lineSize > 4096) { cerr << "SipperBuffBinary::GetNextLine LineSize[" << lineSize << "] exceeded 4096 ." << endl; } else if ((lineSize == 0) && (!eof)) { lineSize = 1; } curRow++; } /* GetNextLine */
[ "kurtkramer@gmail.com" ]
kurtkramer@gmail.com
ba09acaf1e15ff5f9bde66f2162e9a8d19e567ba
5f2720560c50042f115cdfb9201728958d241893
/gef_abertay/platform/win32/system/window_win32.cpp
a32cdfa8af71ddccf2b9ed38c2cb540e3a93299d
[]
no_license
Skelebags/AnimationSystem
0757171a3f813bee11449241652f87454a71b23b
105a5c0978dcfc3ef75527c262ce2037015a1915
refs/heads/main
2023-02-12T06:34:31.956977
2021-01-07T22:42:24
2021-01-07T22:42:24
327,739,055
0
1
null
null
null
null
UTF-8
C++
false
false
4,301
cpp
#include <platform/win32/system/window_win32.h> LRESULT CALLBACK WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam) { switch(umessage) { // Check if the window is being destroyed. case WM_DESTROY: { PostQuitMessage(0); return 0; } // Check if the window is being closed. case WM_CLOSE: { PostQuitMessage(0); return 0; } // All other messages pass to the message handler in the system class. default: { return DefWindowProc(hwnd, umessage, wparam, lparam); } } } namespace gef { WindowWin32::WindowWin32(HINSTANCE hinstance, UInt32 screen_width, UInt32 screen_height, bool fullscreen, WNDPROC wndproc) : hwnd_(NULL) { DEVMODE screen_settings; UInt32 wnd_pos_x, wnd_pos_y; if (wndproc == NULL) wndproc = WndProc; bits_per_pixel_ = 32; // Get the instance of this application. hinstance_ = hinstance; // Give the application a name. application_name_ = "Framework Application"; // Setup the windows class with default settings. WNDCLASSEX wc; memset(&wc, 0, sizeof(wc)); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = wndproc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinstance_; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = application_name_; wc.cbSize = sizeof(WNDCLASSEX); // Register the window class. RegisterClassEx(&wc); // Setup the screen settings depending on whether it is running in full screen or in windowed mode. fullscreen_ = fullscreen; if(fullscreen_) { // Determine the resolution of the clients desktop screen. screen_width = GetSystemMetrics(SM_CXSCREEN); screen_height = GetSystemMetrics(SM_CYSCREEN); width_ = screen_width; height_ = screen_height; // If full screen set the screen to maximum size of the users desktop and 32bit. memset(&screen_settings, 0, sizeof(screen_settings)); screen_settings.dmSize = sizeof(screen_settings); screen_settings.dmPelsWidth = (unsigned long)screen_width; screen_settings.dmPelsHeight = (unsigned long)screen_height; screen_settings.dmBitsPerPel = bits_per_pixel_; screen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Change the display settings to full screen. ChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN); // Set the position of the window to the top left corner. wnd_pos_x = wnd_pos_y = 0; } else { width_ = screen_width; height_ = screen_height; // Place the window in the middle of the screen. if((UInt32)GetSystemMetrics(SM_CXSCREEN) < screen_width) wnd_pos_x = 0; else wnd_pos_x = (UInt32)(GetSystemMetrics(SM_CXSCREEN) - screen_width) >> 1; if((UInt32)GetSystemMetrics(SM_CYSCREEN) < screen_height) wnd_pos_y = 0; else wnd_pos_y = (UInt32)(GetSystemMetrics(SM_CYSCREEN) - screen_height) >> 1; } // Create the window with the screen settings and get the handle to it. if(fullscreen_) { hwnd_ = CreateWindowEx(WS_EX_TOPMOST, application_name_, application_name_, WS_POPUP, wnd_pos_x, wnd_pos_y, screen_width, screen_height, NULL, NULL, hinstance_, NULL); } else { DWORD style = WS_OVERLAPPEDWINDOW; RECT r; r.top = 0; r.bottom = screen_height; r.left = 0; r.right = screen_width; AdjustWindowRect(&r, style, FALSE); hwnd_ = CreateWindowEx(WS_EX_APPWINDOW, application_name_, application_name_, style, wnd_pos_x, wnd_pos_y, r.right - r.left, r.bottom - r.top, NULL, NULL, hinstance_, NULL); } RECT rect; ::GetClientRect(hwnd_, &rect); HRESULT hres = SetWindowText(hwnd_, application_name_); // Bring the window up on the screen and set it as main focus. ShowWindow(hwnd_, SW_SHOW); SetForegroundWindow(hwnd_); SetFocus(hwnd_); // Hide the mouse cursor. // ShowCursor(false); } WindowWin32::~WindowWin32() { // Show the mouse cursor. // ShowCursor(true); // Fix the display settings if leaving full screen mode. if(fullscreen_) ChangeDisplaySettings(NULL, 0); // Remove the window. DestroyWindow(hwnd_); hwnd_ = NULL; // Remove the application instance. UnregisterClass(application_name_, hinstance_); hinstance_ = NULL; } }
[ "tailzdafox@gmail.com" ]
tailzdafox@gmail.com
bdaf76fe4f92bbd2f92a6cd75aca6e936473d7f1
7b448ba6112b2d890a350bbe5d0c81dca8ab42da
/day03/ex03/NinjaTrap.hpp
cb2a4e2da08f23b2cd8b4ddde01cb66c1f576638
[]
no_license
ayoubmoussaid/cpp-pool-42
27a56f5ca1e5dbaa781b6a4045f3332c33bf3639
a56513a5e0bd70cdde08e0887906676fb4ba7a17
refs/heads/master
2023-07-18T02:52:17.293574
2021-09-06T08:24:37
2021-09-06T08:24:37
403,542,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,486
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* NinjaTrap.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amoussai <amoussai@student.1337.ma> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/05 08:08:41 by amoussai #+# #+# */ /* Updated: 2021/06/05 08:10:56 by amoussai ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef NINJATRAP_HPP # define NINJATRAP_HPP # include <iostream> # include <string> # include "ClapTrap.hpp" # include "FragTrap.hpp" # include "ScavTrap.hpp" class NinjaTrap: virtual public ClapTrap { private: NinjaTrap(); public: NinjaTrap(std::string const &name); NinjaTrap(NinjaTrap const &other); virtual ~NinjaTrap(); NinjaTrap &operator=(NinjaTrap const &other); void meleeAttack(std::string const &target); void rangedAttack(std::string const &target); void ninjaShoebox(FragTrap &trap); void ninjaShoebox(NinjaTrap &trap); void ninjaShoebox(ScavTrap &trap); }; #endif
[ "amoussai@student.1337.ma" ]
amoussai@student.1337.ma
41e8916be2cd9a32186edab069c539198e225b9c
1a45250b3028939800d83198fc9f4e2a93921a80
/Game.IO/GIEventSystem.cpp
407fa90c5eab6008790ca19743524e7e61768217
[]
no_license
starfoxcom/Game-io-Project
2842bd8c47d65914c7d5d6885440dc9d72093c4d
3d86ed398b4b9c71121ae82d79fe50127be6e04f
refs/heads/master
2020-12-19T09:39:10.568124
2020-02-19T20:33:24
2020-02-19T20:33:24
235,699,122
0
0
null
null
null
null
UTF-8
C++
false
false
2,469
cpp
#include "GIEventSystem.h" #include "GIGameObject.h" #include "GIWindow.h" GIEventSystem::GIEventSystem() { } GIEventSystem::~GIEventSystem() { } void GIEventSystem::Init(GIGameObject & _player) { m_radius = _player.getDescriptor().Radius; } void GIEventSystem::Update(GIGameObject & _player, vector<GIGameObject> & _food, vector<GIGameObject> & _enemies) { playerRadius(_player, _food, _enemies); playerVelocity(_player); } void GIEventSystem::Render() { } void GIEventSystem::Destroy() { } void GIEventSystem::playerRadius(GIGameObject & _player, vector<GIGameObject> & _food, vector<GIGameObject> & _enemies) { for (int i = 0; i < _food.size(); i++) { if (_player.getInterface()->getGlobalBounds().intersects(_food[i].getInterface()->getGlobalBounds()) && _food[i].getIsColliding() == false) { m_radius += 0.5f; _player.setRadius(m_radius); _player.setOrigin(sf::Vector2f(m_radius, m_radius)); _food[i].setCollidingState(true); _food.erase(_food.begin() + i); } } for (int i = 0; i < _enemies.size(); i++) { if (_player.getInterface()->getGlobalBounds().intersects(_enemies[i].getInterface()->getGlobalBounds()) && _player.getRadius() >= 150) { m_radius += 5; _player.setRadius(m_radius); _player.setOrigin(sf::Vector2f(m_radius, m_radius)); _enemies[i].setCollidingState(true); _enemies.erase(_enemies.begin() + i); } } // for (int i = 0; i < _enemies.size(); i++) // { // // If player collides with the enemy collider // if (_player.getInterface()->getGlobalBounds().intersects(_enemies[i].getInterface()->getGlobalBounds()) && _player.getRadius() >= 35) // { // m_radius -= 1; // _player.setRadius(m_radius); // _player.setOrigin(sf::Vector2f(m_radius, m_radius)); // } // } } void GIEventSystem::playerVelocity(GIGameObject & _player) { if (GIGraphic_API::getSingleton().inRange(_player.getRadius(), 20, 50)) { _player.setVelocity(5.0f); } if (GIGraphic_API::getSingleton().inRange(_player.getRadius(), 50, 80)) { _player.setVelocity(5.0f); } if (GIGraphic_API::getSingleton().inRange(_player.getRadius(), 80, 100)) { _player.setVelocity(2.0f); } if (GIGraphic_API::getSingleton().inRange(_player.getRadius(), 100, 130)) { _player.setVelocity(1.0f); } if (GIGraphic_API::getSingleton().inRange(_player.getRadius(), 130, 160)) { _player.setVelocity(0.8f); } }
[ "idv18c.jmoral@uartesdigitales.edu.mx" ]
idv18c.jmoral@uartesdigitales.edu.mx
33dc826976f263109e71f378cb0d6cbdc34aeb2f
67b030efd49825a74e024d5388f5896e081c39ea
/1967.cpp
cdb704fff2be092a0df3446d3c19311fed14beaf
[]
no_license
rile1036/acmicpc_algorithm
f821fc1907f8e8e0a54a848e42cc7768ed159cf1
e85fb856bf072ccc1109bad053df3fc7a452fea7
refs/heads/master
2020-12-20T08:45:29.927589
2020-02-01T04:13:22
2020-02-01T04:13:22
236,019,613
0
0
null
null
null
null
UTF-8
C++
false
false
945
cpp
#include<iostream> #include<vector> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; #define MAX 10001 int N; int sum = 0; int End; vector <pair <int, int>> vec[MAX]; bool visit[MAX] = { false, }; void DFS(int start, int check_weight) { if (visit[start]) return; visit[start] = true; if (sum < check_weight) { sum = check_weight; End = start; } for (int i = 0; i < vec[start].size(); i++) DFS(vec[start][i].first, check_weight + vec[start][i].second); } void init() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } int main() { cin >> N; int parent, child, weight; for (int i = 0; i < N - 1; i++) { cin >> parent >> child >> weight; vec[parent].push_back(make_pair(child, weight)); vec[child].push_back(make_pair(parent, weight)); } DFS(1, 0); sum = 0; memset(visit, false, sizeof(visit)); DFS(End, 0); cout << sum; return 0; }
[ "rile1036@gmail.com" ]
rile1036@gmail.com
ce13da859fcb9c928c537843c1717090e2e43b85
37fffa1c15d4db9f57d0e4812adae7ba0f1cf910
/src/_test.cpp
b9aed5120ce6f3d08b30c9531c043f8f1659edfc
[]
no_license
Anonymous-Stranger/CSVReader
ef1a1e42a11685e2efc3c9eb810d1eeac251c5c0
b35ca6e076cd05e72dd63a7c61529f5e923b0cfd
refs/heads/master
2021-01-01T17:33:18.609371
2015-12-10T08:42:16
2015-12-10T08:42:16
41,451,517
1
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
/* * _main.cpp * * A test to see if CSVStream is working. Should work with any proper csv file with first row headers. * * Created on: Aug 14, 2015 * Author: Akash */ #include "_test.h" namespace CSVReaderTest { void run(std::string testFile) { CSVReader::CSVStream in {new std::ifstream(testFile)}; // load the file while (!in.empty()) { // loop through file // fetch a record and print it: auto record = in.get(); for (auto& item : record) { std::cout << item.first << ":" << item.second << " "; } std::cout << std::endl; } std::cout << "File read." << std::endl; } }
[ "akashgaonkar@gmail.com" ]
akashgaonkar@gmail.com
3fcaf34bd3925551c3b2e3197cfa573ef1d0fa9a
e44994d72ee3db77784df53315d5b49888cd75c2
/GVRf/Framework/framework/src/main/jni/objects/components/component_jni.cpp
3a1dc51507bd2743eb6769deef66357efddee991
[ "Apache-2.0" ]
permissive
parthmehta209/GearVRf
e3edf690c85d78ab2f02d263a295f4c3198567bb
8c8dd042def4addbd31de5a984689962f8bc72ce
refs/heads/master
2020-04-04T17:53:17.049226
2016-06-20T20:38:12
2016-06-20T20:38:12
60,131,985
0
0
null
2016-06-01T00:07:50
2016-06-01T00:07:49
null
UTF-8
C++
false
false
2,248
cpp
/* Copyright 2015 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "component.h" #include "util/gvr_jni.h" #include "util/gvr_log.h" namespace gvr { extern "C" { JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeComponent_getType(JNIEnv * env, jobject obj, jlong jcomponent); JNIEXPORT void JNICALL Java_org_gearvrf_NativeComponent_setOwnerObject(JNIEnv * env, jobject obj, jlong jcomponent, jlong jowner); JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeComponent_isEnabled(JNIEnv * env, jobject obj, jlong jcomponent); JNIEXPORT void JNICALL Java_org_gearvrf_NativeComponent_setEnable(JNIEnv * env, jobject obj, jlong jlight, jboolean flag); } JNIEXPORT jlong JNICALL Java_org_gearvrf_NativeComponent_getType(JNIEnv * env, jobject obj, jlong jcomponent) { Component* component = reinterpret_cast<Component*>(jcomponent); long long type = component->getType(); return type; } JNIEXPORT void JNICALL Java_org_gearvrf_NativeComponent_setOwnerObject(JNIEnv * env, jobject obj, jlong jcomponent, jlong jowner) { Component* component = reinterpret_cast<Component*>(jcomponent); SceneObject* owner = reinterpret_cast<SceneObject*>(jowner); component->set_owner_object(owner); } JNIEXPORT jboolean JNICALL Java_org_gearvrf_NativeComponent_isEnabled(JNIEnv * env, jobject obj, jlong jcomponent) { Component* component = reinterpret_cast<Component*>(jcomponent); return component->enabled(); } JNIEXPORT void JNICALL Java_org_gearvrf_NativeComponent_setEnable(JNIEnv * env, jobject obj, jlong jcomponent, jboolean flag) { Component* component = reinterpret_cast<Component*>(jcomponent); component->set_enable(flag); } }
[ "nola.donato@samsung.com" ]
nola.donato@samsung.com
569da095545bd19efd17f456c43429ff8114024a
f58f9f58c21e5399799fac4aaefacaa93fb387aa
/A7/analyse2.cpp
4d7b7e820f9eb9ffaffd1abd74916cfb3b56ae93
[]
no_license
NachiketE/CNL
6d1437f9784976d0ec10781fbc1de717316381a6
abb6ab244ca26f155b5f90e7da605f6546551fc5
refs/heads/master
2020-08-31T14:35:17.996452
2019-10-31T07:48:11
2019-10-31T07:48:11
217,819,639
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
cpp
#include <iostream> #include <pcap.h> #include <netinet/in.h> #include <netinet/ip.h> #include <arpa/inet.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <net/ethernet.h> using namespace std; void packetHandler(u_char *user, const struct pcap_pkthdr *h,const u_char *packet); int tcpcount = 0; int udpcount = 0; int ipcount = 0; int ipv6count = 0; int ethercount = 0; int icmpcount = 0; int arpcount = 0; int main() { pcap_t *fp; char errbuf[PCAP_ERRBUF_SIZE]; fp = pcap_open_offline("CapturedPacketspcap.pcap", errbuf); pcap_loop(fp, 0, packetHandler, NULL); cout<<"tcpcount: "<<tcpcount<<endl; cout<<"udpcount: "<<udpcount<<endl; cout<<"ipv6count: "<<ipv6count<<endl; cout<<"ipcount: "<<ipcount<<endl; cout<<"ethercount: "<<ethercount<<endl; cout<<"arpcount: "<<arpcount<<endl; } void packetHandler(u_char *user, const struct pcap_pkthdr *h,const u_char *packet){ const struct ether_header* etherHeader; const struct ip* ipheader; etherHeader=(struct ether_header *)packet; ethercount++; if(ntohs(etherHeader->ether_type)==ETHERTYPE_IP){ ipcount++; ipheader = (struct ip*)(packet+ sizeof(ether_header)); if(ipheader->ip_p==IPPROTO_UDP) udpcount++; if(ipheader->ip_p==IPPROTO_TCP) tcpcount++; } if(ntohs(etherHeader->ether_type)==ETHERTYPE_ARP){ arpcount++; } if(ntohs(etherHeader->ether_type)==ETHERTYPE_IPV6){ ipv6count++; } }
[ "nachiketerlekar@gmail.com" ]
nachiketerlekar@gmail.com
000223d9662d579c4cc69811c24963b9757833a8
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-codeartifact/include/aws/codeartifact/model/ListPackageVersionAssetsResult.h
67fcb43615bb03e7ff0bf79157922c2407916f89
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
14,173
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/codeartifact/CodeArtifact_EXPORTS.h> #include <aws/codeartifact/model/PackageFormat.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/codeartifact/model/AssetSummary.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace CodeArtifact { namespace Model { class AWS_CODEARTIFACT_API ListPackageVersionAssetsResult { public: ListPackageVersionAssetsResult(); ListPackageVersionAssetsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); ListPackageVersionAssetsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p> The format of the package that contains the returned package version assets. * </p> */ inline const PackageFormat& GetFormat() const{ return m_format; } /** * <p> The format of the package that contains the returned package version assets. * </p> */ inline void SetFormat(const PackageFormat& value) { m_format = value; } /** * <p> The format of the package that contains the returned package version assets. * </p> */ inline void SetFormat(PackageFormat&& value) { m_format = std::move(value); } /** * <p> The format of the package that contains the returned package version assets. * </p> */ inline ListPackageVersionAssetsResult& WithFormat(const PackageFormat& value) { SetFormat(value); return *this;} /** * <p> The format of the package that contains the returned package version assets. * </p> */ inline ListPackageVersionAssetsResult& WithFormat(PackageFormat&& value) { SetFormat(std::move(value)); return *this;} /** * <p> The namespace of the package. The package component that specifies its * namespace depends on its type. For example: </p> <ul> <li> <p> The namespace of * a Maven package is its <code>groupId</code>. </p> </li> <li> <p> The namespace * of an npm package is its <code>scope</code>. </p> </li> <li> <p> A Python * package does not contain a corresponding component, so Python packages do not * have a namespace. </p> </li> </ul> */ inline const Aws::String& GetNamespace() const{ return m_namespace; } /** * <p> The namespace of the package. The package component that specifies its * namespace depends on its type. For example: </p> <ul> <li> <p> The namespace of * a Maven package is its <code>groupId</code>. </p> </li> <li> <p> The namespace * of an npm package is its <code>scope</code>. </p> </li> <li> <p> A Python * package does not contain a corresponding component, so Python packages do not * have a namespace. </p> </li> </ul> */ inline void SetNamespace(const Aws::String& value) { m_namespace = value; } /** * <p> The namespace of the package. The package component that specifies its * namespace depends on its type. For example: </p> <ul> <li> <p> The namespace of * a Maven package is its <code>groupId</code>. </p> </li> <li> <p> The namespace * of an npm package is its <code>scope</code>. </p> </li> <li> <p> A Python * package does not contain a corresponding component, so Python packages do not * have a namespace. </p> </li> </ul> */ inline void SetNamespace(Aws::String&& value) { m_namespace = std::move(value); } /** * <p> The namespace of the package. The package component that specifies its * namespace depends on its type. For example: </p> <ul> <li> <p> The namespace of * a Maven package is its <code>groupId</code>. </p> </li> <li> <p> The namespace * of an npm package is its <code>scope</code>. </p> </li> <li> <p> A Python * package does not contain a corresponding component, so Python packages do not * have a namespace. </p> </li> </ul> */ inline void SetNamespace(const char* value) { m_namespace.assign(value); } /** * <p> The namespace of the package. The package component that specifies its * namespace depends on its type. For example: </p> <ul> <li> <p> The namespace of * a Maven package is its <code>groupId</code>. </p> </li> <li> <p> The namespace * of an npm package is its <code>scope</code>. </p> </li> <li> <p> A Python * package does not contain a corresponding component, so Python packages do not * have a namespace. </p> </li> </ul> */ inline ListPackageVersionAssetsResult& WithNamespace(const Aws::String& value) { SetNamespace(value); return *this;} /** * <p> The namespace of the package. The package component that specifies its * namespace depends on its type. For example: </p> <ul> <li> <p> The namespace of * a Maven package is its <code>groupId</code>. </p> </li> <li> <p> The namespace * of an npm package is its <code>scope</code>. </p> </li> <li> <p> A Python * package does not contain a corresponding component, so Python packages do not * have a namespace. </p> </li> </ul> */ inline ListPackageVersionAssetsResult& WithNamespace(Aws::String&& value) { SetNamespace(std::move(value)); return *this;} /** * <p> The namespace of the package. The package component that specifies its * namespace depends on its type. For example: </p> <ul> <li> <p> The namespace of * a Maven package is its <code>groupId</code>. </p> </li> <li> <p> The namespace * of an npm package is its <code>scope</code>. </p> </li> <li> <p> A Python * package does not contain a corresponding component, so Python packages do not * have a namespace. </p> </li> </ul> */ inline ListPackageVersionAssetsResult& WithNamespace(const char* value) { SetNamespace(value); return *this;} /** * <p> The name of the package that contains the returned package version assets. * </p> */ inline const Aws::String& GetPackage() const{ return m_package; } /** * <p> The name of the package that contains the returned package version assets. * </p> */ inline void SetPackage(const Aws::String& value) { m_package = value; } /** * <p> The name of the package that contains the returned package version assets. * </p> */ inline void SetPackage(Aws::String&& value) { m_package = std::move(value); } /** * <p> The name of the package that contains the returned package version assets. * </p> */ inline void SetPackage(const char* value) { m_package.assign(value); } /** * <p> The name of the package that contains the returned package version assets. * </p> */ inline ListPackageVersionAssetsResult& WithPackage(const Aws::String& value) { SetPackage(value); return *this;} /** * <p> The name of the package that contains the returned package version assets. * </p> */ inline ListPackageVersionAssetsResult& WithPackage(Aws::String&& value) { SetPackage(std::move(value)); return *this;} /** * <p> The name of the package that contains the returned package version assets. * </p> */ inline ListPackageVersionAssetsResult& WithPackage(const char* value) { SetPackage(value); return *this;} /** * <p> The version of the package associated with the returned assets. </p> */ inline const Aws::String& GetVersion() const{ return m_version; } /** * <p> The version of the package associated with the returned assets. </p> */ inline void SetVersion(const Aws::String& value) { m_version = value; } /** * <p> The version of the package associated with the returned assets. </p> */ inline void SetVersion(Aws::String&& value) { m_version = std::move(value); } /** * <p> The version of the package associated with the returned assets. </p> */ inline void SetVersion(const char* value) { m_version.assign(value); } /** * <p> The version of the package associated with the returned assets. </p> */ inline ListPackageVersionAssetsResult& WithVersion(const Aws::String& value) { SetVersion(value); return *this;} /** * <p> The version of the package associated with the returned assets. </p> */ inline ListPackageVersionAssetsResult& WithVersion(Aws::String&& value) { SetVersion(std::move(value)); return *this;} /** * <p> The version of the package associated with the returned assets. </p> */ inline ListPackageVersionAssetsResult& WithVersion(const char* value) { SetVersion(value); return *this;} /** * <p> The current revision associated with the package version. </p> */ inline const Aws::String& GetVersionRevision() const{ return m_versionRevision; } /** * <p> The current revision associated with the package version. </p> */ inline void SetVersionRevision(const Aws::String& value) { m_versionRevision = value; } /** * <p> The current revision associated with the package version. </p> */ inline void SetVersionRevision(Aws::String&& value) { m_versionRevision = std::move(value); } /** * <p> The current revision associated with the package version. </p> */ inline void SetVersionRevision(const char* value) { m_versionRevision.assign(value); } /** * <p> The current revision associated with the package version. </p> */ inline ListPackageVersionAssetsResult& WithVersionRevision(const Aws::String& value) { SetVersionRevision(value); return *this;} /** * <p> The current revision associated with the package version. </p> */ inline ListPackageVersionAssetsResult& WithVersionRevision(Aws::String&& value) { SetVersionRevision(std::move(value)); return *this;} /** * <p> The current revision associated with the package version. </p> */ inline ListPackageVersionAssetsResult& WithVersionRevision(const char* value) { SetVersionRevision(value); return *this;} /** * <p> If there are additional results, this is the token for the next set of * results. </p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p> If there are additional results, this is the token for the next set of * results. </p> */ inline void SetNextToken(const Aws::String& value) { m_nextToken = value; } /** * <p> If there are additional results, this is the token for the next set of * results. </p> */ inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); } /** * <p> If there are additional results, this is the token for the next set of * results. </p> */ inline void SetNextToken(const char* value) { m_nextToken.assign(value); } /** * <p> If there are additional results, this is the token for the next set of * results. </p> */ inline ListPackageVersionAssetsResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p> If there are additional results, this is the token for the next set of * results. </p> */ inline ListPackageVersionAssetsResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p> If there are additional results, this is the token for the next set of * results. </p> */ inline ListPackageVersionAssetsResult& WithNextToken(const char* value) { SetNextToken(value); return *this;} /** * <p> The returned list of <a * href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> * objects. </p> */ inline const Aws::Vector<AssetSummary>& GetAssets() const{ return m_assets; } /** * <p> The returned list of <a * href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> * objects. </p> */ inline void SetAssets(const Aws::Vector<AssetSummary>& value) { m_assets = value; } /** * <p> The returned list of <a * href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> * objects. </p> */ inline void SetAssets(Aws::Vector<AssetSummary>&& value) { m_assets = std::move(value); } /** * <p> The returned list of <a * href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> * objects. </p> */ inline ListPackageVersionAssetsResult& WithAssets(const Aws::Vector<AssetSummary>& value) { SetAssets(value); return *this;} /** * <p> The returned list of <a * href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> * objects. </p> */ inline ListPackageVersionAssetsResult& WithAssets(Aws::Vector<AssetSummary>&& value) { SetAssets(std::move(value)); return *this;} /** * <p> The returned list of <a * href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> * objects. </p> */ inline ListPackageVersionAssetsResult& AddAssets(const AssetSummary& value) { m_assets.push_back(value); return *this; } /** * <p> The returned list of <a * href="https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html">AssetSummary</a> * objects. </p> */ inline ListPackageVersionAssetsResult& AddAssets(AssetSummary&& value) { m_assets.push_back(std::move(value)); return *this; } private: PackageFormat m_format; Aws::String m_namespace; Aws::String m_package; Aws::String m_version; Aws::String m_versionRevision; Aws::String m_nextToken; Aws::Vector<AssetSummary> m_assets; }; } // namespace Model } // namespace CodeArtifact } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
5cf666dde40855701bf7431f5199fde3651598ab
735f14e7e197e53c63eb7dfe8bde672b277302d2
/Collections/Person.cpp
fb4f99a81be525bc591459710e8bb5eab320c832
[]
no_license
boyuanf/CPPLearning
688e4d7952c9eaea56971d614aeb86383b94c9a0
bbfacf2ce3a03d9c37c7fd1558326899edbd0e00
refs/heads/master
2021-01-19T00:18:24.113113
2016-10-26T01:08:18
2016-10-26T01:08:18
60,791,634
0
0
null
2016-06-09T18:45:29
2016-06-09T16:59:35
C++
UTF-8
C++
false
false
1,443
cpp
#include "stdafx.h" #include "Person.h" #include <iostream> using namespace std; Person::Person() : firstname(""), lastname(""), arbitrarynumber(0)/*, pResource(nullptr)*/ { } //Person::Person(const Person& p) : firstname(p.firstname), lastname(p.lastname), //arbitrarynumber(p.arbitrarynumber), pResource(new Resource(p.pResource->GetName())) //{ //} // Person::Person(string first,string last, int arbitrary) : firstname(first),lastname(last), arbitrarynumber(arbitrary)/*, pResource(nullptr)*/ { if (arbitrarynumber==0) { throw invalid_argument("arbitrary number for a person cannot be 0"); } cout << "constructing Person " << firstname << " " << lastname << endl; } Person::~Person() { //delete pResource; cout << "destructing Person " << firstname << " " << lastname << endl; } bool Person::operator<(Person& p) { return arbitrarynumber < p.arbitrarynumber; } bool Person::operator<(int i) { return arbitrarynumber < i; } void Person::AddResource() { pResource.reset(); pResource = std::make_shared<Resource>("Resource for " + GetName()); } bool operator<(int i, Person& p) { return i < p.arbitrarynumber; } void Person::SetFirstName(string fName) { firstname = fName; } //Person& Person::operator=(const Person& p) //{ // firstname=p.firstname; // lastname = p.lastname; // arbitrarynumber = p.arbitrarynumber; // delete pResource; // pResource=new Resource(p.pResource->GetName()); // return *this; //}
[ "fengboyuannj@gmail.com" ]
fengboyuannj@gmail.com
db7d3a89bf5da38aa5bfc0c15896307d849753cb
1ed6fc81dc330b86d5bdfaafd918eac18cdc02ec
/src/2376.cc
0f2bd06a156b16a3ec6c79b1e8bede2083f000b8
[]
no_license
libenchao/codepoj
0c9e249af76d3056e5c8c23ab7ddb85ae0fb894e
2c898da0afe46f640754f0b2b75b6062c59609f4
refs/heads/master
2020-05-19T18:55:10.298499
2015-03-12T16:09:52
2015-03-12T16:09:52
29,141,838
0
0
null
null
null
null
UTF-8
C++
false
false
1,126
cc
#include<iostream> #include<cstdio> #include<queue> #include<stack> #include<list> #include<set> #include<map> #include<string> #include<algorithm> #include<vector> using namespace std; const int MAXN = 25001; pair<int,int> data[MAXN]; bool func(pair<int,int> a,pair<int,int> b){ return a.first < b.first; } int main() { int n,t; while(scanf("%d%d",&n,&t) != EOF){ for(int i = 0; i < n; ++i){ int start,end; scanf("%d%d",&start,&end); data[i] = make_pair(start,end); } sort(data,data+n,func); int cur = 1; int dcur = 0; int ans = 0; bool solvable = true; while(cur <= t){ pair<int,int> hehe; bool found = false; for(;dcur < n;dcur++){ if(data[dcur].first <= cur && data[dcur].second >= cur){ if(found && data[dcur].second > hehe.second){ hehe = data[dcur]; }else if(!found){ found = true; hehe = data[dcur]; } }else if(data[dcur].first > cur){ break; } } if(!found){ solvable = false; break; } ans++; cur = hehe.second+1; } if(solvable){ printf("%d\n",ans); }else{ printf("-1\n"); } } return 0; }
[ "libenchao@gmail.com" ]
libenchao@gmail.com
67998d58dfc192412be193fd08adb944b63a9465
6698f9640734a17dbda357c9cd68d940cf22dc52
/main.cpp
60de26e7c265253d9043bdba30e41da6093b66f6
[]
no_license
Zoneshi/CAC2021
d0f863ab6803797587f52fd093e67d10e0fed791
c7d9e78865c97e1a6732d569cb3e0900fb7c101c
refs/heads/main
2023-07-28T03:59:59.641947
2021-09-09T03:04:31
2021-09-09T03:04:31
404,561,281
0
0
null
null
null
null
UTF-8
C++
false
false
8,201
cpp
#if __INTELLISENSE__ #undef __ARM_NEON #undef __ARM_NEON__ #endif #include <iostream> #include <fstream> #include <string> #include <sciplot/sciplot.hpp> #include <Eigen/Dense> #include <Eigen/Geometry> using namespace std; using namespace Eigen; using namespace sciplot; typedef vector<Matrix<double,17,1>> vector_rec; typedef Matrix<double,8,1> Vector8d; Vector4d CL_term(0.0,0.0,0.0,0.0); Matrix<double,4,4> YFYF = MatrixXd::Zero(4,4); Vector4d YFtheta_star(0.0,0.0,0.0,0.0); typedef struct SysPara { Vector4d theta_star; double gamma; double gamma_epsilon; double K; double tau; } syspara; typedef VectorXd (* DynamiModel) (const double &t, const VectorXd &x, const syspara &para); class RungeKutta { private: double m_time_step; DynamiModel m_dynamic_model; public: RungeKutta(DynamiModel dynamic_model, double time_step); void Euler(double &t, VectorXd &x, const syspara &para); void Rk45(double &t, VectorXd &x, const syspara &para); }; RungeKutta::RungeKutta(DynamiModel dynamic_model, double time_step) { m_dynamic_model = dynamic_model; m_time_step = time_step; } void RungeKutta::Euler(double &t, VectorXd &x, const syspara &para) { x = x + m_time_step * m_dynamic_model(t,x,para); t = t + m_time_step; } void RungeKutta::Rk45(double &t, VectorXd &x, const syspara &para) { VectorXd k1 = m_dynamic_model(t, x, para); t = t + m_time_step / 2; VectorXd x1 = x + k1 * m_time_step / 2; VectorXd k2 = m_dynamic_model(t, x1, para); VectorXd x2 = x + k2 * m_time_step / 2; VectorXd k3 = m_dynamic_model(t, x2, para); t = t + m_time_step / 2; VectorXd x3 = x + m_time_step * k3; VectorXd k4 = m_dynamic_model(t, x3, para); x = x + m_time_step / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4); } //----------------------------------------------------------- //| x | theta | xi | YF | //----------------------------------------------------------- //| [0:1] | [2:5] | [6:7] | [8:15] | //----------------------------------------------------------- VectorXd NonlinearDynamics(const double &t, const VectorXd &states, const syspara &para) { Vector2d x(states(0),states(1)); // system states double x1 = states(0); double x2 = states(1); Vector4d theta(states(2),states(3),states(4),states(5)); Vector2d xi(states(6),states(7)); Vector8d YF_vec(states(8),states(9),states(10),states(11),states(12),states(13),states(14),states(15)); Vector2d x_d(1.0,0.0); Vector4d theta_star = para.theta_star; double K = para.K; Vector8d Y_vec(x1*x1, sin(x2), 0.0, 0.0,0.0, x2*sin(t), x1, x1*x2); Matrix<double,2,4> Y = Y_vec.reshaped<RowMajor>(2,4); Matrix<double,2,4> YF = YF_vec.reshaped<RowMajor>(2,4); //****************************************************************************************** Vector2d e = x_d - x; Vector2d u = -Y * theta + K * e; //****************************************************************************************** Vector2d YFtheta = xi - e/para.tau; if (e.norm() > 0.1) { YFYF = YFYF + YF.transpose()*YF; YFtheta_star = YFtheta_star + YF.transpose() * YFtheta; } // YFYF = 0.8*YFYF + 0.01*(YF.transpose()*YF); // YFtheta_star = 0.8*YFtheta_star + 0.01*(YF.transpose() * YFtheta); CL_term = YFYF * theta - YFtheta_star; //****************************************************************************************** Vector2d dot_x = Y * theta_star + u; Vector4d dot_theta = - para.gamma * Y.transpose() * e - para.gamma_epsilon * CL_term; Vector2d dot_xi = (Y * theta + (1/para.tau - K) * e - xi)/para.tau; Vector8d dot_YF = (Y_vec - YF_vec)/para.tau; VectorXd dot_states(states.size()); dot_states <<dot_x, dot_theta, dot_xi, dot_YF; return dot_states; } void DataVisiualization(const MatrixXd &plotdata) { Plot plot_x_2D; plot_x_2D.xlabel("time/[s]"); plot_x_2D.ylabel("x(t)"); plot_x_2D.drawCurve(plotdata(0,all), plotdata(1,all)).label("x_1").lineWidth(2); plot_x_2D.drawCurve(plotdata(0,all), plotdata(2,all)).label("x_2").lineWidth(2); plot_x_2D.grid().show(); Plot plot_theta_2D; plot_theta_2D.xlabel("time/[s]"); plot_theta_2D.ylabel("theta"); plot_theta_2D.drawCurve(plotdata(0,all), plotdata(3,all)).label("theta_1").lineWidth(2); plot_theta_2D.drawCurve(plotdata(0,all), plotdata(4,all)).label("theta_2").lineWidth(2); plot_theta_2D.drawCurve(plotdata(0,all), plotdata(5,all)).label("theta_3").lineWidth(2); plot_theta_2D.drawCurve(plotdata(0,all), plotdata(6,all)).label("theta_4").lineWidth(2); plot_theta_2D.grid().show(); // Use the previous plots as sub-figures in a larger 2x2 figure. Figure fig1 = {{plot_x_2D},{plot_theta_2D}}; fig1.size(600,600); fig1.title("Missile-Type UAV Position & Attitude"); fig1.palette("set1"); fig1.show(); } int main(int argc, char * argv[]) { // output simulation results to specified files const string save_path = "../result.csv"; ofstream save_file(save_path); save_file << "time,x1,x2,theta1,theta2,theta3,theta4,xi1,xi2,YF1,YF2,YF3,YF4,YF5,YF6,YF7,YF8"<<endl; syspara config; config.theta_star = Vector4d(5.0,10.0,15.0,20.0); config.gamma = 100; config.gamma_epsilon = 2; config.K = 5; config.tau = 0.01; //****************************************************************************************** Vector2d x0(0.0,0.0); // initial states Vector4d theta0(0.0,0.0,0.0,0.0); // initial estimates Vector2d xi0(0.0,0.0); // initial xi Vector8d YF0(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0); // initial yf int states_dim = x0.size() + theta0.size() + xi0.size() + YF0.size(); // states dimensions //****************************************************************************************** constexpr double init_time = 0.0; // initial simulation time constexpr double final_time = 1.0; // final simulation time constexpr double time_step = 0.01; // simulation time step constexpr double data_rec_step = 0.01; // data recording time step constexpr int num_rec_step = (int)(data_rec_step/time_step);// data recording numbers //****************************************************************************************** RungeKutta cac = RungeKutta(NonlinearDynamics,time_step); // simulation instance double t = init_time; // simulation time VectorXd states_value(states_dim); // initial states states_value << x0, theta0, xi0, YF0; const bool isplot = true; // gnuplot windows const bool isoutput = true; // console output int iter_num = 0; // iteration numbers Matrix<double,17,1> states; // total system states cout.precision(6); // config the terminal output format cout.flags(ios::fixed); cout.setf(ios::right); vector_rec rec_data; // Simulations results vector<double> // start loop to simulate while (t < final_time) { // augment time and states states << t, states_value; if((iter_num % num_rec_step)==0) { rec_data.push_back(states); for (int i = 0; i < states.size(); i++) { save_file << states(i) << ','; if(isoutput == true) { cout << states(i) << '\t'; } } save_file << endl; if(isoutput == true) { cout << endl; } } cac.Euler(t,states_value,config); iter_num += 1; } save_file.close(); // plot if(isplot == true) { MatrixXd plotdata = Map<MatrixXd> (rec_data[0].data(),17,rec_data.size()); DataVisiualization(plotdata); } return 0; }
[ "shizhongjiao@gmail.com" ]
shizhongjiao@gmail.com
41a0cd28ef23598336a15618216a38efb8e0919e
8a6b35a9fe753f6d13939b6e8519e743549358b5
/Game.cpp
b8aeb05fe5035a90b0a838908eedd4540d10c2da
[]
no_license
RyanSwann1/Snake-CPP-SDL
a6862afb695795a11f36d96cb1650f3028260eb9
98019f5ab9125ef895921d693b54782ebead1fdd
refs/heads/master
2018-01-08T06:46:44.025784
2016-03-10T11:03:27
2016-03-10T11:03:27
53,577,858
0
0
null
null
null
null
UTF-8
C++
false
false
3,736
cpp
#include "Game.h" #include "Window.h" #include "Character.h" #include <cassert> Game::Game(Window& window) { createRenderer(window); m_nextFoodSpawn = 2000; } Game::~Game() { } void Game::render(const Window& window, Character& player) { SDL_RenderClear(m_renderer); //Render player SDL_SetRenderDrawColor(m_renderer, 0, 255, 255, 255); for (auto &i : player.getSnake()) { SDL_RenderFillRect(m_renderer, &i.m_pos); } //Render players head SDL_SetRenderDrawColor(m_renderer, 175, 175, 175, 175); SDL_RenderFillRect(m_renderer, &player.getSnakeHead()); //Render Food SDL_SetRenderDrawColor(m_renderer, 255, 0, 255, 255); for (auto &i : m_food) { SDL_RenderFillRect(m_renderer, &i.m_pos); } //Render background SDL_SetRenderDrawColor(m_renderer, 255, 255, 255, 255); //Apply SDL_RenderPresent(m_renderer); } void Game::update(Character& player) { spawnFood(); player.moveManagement(); playerBounds(player); collisionManagement(player); } void Game::collisionManagement(Character & player) { //Player to Food Collision for (int snakeObject = 0; snakeObject < player.getSnake().size(); snakeObject++) { for (int foodObject = 0; foodObject < m_food.size(); foodObject++) { //If collision detected if (player.collision(player.getSnake()[snakeObject], m_food[foodObject])) { m_food.erase(m_food.begin() + foodObject); //Remove food piece from game player.eat(); } } } } void Game::playerBounds(Character & player) { static const int maxPos = 575; static const int minPos = 0; if (player.getSnake().front().m_pos.x < minPos) { player.setXPosition(maxPos); } if (player.getSnake().front().m_pos.x > maxPos) { player.setXPosition(minPos); } if (player.getSnake().front().m_pos.y < minPos) { player.setYPosition(maxPos); } if (player.getSnake().front().m_pos.y > maxPos) { player.setYPosition(minPos); } } void Game::createRenderer(const Window& window) { m_renderer = SDL_CreateRenderer(window.getWindow(), -1, SDL_RENDERER_ACCELERATED); assert(m_renderer != nullptr); } int Game::getRandomNumber(const int val1, const int val2) const { static std::random_device rd; static std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(val1, val2); return dis(gen); } void Game::spawnFood() { static constexpr int minPos = 20; static constexpr int maxPos = 570; int spawnFood = 0; int randPos = 0; int spawnXPos = 0; int spawnYPos = 0; bool validSpawn = false; /* Javawag: so takes a random point, divides by 25... but coz its an int it rounds down Javawag: so imagine its 30.... 30 / 25 = 1 (it drops the .whatever) Javawag: and then 1 x 25 = 25 :D Javawag: doesnt work with floats though, obv :D */ //https://pastee.org/uazs2 Uint32 currentTime = SDL_GetTicks(); if (SDL_TICKS_PASSED(currentTime, m_nextFoodSpawn)) { while (!validSpawn) { //Get 'X' position spawnXPos = getRandomNumber(minPos, maxPos) / 25 * 25; //while (spawnXPos % 25 != 0) { // spawnXPos = getRandomNumber(minPos, maxPos); //} //Get 'Y' Position spawnYPos = getRandomNumber(minPos, maxPos) / 25 * 25; //while (spawnYPos % 25 != 0) { // spawnYPos = getRandomNumber(minPos, maxPos); //} //Check to see if food is on requested position for (auto &i : m_food) { if (spawnXPos == i.m_pos.x && spawnYPos == i.m_pos.y) { validSpawn = false; break; } } //If there is no food on requested position validSpawn = true; } m_food.push_back(Entity(spawnXPos, spawnYPos)); m_nextFoodSpawn += FOOD_SPAWN_TIME; } }
[ "RyanSwann1992@gmail.com" ]
RyanSwann1992@gmail.com
e21f0b6bceb03c8d251dadd3bc35d6cf88609168
c5d157bef8006d5c6a45e04ca680f526d6e21bba
/Multiplication.h
0ee37e108d1db048665689b94de7975bd4b2d9e6
[]
no_license
moriya1232/proj2
aef66466277db9150278e52453fe329cbd9cd65a
cd4ad6b07774d0db831cf8f3299296301444b0c5
refs/heads/master
2020-04-14T08:57:20.071890
2019-01-13T15:22:58
2019-01-13T15:22:58
163,747,911
0
0
null
null
null
null
UTF-8
C++
false
false
456
h
// // Created by moriya on 08/12/18. // #ifndef UNTITLED5_Multiplication_H #define UNTITLED5_Multiplication_H #include "BinaryExpression.h" #include "Expression.h" using namespace std; class Multiplication: public BinaryExpression { public: Multiplication(Expression* left, Expression* right); double calculate(); Multiplication(); void setRight(Expression* r); void setLeft(Expression* l); }; #endif //UNTITLED5_Multiplication_H
[ "omeromer312@gmail.com" ]
omeromer312@gmail.com
17b7c69acbf49a83bfafb36504e29fd0016b5345
a22d485f7368224a487050f31d1fe8a16fd9dea4
/9_26.cpp
3820fee55859c157a013cfedf575db9605666dea
[]
no_license
xxqcheers/learngit
5b6376034fd122b479eaa526334c08839011521a
ee8784953c70086c61fb1f6511fef6e4962ee650
refs/heads/master
2020-06-04T10:33:57.802595
2014-07-16T16:13:40
2014-07-16T16:13:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,749
cpp
/************************************************************************* > File Name: 9_26.cpp > Author: xuxiaoqiang > Mail:353271054@qq.com > Created Time: 2014年07月16日 星期三 19时46分56秒 ************************************************************************/ #include<iostream> #include<vector> #include<string> #include<list> using namespace std; int main(int argc, const char *argv[]) { /* * 初始化一段元素的副本,所做的工作是什么,利用到了哪个构造函数 * 比如说有个数组名:int a[10]; * vector<int> vec(a,a+10);//可以采用这种初始化方式 * */ // // int a[]={0,1,1,2,3,5,8,13,21,55,89}; //cout<<sizeof(a)/sizeof(int)<<endl; size_t count= sizeof(a)/sizeof(int); vector<int> vec(a,a+count); list<int> lst(a,a+count); for(vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) { //删除vector中的偶数元素 if(*it%2==0) { //这里之所以it,是因为在删除元素的时候迭代器会失效 it=vec.erase(it); --it; } } for(list<int>::iterator it = lst.begin(); it != lst.end();++it) { if(*it%2!=0) { //必须考虑到erase函数调用后,迭代器会失效的问题。 it= lst.erase(it); --it; } } // 测试代码 cout<<"vecotr中的元素------"<<endl; for(vector<int>::iterator it = vec.begin(); it != vec.end(); ++it){ cout << *it << endl; } cout<<"list中的元素------"<<endl; for(list<int>::iterator it = lst.begin(); it != lst.end(); ++it){ cout << *it << endl; } return 0; }
[ "xxqcheers0614@163.com" ]
xxqcheers0614@163.com
442502c4b3d0c3b9331aa3a75232d17fe9407085
42ed875464d2dc24dfce32d435b089c8982e1eb2
/NullAudioService.h
44b5d3f97b68b65f485f9669e0d9bb76d9123e3a
[]
no_license
Benjamin-Russell/Spoose-Invooders
b9e8fc6d2a85016ecfbba14bd249651e30b97a25
7fe13dccf2043eb726fe0686824ec97783b64f5a
refs/heads/master
2016-09-01T06:30:41.343194
2016-03-18T02:44:00
2016-03-18T02:44:00
54,152,784
0
0
null
null
null
null
UTF-8
C++
false
false
334
h
#ifndef NULL_AUDIO_SERVICE_H #define NULL_AUDIO_SERVICE_H #include "Audio.h" #include <vector> #include <SDL_mixer.h> using namespace std; class NullAudioService : public Audio { public: NullAudioService() {}; virtual ~NullAudioService() {}; virtual void playSound(SoundEffect id) {}; virtual void stopAllSounds() {}; }; #endif
[ "benrussell.dev@gmail.com" ]
benrussell.dev@gmail.com
36eb1bafe482d6070d602f697efc6b35b93c98c7
e51e8a6a04d0e57901cca3d866f33e54736053c9
/CodeForces/1345/b/79340407.cpp
6f6a3d1a84c8edf001c8364aa5043f583d79af77
[]
no_license
Nipun4338/Solved-Programming-Problems
7cb638112ef3d135fc6594eac9c6e79c5b0a0592
401a9ecc3157b8b4aa275ceb8c67f4e90213bccd
refs/heads/master
2023-05-17T02:22:57.007396
2021-06-10T17:08:10
2021-06-10T17:08:10
283,442,802
0
0
null
null
null
null
UTF-8
C++
false
false
2,752
cpp
#include<bits/stdc++.h> #define rep0(i,n) for(i=0;i<n;i++) #define rep(i,n) for(i=1;i<=n;i++) #define reps(i,a,n) for(i=a;i<=n;i++) #define mem(ara,n) memset(ara,n,sizeof(ara)) #define memb(ara) memset(ara,false,sizeof(ara)) #define all(x) (x).begin(),(x).end() #define fast ios_base:: sync_with_stdio( false ); cin.tie(0); cout.tie(0); #define eb emplace_back #define em emplace #define pb push_back #define Mp make_pair #define ff first #define ss second #define mod 1000000007 typedef long long ll; using namespace std; const int M = (int)(2e6 + 239); void decitobinbitodeci() { string binary = bitset<8>(128).to_string(); //to binary cout<<binary<<"\n"; unsigned long decimal = bitset<8>(binary).to_ulong(); cout<<decimal<<"\n"; } int getnum(string a) { int i,p=0; rep0(i,a.size()) { p*=10; p+=a[i]-'0'; } return p; } /* 1.always remember for ncr(n,2), you can calculate by n*(n-1)/2 2.Power of 2 -> (1ll<<i) */ int dp[100]; ll F(ll n) { if(n==0) { return 0; } if(n==1) { return 0; } if(n==2) { return 1; } if(dp[n]!=0) { return dp[n]; } dp[n]=F(n-1)+F(n-2); return dp[n]; } int main() { /*#ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif*/ fast set<ll>s; ll sum=2; s.insert(sum); for(int i=0; i<40000; i++) { sum=sum+((i+2)*2)+i+1; s.insert(sum); } vector<ll>v(all(s)); //cout<<v[v.size()-1]<<endl; ll sum2=0; vector<ll>v1; for(int i=0; i<v.size(); i++) { sum2+=v[i]; v1.push_back(sum2); } //cout<<v1[v1.size()-1]<<endl; ll a,b,c=0; cin>>a; while(a--) { cin>>b; if(b<2) { cout<<0<<endl; } else { if(s.find(b)!=s.end()) { cout<<1<<endl; } else { ll x=upper_bound(v.begin(),v.end(),b)-v.begin(); if(v[x]>b) { x--; } ll flag=0,d=0; for(int i=x; i>=0; i--) { //cout<<v[i]<<endl; if(b-v[i]<0) { continue; } else { ll temp=b/v[i]; b-=temp*v[i]; c+=temp; } } cout<<c<<endl; c=0; } } } }
[ "49658560+Nipun4338@users.noreply.github.com" ]
49658560+Nipun4338@users.noreply.github.com
72c574aec621bd184cfbaa7758f2ab8c7bdece3a
ffa83215d4a44581f44173100331bda1900b24fe
/build/Android/Preview/app/src/main/include/Outracks.Simulator.Cl-4ab4e5d1.h
2cdcafebf5707b656915d93572fcc246c6f6d898
[]
no_license
imkimbosung/ARkit_fuse
167d1c77ee497d5b626e69af16e0e84b13c54457
3b378d6408551d6867f2e5b3d7d8b6f5114e7f69
refs/heads/master
2020-04-19T02:34:33.970273
2019-02-04T08:26:54
2019-02-04T08:26:54
167,907,696
0
0
null
null
null
null
UTF-8
C++
false
false
1,501
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Preview.Core/0.1.0/ApplicationStates.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Outracks.Simulator.Cl-de0df58f.h> namespace g{namespace Outracks{namespace Simulator{namespace Client{struct ConnectionLost;}}}} namespace g{namespace Outracks{namespace Simulator{namespace Protocol{struct ExceptionInfo;}}}} namespace g{namespace Uno{struct Exception;}} namespace g{ namespace Outracks{ namespace Simulator{ namespace Client{ // internal sealed class ConnectionLost :441 // { ::g::Outracks::Simulator::Client::State_type* ConnectionLost_typeof(); void ConnectionLost__ctor_2_fn(ConnectionLost* __this, ::g::Outracks::Simulator::Protocol::ExceptionInfo* exception); void ConnectionLost__ctor_3_fn(ConnectionLost* __this, ::g::Uno::Exception* exception); void ConnectionLost__New2_fn(::g::Outracks::Simulator::Protocol::ExceptionInfo* exception, ConnectionLost** __retval); void ConnectionLost__New3_fn(::g::Uno::Exception* exception, ConnectionLost** __retval); struct ConnectionLost : ::g::Outracks::Simulator::Client::ShowingModalDialog { void ctor_2(::g::Outracks::Simulator::Protocol::ExceptionInfo* exception); void ctor_3(::g::Uno::Exception* exception); static ConnectionLost* New2(::g::Outracks::Simulator::Protocol::ExceptionInfo* exception); static ConnectionLost* New3(::g::Uno::Exception* exception); }; // } }}}} // ::g::Outracks::Simulator::Client
[ "ghalsru@naver.com" ]
ghalsru@naver.com
46b8fa66c23eb3786ace6ce8274cd953189c2ab5
74b352eb46c3bbc886f8d6cfd64a90b3ebb8aed2
/快速幂.cpp
2406870ed852d9540393d2ff9373a3f32fd93da1
[]
no_license
Jeblqr/Model
d9c95f90147ec755f7968d1ac90609838385ef83
0d92b695fc7fea0bad916fcfcf5ddde68440eeea
refs/heads/master
2021-05-10T12:46:56.474823
2019-11-12T09:35:07
2019-11-12T09:35:07
118,451,544
8
3
null
null
null
null
UTF-8
C++
false
false
503
cpp
#include <iostream> using namespace std; long long qp(long long a, long long b, long long k) { long long ans = 1; while (b) { if (b & 1) ans = ans * a % k; a = a * a % k; b >>= 1; } return ans; } long long qp(long long a, long long b) { long long ans = 1; while (b) { if (b & 1) ans = ans * a; a = a * a; b >>= 1; } return ans; } int main() { long long a, b, k; cin >> a >> b >> k; cout << qp(a, b) << endl << qp(a, b, k) << endl; return 0; }
[ "noreply@github.com" ]
Jeblqr.noreply@github.com
c15f61941f997269d8bfd737e6dbcd5b7a5b9290
cc2b07d9e4266efcc830451adfb69b925ec10867
/OgreMain/src/OgreDefaultDebugDrawer.cpp
06387dae09095e00056edb16e571142ebe02357d
[ "MIT" ]
permissive
OGRECave/ogre
74c9c318d95010a3e5fba9709ffebc7e781f27a2
15631ca2dd44bd0c925e33411bee05ccac95fc55
refs/heads/master
2023-09-04T21:08:30.326815
2023-09-02T10:49:34
2023-09-02T10:49:34
47,069,819
3,716
1,178
MIT
2023-09-14T05:33:08
2015-11-29T15:57:03
C++
UTF-8
C++
false
false
6,282
cpp
// This file is part of the OGRE project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at https://www.ogre3d.org/licensing. #include "OgreDefaultDebugDrawer.h" #include "OgreStableHeaders.h" namespace Ogre { DefaultDebugDrawer::DefaultDebugDrawer() : mLines(""), mAxes(""), mDrawType(0), mStatic(false), mBoneAxesSize(1.0f) {} void DefaultDebugDrawer::preFindVisibleObjects(SceneManager* source, SceneManager::IlluminationRenderStage irs, Viewport* v) { mDrawType = 0; if (source->getDisplaySceneNodes()) mDrawType |= DT_AXES; if (source->getShowBoundingBoxes()) mDrawType |= DT_WIREBOX; } void DefaultDebugDrawer::beginLines() { if (mLines.getSections().empty()) { const char* matName = "Ogre/Debug/LinesMat"; auto mat = MaterialManager::getSingleton().getByName(matName, RGN_INTERNAL); if (!mat) { mat = MaterialManager::getSingleton().create(matName, RGN_INTERNAL); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setVertexColourTracking(TVC_AMBIENT); } mLines.setBufferUsage(HBU_CPU_TO_GPU); mLines.begin(mat, RenderOperation::OT_LINE_LIST); } else if (mLines.getCurrentVertexCount() == 0) mLines.beginUpdate(0); } void DefaultDebugDrawer::drawWireBox(const AxisAlignedBox& aabb, const ColourValue& colour) { beginLines(); int base = mLines.getCurrentVertexCount(); for (const auto& corner : aabb.getAllCorners()) { mLines.position(corner); mLines.colour(colour); } // see AxisAlignedBox::getAllCorners int idx[] = {0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 6, 1, 5, 2, 4, 3, 7}; for (int i : idx) mLines.index(base + i); } void DefaultDebugDrawer::drawFrustum(const Frustum* frust) { beginLines(); int base = mLines.getCurrentVertexCount(); for (const auto& corner : frust->getWorldSpaceCorners()) { mLines.position(corner); mLines.colour(frust->getDebugColour()); } // see ConvexBody::define int idx[] = {0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 2, 6, 1, 5, 0, 4, 3, 7}; for (int i : idx) mLines.index(base + i); } void DefaultDebugDrawer::drawAxes(const Affine3& pose, float size) { if (mAxes.getSections().empty()) { const char* matName = "Ogre/Debug/AxesMat"; auto mat = MaterialManager::getSingleton().getByName(matName, RGN_INTERNAL); if (!mat) { mat = MaterialManager::getSingleton().create(matName, RGN_INTERNAL); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setPolygonModeOverrideable(false); p->setVertexColourTracking(TVC_AMBIENT); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->setCullingMode(CULL_NONE); p->setDepthWriteEnabled(false); p->setDepthCheckEnabled(false); } mAxes.setBufferUsage(HBU_CPU_TO_GPU); mAxes.begin(mat); } else if (mAxes.getCurrentVertexCount() == 0) mAxes.beginUpdate(0); /* 3 axes, each made up of 2 of these (base plane = XY) * .------------|\ * '------------|/ */ Vector3 basepos[7] = { // stalk Vector3(0, 0.05, 0), Vector3(0, -0.05, 0), Vector3(0.7, -0.05, 0), Vector3(0.7, 0.05, 0), // head Vector3(0.7, -0.15, 0), Vector3(1, 0, 0), Vector3(0.7, 0.15, 0) }; ColourValue col[3] = {ColourValue(1, 0, 0, 0.8), ColourValue(0, 1, 0, 0.8), ColourValue(0, 0, 1, 0.8)}; Matrix3 rot[6]; // x-axis rot[0] = Matrix3::IDENTITY; rot[1].FromAxes(Vector3::UNIT_X, Vector3::NEGATIVE_UNIT_Z, Vector3::UNIT_Y); // y-axis rot[2].FromAxes(Vector3::UNIT_Y, Vector3::NEGATIVE_UNIT_X, Vector3::UNIT_Z); rot[3].FromAxes(Vector3::UNIT_Y, Vector3::UNIT_Z, Vector3::UNIT_X); // z-axis rot[4].FromAxes(Vector3::UNIT_Z, Vector3::UNIT_Y, Vector3::NEGATIVE_UNIT_X); rot[5].FromAxes(Vector3::UNIT_Z, Vector3::UNIT_X, Vector3::UNIT_Y); // 6 arrows for (size_t i = 0; i < 6; ++i) { uint32 base = mAxes.getCurrentVertexCount(); // vertices for (const auto& p : basepos) { mAxes.position(pose * (rot[i] * p * size)); mAxes.colour(col[i / 2]); } // indices mAxes.quad(base + 0, base + 1, base + 2, base + 3); mAxes.triangle(base + 4, base + 5, base + 6); } } void DefaultDebugDrawer::setBoneAxesSize(float size) { mBoneAxesSize = size; } void DefaultDebugDrawer::drawBone(const Node* node, const Affine3 & transform) { drawAxes(transform * node->_getFullTransform(), mBoneAxesSize); } void DefaultDebugDrawer::drawSceneNode(const SceneNode* node) { // skip drawing root scene node as it contains the camera frustum if(!node->getParent()) return; const auto& aabb = node->_getWorldAABB(); //Skip all bounding boxes that are infinite. if (aabb.isInfinite()) { return; } if (mDrawType & DT_AXES) { // remove scale here as it will be in full transform below too Vector3f hs(aabb.getHalfSize() / node->_getDerivedScale()); float sz = std::min(hs[0], hs[1]); sz = std::min(sz, hs[2]); sz = std::max(sz, 1.0f); drawAxes(node->_getFullTransform(), sz); } if (node->getShowBoundingBox() || (mDrawType & DT_WIREBOX)) { drawWireBox(aabb); } } void DefaultDebugDrawer::postFindVisibleObjects(SceneManager* source, SceneManager::IlluminationRenderStage irs, Viewport* v) { auto queue = source->getRenderQueue(); if (mLines.getCurrentVertexCount()) { mLines.end(); mLines._updateRenderQueue(queue); } if (mAxes.getCurrentVertexCount()) { mAxes.end(); mAxes._updateRenderQueue(queue); } if (mStatic) { mLines._updateRenderQueue(queue); mAxes._updateRenderQueue(queue); } } } /* namespace Ogre */
[ "rojtberg@gmail.com" ]
rojtberg@gmail.com
336e245a1bded80a5f35bef862bbed5eaace2688
03a1bb4154a50eef70cb48ec36601f0293739a45
/include/ircd/allocator.h
82b16fabb96d765b7e0b20446bbd86065071eb95
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
bqv/charybdis
3631c3e38c083d9d3d16be8b38fb09f659ddfa07
95a0073101f03c22226c504d6fd21c18965ffd78
refs/heads/master
2021-05-26T10:32:29.044336
2020-05-13T19:30:03
2020-05-13T19:30:03
254,097,200
0
0
NOASSERTION
2020-04-08T13:34:25
2020-04-08T13:34:24
null
UTF-8
C++
false
false
21,972
h
// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2018 Jason Volk <jason@zemos.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. #pragma once #define HAVE_IRCD_ALLOCATOR_H /// Suite of custom allocator templates for special behavior and optimization /// /// These tools can be used as alternatives to the standard allocator. Most /// templates implement the std::allocator concept and can be used with /// std:: containers by specifying them in the container's template parameter. /// namespace ircd::allocator { struct state; struct scope; struct profile; template<class T = void> struct callback; template<class T = char> struct dynamic; template<class T = char, size_t = 512> struct fixed; template<class T = char, size_t L0_SIZE = 512> struct twolevel; template<class T> struct node; size_t rlimit_as(); size_t rlimit_data(); size_t rlimit_memlock(); std::unique_ptr<char, decltype(&std::free)> aligned_alloc(const size_t &align, const size_t &size); profile &operator+=(profile &, const profile &); profile &operator-=(profile &, const profile &); profile operator+(const profile &, const profile &); profile operator-(const profile &, const profile &); string_view info(const mutable_buffer &); string_view get(const string_view &var, const mutable_buffer &val); string_view set(const string_view &var, const string_view &val, const mutable_buffer &cur = {}); bool trim(const size_t &pad = 0) noexcept; // malloc_trim(3) } /// jemalloc specific suite; note that some of the primary ircd::allocator /// interface has different functionality when je::available. namespace ircd::allocator::je { extern const bool available; } /// Valgrind memcheck hypercall suite /// note: definitions located in ircd/vg.cc namespace ircd::allocator::vg { bool defined(const const_buffer &); void set_defined(const const_buffer &); void set_undefined(const const_buffer &); void set_noaccess(const const_buffer &); } /// Valgrind hypercall suite /// note: definitions located in ircd/vg.cc namespace ircd::vg { size_t errors(); bool active(); } namespace ircd { using allocator::aligned_alloc; } /// Profiling counters. The purpose of this device is to gauge whether unwanted /// or non-obvious allocations are taking place for a specific section. This /// profiler has that very specific purpose and is not a replacement for /// full-fledged memory profiling. This works by replacing global operator new /// and delete, not any deeper hooks on malloc() at this time. To operate this /// device you must first recompile and relink with RB_PROF_ALLOC defined at /// least for the ircd/allocator.cc unit. /// /// 1. Create an instance by copying the this_thread variable which will /// snapshot the current counters. /// 2. At some later point, create a second instance by copying the /// this_thread variable again. /// 3. Use the arithmetic operators to compute the difference between the two /// snapshots and the result will be the count isolated between them. struct ircd::allocator::profile { uint64_t alloc_count {0}; uint64_t free_count {0}; size_t alloc_bytes {0}; size_t free_bytes {0}; /// Explicitly enabled by define at compile time only. Note: replaces /// global `new` and `delete` when enabled. static thread_local profile this_thread; }; /// This object hooks and replaces global ::malloc() and family for the /// lifetime of the instance, redirecting those calls to the user's provided /// callbacks. This functionality may not be available on all platforms so it /// cannot be soley relied upon in a production release. It may still be used /// optimistically as an optimization in production. /// /// This device is useful to control dynamic memory at level where specific /// class allocators are too fine-grained and replacing global new is too /// coarse (and far too intrusive to the whole process). Instead this works /// on the stack for everything further up the stack. /// /// This class is friendly. It takes control from any other previous instance /// of allocator::scope and then restores their control after this goes out of /// scope. Once all instances of allocator::scope go out of scope, the previous /// global __malloc_hook is reinstalled. /// struct ircd::allocator::scope { using alloc_closure = std::function<void *(const size_t &)>; using realloc_closure = std::function<void *(void *const &ptr, const size_t &)>; using free_closure = std::function<void (void *const &ptr)>; static void hook_init() noexcept; static void hook_fini() noexcept; static scope *current; scope *theirs; alloc_closure user_alloc; realloc_closure user_realloc; free_closure user_free; public: scope(alloc_closure = {}, realloc_closure = {}, free_closure = {}); scope(const scope &) = delete; scope(scope &&) = delete; ~scope() noexcept; }; /// Internal state structure for some of these tools. This is a very small and /// simple interface to a bit array representing the availability of an element /// in a pool of elements. The actual array of the proper number of bits must /// be supplied by the user of the state. The allocator using this interface /// can use any strategy to flip these bits but the default next()/allocate() /// functions scan for the next available contiguous block of zero bits and /// then wrap around when reaching the end of the array. Once a full iteration /// of the array is made without finding satisfaction, an std::bad_alloc is /// thrown. /// struct ircd::allocator::state { using word_t = unsigned long long; using size_type = std::size_t; size_t size { 0 }; word_t *avail { nullptr }; size_t last { 0 }; static uint byte(const uint &i) { return i / (sizeof(word_t) * 8); } static uint bit(const uint &i) { return i % (sizeof(word_t) * 8); } static word_t mask(const uint &pos) { return word_t(1) << bit(pos); } bool test(const uint &pos) const { return avail[byte(pos)] & mask(pos); } void bts(const uint &pos) { avail[byte(pos)] |= mask(pos); } void btc(const uint &pos) { avail[byte(pos)] &= ~mask(pos); } uint next(const size_t &n) const; public: bool available(const size_t &n = 1) const; void deallocate(const uint &p, const size_t &n); uint allocate(std::nothrow_t, const size_t &n, const uint &hint = -1); uint allocate(const size_t &n, const uint &hint = -1); state(const size_t &size = 0, word_t *const &avail = nullptr) :size{size} ,avail{avail} ,last{0} {} }; /// The callback allocator is a shell around the pre-c++17/20 boilerplate /// jumble for allocator template creation. This is an alternative to virtual /// functions to accomplish the same thing here. Implement the principal /// allocate and deallocate functions and maintain an instance of /// allocator::callback with them somewhere. template<class T> struct ircd::allocator::callback { struct allocator; public: using allocate_callback = std::function<T *(const size_t &, const T *const &)>; using deallocate_callback = std::function<void (T *const &, const size_t &)>; allocate_callback ac; deallocate_callback dc; allocator operator()(); operator allocator(); callback(allocate_callback ac, deallocate_callback dc) :ac{std::move(ac)} ,dc{std::move(dc)} {} }; template<class T> struct ircd::allocator::callback<T>::allocator { using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using is_always_equal = std::true_type; using propagate_on_container_move_assignment = std::true_type; callback *s; public: template<class U> struct rebind { typedef ircd::allocator::callback<T>::allocator other; }; T * __attribute__((malloc, returns_nonnull, warn_unused_result)) allocate(const size_type n, const T *const hint = nullptr) { assert(s && s->ac); return s->ac(n, hint); } void deallocate(T *const p, const size_type n = 1) { assert(s && s->dc); return s->dc(p, n); } template<class U> allocator(const typename ircd::allocator::callback<U>::allocator &s) noexcept :s{s.s} {} allocator(callback &s) noexcept :s{&s} {} allocator(allocator &&) = default; allocator(const allocator &) = default; friend bool operator==(const allocator &a, const allocator &b) { return &a == &b; } friend bool operator!=(const allocator &a, const allocator &b) { return &a == &b; } }; template<class T> typename ircd::allocator::callback<T>::allocator ircd::allocator::callback<T>::operator()() { return ircd::allocator::callback<T>::allocator(*this); } template<class T> ircd::allocator::callback<T>::operator allocator() { return ircd::allocator::callback<T>::allocator(*this); } /// The fixed allocator creates a block of data with a size known at compile- /// time. This structure itself is the state object for the actual allocator /// instance used in the container. Create an instance of this structure, /// perhaps on your stack. Then specify the ircd::allocator::fixed::allocator /// in the template for the container. Then pass a reference to the state /// object as an argument to the container when constructing. STL containers /// have an overloaded constructor for this when specializing the allocator /// template as we are here. /// template<class T, size_t MAX> struct ircd::allocator::fixed :state { struct allocator; using value = std::aligned_storage<sizeof(T), alignof(T)>; std::array<word_t, MAX / 8> avail {{0}}; std::array<typename value::type, MAX> buf; public: bool in_range(const T *const &ptr) const { const auto base(reinterpret_cast<const T *>(buf.data())); return ptr >= base && ptr < base + MAX; } allocator operator()(); operator allocator(); fixed() { static_cast<state &>(*this) = { MAX, avail.data() }; } }; /// The actual allocator template as used by the container. /// /// This has to be a very light, small and copyable object which cannot hold /// our actual memory or state (lest we just use dynamic allocation for that!) /// which means we have to pass this a reference to our ircd::allocator::fixed /// instance. We can do that through the container's custom-allocator overload /// at its construction. /// template<class T, size_t SIZE> struct ircd::allocator::fixed<T, SIZE>::allocator { using value_type = T; using pointer = T *; using const_pointer = const T *; using reference = T &; using const_reference = const T &; using size_type = std::size_t; using difference_type = std::ptrdiff_t; fixed *s; public: template<class U> struct rebind { using other = typename fixed<U, SIZE>::allocator; }; size_type max_size() const { return SIZE; } auto address(reference x) const { return &x; } auto address(const_reference x) const { return &x; } pointer __attribute__((malloc, warn_unused_result)) allocate(std::nothrow_t, const size_type &n, const const_pointer &hint = nullptr) { const auto base(reinterpret_cast<pointer>(s->buf.data())); const uint hintpos(hint? uint(hint - base) : uint(-1)); const pointer ret(base + s->state::allocate(std::nothrow, n, hintpos)); return s->in_range(ret)? ret : nullptr; } pointer __attribute__((malloc, returns_nonnull, warn_unused_result)) allocate(const size_type &n, const const_pointer &hint = nullptr) { const auto base(reinterpret_cast<pointer>(s->buf.data())); const uint hintpos(hint? uint(hint - base) : uint(-1)); return base + s->state::allocate(n, hintpos); } void deallocate(const pointer &p, const size_type &n) { const auto base(reinterpret_cast<pointer>(s->buf.data())); s->state::deallocate(p - base, n); } template<class U, size_t OTHER_SIZE = SIZE> allocator(const typename fixed<U, OTHER_SIZE>::allocator &s) noexcept :s{reinterpret_cast<fixed<T, SIZE> *>(s.s)} { static_assert(OTHER_SIZE == SIZE); } allocator(fixed &s) noexcept :s{&s} {} allocator(allocator &&) = default; allocator(const allocator &) = default; friend bool operator==(const allocator &a, const allocator &b) { return &a == &b; } friend bool operator!=(const allocator &a, const allocator &b) { return &a == &b; } }; template<class T, size_t SIZE> typename ircd::allocator::fixed<T, SIZE>::allocator ircd::allocator::fixed<T, SIZE>::operator()() { return ircd::allocator::fixed<T, SIZE>::allocator(*this); } template<class T, size_t SIZE> ircd::allocator::fixed<T, SIZE>::operator allocator() { return ircd::allocator::fixed<T, SIZE>::allocator(*this); } /// The dynamic allocator provides a pool of a fixed size known at runtime. /// /// This allocator conducts a single new and delete for a pool allowing an STL /// container to operate without interacting with the rest of the system and /// without fragmentation. This is not as useful as the allocator::fixed in /// practice as the standard allocator is as good as this in many cases. This /// is still available as an analog to the fixed allocator in this suite. /// template<class T> struct ircd::allocator::dynamic :state { struct allocator; size_t head_size, data_size; std::unique_ptr<uint8_t[]> arena; T *buf; public: allocator operator()(); operator allocator(); dynamic(const size_t &size) :state{size} ,head_size{size / 8} ,data_size{sizeof(T) * size + 16} ,arena { new __attribute__((aligned(16))) uint8_t[head_size + data_size] } ,buf { reinterpret_cast<T *>(arena.get() + head_size + (head_size % 16)) } { state::avail = reinterpret_cast<word_t *>(arena.get()); } }; /// The actual template passed to containers for using the dynamic allocator. /// /// See the notes for ircd::allocator::fixed::allocator for details. /// template<class T> struct ircd::allocator::dynamic<T>::allocator { using value_type = T; using pointer = T *; using const_pointer = const T *; using reference = T &; using const_reference = const T &; using size_type = std::size_t; using difference_type = std::ptrdiff_t; dynamic *s; public: template<class U> struct rebind { using other = typename dynamic<U>::allocator; }; size_type max_size() const { return s->size; } auto address(reference x) const { return &x; } auto address(const_reference x) const { return &x; } pointer __attribute__((malloc, returns_nonnull, warn_unused_result)) allocate(const size_type &n, const const_pointer &hint = nullptr) { const uint hintpos(hint? hint - s->buf : -1); return s->buf + s->state::allocate(n, hintpos); } void deallocate(const pointer &p, const size_type &n) { const uint pos(p - s->buf); s->state::deallocate(pos, n); } template<class U> allocator(const typename dynamic<U>::allocator &s) noexcept :s{reinterpret_cast<dynamic *>(s.s)} {} allocator(dynamic &s) noexcept :s{&s} {} allocator(allocator &&) = default; allocator(const allocator &) = default; friend bool operator==(const allocator &a, const allocator &b) { return &a == &b; } friend bool operator!=(const allocator &a, const allocator &b) { return &a == &b; } }; template<class T> typename ircd::allocator::dynamic<T>::allocator ircd::allocator::dynamic<T>::operator()() { return ircd::allocator::dynamic<T>::allocator(*this); } template<class T> ircd::allocator::dynamic<T>::operator allocator() { return ircd::allocator::dynamic<T>::allocator(*this); } /// Allows elements of an STL container to be manually handled by the user. /// /// C library containers usually allow the user to manually construct a node /// and then insert it and remove it from the container. With STL containers /// we can use devices like allocator::fixed, but what if we don't want to have /// a bound on the allocator's size either at compile time or at runtime? What /// if we simply want to manually handle the container's elements, like on the /// stack, and in different frames, and then manipulate the container -- or /// even better and safer: have the elements add and remove themselves while /// storing the container's node data too? /// /// This device helps the user achieve that by simply providing a variable /// set by the user indicating where the 'next' block of memory is when the /// container requests it. Whether the container is requesting memory which /// should be fulfilled by that 'next' block must be ensured and asserted by /// the user, but this is likely the case. /// template<class T> struct ircd::allocator::node { struct allocator; struct monotonic; T *next {nullptr}; node() = default; }; /// The actual template passed to containers for using the allocator. /// /// See the notes for ircd::allocator::fixed::allocator for details. /// template<class T> struct ircd::allocator::node<T>::allocator { using value_type = T; using pointer = T *; using const_pointer = const T *; using reference = T &; using const_reference = const T &; using size_type = std::size_t; using difference_type = std::ptrdiff_t; node *s; public: template<class U> struct rebind { using other = typename node<U>::allocator; }; size_type max_size() const { return std::numeric_limits<size_t>::max(); } auto address(reference x) const { return &x; } auto address(const_reference x) const { return &x; } template<class U, class... args> void construct(U *p, args&&... a) noexcept { new (p) U(std::forward<args>(a)...); } void construct(pointer p, const_reference val) { new (p) T(val); } pointer __attribute__((returns_nonnull, warn_unused_result)) allocate(const size_type &n, const const_pointer &hint = nullptr) { assert(n == 1); assert(hint == nullptr); assert(s->next != nullptr); return s->next; } void deallocate(const pointer &p, const size_type &n) { assert(n == 1); } template<class U> allocator(const typename node<U>::allocator &s) noexcept :s{reinterpret_cast<node *>(s.s)} { } template<class U> allocator(const U &s) noexcept :s{reinterpret_cast<node *>(s.s)} { } allocator(node &s) noexcept :s{&s} { } allocator() = default; allocator(allocator &&) noexcept = default; allocator(const allocator &) = default; friend bool operator==(const allocator &a, const allocator &b) { return &a == &b; } friend bool operator!=(const allocator &a, const allocator &b) { return &a == &b; } }; /// The twolevel allocator uses both a fixed allocator (first level) and then /// the standard allocator (second level) when the fixed allocator is exhausted. /// This has the intent that the fixed allocator will mostly be used, but the /// fallback to the standard allocator is seamlessly available for robustness. template<class T, size_t L0_SIZE> struct ircd::allocator::twolevel { struct allocator; fixed<T, L0_SIZE> l0; std::allocator<T> l1; public: allocator operator()(); operator allocator(); twolevel() = default; }; template<class T, size_t L0_SIZE> struct ircd::allocator::twolevel<T, L0_SIZE>::allocator { using value_type = T; using pointer = T *; using const_pointer = const T *; using reference = T &; using const_reference = const T &; using size_type = std::size_t; using difference_type = std::ptrdiff_t; twolevel *s; public: template<class U, size_t OTHER_L0_SIZE = L0_SIZE> struct rebind { using other = typename twolevel<U, OTHER_L0_SIZE>::allocator; }; size_type max_size() const { return std::numeric_limits<size_type>::max(); } auto address(reference x) const { return &x; } auto address(const_reference x) const { return &x; } pointer __attribute__((malloc, returns_nonnull, warn_unused_result)) allocate(const size_type &n, const const_pointer &hint = nullptr) { assert(s); return s->l0.allocate(std::nothrow, n, hint)?: s->l1.allocate(n, hint); } void deallocate(const pointer &p, const size_type &n) { assert(s); if(likely(s->l0.in_range(p))) s->l0.deallocate(p, n); else s->l1.deallocate(p, n); } template<class U, size_t OTHER_L0_SIZE = L0_SIZE> allocator(const typename twolevel<U, OTHER_L0_SIZE>::allocator &s) noexcept :s{reinterpret_cast<twolevel<T, L0_SIZE> *>(s.s)} { static_assert(OTHER_L0_SIZE == L0_SIZE); } allocator(twolevel &s) noexcept :s{&s} {} allocator(allocator &&) = default; allocator(const allocator &) = default; friend bool operator==(const allocator &a, const allocator &b) { return &a == &b; } friend bool operator!=(const allocator &a, const allocator &b) { return &a == &b; } }; template<class T, size_t L0_SIZE> typename ircd::allocator::twolevel<T, L0_SIZE>::allocator ircd::allocator::twolevel<T, L0_SIZE>::operator()() { return ircd::allocator::twolevel<T, L0_SIZE>::allocator(*this); } template<class T, size_t L0_SIZE> ircd::allocator::twolevel<T, L0_SIZE>::operator allocator() { return ircd::allocator::twolevel<T, L0_SIZE>::allocator(*this); }
[ "jason@zemos.net" ]
jason@zemos.net
830e81ac7f469d260a2dedb2e2f163dd2ba1b6a1
5ddc3704f976fb4f1191782abfa6bb3c947c9c6d
/src/modules/SX1272.cpp
82040d7273d4dba6e1ddb5d9b6d1c4497f978bfc
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Bambofy/LoRaLib
2dcdfc946632680e461e4ff7ad9e04fb3829de61
a887f79066c50c7a468e8392a46f7b280ddc364d
refs/heads/master
2020-03-26T09:49:24.194467
2018-08-02T18:23:56
2018-08-02T18:23:56
144,766,705
1
0
MIT
2018-08-14T20:02:27
2018-08-14T20:02:27
null
UTF-8
C++
false
false
7,562
cpp
#include "SX1272.h" SX1272::SX1272(Module* mod) : SX127x(mod) { } int16_t SX1272::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) { // execute common part int16_t state = SX127x::begin(SX1272_CHIP_VERSION, syncWord, currentLimit, preambleLength); if(state != ERR_NONE) { return(state); } // configure settings not accessible by API state = config(); if(state != ERR_NONE) { return(state); } // mitigation of receiver spurious response // see SX1272/73 Errata, section 2.2 for details state = _mod->SPIsetRegValue(0x31, 0b10000000, 7, 7); if(state != ERR_NONE) { return(state); } // configure publicly accessible settings state = setFrequency(freq); if(state != ERR_NONE) { return(state); } state = setBandwidth(bw); if(state != ERR_NONE) { return(state); } state = setSpreadingFactor(sf); if(state != ERR_NONE) { return(state); } state = setCodingRate(cr); if(state != ERR_NONE) { return(state); } state = setOutputPower(power); if(state != ERR_NONE) { return(state); } state = setGain(gain); if(state != ERR_NONE) { return(state); } return(state); } int16_t SX1272::setFrequency(float freq) { // check frequency range if((freq < 860.0) || (freq > 1020.0)) { return(ERR_INVALID_FREQUENCY); } // set frequency return(SX127x::setFrequencyRaw(freq)); } int16_t SX1272::setBandwidth(float bw) { uint8_t newBandwidth; // check alowed bandwidth values if(abs(bw - 125.0) <= 0.001) { newBandwidth = SX1272_BW_125_00_KHZ; } else if(abs(bw - 250.0) <= 0.001) { newBandwidth = SX1272_BW_250_00_KHZ; } else if(abs(bw - 500.0) <= 0.001) { newBandwidth = SX1272_BW_500_00_KHZ; } else { return(ERR_INVALID_BANDWIDTH); } // set bandwidth and if successful, save the new setting int16_t state = SX1272::setBandwidthRaw(newBandwidth); if(state == ERR_NONE) { SX127x::_bw = bw; } return(state); } int16_t SX1272::setSpreadingFactor(uint8_t sf) { uint8_t newSpreadingFactor; // check allowed spreading factor values switch(sf) { case 6: newSpreadingFactor = SX127X_SF_6; break; case 7: newSpreadingFactor = SX127X_SF_7; break; case 8: newSpreadingFactor = SX127X_SF_8; break; case 9: newSpreadingFactor = SX127X_SF_9; break; case 10: newSpreadingFactor = SX127X_SF_10; break; case 11: newSpreadingFactor = SX127X_SF_11; break; case 12: newSpreadingFactor = SX127X_SF_12; break; default: return(ERR_INVALID_SPREADING_FACTOR); } // set spreading factor and if successful, save the new setting int16_t state = SX1272::setSpreadingFactorRaw(newSpreadingFactor); if(state == ERR_NONE) { SX127x::_sf = sf; } return(state); } int16_t SX1272::setCodingRate(uint8_t cr) { uint8_t newCodingRate; // check allowed coding rate values switch(cr) { case 5: newCodingRate = SX1272_CR_4_5; break; case 6: newCodingRate = SX1272_CR_4_6; break; case 7: newCodingRate = SX1272_CR_4_7; break; case 8: newCodingRate = SX1272_CR_4_8; break; default: return(ERR_INVALID_CODING_RATE); } // set coding rate and if successful, save the new setting int16_t state = SX1272::setCodingRateRaw(newCodingRate); if(state == ERR_NONE) { SX127x::_cr = cr; } return(state); } int16_t SX1272::setOutputPower(int8_t power) { // check allowed power range if(!(((power >= -1) && (power <= 17)) || (power == 20))) { return(ERR_INVALID_OUTPUT_POWER); } // set mode to standby int16_t state = SX127x::standby(); // set output power if(power < 2) { // power is less than 2 dBm, enable PA0 on RFIO state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX127X_PA_SELECT_RFO, 7, 7); state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, (power + 1), 3, 0); state |= _mod->SPIsetRegValue(SX1272_REG_PA_DAC, SX127X_PA_BOOST_OFF, 2, 0); } else if((power >= 2) && (power <= 17)) { // power is 2 - 17 dBm, enable PA1 + PA2 on PA_BOOST state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX127X_PA_SELECT_BOOST, 7, 7); state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, (power - 2), 3, 0); state |= _mod->SPIsetRegValue(SX1272_REG_PA_DAC, SX127X_PA_BOOST_OFF, 2, 0); } else if(power == 20) { // power is 20 dBm, enable PA1 + PA2 on PA_BOOST and enable high power control state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, SX127X_PA_SELECT_BOOST, 7, 7); state |= _mod->SPIsetRegValue(SX127X_REG_PA_CONFIG, (power - 5), 3, 0); state |= _mod->SPIsetRegValue(SX1272_REG_PA_DAC, SX127X_PA_BOOST_ON, 2, 0); } return(state); } int16_t SX1272::setGain(uint8_t gain) { // check allowed range if(gain > 6) { return(ERR_INVALID_GAIN); } // set mode to standby int16_t state = SX127x::standby(); // set gain if(gain == 0) { // gain set to 0, enable AGC loop state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_2, SX1272_AGC_AUTO_ON, 2, 2); } else { state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_2, SX1272_AGC_AUTO_OFF, 2, 2); state |= _mod->SPIsetRegValue(SX127X_REG_LNA, (gain << 5) | SX127X_LNA_BOOST_ON); } return(state); } int16_t SX1272::setBandwidthRaw(uint8_t newBandwidth) { // set mode to standby int16_t state = SX127x::standby(); // write register state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, newBandwidth, 7, 6); return(state); } int16_t SX1272::setSpreadingFactorRaw(uint8_t newSpreadingFactor) { // set mode to standby int16_t state = SX127x::standby(); // write registers if(newSpreadingFactor == SX127X_SF_6) { state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_HEADER_IMPL_MODE | SX1272_RX_CRC_MODE_OFF, 2, 1); state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_2, SX127X_SF_6 | SX127X_TX_MODE_SINGLE, 7, 3); state |= _mod->SPIsetRegValue(SX127X_REG_DETECT_OPTIMIZE, SX127X_DETECT_OPTIMIZE_SF_6, 2, 0); state |= _mod->SPIsetRegValue(SX127X_REG_DETECTION_THRESHOLD, SX127X_DETECTION_THRESHOLD_SF_6); } else { state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_HEADER_EXPL_MODE | SX1272_RX_CRC_MODE_ON, 2, 1); state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_2, newSpreadingFactor | SX127X_TX_MODE_SINGLE, 7, 3); state |= _mod->SPIsetRegValue(SX127X_REG_DETECT_OPTIMIZE, SX127X_DETECT_OPTIMIZE_SF_7_12, 2, 0); state |= _mod->SPIsetRegValue(SX127X_REG_DETECTION_THRESHOLD, SX127X_DETECTION_THRESHOLD_SF_7_12); } return(state); } int16_t SX1272::setCodingRateRaw(uint8_t newCodingRate) { // set mode to standby int16_t state = SX127x::standby(); // write register state |= _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, newCodingRate, 5, 3); return(state); } int16_t SX1272::config() { // configure common registers int16_t state = SX127x::config(); if(state != ERR_NONE) { return(state); } // calculate symbol length and set low datarate optimization, if needed uint16_t base = 1; float symbolLength = (float)(base << _sf) / (float)_bw; if(symbolLength >= 0.016) { state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_ON, 0, 0); } else { state = _mod->SPIsetRegValue(SX127X_REG_MODEM_CONFIG_1, SX1272_LOW_DATA_RATE_OPT_OFF, 0, 0); } return(state); }
[ "jgromes@users.noreply.github.com" ]
jgromes@users.noreply.github.com
6e0314440298318178480414eccafecd6ccd54d0
e217eaf05d0dab8dd339032b6c58636841aa8815
/IfcBridge/src/OpenInfraPlatform/IfcBridge/entity/include/IfcFireSuppressionTerminalTypeEnum.h
5234858a43d74aef6e00bc3fb95e55134cffbb01
[]
no_license
bigdoods/OpenInfraPlatform
f7785ebe4cb46e24d7f636e1b4110679d78a4303
0266e86a9f25f2ea9ec837d8d340d31a58a83c8e
refs/heads/master
2021-01-21T03:41:20.124443
2016-01-26T23:20:21
2016-01-26T23:20:21
57,377,206
0
1
null
2016-04-29T10:38:19
2016-04-29T10:38:19
null
UTF-8
C++
false
false
1,554
h
/*! \verbatim * \copyright Copyright (c) 2014 Julian Amann. All rights reserved. * \date 2014-02-15 23:00 * \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann) * \brief This file is part of the BlueFramework. * \endverbatim */ #pragma once #include <vector> #include <map> #include <sstream> #include <string> #include "../../model/shared_ptr.h" #include "../../model/IfcBridgeObject.h" namespace OpenInfraPlatform { namespace IfcBridge { // TYPE IfcFireSuppressionTerminalTypeEnum = ENUMERATION OF (BREECHINGINLET ,FIREHYDRANT ,HOSEREEL ,SPRINKLER ,SPRINKLERDEFLECTOR ,USERDEFINED ,NOTDEFINED); class IfcFireSuppressionTerminalTypeEnum : public IfcBridgeAbstractEnum, public IfcBridgeType { public: enum IfcFireSuppressionTerminalTypeEnumEnum { ENUM_BREECHINGINLET, ENUM_FIREHYDRANT, ENUM_HOSEREEL, ENUM_SPRINKLER, ENUM_SPRINKLERDEFLECTOR, ENUM_USERDEFINED, ENUM_NOTDEFINED }; IfcFireSuppressionTerminalTypeEnum(); IfcFireSuppressionTerminalTypeEnum( IfcFireSuppressionTerminalTypeEnumEnum e ) { m_enum = e; } ~IfcFireSuppressionTerminalTypeEnum(); virtual const char* classname() const { return "IfcFireSuppressionTerminalTypeEnum"; } virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const; static shared_ptr<IfcFireSuppressionTerminalTypeEnum> readStepData( std::string& arg ); IfcFireSuppressionTerminalTypeEnumEnum m_enum; }; } // end namespace IfcBridge } // end namespace OpenInfraPlatform
[ "planung.cms.bv@tum.de" ]
planung.cms.bv@tum.de
0514e2a231e4858358837db280888528eca15267
19d0ce325216c56a0260edfb38ff8c328cb754f4
/Export/android/release/obj/src/openfl/display/ShaderData.cpp
7bc721dd4f6503cad7eebb6ff6bdac8fab70c4f9
[]
no_license
HerbinCommando/TokyoTrail
42fcb0569e5028c2e96b100ad20008304370c16e
8737240e8782f5357f472dead574fb956243e48a
refs/heads/master
2021-01-01T20:08:20.336935
2017-08-06T05:58:30
2017-08-06T05:58:30
98,772,096
0
0
null
null
null
null
UTF-8
C++
false
true
7,591
cpp
// Generated by Haxe 3.4.2 #include <hxcpp.h> #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_openfl_display_ShaderData #include <openfl/display/ShaderData.h> #endif #ifndef INCLUDED_openfl_display_ShaderInput_openfl_display_BitmapData #include <openfl/display/ShaderInput_openfl_display_BitmapData.h> #endif #ifndef INCLUDED_openfl_display_ShaderParameter_Float #include <openfl/display/ShaderParameter_Float.h> #endif #ifndef INCLUDED_openfl_utils_ByteArrayData #include <openfl/utils/ByteArrayData.h> #endif #ifndef INCLUDED_openfl_utils_IDataInput #include <openfl/utils/IDataInput.h> #endif #ifndef INCLUDED_openfl_utils_IDataOutput #include <openfl/utils/IDataOutput.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_8d46640c38533f59_24_new,"openfl.display.ShaderData","new",0x6406164b,"openfl.display.ShaderData.new","openfl/display/ShaderData.hx",24,0xa8261943) namespace openfl{ namespace display{ void ShaderData_obj::__construct( ::openfl::utils::ByteArrayData byteArray){ HX_STACKFRAME(&_hx_pos_8d46640c38533f59_24_new) } Dynamic ShaderData_obj::__CreateEmpty() { return new ShaderData_obj; } void *ShaderData_obj::_hx_vtable = 0; Dynamic ShaderData_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ShaderData_obj > _hx_result = new ShaderData_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool ShaderData_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2602c5dd; } hx::ObjectPtr< ShaderData_obj > ShaderData_obj::__new( ::openfl::utils::ByteArrayData byteArray) { hx::ObjectPtr< ShaderData_obj > __this = new ShaderData_obj(); __this->__construct(byteArray); return __this; } hx::ObjectPtr< ShaderData_obj > ShaderData_obj::__alloc(hx::Ctx *_hx_ctx, ::openfl::utils::ByteArrayData byteArray) { ShaderData_obj *__this = (ShaderData_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ShaderData_obj), true, "openfl.display.ShaderData")); *(void **)__this = ShaderData_obj::_hx_vtable; __this->__construct(byteArray); return __this; } ShaderData_obj::ShaderData_obj() { } void ShaderData_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ShaderData); HX_MARK_DYNAMIC; HX_MARK_MEMBER_NAME(aAlpha,"aAlpha"); HX_MARK_MEMBER_NAME(aPosition,"aPosition"); HX_MARK_MEMBER_NAME(aTexCoord,"aTexCoord"); HX_MARK_MEMBER_NAME(uImage0,"uImage0"); HX_MARK_MEMBER_NAME(uMatrix,"uMatrix"); HX_MARK_END_CLASS(); } void ShaderData_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_DYNAMIC; HX_VISIT_MEMBER_NAME(aAlpha,"aAlpha"); HX_VISIT_MEMBER_NAME(aPosition,"aPosition"); HX_VISIT_MEMBER_NAME(aTexCoord,"aTexCoord"); HX_VISIT_MEMBER_NAME(uImage0,"uImage0"); HX_VISIT_MEMBER_NAME(uMatrix,"uMatrix"); } hx::Val ShaderData_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"aAlpha") ) { return hx::Val( aAlpha ); } break; case 7: if (HX_FIELD_EQ(inName,"uImage0") ) { return hx::Val( uImage0 ); } if (HX_FIELD_EQ(inName,"uMatrix") ) { return hx::Val( uMatrix ); } break; case 9: if (HX_FIELD_EQ(inName,"aPosition") ) { return hx::Val( aPosition ); } if (HX_FIELD_EQ(inName,"aTexCoord") ) { return hx::Val( aTexCoord ); } } HX_CHECK_DYNAMIC_GET_FIELD(inName); return super::__Field(inName,inCallProp); } hx::Val ShaderData_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"aAlpha") ) { aAlpha=inValue.Cast< ::openfl::display::ShaderParameter_Float >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"uImage0") ) { uImage0=inValue.Cast< ::openfl::display::ShaderInput_openfl_display_BitmapData >(); return inValue; } if (HX_FIELD_EQ(inName,"uMatrix") ) { uMatrix=inValue.Cast< ::openfl::display::ShaderParameter_Float >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"aPosition") ) { aPosition=inValue.Cast< ::openfl::display::ShaderParameter_Float >(); return inValue; } if (HX_FIELD_EQ(inName,"aTexCoord") ) { aTexCoord=inValue.Cast< ::openfl::display::ShaderParameter_Float >(); return inValue; } } try { return super::__SetField(inName,inValue,inCallProp); } catch(Dynamic e) { HX_DYNAMIC_SET_FIELD(inName,inValue); } return inValue; } void ShaderData_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("aAlpha","\x3d","\x17","\x62","\x7d")); outFields->push(HX_HCSTRING("aPosition","\x2a","\x26","\x25","\x92")); outFields->push(HX_HCSTRING("aTexCoord","\xcf","\x8c","\x5d","\xf2")); outFields->push(HX_HCSTRING("uImage0","\xca","\x0a","\x76","\x34")); outFields->push(HX_HCSTRING("uMatrix","\x96","\xf0","\xab","\xf1")); HX_APPEND_DYNAMIC_FIELDS(outFields); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo ShaderData_obj_sMemberStorageInfo[] = { {hx::fsObject /*::openfl::display::ShaderParameter_Float*/ ,(int)offsetof(ShaderData_obj,aAlpha),HX_HCSTRING("aAlpha","\x3d","\x17","\x62","\x7d")}, {hx::fsObject /*::openfl::display::ShaderParameter_Float*/ ,(int)offsetof(ShaderData_obj,aPosition),HX_HCSTRING("aPosition","\x2a","\x26","\x25","\x92")}, {hx::fsObject /*::openfl::display::ShaderParameter_Float*/ ,(int)offsetof(ShaderData_obj,aTexCoord),HX_HCSTRING("aTexCoord","\xcf","\x8c","\x5d","\xf2")}, {hx::fsObject /*::openfl::display::ShaderInput_openfl_display_BitmapData*/ ,(int)offsetof(ShaderData_obj,uImage0),HX_HCSTRING("uImage0","\xca","\x0a","\x76","\x34")}, {hx::fsObject /*::openfl::display::ShaderParameter_Float*/ ,(int)offsetof(ShaderData_obj,uMatrix),HX_HCSTRING("uMatrix","\x96","\xf0","\xab","\xf1")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *ShaderData_obj_sStaticStorageInfo = 0; #endif static ::String ShaderData_obj_sMemberFields[] = { HX_HCSTRING("aAlpha","\x3d","\x17","\x62","\x7d"), HX_HCSTRING("aPosition","\x2a","\x26","\x25","\x92"), HX_HCSTRING("aTexCoord","\xcf","\x8c","\x5d","\xf2"), HX_HCSTRING("uImage0","\xca","\x0a","\x76","\x34"), HX_HCSTRING("uMatrix","\x96","\xf0","\xab","\xf1"), ::String(null()) }; static void ShaderData_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ShaderData_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void ShaderData_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ShaderData_obj::__mClass,"__mClass"); }; #endif hx::Class ShaderData_obj::__mClass; void ShaderData_obj::__register() { hx::Object *dummy = new ShaderData_obj; ShaderData_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl.display.ShaderData","\xd9","\x94","\x7c","\x97"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = ShaderData_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(ShaderData_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ShaderData_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ShaderData_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ShaderData_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ShaderData_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace display
[ "heath@wgcells.com" ]
heath@wgcells.com
e46a8b199794883d74681133c34801e7abdd3ad4
078927a49a6c5f7e3de1a99cc9b13aad233c0a7d
/Eudora_W_source/Sandbox/Eudora/QCPersonalityCommand.cpp
8f71f53a6dcaa3af62b6ff18a69a919a34cee2f0
[]
no_license
avar/rhqben
ac74c3893bf965eaf8911579f68fe7557f907dcc
966db0f6a3c7d78cc9ddcab1709f9ac38fdcdd5b
refs/heads/master
2020-03-18T07:45:21.766714
2018-05-22T20:15:44
2018-05-22T20:16:47
134,471,376
0
1
null
null
null
null
UTF-8
C++
false
false
1,850
cpp
// QCPersonalityCommand.cpp: implementation of the QCPersonalityCommand class. // ////////////////////////////////////////////////////////////////////// #include "STDAFX.H" #include "QCCommandActions.h" #include "QCPersonalityCommand.h" #include "QCPersonalityDirector.h" #include "resource.h" // fake command id prompt #include "summary.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IMPLEMENT_DYNAMIC(QCPersonalityCommand, QCCommandObject) QCPersonalityCommand::QCPersonalityCommand( QCPersonalityDirector* pDirector, LPCSTR szPersonality ) : QCCommandObject( pDirector ) { m_szPersonality = szPersonality; } QCPersonalityCommand::~QCPersonalityCommand() { } /////////////////////////////////////////////////////////////////////////////// // // void QCPersonalityCommand::Execute( COMMAND_ACTION_TYPE theAction, void* pData ) { NotifyDirector( theAction, pData ); switch( theAction ) { case CA_CHANGE_PERSONA: { ASSERT( pData ); CSummary* pSummary = ( CSummary* ) pData; ASSERT_KINDOF(CSummary, pSummary); if ( ! pSummary->IsComp() ) pSummary->SetPersona( m_szPersonality ); } break; } } UINT QCPersonalityCommand::GetFlyByID( COMMAND_ACTION_TYPE theAction ) { switch( theAction ) { case CA_CHANGE_PERSONA: return ID_CHANGE_PERSONA; break; } return 0; } CString QCPersonalityCommand::GetToolTip( COMMAND_ACTION_TYPE theAction) { CString szToolTip( "" ); switch( theAction ) { case CA_CHANGE_PERSONA: szToolTip.LoadString( IDS_USERDEF_TOOLTIP_CHANGE_PERSONA ); szToolTip += " "; szToolTip += m_szPersonality; break; } return szToolTip; }
[ "avarab@gmail.com" ]
avarab@gmail.com
0be3e5e3c648573c2cd46adfaa1a4dda284495ec
e65e6b345e98633cccc501ad0d6df9918b2aa25e
/Contests/2050/A.cpp
1716a17ea4a270c23f98f859fe29fc93f28dc417
[]
no_license
wcysai/CodeLibrary
6eb99df0232066cf06a9267bdcc39dc07f5aab29
6517cef736f1799b77646fe04fb280c9503d7238
refs/heads/master
2023-08-10T08:31:58.057363
2023-07-29T11:56:38
2023-07-29T11:56:38
134,228,833
5
2
null
null
null
null
UTF-8
C++
false
false
507
cpp
/************************************************************************* > File Name: A.cpp > Author: Roundgod > Mail: wcysai@foxmail.com > Created Time: 2018-05-25 16:26:35 ************************************************************************/ #include<bits/stdc++.h> #define MAXN 5005 #define INF 1000000000 #define MOD 1000000007 #define F first #define S second using namespace std; typedef long long ll; typedef pair<int,int> P; int t,n,k,a[MAXN]; int main() { return 0; }
[ "wcysai@foxmail.com" ]
wcysai@foxmail.com
fb90ca903f3accf7bd11607ab8ef396dbdf203bb
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_new_hunk_626.cpp
65f630ae443c2c08936afb2e2e7c87b3035cc13d
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
" 55 Failed sending network data.\n" "\n" " 56 Failure in receiving network data.\n" "\n" " 58 Problem with the local certificate.\n" "\n" " 59 Couldn't use specified SSL cipher.\n" "\n" , stdout); fputs( " 60 Peer certificate cannot be authenticated with known CA certifi-\n" " cates.\n" "\n" " 61 Unrecognized transfer encoding.\n" "\n" " 62 Invalid LDAP URL.\n"
[ "993273596@qq.com" ]
993273596@qq.com
39da6b31529b3dc5771be186b26f24eb2ebef468
0cbf959d84aee41ee069812d8c357e6ddbd2f451
/Source/NetworkTestGame/NetworkTestGame.cpp
2abe70566c5993b1020a8bfdb579caececdc0d78
[]
no_license
SeverZmith/NetworkTestGame
3a0d580f78701240417704b298be3209d5f22bf5
fe22a1cb29c09048b5c0e150c11a714149ea3a38
refs/heads/master
2020-03-22T17:16:52.621769
2018-07-24T11:46:14
2018-07-24T11:46:14
140,385,452
1
1
null
null
null
null
UTF-8
C++
false
false
221
cpp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "NetworkTestGame.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, NetworkTestGame, "NetworkTestGame" );
[ "eric.g.smith.24@gmail.com" ]
eric.g.smith.24@gmail.com
5a0e2c5cd69c676c1571693476a3da619a7ac570
af5a05a4955e899fd1c10affda35618a81c749bc
/Classes/Item.h
10b4fecd9ed7133ea3d9dbd97fe0ad7e2534cc5a
[]
no_license
kosakasakas/BabylonClicker
f6cd1ae71f18904a80dd940da928e637e7bb59cf
e6b4d5d599c31e64b60a09e97d299bfd70973e72
refs/heads/master
2021-01-01T19:20:54.875607
2014-10-14T01:36:38
2014-10-14T01:36:38
21,559,342
0
1
null
null
null
null
UTF-8
C++
false
false
342
h
// // Item.h // BabylonClicker // // Created by Takahiro Kosaka on 2014/08/14. // // #ifndef __BabylonClicker__Item__ #define __BabylonClicker__Item__ #include <iostream> #include "GameObject.h" class Item : public GameObject { public: Item(ObjectData* data); virtual ~Item(); }; #endif /* defined(__BabylonClicker__Item__) */
[ "takahiro.kosaka@dena.com" ]
takahiro.kosaka@dena.com
131a4f6205cc6fad8a4e28e876c350bb87cfb089
aa9174a5e178829b674d42758e7d453f13b83606
/Data_Structure_with_C++/oned_Array/passArray_to_fun.cpp
c976f88655e2c3097de633799b98695c61f09267
[]
no_license
tmrindia/Important-Programmes
c27121dd5a4ff520ca04f3e597e25d57e0b952b9
e8034ad63c3038a0d63b3255379acdb6d64bb192
refs/heads/master
2020-04-29T12:21:01.130606
2014-10-23T18:14:27
2014-10-23T18:14:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
434
cpp
// Another Array program in C++ to pass array to a function #include <iostream> using namespace std; int funarray(int[],int); int main() { int a[5],i,sum_array; cout<<"Enter the array elements: "; for(i=0;i<=4;i++) { cin>>a[i]; } sum_array=funarray(a,4); cout<<"The sum of array elements are: "<<sum_array; return 0; } int funarray(int p[],int q) { int i,s=0; for(i=0;i<=q;i++) { s=s+p[i]; } return (s); }
[ "chitrankdixit@gmail.com" ]
chitrankdixit@gmail.com
7e278c16c6819ce2d10f9c989d29bcebc15da1a2
69ce778045b73023c19e59dfff4fa3cbc47270af
/Plugins/DlgSystem/Source/DlgSystemEditor/Private/BlueprintNodes/DialogueK2Node_SwitchDialogueCallback.cpp
942fd894a3d5462879697acd64cdeecb378461df
[ "MIT" ]
permissive
karakune/Rosetta
e410d70fb1579029982c60c2072359fdc32e534f
fb2b582bca68d1a8d0a9e1be85b873cdbfad72e2
refs/heads/master
2020-11-27T14:11:32.038881
2019-12-11T08:27:16
2019-12-11T08:27:16
229,478,145
0
0
null
null
null
null
UTF-8
C++
false
false
7,463
cpp
// Copyright 2017-2018 Csaba Molnar, Daniel Butum #include "DialogueK2Node_SwitchDialogueCallback.h" #include "BlueprintNodeSpawner.h" #include "BlueprintActionDatabaseRegistrar.h" #include "EdGraphSchema_K2.h" #include "Kismet/KismetMathLibrary.h" #include "UObject/UObjectIterator.h" #include "DlgSystemEditorPrivatePCH.h" #include "DlgManager.h" #include "DialogueBlueprintUtilities.h" #define LOCTEXT_NAMESPACE "DlgK2Node_Select" UDialogueK2Node_SwitchDialogueCallback::UDialogueK2Node_SwitchDialogueCallback(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { FunctionName = TEXT("NotEqual_NameName"); FunctionClass = UKismetMathLibrary::StaticClass(); bHasDefaultPin = true; AdvancedPinDisplay = ENodeAdvancedPins::NoPins; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin UEdGraphNode interface void UDialogueK2Node_SwitchDialogueCallback::AllocateDefaultPins() { RefreshPinNames(); Super::AllocateDefaultPins(); } FText UDialogueK2Node_SwitchDialogueCallback::GetNodeTitle(ENodeTitleType::Type TitleType) const { return LOCTEXT("DlgCallbackSwitch_NodeTitle", "Switch on Relevant Dialogue Callback"); } FText UDialogueK2Node_SwitchDialogueCallback::GetTooltipText() const { return LOCTEXT("DlgCallbackSwitch_Tooltip", "Selects an output based on the input"); } // End UEdGraphNode interface //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin UK2Node Interface void UDialogueK2Node_SwitchDialogueCallback::GetMenuActions(FBlueprintActionDatabaseRegistrar& ActionRegistrar) const { // actions get registered under specific object-keys; the idea is that // actions might have to be updated (or deleted) if their object-key is // mutated (or removed)... here we use the node's class (so if the node // type disappears, then the action should go with it) UClass* ActionKey = GetClass(); // to keep from needlessly instantiating a UBlueprintNodeSpawner, first // check to make sure that the registrar is looking for actions of this type // (could be regenerating actions for a specific asset, and therefore the // registrar would only accept actions corresponding to that asset) if (ActionRegistrar.IsOpenForRegistration(ActionKey)) { UBlueprintNodeSpawner* NodeSpawner = UBlueprintNodeSpawner::Create(GetClass()); check(NodeSpawner); ActionRegistrar.AddBlueprintAction(ActionKey, NodeSpawner); } } FText UDialogueK2Node_SwitchDialogueCallback::GetMenuCategory() const { return LOCTEXT("DlgCallbackSwitch_MenuCategory", "Dialogue Switch"); } void UDialogueK2Node_SwitchDialogueCallback::CreateSelectionPin() { const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>(); UEdGraphPin* Pin = CreatePin(EGPD_Input, K2Schema->PC_Name, GetSelectionPinName()); K2Schema->SetPinAutogeneratedDefaultValueBasedOnType(Pin); } // End UK2Node Interface //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin UK2Node_Switch Interface FEdGraphPinType UDialogueK2Node_SwitchDialogueCallback::GetPinType() const { FEdGraphPinType PinType; PinType.PinCategory = UEdGraphSchema_K2::PC_Name; return PinType; } void UDialogueK2Node_SwitchDialogueCallback::RemovePinFromSwitchNode(UEdGraphPin* TargetPin) { // Stop removing option pins, should never arrive here if (TargetPin != GetDefaultPin()) { return; } Super::RemovePinFromSwitchNode(TargetPin); } bool UDialogueK2Node_SwitchDialogueCallback::CanRemoveExecutionPin(UEdGraphPin* TargetPin) const { // Do not allow to remove normal pins, only the execution pin if (TargetPin != GetDefaultPin()) { return false; } return Super::CanRemoveExecutionPin(TargetPin); } FName UDialogueK2Node_SwitchDialogueCallback::GetPinNameGivenIndex(int32 Index) const { return Index < DialoguePinNames.Num() ? DialoguePinNames[Index] : NAME_None; } FName UDialogueK2Node_SwitchDialogueCallback::GetUniquePinName() { checkNoEntry(); return NAME_None; } void UDialogueK2Node_SwitchDialogueCallback::CreateCasePins() { const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>(); for (const auto& PinName : DialoguePinNames) { CreatePin(EGPD_Output, K2Schema->PC_Exec, PinName); } } void UDialogueK2Node_SwitchDialogueCallback::CreateFunctionPin() { // Copied from base class, because it is not exported // TODO PR // Set properties on the function pin UEdGraphPin* FunctionPin = CreatePin(EGPD_Input, UEdGraphSchema_K2::PC_Object, FunctionClass, FunctionName); FunctionPin->bDefaultValueIsReadOnly = true; FunctionPin->bNotConnectable = true; FunctionPin->bHidden = true; UFunction* Function = FindField<UFunction>(FunctionClass, FunctionName); const bool bIsStaticFunc = Function->HasAllFunctionFlags(FUNC_Static); if (bIsStaticFunc) { // Wire up the self to the CDO of the class if it's not us if (UBlueprint* BP = GetBlueprint()) { UClass* FunctionOwnerClass = Function->GetOuterUClass(); if (!BP->SkeletonGeneratedClass->IsChildOf(FunctionOwnerClass)) { FunctionPin->DefaultObject = FunctionOwnerClass->GetDefaultObject(); } } } } void UDialogueK2Node_SwitchDialogueCallback::AddPinToSwitchNode() { // overwrite default behaviour, should never be used if (RefreshPinNames()) { ReconstructNode(); } } // End UK2Node_Switch Interface //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Begin own functions bool UDialogueK2Node_SwitchDialogueCallback::RefreshPinNames() { const FName ParticipantName = FDialogueBlueprintUtilities::GetParticipantNameFromNode(this); if (ParticipantName == NAME_None) { return false; } TArray<FName> NewPinNames; switch (CallbackType) { case EDlgDialogueCallback::DlgEvent: UDlgManager::GetAllDialoguesEventNames(ParticipantName, NewPinNames); break; case EDlgDialogueCallback::DlgCondition: UDlgManager::GetAllDialoguesConditionNames(ParticipantName, NewPinNames); break; case EDlgDialogueCallback::DlgFloatValue: UDlgManager::GetAllDialoguesFloatNames(ParticipantName, NewPinNames); break; case EDlgDialogueCallback::DlgIntValue: UDlgManager::GetAllDialoguesIntNames(ParticipantName, NewPinNames); break; case EDlgDialogueCallback::DlgBoolValue: UDlgManager::GetAllDialoguesBoolNames(ParticipantName, NewPinNames); break; case EDlgDialogueCallback::DlgNameValue: UDlgManager::GetAllDialoguesNameNames(ParticipantName, NewPinNames); break; default: unimplemented(); } // Size changed, simply copy if (NewPinNames.Num() != DialoguePinNames.Num()) { DialoguePinNames = NewPinNames; return true; } // Find any difference, if any for (int32 i = 0; i < NewPinNames.Num(); ++i) { if (NewPinNames[i] != DialoguePinNames[i]) { DialoguePinNames = NewPinNames; return true; } } return false; } // End own functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////// #undef LOCTEXT_NAMESPACE
[ "pilon.matthieu@gmail.com" ]
pilon.matthieu@gmail.com
36c42cadf0554b5587458017ec12b9fc99a32942
246a16842feb7633edbe6291ff36b4c93edbb3c7
/asio-boost/asio_81.cpp
693ac92ce8921d18e0e44f72ea33a01ad7f792e7
[]
no_license
curtkim/c-first
2c223949912c708734648cf29f98778249f79346
f6fa50108ab7c032b74199561698cef087405c37
refs/heads/master
2023-06-08T10:57:35.159250
2023-05-28T05:52:20
2023-05-28T05:52:20
213,894,731
3
1
null
null
null
null
UTF-8
C++
false
false
4,015
cpp
#include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <iostream> boost::mutex global_stream_lock; void WorkerThread( boost::shared_ptr< boost::asio::io_service > io_service ) { global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Thread Start" << std::endl; global_stream_lock.unlock(); while( true ) { try { boost::system::error_code ec; io_service->run( ec ); if( ec ) { global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Error: " << ec << std::endl; global_stream_lock.unlock(); } break; } catch( std::exception & ex ) { global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Exception: " << ex.what() << std::endl; global_stream_lock.unlock(); } } global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Thread Finish" << std::endl; global_stream_lock.unlock(); } void OnAccept( const boost::system::error_code & ec, boost::shared_ptr< boost::asio::ip::tcp::socket > sock ) { if( ec ) { global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Error: " << ec << std::endl; global_stream_lock.unlock(); } else { global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Accepted!" << std::endl; global_stream_lock.unlock(); } } int main( int argc, char * argv[] ) { boost::shared_ptr< boost::asio::io_service > io_service( new boost::asio::io_service ); boost::shared_ptr< boost::asio::io_service::work > work( new boost::asio::io_service::work( *io_service ) ); boost::shared_ptr< boost::asio::io_service::strand > strand( new boost::asio::io_service::strand( *io_service ) ); global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Press [return] to exit." << std::endl; global_stream_lock.unlock(); boost::thread_group worker_threads; for( int x = 0; x < 2; ++x ) { worker_threads.create_thread( boost::bind( &WorkerThread, io_service ) ); } boost::shared_ptr< boost::asio::ip::tcp::acceptor > acceptor( new boost::asio::ip::tcp::acceptor( *io_service ) ); boost::shared_ptr< boost::asio::ip::tcp::socket > sock( new boost::asio::ip::tcp::socket( *io_service ) ); try { boost::asio::ip::tcp::resolver resolver( *io_service ); boost::asio::ip::tcp::resolver::query query( "127.0.0.1", boost::lexical_cast< std::string >( 7777 ) ); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve( query ); acceptor->open( endpoint.protocol() ); acceptor->set_option( boost::asio::ip::tcp::acceptor::reuse_address( false ) ); acceptor->bind( endpoint ); acceptor->listen( boost::asio::socket_base::max_connections ); acceptor->async_accept( *sock, boost::bind( OnAccept, _1, sock ) ); global_stream_lock.lock(); std::cout << "Listening on: " << endpoint << std::endl; global_stream_lock.unlock(); } catch( std::exception & ex ) { global_stream_lock.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Exception: " << ex.what() << std::endl; global_stream_lock.unlock(); } std::cin.get(); boost::system::error_code ec; acceptor->close( ec ); sock->shutdown( boost::asio::ip::tcp::socket::shutdown_both, ec ); sock->close( ec ); io_service->stop(); worker_threads.join_all(); return 0; }
[ "curt.k@kakaocorp.com" ]
curt.k@kakaocorp.com
be50f37cbeae83b414311ce0c9e48c5f0a5e5e4b
b6261b92c271f2cc20f2b39d92bf63211a90d6bb
/Project/FirstGraphicTest/Source/CommandBuffer.cpp
a8e5cd49b0a98cc1acee95144cd3132b58b0986c
[]
no_license
WARHEAD117/Vulkan
72aacd222e30b4a95ea6aac0ba136cb5a04fdec1
61c280c9414d6f29e8c74365a8e86e6788f0c5d0
refs/heads/master
2022-05-22T06:53:55.778301
2020-04-28T02:58:00
2020-04-28T02:58:00
259,514,591
0
0
null
null
null
null
UTF-8
C++
false
false
1,310
cpp
#include "CommandBuffer.h" CommandBuffer::CommandBuffer() { } CommandBuffer::~CommandBuffer() { } void CommandBuffer::Finalize() { for (VkCommandBuffer commandBuffer : m_CommandBuffers) { vkFreeCommandBuffers(m_Device, m_CommandPool, 1, &commandBuffer); } } void CommandBuffer::Init(VkDevice device, uint32_t swapCount, VkCommandPool commandPool) { m_Device = device; m_CommandPool = commandPool; m_CommandBuffers.resize(swapCount); VkCommandBufferAllocateInfo allocCmdBufInfo = {}; allocCmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocCmdBufInfo.commandPool = commandPool; allocCmdBufInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocCmdBufInfo.commandBufferCount = static_cast<uint32_t>(m_CommandBuffers.size()); vkAllocateCommandBuffers(m_Device, &allocCmdBufInfo, m_CommandBuffers.data()); } void CommandBuffer::Begin(uint32_t index) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = 0; beginInfo.pInheritanceInfo = nullptr; vkBeginCommandBuffer(m_CommandBuffers[index], &beginInfo); } void CommandBuffer::End(uint32_t index) { vkEndCommandBuffer(m_CommandBuffers[index]); } VkCommandBuffer CommandBuffer::GetCommandBuffer(uint32_t index) { return m_CommandBuffers[index]; }
[ "johngary_gy@live.com" ]
johngary_gy@live.com
d4e90242eac64d8e72e80c509672984b7fc04bb3
ae219d28725c9dd58c200ae76ba3bf3f2a90d557
/BrowserLauncher/xulrunner-sdk/include/nsIFaviconService.h
232ca3a8c702b067ad9756523b7c540067bb1075
[]
no_license
pepekinha/src
de1f0c64cf1238e019f4daf7f87d95849304d88e
5223858f05f6791f1dec30df1dbb91ae3e4f5952
refs/heads/master
2021-01-22T01:05:54.659896
2014-04-06T01:43:37
2014-04-06T01:43:37
27,421,524
3
2
null
null
null
null
UTF-8
C++
false
false
25,634
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/release-mozilla-1.9.2-xulrunner_win32_build/build/toolkit/components/places/public/nsIFaviconService.idl */ #ifndef __gen_nsIFaviconService_h__ #define __gen_nsIFaviconService_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIURI; /* forward declaration */ /* starting interface: nsIFaviconService */ #define NS_IFAVICONSERVICE_IID_STR "66f6b992-e2d3-43da-ba2a-d966e34a7654" #define NS_IFAVICONSERVICE_IID \ {0x66f6b992, 0xe2d3, 0x43da, \ { 0xba, 0x2a, 0xd9, 0x66, 0xe3, 0x4a, 0x76, 0x54 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIFaviconService : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IFAVICONSERVICE_IID) /** * Declares that a given page uses a favicon with the given URI. * * You needn't have specified any data at this point. An entry linking the * favicon with the page will be create with no data. You can populate it * later with SetFaviconData. However, any favicons not associated with a * visited web page, a bookmark, or a "place:" URI will be expired when * history cleanup is done * (typically at app shutdown, but also possibly * if the user clears their * cache or history). * * This will send out history notifications if the new favicon has any data. * This means that you should try to set data first if you have it, otherwise * the page might not get a notification sent for it since data setting does * not send notifications. * * @param aPageURI * URI of the page whose favicon is being set. * @param aFaviconURI * URI of the favicon to associate with the page. */ /* void setFaviconUrlForPage (in nsIURI aPageURI, in nsIURI aFaviconURI); */ NS_SCRIPTABLE NS_IMETHOD SetFaviconUrlForPage(nsIURI *aPageURI, nsIURI *aFaviconURI) = 0; /** * Same as SetFaviconUrlForPage except that this also attempts to set the * data by loading the favicon URI. An async request will be created for * this URI and if the data is available, it will asynchronously get * saved in the database without any further work from the caller. * * If the icon data already exists, we won't normally try to re-load the * icon from the net (or more likely the cache). If the icon is in the * failed favicon cache we won't do anything. Use forceReload to force * a reload of the data. This will remove the favicon from the failed * cache. If it then fails again, it will be re-added to the failed cache. * * SetFaviconUrlForPage and SetFaviconData will take any URI you provide * and save it. This function is intended for automatic usage, and will * only save favicons for "good" URIs, as defined by what gets added to * history. For "bad" URIs, this function will succeed and do nothing. * This function will also ignore the error page favicon URI * (chrome://global/skin/icons/warning-16.png). Icons that fail to load * will automatically be added to the failed favicon cache. * * This function will not save favicons for non-bookmarked URIs when * history is disabled (expiration time is 0 days). The rest of the functions * here will always store favicons even when history is disabled. * * @param aPageURI * URI of the page whose favicon is being set. * @param aFaviconURI * URI of the favicon to associate with the page. * @param aForceReload * Unset is normal behavior, we will only try to reload the favicon * if we don't have it or if it has expired from the cache. If set, * it will always try to reload the favicon. */ /* void setAndLoadFaviconForPage (in nsIURI aPageURI, in nsIURI aFaviconURI, in boolean aForceReload); */ NS_SCRIPTABLE NS_IMETHOD SetAndLoadFaviconForPage(nsIURI *aPageURI, nsIURI *aFaviconURI, PRBool aForceReload) = 0; /** * Stores the data of a given favicon. You must specify the MIME type * unless you're clearing the data. * * You can set the data even if you haven't called SetFaviconUrlForPage * yet. It will be stored but will not be associated with any page. * However, any favicons not associated with a visited web page, bookmark, * or "place:" URI will be expired when history cleanup is done. This might * be done at any time on a timer, so you should not let the message loop * run between calls or your icon may get deleted. * * It is best to set the favicon data, and then associate it with a page. * This will make the notifications more efficient since the icon will * already have data when the set favicon observer messages goes out. * * The expiration time is stored. This will be used if you call * SetAndLoadFaviconForPage to see whether the data needs reloading. * * Do not use this function for chrome: icon URIs. You should reference the * chrome image yourself. The GetFaviconLinkForIcon/Page will ignore any * associated data if the favicon URI is "chrome:" and just return the same * chrome URI. * * This function does NOT send out notifications that the data has changed. * Potentially, many pages could be referencing the favicon and they could * be visible in a history view or toolbar. But sending out those * notifications is very intensive. Those pages will keep the old icon * until they have been refreshed by other means. * * This function tries to optimize the favicon size, if it is bigger * than defined limit we will try to convert it to a 16x16 png image. If the * conversion fails and favicon is bigger than our max accepted favicon size * we will fail and the favicon won't be saved. * * @param aFaviconURI * URI of the favicon whose data is being set. * @param aData * Binary contents of the favicon to save * @param aDataLength * Length of binary data * @param aMimeType * MIME type of the data to store. This is important so that we know * what to report when the favicon is used. * @param aExpiration * Time in microseconds since the epoch when this favicon expires. * Until this time, we won't try to load it again. * @throws NS_ERROR_FAILURE * Thrown if the favicon is overbloated and won't be saved to the db. */ /* void setFaviconData (in nsIURI aFaviconURI, [array, size_is (aDataLen), const] in octet aData, in unsigned long aDataLen, in AUTF8String aMimeType, in PRTime aExpiration); */ NS_SCRIPTABLE NS_IMETHOD SetFaviconData(nsIURI *aFaviconURI, const PRUint8 *aData, PRUint32 aDataLen, const nsACString & aMimeType, PRTime aExpiration) = 0; /** * Stores the data of a given favicon. The data is provided by a string * containing a data URL. * * This function tries to optimize the favicon size, if it is bigger * than defined limit we will try to convert it to a 16x16 png image. If the * conversion fails and favicon is bigger than our max accepted favicon size * we will fail and the favicon won't be saved. * * @see setFaviconData * * @param aFaviconURI * URI of the favicon whose data is being set. * @param aDataURL * string containing a data URL that represents the contents of * the favicon to save * @param aExpiration * Time in microseconds since the epoch when this favicon expires. * Until this time, we won't try to load it again. * @throws NS_ERROR_FAILURE * Thrown if the favicon is overbloated and won't be saved to the db. */ /* void setFaviconDataFromDataURL (in nsIURI aFaviconURI, in AString aDataURL, in PRTime aExpiration); */ NS_SCRIPTABLE NS_IMETHOD SetFaviconDataFromDataURL(nsIURI *aFaviconURI, const nsAString & aDataURL, PRTime aExpiration) = 0; /** * Retrieves the given favicon data. Throws if we don't have data. * * If there is no data but we have an entry for this favicon, aDataLen will * be 0 and aData will be NULL. * * @param aFaviconURI * URI of the favicon whose data is being read * @param aData * Output parameter where the binary favicon data will be placed. * This will be null if we have this URI but have no data associated * with it. * @param aDataLen * Output parameter where the size of the binary data will be placed. * @param aMimeType * Output parameter where the MIME type will be placed. * @throws NS_ERROR_NOT_AVAILABLE * Thrown when we have never heard of this favicon URI. */ /* void getFaviconData (in nsIURI aFaviconURI, out AUTF8String aMimeType, out unsigned long aDataLen, [array, size_is (aDataLen), retval] out octet aData); */ NS_SCRIPTABLE NS_IMETHOD GetFaviconData(nsIURI *aFaviconURI, nsACString & aMimeType NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM, PRUint8 **aData NS_OUTPARAM) = 0; /** * Retrieves the given favicon data as a data URL. Throws if we don't * have data. * * If there is no data but we have an entry for this favicon, the return * value will be NULL. * * @see getFaviconData * * @param aFaviconURI * URI of the favicon whose data is being read * @returns A data URL containing the data of the favicon. This will be * null if we have this URL but have no data associated with it. * @throws NS_ERROR_NOT_AVAILABLE * Thrown when we have never heard of this favicon URL. */ /* AString getFaviconDataAsDataURL (in nsIURI aFaviconURI); */ NS_SCRIPTABLE NS_IMETHOD GetFaviconDataAsDataURL(nsIURI *aFaviconURI, nsAString & _retval NS_OUTPARAM) = 0; /** * Retrieves the URI of the favicon for the given page. * * @param aPageURI * URI of the page whose favicon is desired * @returns The URI of the favicon associated with that page. Returning a * URI here does NOT mean that we have data for this favicon, only * that we know what the favicon should be. * @throws NS_ERROR_NOT_AVAILABLE * When the page is not found or it has no favicon. */ /* nsIURI getFaviconForPage (in nsIURI aPageURI); */ NS_SCRIPTABLE NS_IMETHOD GetFaviconForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) = 0; /** * For a given page, this will give you a URI that, when displayed in chrome, * will result in the given page's favicon. Unlike the other get functions, * we needn't have heard of the page or its favicon: the default one will * be returned in this case. * * @see getFaviconLinkForIcon * This function only adds the extra level of indirection, looking up * the favicon based on the page URI and using the default if not found. * * @param aPageURI * URI of the page whose favicon is desired * @returns A URI that will give you the icon image. This is NOT the URI of * the icon as set on the page, but a URI that will give you the * data out of the favicon service. For a normal page with a * favicon we've stored, this will be an annotation URI which will * then cause the corresponding favicon data to be loaded from this * service. For pages where we don't have a favicon, this will be a * chrome URI of the default icon for a web page. */ /* nsIURI getFaviconImageForPage (in nsIURI aPageURI); */ NS_SCRIPTABLE NS_IMETHOD GetFaviconImageForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) = 0; /** * For a given icon URI, this will return a URI that will result in the image. * In most cases, this is an annotation URI. For chrome, this will do nothing * and return the input URI. * * @param aFaviconURI * The URI of an icon in the favicon service. * @returns A URI that will load the desired icon. This is NOT the URI of the * icon as set on the page, but a URI that will give you the data * out of the favicon service. For a normal page with a favicon * we've stored, this will be an annotation URI which will then * cause the corresponding favicon data to be loaded from this * service. For pages where we don't have a favicon, this will be a * chrome URI of the default icon for a web page. For chrome, the * output will be the same as the input. * * No validity checking is done. If you pass an icon URI that we've * never seen, you'll get back a URI that references an invalid * icon. The moz-anno protocol handler's special case for "favicon" * annotations will detect most invalid icons and it will resolve to * the default icon, although without caching. For invalid chrome * URIs, you'll get a broken image. */ /* nsIURI getFaviconLinkForIcon (in nsIURI aFaviconURI); */ NS_SCRIPTABLE NS_IMETHOD GetFaviconLinkForIcon(nsIURI *aFaviconURI, nsIURI **_retval NS_OUTPARAM) = 0; /** * Expire all known favicons from the database. * * @note This is an async method. * On successful completion a "places-favicons-expired" notification is * dispatched through observer's service. */ /* void expireAllFavicons (); */ NS_SCRIPTABLE NS_IMETHOD ExpireAllFavicons(void) = 0; /** * Adds a given favicon's URI to the failed favicon cache. * * The lifespan of the favicon cache is up to the caching system. This cache * will also be written to if you use setAndLoadFaviconForPage and it * encounters an error. * * @see isFailedFavicon */ /* void addFailedFavicon (in nsIURI aFaviconURI); */ NS_SCRIPTABLE NS_IMETHOD AddFailedFavicon(nsIURI *aFaviconURI) = 0; /** * Removes the given favicon from the failed favicon cache. If the icon is * not in the cache, this function will silently succeed. */ /* void removeFailedFavicon (in nsIURI aFaviconURI); */ NS_SCRIPTABLE NS_IMETHOD RemoveFailedFavicon(nsIURI *aFaviconURI) = 0; /** * Checks to see if this favicon is in the failed favicon cache. Returns true * if the favicon is in the failed cache, meaning you probably shouldn't try * to load it. A false return value means that it's worth trying to load it. * This allows you to avoid trying to load "foo.com/favicon.ico" for every * page on a site that doesn't have a favicon. */ /* boolean isFailedFavicon (in nsIURI aFaviconURI); */ NS_SCRIPTABLE NS_IMETHOD IsFailedFavicon(nsIURI *aFaviconURI, PRBool *_retval NS_OUTPARAM) = 0; /** * The default favicon URI */ /* readonly attribute nsIURI defaultFavicon; */ NS_SCRIPTABLE NS_IMETHOD GetDefaultFavicon(nsIURI * *aDefaultFavicon) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIFaviconService, NS_IFAVICONSERVICE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIFAVICONSERVICE \ NS_SCRIPTABLE NS_IMETHOD SetFaviconUrlForPage(nsIURI *aPageURI, nsIURI *aFaviconURI); \ NS_SCRIPTABLE NS_IMETHOD SetAndLoadFaviconForPage(nsIURI *aPageURI, nsIURI *aFaviconURI, PRBool aForceReload); \ NS_SCRIPTABLE NS_IMETHOD SetFaviconData(nsIURI *aFaviconURI, const PRUint8 *aData, PRUint32 aDataLen, const nsACString & aMimeType, PRTime aExpiration); \ NS_SCRIPTABLE NS_IMETHOD SetFaviconDataFromDataURL(nsIURI *aFaviconURI, const nsAString & aDataURL, PRTime aExpiration); \ NS_SCRIPTABLE NS_IMETHOD GetFaviconData(nsIURI *aFaviconURI, nsACString & aMimeType NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM, PRUint8 **aData NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetFaviconDataAsDataURL(nsIURI *aFaviconURI, nsAString & _retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetFaviconForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetFaviconImageForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetFaviconLinkForIcon(nsIURI *aFaviconURI, nsIURI **_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD ExpireAllFavicons(void); \ NS_SCRIPTABLE NS_IMETHOD AddFailedFavicon(nsIURI *aFaviconURI); \ NS_SCRIPTABLE NS_IMETHOD RemoveFailedFavicon(nsIURI *aFaviconURI); \ NS_SCRIPTABLE NS_IMETHOD IsFailedFavicon(nsIURI *aFaviconURI, PRBool *_retval NS_OUTPARAM); \ NS_SCRIPTABLE NS_IMETHOD GetDefaultFavicon(nsIURI * *aDefaultFavicon); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIFAVICONSERVICE(_to) \ NS_SCRIPTABLE NS_IMETHOD SetFaviconUrlForPage(nsIURI *aPageURI, nsIURI *aFaviconURI) { return _to SetFaviconUrlForPage(aPageURI, aFaviconURI); } \ NS_SCRIPTABLE NS_IMETHOD SetAndLoadFaviconForPage(nsIURI *aPageURI, nsIURI *aFaviconURI, PRBool aForceReload) { return _to SetAndLoadFaviconForPage(aPageURI, aFaviconURI, aForceReload); } \ NS_SCRIPTABLE NS_IMETHOD SetFaviconData(nsIURI *aFaviconURI, const PRUint8 *aData, PRUint32 aDataLen, const nsACString & aMimeType, PRTime aExpiration) { return _to SetFaviconData(aFaviconURI, aData, aDataLen, aMimeType, aExpiration); } \ NS_SCRIPTABLE NS_IMETHOD SetFaviconDataFromDataURL(nsIURI *aFaviconURI, const nsAString & aDataURL, PRTime aExpiration) { return _to SetFaviconDataFromDataURL(aFaviconURI, aDataURL, aExpiration); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconData(nsIURI *aFaviconURI, nsACString & aMimeType NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM, PRUint8 **aData NS_OUTPARAM) { return _to GetFaviconData(aFaviconURI, aMimeType, aDataLen, aData); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconDataAsDataURL(nsIURI *aFaviconURI, nsAString & _retval NS_OUTPARAM) { return _to GetFaviconDataAsDataURL(aFaviconURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) { return _to GetFaviconForPage(aPageURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconImageForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) { return _to GetFaviconImageForPage(aPageURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconLinkForIcon(nsIURI *aFaviconURI, nsIURI **_retval NS_OUTPARAM) { return _to GetFaviconLinkForIcon(aFaviconURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD ExpireAllFavicons(void) { return _to ExpireAllFavicons(); } \ NS_SCRIPTABLE NS_IMETHOD AddFailedFavicon(nsIURI *aFaviconURI) { return _to AddFailedFavicon(aFaviconURI); } \ NS_SCRIPTABLE NS_IMETHOD RemoveFailedFavicon(nsIURI *aFaviconURI) { return _to RemoveFailedFavicon(aFaviconURI); } \ NS_SCRIPTABLE NS_IMETHOD IsFailedFavicon(nsIURI *aFaviconURI, PRBool *_retval NS_OUTPARAM) { return _to IsFailedFavicon(aFaviconURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetDefaultFavicon(nsIURI * *aDefaultFavicon) { return _to GetDefaultFavicon(aDefaultFavicon); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIFAVICONSERVICE(_to) \ NS_SCRIPTABLE NS_IMETHOD SetFaviconUrlForPage(nsIURI *aPageURI, nsIURI *aFaviconURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFaviconUrlForPage(aPageURI, aFaviconURI); } \ NS_SCRIPTABLE NS_IMETHOD SetAndLoadFaviconForPage(nsIURI *aPageURI, nsIURI *aFaviconURI, PRBool aForceReload) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAndLoadFaviconForPage(aPageURI, aFaviconURI, aForceReload); } \ NS_SCRIPTABLE NS_IMETHOD SetFaviconData(nsIURI *aFaviconURI, const PRUint8 *aData, PRUint32 aDataLen, const nsACString & aMimeType, PRTime aExpiration) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFaviconData(aFaviconURI, aData, aDataLen, aMimeType, aExpiration); } \ NS_SCRIPTABLE NS_IMETHOD SetFaviconDataFromDataURL(nsIURI *aFaviconURI, const nsAString & aDataURL, PRTime aExpiration) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFaviconDataFromDataURL(aFaviconURI, aDataURL, aExpiration); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconData(nsIURI *aFaviconURI, nsACString & aMimeType NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM, PRUint8 **aData NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFaviconData(aFaviconURI, aMimeType, aDataLen, aData); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconDataAsDataURL(nsIURI *aFaviconURI, nsAString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFaviconDataAsDataURL(aFaviconURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFaviconForPage(aPageURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconImageForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFaviconImageForPage(aPageURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetFaviconLinkForIcon(nsIURI *aFaviconURI, nsIURI **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFaviconLinkForIcon(aFaviconURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD ExpireAllFavicons(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->ExpireAllFavicons(); } \ NS_SCRIPTABLE NS_IMETHOD AddFailedFavicon(nsIURI *aFaviconURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->AddFailedFavicon(aFaviconURI); } \ NS_SCRIPTABLE NS_IMETHOD RemoveFailedFavicon(nsIURI *aFaviconURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveFailedFavicon(aFaviconURI); } \ NS_SCRIPTABLE NS_IMETHOD IsFailedFavicon(nsIURI *aFaviconURI, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsFailedFavicon(aFaviconURI, _retval); } \ NS_SCRIPTABLE NS_IMETHOD GetDefaultFavicon(nsIURI * *aDefaultFavicon) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDefaultFavicon(aDefaultFavicon); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsFaviconService : public nsIFaviconService { public: NS_DECL_ISUPPORTS NS_DECL_NSIFAVICONSERVICE nsFaviconService(); private: ~nsFaviconService(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsFaviconService, nsIFaviconService) nsFaviconService::nsFaviconService() { /* member initializers and constructor code */ } nsFaviconService::~nsFaviconService() { /* destructor code */ } /* void setFaviconUrlForPage (in nsIURI aPageURI, in nsIURI aFaviconURI); */ NS_IMETHODIMP nsFaviconService::SetFaviconUrlForPage(nsIURI *aPageURI, nsIURI *aFaviconURI) { return NS_ERROR_NOT_IMPLEMENTED; } /* void setAndLoadFaviconForPage (in nsIURI aPageURI, in nsIURI aFaviconURI, in boolean aForceReload); */ NS_IMETHODIMP nsFaviconService::SetAndLoadFaviconForPage(nsIURI *aPageURI, nsIURI *aFaviconURI, PRBool aForceReload) { return NS_ERROR_NOT_IMPLEMENTED; } /* void setFaviconData (in nsIURI aFaviconURI, [array, size_is (aDataLen), const] in octet aData, in unsigned long aDataLen, in AUTF8String aMimeType, in PRTime aExpiration); */ NS_IMETHODIMP nsFaviconService::SetFaviconData(nsIURI *aFaviconURI, const PRUint8 *aData, PRUint32 aDataLen, const nsACString & aMimeType, PRTime aExpiration) { return NS_ERROR_NOT_IMPLEMENTED; } /* void setFaviconDataFromDataURL (in nsIURI aFaviconURI, in AString aDataURL, in PRTime aExpiration); */ NS_IMETHODIMP nsFaviconService::SetFaviconDataFromDataURL(nsIURI *aFaviconURI, const nsAString & aDataURL, PRTime aExpiration) { return NS_ERROR_NOT_IMPLEMENTED; } /* void getFaviconData (in nsIURI aFaviconURI, out AUTF8String aMimeType, out unsigned long aDataLen, [array, size_is (aDataLen), retval] out octet aData); */ NS_IMETHODIMP nsFaviconService::GetFaviconData(nsIURI *aFaviconURI, nsACString & aMimeType NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM, PRUint8 **aData NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* AString getFaviconDataAsDataURL (in nsIURI aFaviconURI); */ NS_IMETHODIMP nsFaviconService::GetFaviconDataAsDataURL(nsIURI *aFaviconURI, nsAString & _retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIURI getFaviconForPage (in nsIURI aPageURI); */ NS_IMETHODIMP nsFaviconService::GetFaviconForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIURI getFaviconImageForPage (in nsIURI aPageURI); */ NS_IMETHODIMP nsFaviconService::GetFaviconImageForPage(nsIURI *aPageURI, nsIURI **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIURI getFaviconLinkForIcon (in nsIURI aFaviconURI); */ NS_IMETHODIMP nsFaviconService::GetFaviconLinkForIcon(nsIURI *aFaviconURI, nsIURI **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* void expireAllFavicons (); */ NS_IMETHODIMP nsFaviconService::ExpireAllFavicons() { return NS_ERROR_NOT_IMPLEMENTED; } /* void addFailedFavicon (in nsIURI aFaviconURI); */ NS_IMETHODIMP nsFaviconService::AddFailedFavicon(nsIURI *aFaviconURI) { return NS_ERROR_NOT_IMPLEMENTED; } /* void removeFailedFavicon (in nsIURI aFaviconURI); */ NS_IMETHODIMP nsFaviconService::RemoveFailedFavicon(nsIURI *aFaviconURI) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isFailedFavicon (in nsIURI aFaviconURI); */ NS_IMETHODIMP nsFaviconService::IsFailedFavicon(nsIURI *aFaviconURI, PRBool *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIURI defaultFavicon; */ NS_IMETHODIMP nsFaviconService::GetDefaultFavicon(nsIURI * *aDefaultFavicon) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /** * Notification sent when favicons are expired. */ #define NS_PLACES_FAVICONS_EXPIRED_TOPIC_ID "places-favicons-expired" #endif /* __gen_nsIFaviconService_h__ */
[ "highnetlan@gmail.com" ]
highnetlan@gmail.com
10d749c616e3289b4a6505be2f00a728eadb4084
603c19c6dd4697e018f3ed028a2bacfca6179247
/learningRepositoryCPlusPlus/learningRepositoryCPlusPlus/Figure.h
d5065235f78d3a1d2b94eb986ed224df155bd4a9
[]
no_license
Obi-Gun/learningRepositoryCPlusPlus
5cd65d956ae1c9ac05c0a988b913b2d2cfb6ca13
99b0e344d5b9b85a5a85198631ce85593534a443
refs/heads/master
2021-04-02T16:23:04.023924
2020-08-18T22:40:46
2020-08-18T22:40:46
248,294,742
0
0
null
2020-03-30T14:59:32
2020-03-18T17:12:20
C++
UTF-8
C++
false
false
133
h
#ifndef Figure_Class #define Figure_Class class Figure { public: //virtual ~Figure() = 0; virtual int calcSquare() = 0; }; #endif
[ "alexandr.010@yandex.ru" ]
alexandr.010@yandex.ru
57db770f64613f0f28f1f20f4401b1c89e400559
80487a4e66982296862d6af87dc4fc8211d273e0
/Coding ninjas Competitve Programming/Sorting and Searching application/Murder.cpp
91a39212a7819cc00f379b7858bc3a2236c85fa3
[]
no_license
Tarunkmr0023/Competitve-Coding
e4ba476b19609679e942e4089ac67c0c3c90fd43
e0e7af8b2c6c6d4296eba880794654f23372c9f9
refs/heads/main
2023-03-06T04:30:01.762077
2021-02-15T14:56:30
2021-02-15T14:56:30
339,110,664
0
0
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long ll minihelper (int *arr1, int size1, int *arr2, int size2) { int currMaxIndex = size1; ll currAns = 0, finalAns = 0; for(int i = 0; i < size1; i++) { if (arr1[i] >= arr2[0]) { currMaxIndex = i; break; } else currAns += arr1[i]; } finalAns = currAns; for (int i = 1; i < size2; ++i) { ll localCurrAns = currAns; while (arr2[i] > arr1[currMaxIndex] && currMaxIndex < size1) { localCurrAns += arr1[currMaxIndex]; currMaxIndex++; } currAns = localCurrAns; finalAns += localCurrAns; } return finalAns; } ll helper (int *arr, int si, int ei) { if(si >= ei) return 0; int mid = (si + ei) / 2; int n1 = mid - si + 1; int n2 = ei - mid; int arr1[n1]; int arr2[n2]; for(int i = si, k = 0; i <= mid; ++i, ++k) arr1[k] = arr[i]; for(int i = mid + 1, k = 0; i <= ei; ++i, ++k) arr2[k] = arr[i]; sort(arr1, arr1 + n1); sort(arr2, arr2 + n2); ll answer = minihelper(arr1, n1, arr2, n2); answer += helper(arr, si, mid) + helper(arr, mid + 1, ei); return answer; } int main () { int t; cin >> t; while (t--) { int n; cin >> n; int arr[n]; for (int i = 0; i < n; ++i) cin >> arr[i]; cout << helper(arr, 0, n - 1) << endl; } return 0; }
[ "noreply@github.com" ]
Tarunkmr0023.noreply@github.com
4cdb04a3717d65c04bdc5de2b91a5dab96fbc3b9
395b5c2344e9df491916049a8b47a59cd046d05a
/Lesson14/main.cpp
9ceaf41c031401d9f92150afe357d897dd6cee0e
[]
no_license
Lauro199471/OpenCV-Tutorial
eeaab4d01a6b498ed78cd1a9c0d60e46bcae5053
acf01802f22d0684e4eb98b2a56a6415940bd126
refs/heads/master
2020-03-08T19:50:32.540091
2018-04-29T18:21:55
2018-04-29T18:21:55
128,365,733
0
0
null
null
null
null
UTF-8
C++
false
false
2,946
cpp
// Simple Example of Detecting a Red Object #include <opencv2/opencv.hpp> //calls the header files for each OpenCV module #include <iostream> #define USB_CAM_ID 0 #define running 1 using namespace cv; using namespace std; int main(int argc, char* argv[]) { //open the video file for reading VideoCapture cap(USB_CAM_ID); // if not success, exit program if (cap.isOpened() == false) { cout << "Cannot open the video file" << endl; return -1; } // create a window called "Control" namedWindow("Control", CV_WINDOW_AUTOSIZE); // HSV(HUE Saturation Value) max range //Hue (0 - 179) //Saturation (0 - 255) //Value (0 - 255) int LowH = 0; int HighH = 179; int LowS = 0; int HighS = 255; int LowV = 0; int HighV = 255; // Create trackbars(sliders) in "Control" window for HSV cvCreateTrackbar("LowH", "Control", &LowH, 179); cvCreateTrackbar("HighH", "Control", &HighH, 179); cvCreateTrackbar("LowS", "Control", &LowS, 255); cvCreateTrackbar("HighS", "Control", &HighS, 255); cvCreateTrackbar("LowV", "Control", &LowV, 255); cvCreateTrackbar("HighV", "Control", &HighV, 255); while (running) { // Get Frame from USB Camera Mat frame_raw; bool bSuccess = cap.read(frame_raw); // read a new frame from camera and store it in 'frame_raw' matrix if (bSuccess == false) { cout << "Cannot read a frame from video stream" << endl; break; } // Convert 'frame_raw' to a HSV Matrix Mat frame_HSV; cvtColor(frame_raw,frame_HSV,COLOR_BGR2HSV); //-- Detect the object based on HSV Range Values Mat frameFilter; inRange(frame_HSV, Scalar(LowH, LowS, LowV), Scalar(HighH, HighS, HighV), frameFilter); //morphological opening (remove small objects from the foreground) // erode = destory. The erosion makes the object in white smaller. // dilate = To resize something. The dilatation makes the object in white bigger. erode(frameFilter, frameFilter, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); dilate(frameFilter, frameFilter, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); //morphological closing (fill small holes in the foreground) dilate(frameFilter, frameFilter, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); erode(frameFilter, frameFilter, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) ); //show the thresholded image imshow("Thresholded Image", frameFilter); //show the original image imshow("Original", frame_raw); //wait for for 1 ms until any key is pressed. //If the 'Esc' key is pressed, break the while loop. //If the any other key is pressed, continue the loop //If any key is not pressed withing 1 ms, continue the loop if (waitKey(1) == 27) { cout << "Esc key is pressed by user. Stoppig the video" << endl; break; } } return 0; }
[ "lauro199471@gmail.com" ]
lauro199471@gmail.com
626e755a64f94a5625b40c60fe87026624c0f713
0cd8bbc974b822c46b64712d3be53e9808a5c246
/112.cpp
062dcb5e5d7ad67b4976811e0acd15f01f103ddc
[]
no_license
limon2009/ACM-UVA-Online-Judge-solution
b78e8f709c88e5db6fdac83a7bd5ec71f7ab00b0
0f86718d3c609e654a3c16a29e0f91620ac40cd1
refs/heads/master
2021-08-11T04:58:42.829356
2017-11-13T06:14:09
2017-11-13T06:14:09
110,505,263
1
3
null
null
null
null
UTF-8
C++
false
false
2,157
cpp
#include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> #define MAXN 1000000 char St[MAXN]; char input[MAXN]; int sth, rh, N, td; struct ss { int val; }data[MAXN]; void SetStack() { int i, j, k, f ; char temp[20]; for(i = rh; input[i]; i++) { if(input[i] == ' ') continue; if(input[i] == '(') { St[sth++] = '('; data[td++].val = -214748364; } else if(input[i] == ')') { sth--; data[td++].val = -214748364; } else if(isdigit(input[i]) || input[i] == '-') { f = 1; if(input[i] == '-'){ f = -1; i++; } for(j = i, k = 0; isdigit(input[j]) && input[j]; j++) temp[k++] = input[j]; temp[k] = NULL; data[td++].val = f * atoi(temp); i = j-1; } } } int Recur(int val) { if(data[rh+3].val == -214748364 && data[rh+5].val == -214748364) { rh += 6; if(val == N) return 1; return 0; } if(data[rh+3].val != -214748364) { rh += 2; if(Recur(val+data[rh+1].val)) return 1; rh++; if(data[rh+1].val != -214748364) { if(Recur(val+data[rh+1].val)) return 1; rh++; }else { rh += 2; return 0; } }else { rh += 4; if(Recur(val+data[rh+1].val)) return 1; rh++; } return 0; } void Cal() { if(td <= 2) { printf("no\n"); return; } rh = 0; if(Recur(data[1].val)) printf("yes\n"); else printf("no\n"); } int Blank() { int i; for(i = 0; input[i]; i++) { if(isdigit(input[i]) || input[i] == '(' || input[i] == ')') return 0; if(input[i] == '-') return 0; } return 1; } void Set() { int i, k = 0, f; char temp[50]; for(i = 0; input[i] && input[i] == ' '; i++); f = 1; if(input[i] == '-') { f = -1; i++; } for(i; isdigit(input[i]); i++) temp[k++] = input[i]; temp[k] = NULL; N = f * atoi(temp); rh = i; f = 0; while(1) { for(i =rh; input[i]; i++) { if(input[i] == '(') { f = 1; break; } } if(f)break; else { gets(input); rh = 0; } } sth = td = 0; SetStack(); while(sth) { rh = 0; gets(input); SetStack(); } } int main() { int i; // freopen("c:\\h.txt","r",stdin); //freopen("c:\\out.txt","w",stdout); while(gets(input)) { if(Blank()) continue; Set(); Cal(); } return 0; }
[ "md.moniruzzaman@bjitgroup.com" ]
md.moniruzzaman@bjitgroup.com
2eb7d5ea400fa5f32d81e9322d3a554cfbfb215b
480ee7a56def11d0e611dcdf5e827284d70a9185
/httpserver/epoll/http.h
02ae478339ae26175714803ab2205bcf0dbe5fae
[]
no_license
HaoDongddd/EasyHttpServer
5550e6838b6b4a0989bc7a89d4cc32d2d94c6e4e
d237ecdb12cb89a247a5fc24371fae7cb89141e9
refs/heads/master
2023-04-05T14:06:50.783891
2021-04-13T15:38:48
2021-04-13T15:38:48
346,695,708
0
0
null
null
null
null
UTF-8
C++
false
false
3,013
h
#ifndef HTTP_H #define HTTP_H #include <iostream> #include <string> #include <map> #include <queue> #include <cstring> #include <utility> #include <ctype.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/epoll.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string> #define WWWROOT "./index" using namespace std; class Myhttp { typedef int LINE_STATUS; int http_status; int line_status; int request_line_status; int header_status; int send_status; int send_task_count;//发送任务计数 bool f_responese; bool request_err; bool closed; bool keep_alive;//标记 bool init_respon_once;//非keep-alive只init一次responese的标志 volatile int parse_index; map<string,string> headers; queue<string> url_que;//长连接下的url队列 char* buf; char* file; char* send_buf; long file_size; long buf_len; long already_send; volatile int recv_len; int send_len; enum{ rline_start, rline_method, rline_method_sp, rline_url, rline_url_sp, rline_version, rline_almost_done, header_start, header_key, header_colon, header_colon_sp, header_value, header_almost_done, header_blank, CHECK_REQUEST_LINE, CHECK_HEADER, CHECK_BODY, LINE_OPEN, LINE_DONE, REQUEST_ERROR, LINE_NEXT, RLINE_DONE, HEADER_DONE, REQUEST_DONE, BAD_REQUEST, CONN_CLOSED, }; enum{ start_send,//开始发送 sending,//发送中 send_done//发送完成 };//某个responese的send状态 string method,url,version; string key,value; string url_for_send; LINE_STATUS parse_request_line(); LINE_STATUS parse_header(); LINE_STATUS parse_body(); LINE_STATUS get_line(int); void init_responese(); bool get_file(); public: Myhttp():http_status(CHECK_REQUEST_LINE),line_status(LINE_OPEN),f_responese(false),parse_index(0),recv_len(0),buf_len(4096),request_line_status(rline_start),header_status(header_start) { send_task_count = 0; keep_alive = true; init_respon_once = false; file_size = 0; send_len = 0; already_send = 0; closed = false; //printf("im new\n"); send_status = start_send; buf = new char[buf_len]; send_buf = NULL; } ~Myhttp() { if(send_buf != NULL) delete []send_buf; //printf("i go\n"); delete []buf; } bool is_parse_ended(); bool is_respon_ended(); bool is_closed(); bool is_keep_alive(); bool has_send_tasks(); void parse_packet(int sock ,int id); void send_responese(int); void send_responese_for_keepalive(int); void reset_parse_flag();//keep-alive打开时才需要清除标志位 void reset_responese_flag(); }; #endif
[ "1263967171@qq.com" ]
1263967171@qq.com
348b2952459e4ef4d93d3e2c2f0587ac729ec969
d19647286d211653accd333f70e6ff5b7bb09edb
/dynamic_programming/leetcode72.cpp
19817a331a007f7be4de4e87290e8f3a92001085
[]
no_license
mrgao12/algorithm
36c8223ee76430504c7cb6d0a93461733246c3f0
5522918a296d15d4ba70f8cc7406040c511f3ec7
refs/heads/master
2021-01-08T03:24:52.571696
2020-06-11T08:07:40
2020-06-11T08:07:40
241,898,375
1
0
null
null
null
null
UTF-8
C++
false
false
1,292
cpp
#include <iostream> #include <vector> using namespace std; /** * leetcode 72 Edit Distance * Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. * You have the following 3 operations permitted on a word: * 1. Insert a character * 2. Delete a character * 3. Replace a character * problem detail:https://leetcode-cn.com/problems/edit-distance * **/ class Solution { public: int minDistance( string word1, string word2 ) { int m = word1.length(), n = word2.length(); vector < vector< int > > dp ( m+1, vector < int > ( n+1 ) ); for ( int i = 0; i <= m; i++ ) { for ( int j = 0; j <= n; j++ ) { if ( i == 0 ) dp[i][j] = j; else if ( j == 0 ) dp[i][j] = i; else { if ( word1[i-1] == word2[j-1] ) dp[i][j] = dp[i-1][j-1]; else dp[i][j] = min ( dp[i-1][j-1], min ( dp[i-1][j], dp[i][j-1] ) ) + 1; } } } return dp[m][n]; } }; int main() { string a, b; Solution res; while ( cin>>a>>b ) { cout << res.minDistance ( a, b ) << endl; } system("pause"); return 0; }
[ "gaoyong.chn@gmail.com" ]
gaoyong.chn@gmail.com
fd9a9882196dee09866918d9f764aacea265a209
fbe34dc61c8b3ac0d047b057a58972dc77731074
/1030. Travel Plan/src.cpp
adc64d177652dcc54d6abc6f8406e3f342f88e82
[]
no_license
moaiweishui/pat
4c204deec03611f015ce45ff8afd1ba68b77a9e4
637a4d5c47a70b18150ef6eff64e31806674a67f
refs/heads/master
2021-01-19T16:37:06.778775
2017-12-03T13:13:38
2017-12-03T13:13:38
101,012,062
1
0
null
null
null
null
UTF-8
C++
false
false
3,289
cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <math.h> #include <float.h> #include <limits.h> #include <string.h> #include <string> #include <iomanip> #include <vector> #include <set> #include <queue> #include <stack> #include <unordered_set> #include <unordered_map> using namespace std; int main() { int N, M, start, end; cin >> N >> M >> start >> end; vector<vector<long>> dis_matrix(500, vector<long>(500, INT_MAX)); vector<vector<long>> cost_matrix(500, vector<long>(500, INT_MAX)); int node1, node2, dist, cost; for (int i = 0; i < M; i++) { cin >> node1 >> node2 >> dist >> cost; dis_matrix[node1][node2] = dist; dis_matrix[node2][node1] = dist; cost_matrix[node1][node2] = cost; cost_matrix[node2][node1] = cost; } vector<long> dis(500, 0); vector<long> cos(500, 0); vector<int> prev(500, 0); unordered_set<int> S_set; unordered_set<int> T_set; S_set.insert(start); for (int i = 0; i < N; i++) { if (i != start) { T_set.insert(i); dis[i] = dis_matrix[i][start]; cos[i] = cost_matrix[i][start]; if (dis_matrix[i][start] == INT_MAX) prev[i] = -1; else prev[i] = start; } } while (!T_set.empty()) { int shortest_node; int shortest_dis = INT_MAX; int lowest_cost = INT_MAX; for (auto it = T_set.begin(); it != T_set.end(); it++) { if (dis[(*it)] < shortest_dis || (dis[(*it)] == shortest_dis && cos[(*it)] < lowest_cost)) { shortest_node = (*it); shortest_dis = dis[shortest_node]; lowest_cost = cos[shortest_node]; } } S_set.insert(shortest_node); auto findit = T_set.find(shortest_node); T_set.erase(findit); for (auto it = T_set.begin(); it != T_set.end(); it++) { int curr_node = (*it); if (dis_matrix[curr_node][shortest_node] != INT_MAX) { if (dis_matrix[curr_node][shortest_node] + shortest_dis < dis[curr_node]) { dis[curr_node] = dis_matrix[curr_node][shortest_node] + shortest_dis; cos[curr_node] = cost_matrix[curr_node][shortest_node] + lowest_cost; prev[curr_node] = shortest_node; } else if (dis_matrix[curr_node][shortest_node] + shortest_dis == dis[curr_node] && cost_matrix[curr_node][shortest_node] + lowest_cost < cos[curr_node]) { dis[curr_node] = dis_matrix[curr_node][shortest_node] + shortest_dis; cos[curr_node] = cost_matrix[curr_node][shortest_node] + lowest_cost; prev[curr_node] = shortest_node; } } } } vector<int> path; int pt = end; while (pt != start) { path.push_back(pt); pt = prev[pt]; } path.push_back(start); for (int i = path.size() - 1; i >= 0; i--) cout << path[i] << ' '; cout << dis[end] << ' ' << cos[end]; return 0; }
[ "noreply@github.com" ]
moaiweishui.noreply@github.com
3377ee5aaf11ddfc1d4376298b49a8f4e634a5f3
dd5ba03f18b52615ee5f9e978f3dfc1efdef9fc8
/common_factor_count.cpp
2e13f4343e55a7584a2a60d350bbc6eb3c08a7f6
[]
no_license
Yu-JinChoi/c_c-_exercise
72301f9b9e115c507c91ed11325a05897d6465e9
3dc71b403c88a15861c27b4bd9fbfe502c0981f5
refs/heads/master
2023-02-04T07:56:11.804614
2020-12-26T09:06:44
2020-12-26T09:06:44
324,518,525
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include <stdio.h> int main() { int n, k, j = 0; scanf("%d %d", &n, &k); for (int i = 100; i >= 1; i--) { if (n % i == 0 && k % i == 0) { printf("%d ", i); j++; } } printf("%d", j); printf("\n"); }
[ "hani6065@naver.com" ]
hani6065@naver.com
0e335cf5ce9d6617bb5dbcd36dc4ca2cb26a0f5b
44f30dcdcd0ec54ad119a8d924c6c100ff68b8c8
/AboutDialog.cpp
a993258c9d0bfe961a37c3179f7c0af0317618eb
[]
no_license
rfatkullin/Tetris3D
91a55fc0c4557982579a8bb483cf82221eb90cd4
2f3aafb8be98dc71b7469b36334f98a77bc4dc33
refs/heads/master
2021-01-01T05:30:25.679168
2011-12-20T16:46:16
2011-12-20T16:46:16
2,539,476
0
0
null
null
null
null
UTF-8
C++
false
false
1,557
cpp
#include "AboutDialog.h" AboutDialog :: AboutDialog( QWidget* apParent ) : QDialog( apParent ) { QPushButton* ok_button = new QPushButton( "OK" ); QVBoxLayout* ver_layout = new QVBoxLayout(); QHBoxLayout* first_hor_layout = new QHBoxLayout(); QHBoxLayout* second_hor_layout = new QHBoxLayout(); QHBoxLayout* third_hor_layout = new QHBoxLayout(); QLabel* game_name_label = new QLabel( "Tetris3D v1.0" ); QLabel* my_name_label = new QLabel( "(C) 2011 Fatkullin Rustam" ); connect( ok_button, SIGNAL( clicked() ), this, SLOT( accept() ) ); first_hor_layout -> addStretch(); first_hor_layout -> addWidget( game_name_label ); first_hor_layout -> addStretch(); second_hor_layout -> addStretch(); second_hor_layout -> addWidget( my_name_label ); second_hor_layout -> addStretch(); third_hor_layout -> addStretch(); third_hor_layout -> addWidget( ok_button ); ver_layout -> addLayout( first_hor_layout ); ver_layout -> addLayout( second_hor_layout ); ver_layout -> addLayout( third_hor_layout ); setLayout( ver_layout ); setFixedSize( sizeHint() ); setWindowFlags( Qt::Dialog | Qt::WindowTitleHint ); } void AboutDialog :: Show() { QPoint parent_widget_pos = parentWidget() -> pos(); QSize parent_widget_size = parentWidget() -> size(); move( parent_widget_pos.x() + parent_widget_size.width() / 2 - width() / 2, parent_widget_pos.y() + parent_widget_size.height() / 2 - height() / 2 ); exec(); }
[ "rfatkullin@yandex.ru" ]
rfatkullin@yandex.ru
d0666d67e693c63e50968b31b86eef0511212b84
372d949ac03a01615405d9987adea757fc95ebc1
/include/camp/map.hpp
594dc6ddd01a26db1a1e217f3f6f7557c42f1563
[ "BSD-3-Clause" ]
permissive
LLNL/camp
892c7e89c2c352076a57f068aff9b3650fe529e7
2b1ed462295485cb4813e6f4208aea195660bc20
refs/heads/main
2023-08-31T04:30:53.303022
2023-07-26T18:12:51
2023-07-26T18:12:51
145,623,498
64
19
NOASSERTION
2023-09-07T17:43:32
2018-08-21T21:54:40
C++
UTF-8
C++
false
false
1,308
hpp
/* Copyright (c) 2016-18, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Maintained by Tom Scogland <scogland1@llnl.gov> CODE-756261, All rights reserved. This file is part of camp. For details about use and distribution, please read LICENSE and NOTICE from http://github.com/llnl/camp */ #ifndef CAMP_LIST_MAP_HPP #define CAMP_LIST_MAP_HPP #include "camp/helpers.hpp" // declptr #include "camp/list/list.hpp" #include "camp/value.hpp" namespace camp { // TODO: document namespace detail { template <typename Key, typename Val> Val lookup(list<Key, Val>*); template <typename> nil lookup(...); template <typename Seq, typename = nil> struct lookup_table; template <typename... Keys, typename... Values> struct lookup_table<list<list<Keys, Values>...>> : list<Keys, Values>... { }; } // namespace detail template <typename Seq, typename Key> struct at_key_s { using type = decltype(detail::lookup<Key>(declptr<detail::lookup_table<Seq>>())); }; /** * @brief Get value at Key from Map * * @tparam Map The map, or associative list, to index * @tparam Key The key to find */ template <typename Map, typename Key> using at_key = typename at_key_s<Map, Key>::type; } // namespace camp #endif /* CAMP_LIST_MAP_HPP */
[ "scogland1@llnl.gov" ]
scogland1@llnl.gov
61c28b9d3bf3cf265f24d20681b12d8e83f0f556
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/net/socket/fuzzed_socket.cc
40c0adfee26fd03c424e728d4e16bac687e34830
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
7,774
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/socket/fuzzed_socket.h" #include <algorithm> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/test/fuzzed_data_provider.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/io_buffer.h" #include "net/log/net_log_source_type.h" namespace net { namespace { // Some of the socket errors that can be returned by normal socket connection // attempts. const Error kConnectErrors[] = { ERR_CONNECTION_RESET, ERR_CONNECTION_CLOSED, ERR_FAILED, ERR_CONNECTION_TIMED_OUT, ERR_ACCESS_DENIED, ERR_CONNECTION_REFUSED, ERR_ADDRESS_UNREACHABLE}; // Some of the socket errors that can be returned by normal socket reads / // writes. The first one is returned when no more input data remains, so it's // one of the most common ones. const Error kReadWriteErrors[] = {ERR_CONNECTION_CLOSED, ERR_FAILED, ERR_TIMED_OUT, ERR_CONNECTION_RESET}; } // namespace FuzzedSocket::FuzzedSocket(base::FuzzedDataProvider* data_provider, net::NetLog* net_log) : data_provider_(data_provider), net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::SOCKET)), remote_address_(IPEndPoint(IPAddress::IPv4Localhost(), 80)), weak_factory_(this) {} FuzzedSocket::~FuzzedSocket() {} int FuzzedSocket::Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback) { DCHECK(!connect_pending_); DCHECK(!read_pending_); bool sync; int result; if (net_error_ != OK) { // If an error has already been generated, use it to determine what to do. result = net_error_; sync = !error_pending_; } else { // Otherwise, use |data_provider_|. sync = data_provider_->ConsumeBool(); result = data_provider_->ConsumeUint8(); if (result > buf_len) result = buf_len; if (result > 0) { base::StringPiece data = data_provider_->ConsumeBytes(result); result = data.length(); std::copy(data.data(), data.data() + result, buf->data()); } if (result == 0) { net_error_ = ConsumeReadWriteErrorFromData(); result = net_error_; if (!sync) error_pending_ = true; } } // Graceful close of a socket returns OK, at least in theory. This doesn't // perfectly reflect real socket behavior, but close enough. if (result == ERR_CONNECTION_CLOSED) result = 0; if (sync) { if (result > 0) total_bytes_read_ += result; return result; } read_pending_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FuzzedSocket::OnReadComplete, weak_factory_.GetWeakPtr(), callback, result)); return ERR_IO_PENDING; } int FuzzedSocket::Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback) { DCHECK(!connect_pending_); DCHECK(!write_pending_); bool sync; int result; if (net_error_ != OK) { // If an error has already been generated, use it to determine what to do. result = net_error_; sync = !error_pending_; } else { // Otherwise, use |data_|. sync = data_provider_->ConsumeBool(); result = data_provider_->ConsumeUint8(); if (result > buf_len) result = buf_len; if (result == 0) { net_error_ = ConsumeReadWriteErrorFromData(); result = net_error_; if (!sync) error_pending_ = true; } } if (sync) { if (result > 0) total_bytes_written_ += result; return result; } write_pending_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FuzzedSocket::OnWriteComplete, weak_factory_.GetWeakPtr(), callback, result)); return ERR_IO_PENDING; } int FuzzedSocket::SetReceiveBufferSize(int32_t size) { return OK; } int FuzzedSocket::SetSendBufferSize(int32_t size) { return OK; } int FuzzedSocket::Connect(const CompletionCallback& callback) { // Sockets can normally be reused, but don't support it here. DCHECK_NE(net_error_, OK); DCHECK(!connect_pending_); DCHECK(!read_pending_); DCHECK(!write_pending_); DCHECK(!error_pending_); DCHECK(!total_bytes_read_); DCHECK(!total_bytes_written_); bool sync = true; Error result = OK; if (fuzz_connect_result_) { // Decide if sync or async. Use async, if no data is left. sync = data_provider_->ConsumeBool(); // Decide if the connect succeeds or not, and if so, pick an error code. if (data_provider_->ConsumeBool()) result = data_provider_->PickValueInArray(kConnectErrors); } if (sync) { net_error_ = result; return result; } connect_pending_ = true; if (result != OK) error_pending_ = true; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FuzzedSocket::OnConnectComplete, weak_factory_.GetWeakPtr(), callback, result)); return ERR_IO_PENDING; } void FuzzedSocket::Disconnect() { net_error_ = ERR_CONNECTION_CLOSED; weak_factory_.InvalidateWeakPtrs(); connect_pending_ = false; read_pending_ = false; write_pending_ = false; error_pending_ = false; } bool FuzzedSocket::IsConnected() const { return net_error_ == OK && !error_pending_; } bool FuzzedSocket::IsConnectedAndIdle() const { return IsConnected(); } int FuzzedSocket::GetPeerAddress(IPEndPoint* address) const { if (!IsConnected()) return ERR_SOCKET_NOT_CONNECTED; *address = remote_address_; return OK; } int FuzzedSocket::GetLocalAddress(IPEndPoint* address) const { if (!IsConnected()) return ERR_SOCKET_NOT_CONNECTED; *address = IPEndPoint(IPAddress(127, 0, 0, 1), 43434); return OK; } const NetLogWithSource& FuzzedSocket::NetLog() const { return net_log_; } void FuzzedSocket::SetSubresourceSpeculation() {} void FuzzedSocket::SetOmniboxSpeculation() {} bool FuzzedSocket::WasEverUsed() const { return total_bytes_written_ != 0 || total_bytes_read_ != 0; } void FuzzedSocket::EnableTCPFastOpenIfSupported() {} bool FuzzedSocket::WasNpnNegotiated() const { return false; } NextProto FuzzedSocket::GetNegotiatedProtocol() const { return kProtoUnknown; } bool FuzzedSocket::GetSSLInfo(SSLInfo* ssl_info) { return false; } void FuzzedSocket::GetConnectionAttempts(ConnectionAttempts* out) const { out->clear(); } void FuzzedSocket::ClearConnectionAttempts() {} void FuzzedSocket::AddConnectionAttempts(const ConnectionAttempts& attempts) {} int64_t FuzzedSocket::GetTotalReceivedBytes() const { return total_bytes_read_; } Error FuzzedSocket::ConsumeReadWriteErrorFromData() { return data_provider_->PickValueInArray(kReadWriteErrors); } void FuzzedSocket::OnReadComplete(const CompletionCallback& callback, int result) { CHECK(read_pending_); read_pending_ = false; if (result <= 0) { error_pending_ = false; } else { total_bytes_read_ += result; } callback.Run(result); } void FuzzedSocket::OnWriteComplete(const CompletionCallback& callback, int result) { CHECK(write_pending_); write_pending_ = false; if (result <= 0) { error_pending_ = false; } else { total_bytes_written_ += result; } callback.Run(result); } void FuzzedSocket::OnConnectComplete(const CompletionCallback& callback, int result) { CHECK(connect_pending_); connect_pending_ = false; if (result < 0) error_pending_ = false; callback.Run(result); } } // namespace net
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
ed93c13399d6c9675fe809ca8c8f04ae2813290c
457586a0d32290f868883e8486a920e509d57d5c
/code/cpp/hello-world.h
a3f917f2b68520ced1b3257eedc06e10b4841432
[]
no_license
taksebeperevod/game-programming-patterns
ce1dd1abb192ccc576dc0ad0aacb5508302e87ee
0e563e376f018f0ee6ede280512ea452a907b13c
refs/heads/master
2020-12-25T01:37:56.381094
2014-09-08T18:30:01
2014-09-08T18:30:01
23,188,081
3
1
null
2014-10-29T10:39:11
2014-08-21T13:28:06
C++
UTF-8
C++
false
false
232
h
#include <iostream> class HelloWorld { public: //^1 // 64 characters --------------------------------------------------------| static void Do() { //^2 std::cout << "Hello world." << std::endl; //^2 } //^1 };
[ "robert@stuffwithstuff.com" ]
robert@stuffwithstuff.com
f59545f447313c692657bf8f4172458f1b84c046
def8fd457e8e24904e0e6e3ddf212a2c5bc83fce
/list3.cpp
a646a561ebfb30c0898f6e23647a99316d3a873f
[]
no_license
Anchal-Mittal/Linked_List
b1f8cfaeb7e096171fc433a96a2d3d0409f1d015
3821b58afca4fbfecee52dc1882db7b46e82f2ce
refs/heads/master
2021-09-09T13:50:38.008416
2018-03-16T18:20:23
2018-03-16T18:20:23
116,420,169
0
0
null
null
null
null
UTF-8
C++
false
false
2,099
cpp
//=========================================deleting an element from linked list exist at head=========================== #include <iostream> #include<cstdio> using namespace std; //===========================================creating a node=========================================================== class Node { public: int info; Node *next; Node(int el, Node *n=0){ info=el; next=n; } }; //=================================================creating a list====================================================== class List{ public: Node *head; Node *tail; List(){ head=tail=NULL; } void insertElement(); void traverse(); void deleteElement(); }; //========================================================insert the element =========================================== void List :: insertElement(){ char ch; int info; do{ cout << "ENTER THE ELEMENT DO U WANT TO INSERT " << endl; cin >> info; if(head==NULL) head=tail=new Node(info); else head=new Node(info,head); cout << "IF U WANT TO INSERT MORE ELEMENT " << endl; cin >> ch; }while(ch== 'Y'|| ch=='y'); } //===============================================delete an element ===================================================== void List :: deleteElement(){ cout << "\nDELETING FROM THE TAIL" << endl; if(head==NULL){ cout << "LIST IS ALREADY EMPTY " << endl; return; } else{ int el; Node *temp=head; el=temp->info; head=head->next; cout << "THE DELETED ELEMENT IS "<<el << endl; delete temp; } } //=============================================traversev a list========================================================= void List :: traverse(){ Node *node = head; while(node !=NULL){ cout << node ->info << " ->"; node =node->next; } } int main(){ List list; list.insertElement(); list.traverse(); list.deleteElement(); list.traverse(); return 0; }
[ "noreply@github.com" ]
Anchal-Mittal.noreply@github.com
315a9d97bc811882eba5a1bb4960a05660903edc
07545d44cc50120acf80abe0ec3a946aa353cca5
/fsfx101/bootloader/characters.h
3ce67ea90cb7b958b057b40cb0faffd9848ccb7e
[]
no_license
freestatefx/5u
930f3ce0ba610c03eb7030c37afb1bc28c809183
c7272fa244b8d47fb37e45de622c4b42cda602b7
refs/heads/master
2022-09-30T11:42:46.071893
2020-06-04T16:08:14
2020-06-04T16:08:14
109,459,158
1
0
null
null
null
null
UTF-8
C++
false
false
1,688
h
// Copyright 2012 Olivier Gillet. // // Author: Olivier Gillet (ol.gillet@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // See http://creativecommons.org/licenses/MIT/ for more information. // // ----------------------------------------------------------------------------- // // Resources definitions. // // Automatically generated with: // make resources #ifndef BRAIDS_BOOTLOADER_CHARACTERS_H_ #define BRAIDS_BOOTLOADER_CHARACTERS_H_ #include "stmlib/stmlib.h" namespace braids { extern const uint16_t chr_characters[]; } // namespace braids #endif // BRAIDS_BOOTLOADER_CHARACTERS_H_
[ "noreply@github.com" ]
freestatefx.noreply@github.com
2e520106f74aca6ac3ac5457a7ddb8b926e10c84
f1c85d864edaf4c9ac9fa4853d5067b06a0185c6
/The_Eye/inc/PID.h
5dc8294dba9eae879e901afde201e0a6336d8866
[ "MIT" ]
permissive
michprev/flyhero-stm32
886d231139caeb86bacd2b01f40a0cb92eee8d98
51c659cdd4e1d50446a563bb11e800defda9a298
refs/heads/master
2021-10-08T02:51:24.855720
2017-08-11T23:04:38
2017-08-11T23:04:38
76,754,235
0
1
MIT
2018-12-06T22:14:15
2016-12-18T00:08:33
C
UTF-8
C++
false
false
634
h
/* * PID.h * * Created on: 14. 7. 2017 * Author: michp */ #ifndef PID_H_ #define PID_H_ #include "cmath" #include "Biquad_Filter.h" #include "Timer.h" namespace flyhero { class PID { private: Biquad_Filter d_term_lpf; uint32_t last_t; float Kp, Ki, Kd; float integrator; float i_max; float last_d; float last_error; public: PID(float i_max = 0, float Kp = 0, float Ki = 0, float Kd = 0); float Get_PID(float error); void Set_Kp(float Kp); void Set_Ki(float Ki); void Set_Kd(float Kd); void Set_I_Max(float i_max); }; } /* namespace flyhero */ #endif /* PID_H_ */
[ "michprev@gmail.com" ]
michprev@gmail.com
24a6bf1e086dea57d5a7599ccb04ccf1ad959304
e3c0499cc58c9fbec887a2e85672d5e29588f9e0
/opt/ir_decl.cpp
c10c149fb81731dd20aa4fa3cc9fa6cf04227bcd
[ "BSD-3-Clause" ]
permissive
stevenknown/xoc
bf19fba2a7851f0c91d62846b61f12000993fa94
3514aaf0d742e7c1bff956f5a5e96a92102abe8a
refs/heads/master
2023-05-14T10:18:34.851859
2023-04-29T08:15:24
2023-04-29T08:15:24
40,242,945
132
19
NOASSERTION
2023-09-08T08:04:04
2015-08-05T12:02:52
C++
UTF-8
C++
false
false
9,469
cpp
/*@ Copyright (c) 2013-2021, Su Zhenyu steven.known@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Su Zhenyu 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 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @*/ #include "cominc.h" #include "comopt.h" namespace xoc { // //START CLd // IR * CLd::dupIRTreeByStmt(IR const* src, Region * rg) { ASSERT0(src->is_st()); IR * ld = rg->getIRMgr()->buildLoad(ST_idinfo(src), src->getOffset(), src->getType()); ld->copyRef(src, rg); return ld; } //END CLd // //START CPr // IR * CPr::dupIRTreeByRef(IR const* src, Region * rg) { ASSERT0(src->isPROp()); IR * pr = rg->getIRMgr()->buildPRdedicated(src->getPrno(), src->getType()); pr->copyRef(src, rg); return pr; } //END CPr // //START CILd // IR * CILd::dupIRTreeByStmt(IR const* src, Region * rg) { ASSERT0(src->is_ist()); IR * ild = rg->getIRMgr()->buildILoad(rg->dupIRTree(IST_base(src)), IST_ofst(src), src->getType()); ild->copyRef(src, rg); ILD_base(ild)->copyRefForTree(IST_base(src), rg); return ild; } //END CILd // //START CArray // IR * CArray::dupIRTreeByStmt(IR const* src, Region * rg) { ASSERT0(src->is_starray()); IR * arr = rg->getIRMgr()->buildArray(rg->dupIRTree(ARR_base(src)), rg->dupIRTreeList(ARR_sub_list(src)), src->getType(), ARR_elemtype(src), ((CStArray*)src)->getDimNum(), ARR_elem_num_buf(src)); arr->setOffset(src->getOffset()); arr->copyRef(src, rg); ARR_base(arr)->copyRefForTree(ARR_base(src), rg); ARR_sub_list(arr)->copyRefForTree(ARR_sub_list(src), rg); return arr; } //END CArray // //START CStArray // IR * CStArray::dupIRTreeByExp(IR const* src, IR * rhs, Region * rg) { ASSERT0(src->is_array()); IR * starr = rg->getIRMgr()->buildStoreArray(rg->dupIRTree(ARR_base(src)), rg->dupIRTreeList(ARR_sub_list(src)), src->getType(), ARR_elemtype(src), ((CStArray*)src)->getDimNum(), ARR_elem_num_buf(src), rhs); starr->setOffset(src->getOffset()); starr->copyRef(src, rg); ARR_base(starr)->copyRefForTree(ARR_base(src), rg); ARR_sub_list(starr)->copyRefForTree(ARR_sub_list(src), rg); return starr; } //END CStArray // //START CISt // IR * CISt::dupIRTreeByExp(IR const* src, IR * rhs, Region * rg) { ASSERT0(src->is_ild()); IR * ist = rg->getIRMgr()->buildIStore(rg->dupIRTree(ILD_base(src)), rhs, src->getOffset(), src->getType()); ist->copyRef(src, rg); IST_base(ist)->copyRefForTree(ILD_base(src), rg); return ist; } //END CISt // //START CSt // IR * CSt::dupIRTreeByExp(IR const* src, IR * rhs, Region * rg) { ASSERT0(src->is_ld()); IR * st = rg->getIRMgr()->buildStore(LD_idinfo(src), src->getType(), src->getOffset(), rhs); st->copyRef(src, rg); return st; } //END CSt // //START CStpr // IR * CStpr::dupIRTreeByExp(IR const* src, IR * rhs, Region * rg) { ASSERT0(src->is_pr()); IR * stpr = rg->getIRMgr()->buildStorePR(PR_no(src), src->getType(), rhs); stpr->copyRef(src, rg); return stpr; } //END CStpr //The function only invoked at debug mode. //Make sure IR_ICALL is the largest ir. bool checkMaxIRCode() { //Change MAX_OFFSET_AT_FREE_TABLE if IR_ICALL is not the largest. for (UINT i = IR_UNDEF; i < IR_CODE_NUM; i++) { ASSERT0(IRCSIZE(i) <= IRCSIZE(IR_ICALL)); } return true; } //The function only invoked at debug mode. //Make sure IR_ICALL is the largest ir. bool checkIRCodeBitSize() { return IR_CODE_NUM <= 1 << IR_CODE_BIT_SIZE; } // //START CIf // void CIf::addToTrueBody(UINT num, ...) { va_list ptr; va_start(ptr, num); IR * ir = (IR*)va_arg(ptr, IR*); IR * last = nullptr; while (num > 0) { xcom::add_next(&IF_truebody(this), &last, ir); ir = (IR*)va_arg(ptr, IR*); ASSERT0(!ir->is_undef()); num--; } va_end(ptr); } void CIf::addToFalseBody(UINT num, ...) { va_list ptr; va_start(ptr, num); IR * ir = (IR*)va_arg(ptr, IR*); IR * last = nullptr; while (num > 0) { xcom::add_next(&IF_falsebody(this), &last, ir); ir = (IR*)va_arg(ptr, IR*); ASSERT0(!ir->is_undef()); num--; } va_end(ptr); } //END CIf // //START CWhileDo // void CWhileDo::addToBody(UINT num, ...) { va_list ptr; va_start(ptr, num); IR * ir = (IR*)va_arg(ptr, IR*); IR * last = nullptr; while (num > 0) { xcom::add_next(&LOOP_body(this), &last, ir); ir = (IR*)va_arg(ptr, IR*); ASSERT0(!ir->is_undef()); num--; } va_end(ptr); } //END CWhileDo // //START CSwitch // void CSwitch::addToBody(UINT num, ...) { va_list ptr; va_start(ptr, num); IR * ir = (IR*)va_arg(ptr, IR*); IR * last = nullptr; while (num > 0) { xcom::add_next(&SWITCH_body(this), &last, ir); ir = (IR*)va_arg(ptr, IR*); ASSERT0(!ir->is_undef()); num--; } va_end(ptr); } //The function collects the LabelInfo for each branch-target. //Note the default-label is collected too. void CSwitch::collectLabel(OUT List<LabelInfo const*> & lst) const { lst.append_tail(getDefLab()); for (IR const* cs = getCaseList(); cs != nullptr; cs = cs->get_next()) { lst.append_tail(CASE_lab(cs)); } } //END CSwitch // //START CIGoto // //The function collects the LabelInfo for each branch-target. void CIGoto::collectLabel(OUT List<LabelInfo const*> & lst) const { for (IR const* cs = getCaseList(); cs != nullptr; cs = cs->get_next()) { lst.append_tail(CASE_lab(cs)); } } //END CIGoto // //START CCall // //Build dummyuse expression to represent potential memory objects that //the Call referrenced. //Note dummyuse may be a list of IR. void CCall::addDummyUse(Region * rg) { IR * newdummyuse = rg->getIRMgr()->buildILoad( rg->getIRMgr()->buildImmAny(0), rg->getTypeMgr()->getAny()); IR_parent(newdummyuse) = this; xcom::insertbefore(&CALL_dummyuse(this), CALL_dummyuse(this), newdummyuse); } //END CCall // //START CPhi // IR * CPhi::getOpnd(UINT idx) const { UINT i = 0; IR * x = PHI_opnd_list(this); for (; x != nullptr && i < idx; x = x->get_next(), i++) {;} return x; } IR * CPhi::dupIRTreeByRef(IR const* src, Region * rg) { ASSERT0(src->isPROp()); //Type cast if host compiler does NOT support C11. IR * phi = rg->getIRMgr()->buildPhi(src->getPrno(), src->getType(), (IR*)nullptr); phi->copyRef(src, rg); return phi; } void CPhi::insertOpndAt(UINT pos, IR * exp) { IR * marker = PHI_opnd_list(this); IR * last = nullptr; UINT i = 0; for (; marker != nullptr && i <= pos; marker = marker->get_next(), i++) { last = marker; } if (marker != nullptr) { //Insert phi operand into operand-list before 'marker'. insertOpndBefore(marker, exp); return; } //Append a new phi operand to tail of operand-list. ASSERT0(i == pos); //'last' may be nullptr, because the operand list may be empty before //insertion. During several CFG edge removing and building, //there may appear single operand PHI. //If CFG optimization perform removing single edge then //adding a new edge, the PHI operand is empty when adding the new edge. xcom::add_next(&PHI_opnd_list(this), &last, exp); setParent(exp); } //END CPhi // //START CRegion // MDSet * CRegion::getMayDef() const { return REGION_ru(this)->getMayDef(); } bool CRegion::is_readonly() const { ASSERT0(rg); return rg->is_readonly(); } MDSet * CRegion::getMayUse() const { return REGION_ru(this)->getMayUse(); } MDSet * CRegion::genMayDef() const { return REGION_ru(this)->genMayDef(); } MDSet * CRegion::genMayUse() const { return REGION_ru(this)->genMayUse(); } //END CRegion } //namespace xoc
[ "steven.known@gmail.com" ]
steven.known@gmail.com
6f440628ea14fa1c87168fabb4df4b690da3307b
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-es/include/aws/es/model/UpdatePackageResult.h
54e730f2fa80af508aefa73615a43774090f919c
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
2,143
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/es/ElasticsearchService_EXPORTS.h> #include <aws/es/model/PackageDetails.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace ElasticsearchService { namespace Model { /** * <p> Container for response returned by <code> <a>UpdatePackage</a> </code> * operation. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/es-2015-01-01/UpdatePackageResponse">AWS * API Reference</a></p> */ class AWS_ELASTICSEARCHSERVICE_API UpdatePackageResult { public: UpdatePackageResult(); UpdatePackageResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); UpdatePackageResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>Information about the package <code>PackageDetails</code>.</p> */ inline const PackageDetails& GetPackageDetails() const{ return m_packageDetails; } /** * <p>Information about the package <code>PackageDetails</code>.</p> */ inline void SetPackageDetails(const PackageDetails& value) { m_packageDetails = value; } /** * <p>Information about the package <code>PackageDetails</code>.</p> */ inline void SetPackageDetails(PackageDetails&& value) { m_packageDetails = std::move(value); } /** * <p>Information about the package <code>PackageDetails</code>.</p> */ inline UpdatePackageResult& WithPackageDetails(const PackageDetails& value) { SetPackageDetails(value); return *this;} /** * <p>Information about the package <code>PackageDetails</code>.</p> */ inline UpdatePackageResult& WithPackageDetails(PackageDetails&& value) { SetPackageDetails(std::move(value)); return *this;} private: PackageDetails m_packageDetails; }; } // namespace Model } // namespace ElasticsearchService } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com